Skip to content

Create a Math Library to Combine Pyth Prices in Solidity #1722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions target_chains/ethereum/sdk/rust/PythUtilis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
pragma solidity ^0.8.0;

library PythUtils {
/// @notice Converts a Pyth price to a uint256 with a target number of decimals
/// @param price The Pyth price
/// @param expo The Pyth price exponent
/// @param targetDecimals The target number of decimals
/// @return The price as a uint256
/// @dev Function will lose precision if targetDecimals is less than the Pyth price decimals.
/// This method will truncate any digits that cannot be represented by the targetDecimals.
/// e.g. If the price is 0.000123 and the targetDecimals is 2, the result will be 0

function convertToUint(
int256 price,
int32 expo,
uint8 targetDecimals
) internal pure returns (uint256) {
if (price < 0 || expo > 0 || expo < -255) {
revert();
}

uint8 priceDecimals = uint8(uint32(-1 * expo));

if (targetDecimals >= priceDecimals) {
return
uint(uint256(price)) *
10 ** uint32(targetDecimals - priceDecimals);
} else {
return
uint(uint256(price)) /
10 ** uint32(priceDecimals - targetDecimals);
}
}
}
2 changes: 1 addition & 1 deletion target_chains/ethereum/sdk/solidity/PythUtils.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ library PythUtils {
10 ** uint32(priceDecimals - targetDecimals);
}
}
}
}