forked from pyth-network/pyth-crosschain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPythUtilis.rs
34 lines (30 loc) · 1.17 KB
/
PythUtilis.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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);
}
}
}