PythUtils.sol 1.2 KB

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