PythUtils.sol 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. // SPDX-License-Identifier: Apache-2.0
  2. pragma solidity ^0.8.0;
  3. library PythUtils {
  4. /// @notice Converts a Pyth price to a uint256 with a target number of decimals
  5. /// @param price The Pyth price
  6. /// @param expo The Pyth price exponent
  7. /// @param targetDecimals The target number of decimals
  8. /// @return The price as a uint256
  9. /// @dev Function will lose precision if targetDecimals is less than the Pyth price decimals.
  10. /// This method will truncate any digits that cannot be represented by the targetDecimals.
  11. /// e.g. If the price is 0.000123 and the targetDecimals is 2, the result will be 0
  12. function convertToUint(
  13. int64 price,
  14. int32 expo,
  15. uint8 targetDecimals
  16. ) public pure returns (uint256) {
  17. if (price < 0 || expo > 0 || expo < -255) {
  18. revert();
  19. }
  20. uint8 priceDecimals = uint8(uint32(-1 * expo));
  21. if (targetDecimals >= priceDecimals) {
  22. return
  23. uint(uint64(price)) *
  24. 10 ** uint32(targetDecimals - priceDecimals);
  25. } else {
  26. return
  27. uint(uint64(price)) /
  28. 10 ** uint32(priceDecimals - targetDecimals);
  29. }
  30. }
  31. }