@venusprotocol/oracle 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ import "./BEP20Interface.sol";
5
+
6
+ interface VBep20Interface is BEP20Interface {
7
+ /**
8
+ * @notice Underlying asset for this VToken
9
+ */
10
+ function underlying() external view returns (address);
11
+ }
@@ -0,0 +1,81 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ library FixedPoint {
5
+ // range: [0, 2**112 - 1]
6
+ // resolution: 1 / 2**112
7
+ struct uq112x112 {
8
+ uint224 _x;
9
+ }
10
+
11
+ // returns a uq112x112 which represents the ratio of the numerator to the denominator
12
+ // equivalent to encode(numerator).div(denominator)
13
+ function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
14
+ require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
15
+ return uq112x112((uint224(numerator) << 112) / denominator);
16
+ }
17
+
18
+ // decode a uq112x112 into a uint with 18 decimals of precision
19
+ function decode112with18(uq112x112 memory self) internal pure returns (uint256) {
20
+ // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
21
+ // instead, get close to:
22
+ // (x * 1e18) >> 112
23
+ // without risk of overflowing, e.g.:
24
+ // (x) / 2 ** (112 - lg(1e18))
25
+ return uint256(self._x) / 5192296858534827;
26
+ }
27
+ }
28
+
29
+ // library with helper methods for oracles that are concerned with computing average prices
30
+ library PancakeOracleLibrary {
31
+ using FixedPoint for *;
32
+
33
+ // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
34
+ function currentBlockTimestamp() internal view returns (uint32) {
35
+ return uint32(block.timestamp % 2**32);
36
+ }
37
+
38
+ // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
39
+ function currentCumulativePrices(address pair)
40
+ internal
41
+ view
42
+ returns (
43
+ uint256 price0Cumulative,
44
+ uint256 price1Cumulative,
45
+ uint32 blockTimestamp
46
+ )
47
+ {
48
+ blockTimestamp = currentBlockTimestamp();
49
+ price0Cumulative = IPancakePair(pair).price0CumulativeLast();
50
+ price1Cumulative = IPancakePair(pair).price1CumulativeLast();
51
+
52
+ // if time has elapsed since the last update on the pair, mock the accumulated price values
53
+ (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPancakePair(pair).getReserves();
54
+ if (blockTimestampLast != blockTimestamp) {
55
+ unchecked {
56
+ // subtraction overflow is desired
57
+ uint32 timeElapsed = blockTimestamp - blockTimestampLast;
58
+ // addition overflow is desired
59
+ // counterfactual
60
+ price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
61
+ // counterfactual
62
+ price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
63
+ }
64
+ }
65
+ }
66
+ }
67
+
68
+ interface IPancakePair {
69
+ function getReserves()
70
+ external
71
+ view
72
+ returns (
73
+ uint112 reserve0,
74
+ uint112 reserve1,
75
+ uint32 blockTimestampLast
76
+ );
77
+
78
+ function price0CumulativeLast() external view returns (uint256);
79
+
80
+ function price1CumulativeLast() external view returns (uint256);
81
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.10;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
5
+ import "../interfaces/FeedRegistryInterface.sol";
6
+ import "../interfaces/VBep20Interface.sol";
7
+ import "../interfaces/BEP20Interface.sol";
8
+
9
+ contract BinanceOracle is Initializable {
10
+ FeedRegistryInterface public feedRegistry;
11
+
12
+ function initialize(FeedRegistryInterface feed) public initializer {
13
+ feedRegistry = feed;
14
+ }
15
+
16
+ function getUnderlyingPrice(VBep20Interface vToken) public view returns (uint256) {
17
+ BEP20Interface underlyingToken = BEP20Interface(vToken.underlying());
18
+
19
+ string memory symbol = underlyingToken.symbol();
20
+
21
+ if (keccak256(bytes(symbol)) == keccak256(bytes("WBNB"))) {
22
+ symbol = "BNB";
23
+ }
24
+
25
+ (, int256 answer, , , ) = feedRegistry.latestRoundDataByName(symbol, "USD");
26
+
27
+ uint256 decimalDelta = feedRegistry.decimalsByName(symbol, "USD");
28
+ return (uint256(answer) * (10**(18 - decimalDelta))) * (10**(18 - underlyingToken.decimals()));
29
+ }
30
+ }
@@ -0,0 +1,97 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+ pragma experimental ABIEncoderV2;
4
+
5
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
6
+ import "../interfaces/BEP20Interface.sol";
7
+ import "../interfaces/VBep20Interface.sol";
8
+ import "../interfaces/OracleInterface.sol";
9
+
10
+ struct ValidateConfig {
11
+ /// @notice asset address
12
+ address asset;
13
+ /// @notice upper bound of deviation between reported price and anchor price,
14
+ /// beyond which the reported price will be invalidated
15
+ uint256 upperBoundRatio;
16
+ /// @notice lower bound of deviation between reported price and anchor price,
17
+ /// below which the reported price will be invalidated
18
+ uint256 lowerBoundRatio;
19
+ }
20
+
21
+ // BoundValidator provides some common functions and can be used
22
+ // to wrap up other contracts to form pivot oracles
23
+ contract BoundValidator is OwnableUpgradeable, BoundValidatorInterface {
24
+ /// @notice validation configs by asset
25
+ mapping(address => ValidateConfig) public validateConfigs;
26
+
27
+ /// @notice Emit this event when new validate configs are added
28
+ event ValidateConfigAdded(address indexed asset, uint256 indexed upperBound, uint256 indexed lowerBound);
29
+
30
+ function initialize() public initializer {
31
+ __Ownable_init();
32
+ }
33
+
34
+ /**
35
+ * @notice Add multiple validation configs at the same time
36
+ * @param configs config array
37
+ */
38
+ function setValidateConfigs(ValidateConfig[] memory configs) external virtual onlyOwner {
39
+ require(configs.length > 0, "invalid validate config length");
40
+ for (uint8 i = 0; i < configs.length; i++) {
41
+ setValidateConfig(configs[i]);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @notice Add single validation config
47
+ * @param config config struct
48
+ */
49
+ function setValidateConfig(ValidateConfig memory config) public virtual onlyOwner {
50
+ require(config.asset != address(0), "asset can't be zero address");
51
+ require(config.upperBoundRatio > 0 && config.lowerBoundRatio > 0, "bound must be positive");
52
+ require(config.upperBoundRatio > config.lowerBoundRatio, "upper bound must be higher than lowner bound");
53
+ validateConfigs[config.asset] = config;
54
+ emit ValidateConfigAdded(config.asset, config.upperBoundRatio, config.lowerBoundRatio);
55
+ }
56
+
57
+ /**
58
+ * @notice Test reported asset price against anchor price
59
+ * @param vToken vToken address
60
+ * @param reporterPrice the price to be tested
61
+ */
62
+ function validatePriceWithAnchorPrice(
63
+ address vToken,
64
+ uint256 reporterPrice,
65
+ uint256 anchorPrice
66
+ ) public view virtual override returns (bool) {
67
+ address asset = VBep20Interface(vToken).underlying();
68
+
69
+ require(validateConfigs[asset].upperBoundRatio != 0, "validation config not exist");
70
+ require(anchorPrice != 0, "anchor price is not valid");
71
+ return _isWithinAnchor(asset, reporterPrice, anchorPrice);
72
+ }
73
+
74
+ /**
75
+ * @notice Test whether the reported price is within the predefined bounds
76
+ * @param asset asset address
77
+ * @param reporterPrice the price to be tested
78
+ * @param anchorPrice anchor price as testing anchor
79
+ */
80
+ function _isWithinAnchor(
81
+ address asset,
82
+ uint256 reporterPrice,
83
+ uint256 anchorPrice
84
+ ) internal view returns (bool) {
85
+ if (reporterPrice > 0) {
86
+ uint256 anchorRatio = (anchorPrice * 100e16) / reporterPrice;
87
+ uint256 upperBoundAnchorRatio = validateConfigs[asset].upperBoundRatio;
88
+ uint256 lowerBoundAnchorRatio = validateConfigs[asset].lowerBoundRatio;
89
+ return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
90
+ }
91
+ return false;
92
+ }
93
+
94
+ // BoundValidator is to get inherited, so it's a good practice to add some storage gaps like
95
+ // OpenZepplin proposed in their contracts: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
96
+ uint256[49] private __gap;
97
+ }
@@ -0,0 +1,172 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+ pragma experimental ABIEncoderV2;
4
+
5
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
6
+ import "../interfaces/VBep20Interface.sol";
7
+ import "../interfaces/AggregatorV2V3Interface.sol";
8
+ import "../interfaces/OracleInterface.sol";
9
+
10
+ struct TokenConfig {
11
+ /// @notice underlying token address, which can't be zero address and can be used for existance check
12
+ address asset;
13
+ /// @notice chainlink feed address
14
+ address feed;
15
+ /// @notice expiration period of this asset
16
+ uint256 maxStalePeriod;
17
+ }
18
+
19
+ contract ChainlinkOracle is OwnableUpgradeable, OracleInterface {
20
+ /// @notice VAI token is considered $1 constantly in oracle for now
21
+ uint256 public constant VAI_VALUE = 1e18;
22
+
23
+ /// @notice TODO: might be removed some day, it's for enabling us to force set the prices to
24
+ /// certain values in some urgent conditions
25
+ mapping(address => uint256) public prices;
26
+
27
+ /// @notice token config by assets
28
+ mapping(address => TokenConfig) public tokenConfigs;
29
+
30
+ /// @notice emit when forced price is set
31
+ event PricePosted(
32
+ address asset,
33
+ uint256 previousPriceMantissa,
34
+ uint256 requestedPriceMantissa,
35
+ uint256 newPriceMantissa
36
+ );
37
+
38
+ /// @notice emit when token config is added
39
+ event TokenConfigAdded(address asset, address feed, uint256 maxStalePeriod);
40
+
41
+ modifier notNullAddress(address someone) {
42
+ require(someone != address(0), "can't be zero address");
43
+ _;
44
+ }
45
+
46
+ function initialize() public initializer {
47
+ __Ownable_init();
48
+ }
49
+
50
+ /**
51
+ * @notice Get the Chainlink price of underlying asset of input vToken, revert when vToken is zero address
52
+ * @param vToken vToken address
53
+ * @return price in USD, with 18 decimals
54
+ */
55
+ function getUnderlyingPrice(address vToken) public view override returns (uint256) {
56
+ string memory symbol = VBep20Interface(vToken).symbol();
57
+ // VBNB token doesn't have `underlying` method, so it has to skip `_getUnderlyingPriceInternal
58
+ // method and directly goes into `_getChainlinkPrice`
59
+ if (_compareStrings(symbol, "vBNB")) {
60
+ return _getChainlinkPrice(vToken);
61
+ // VAI price is constantly 1 at the moment, but not guarantee in the future
62
+ } else if (_compareStrings(symbol, "VAI")) {
63
+ return VAI_VALUE;
64
+ // @TODO: This is some history code, keep it here in case of messing up
65
+ } else {
66
+ return _getUnderlyingPriceInternal(VBep20Interface(vToken));
67
+ }
68
+ }
69
+
70
+ /**
71
+ * @notice Get the Chainlink price of underlying asset of input vToken or cached price when it's been set
72
+ * @dev The decimals of underlying tokens is considered to ensure the returned prices are in 18 decimals
73
+ * @param vToken vToken address
74
+ * @return price in USD, with 18 decimals
75
+ */
76
+ function _getUnderlyingPriceInternal(VBep20Interface vToken) internal view returns (uint256 price) {
77
+ VBep20Interface token = VBep20Interface(vToken.underlying());
78
+
79
+ if (prices[address(token)] != 0) {
80
+ price = prices[address(token)];
81
+ } else {
82
+ price = _getChainlinkPrice(address(vToken));
83
+ }
84
+
85
+ uint256 decimalDelta = uint256(18) - uint256(token.decimals());
86
+ return price * (10**decimalDelta);
87
+ }
88
+
89
+ /**
90
+ * @notice Get the Chainlink price of underlying asset of input vToken, revert if token config doesn't exit
91
+ * @dev The decimals of feeds are considered
92
+ * @param vToken vToken address
93
+ * @return price in USD, with 18 decimals
94
+ */
95
+ function _getChainlinkPrice(address vToken)
96
+ internal
97
+ view
98
+ notNullAddress(tokenConfigs[VBep20Interface(vToken).underlying()].asset)
99
+ returns (uint256)
100
+ {
101
+ address asset = VBep20Interface(vToken).underlying();
102
+
103
+ TokenConfig storage tokenConfig = tokenConfigs[asset];
104
+ AggregatorV2V3Interface feed = AggregatorV2V3Interface(tokenConfig.feed);
105
+
106
+ // note: maxStalePeriod cannot be 0
107
+ uint256 maxStalePeriod = tokenConfig.maxStalePeriod;
108
+
109
+ // Chainlink USD-denominated feeds store answers at 8 decimals, mostly
110
+ uint256 decimalDelta = uint256(18) - feed.decimals();
111
+
112
+ (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
113
+ require(answer > 0, "chainlink price must be positive");
114
+
115
+ require(block.timestamp > updatedAt, "updatedAt exceeds block time");
116
+ uint256 deltaTime = block.timestamp - updatedAt;
117
+ require(deltaTime <= maxStalePeriod, "chainlink price expired");
118
+
119
+ return uint256(answer) * (10**decimalDelta);
120
+ }
121
+
122
+ /**
123
+ * @notice Set the forced prices of the underlying token of input vToken
124
+ * @param vToken vToken address
125
+ * @param underlyingPriceMantissa price in 18 decimals
126
+ */
127
+ function setUnderlyingPrice(VBep20Interface vToken, uint256 underlyingPriceMantissa) external onlyOwner {
128
+ address asset = address(vToken.underlying());
129
+ emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
130
+ prices[asset] = underlyingPriceMantissa;
131
+ }
132
+
133
+ /**
134
+ * @notice Set the forced prices of the input token
135
+ * @param asset asset address
136
+ * @param price price in 18 decimals
137
+ */
138
+ function setDirectPrice(address asset, uint256 price) external onlyOwner {
139
+ emit PricePosted(asset, prices[asset], price, price);
140
+ prices[asset] = price;
141
+ }
142
+
143
+ /**
144
+ * @notice Add multiple token configs at the same time
145
+ * @param tokenConfigs_ config array
146
+ */
147
+ function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {
148
+ require(tokenConfigs_.length > 0, "length can't be 0");
149
+ for (uint256 i = 0; i < tokenConfigs_.length; i++) {
150
+ setTokenConfig(tokenConfigs_[i]);
151
+ }
152
+ }
153
+
154
+ /**
155
+ * @notice Add single token config, vToken & feed cannot be zero address, and maxStalePeriod must be positive
156
+ * @param tokenConfig token config struct
157
+ */
158
+ function setTokenConfig(TokenConfig memory tokenConfig)
159
+ public
160
+ onlyOwner
161
+ notNullAddress(tokenConfig.asset)
162
+ notNullAddress(tokenConfig.feed)
163
+ {
164
+ require(tokenConfig.maxStalePeriod > 0, "stale period can't be zero");
165
+ tokenConfigs[tokenConfig.asset] = tokenConfig;
166
+ emit TokenConfigAdded(tokenConfig.asset, tokenConfig.feed, tokenConfig.maxStalePeriod);
167
+ }
168
+
169
+ function _compareStrings(string memory a, string memory b) internal pure returns (bool) {
170
+ return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
171
+ }
172
+ }
@@ -0,0 +1,129 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ import "@openzeppelin/contracts/utils/math/SafeMath.sol";
5
+ import "@openzeppelin/contracts/utils/math/SafeCast.sol";
6
+ import "@openzeppelin/contracts/utils/math/SignedMath.sol";
7
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
8
+ import "../interfaces/PythInterface.sol";
9
+ import "../interfaces/OracleInterface.sol";
10
+ import "../interfaces/BEP20Interface.sol";
11
+ import "../interfaces/VBep20Interface.sol";
12
+
13
+ struct TokenConfig {
14
+ bytes32 pythId;
15
+ address asset;
16
+ uint64 maxStalePeriod;
17
+ }
18
+
19
+ /**
20
+ * PythOracle contract reads prices from actual Pyth oracle contract which accepts/verifies and stores the
21
+ * updated prices from external sources
22
+ */
23
+ contract PythOracle is OwnableUpgradeable, OracleInterface {
24
+ using SafeMath for uint256;
25
+
26
+ // To calculate 10 ** n(which is a signed type)
27
+ using SignedMath for int256;
28
+
29
+ // To cast int64/int8 types from Pyth to unsigned types
30
+ using SafeCast for int256;
31
+
32
+ /// @notice price decimals
33
+ uint256 public constant EXP_SCALE = 1e18;
34
+
35
+ /// @notice the actual pyth oracle address fetch & store the prices
36
+ IPyth public underlyingPythOracle;
37
+
38
+ /// @notice emit when setting a new pyth oracle address
39
+ event PythOracleSet(address indexed newPythOracle);
40
+
41
+ /// @notice emit when token config added
42
+ event TokenConfigAdded(address indexed vToken, bytes32 indexed pythId, uint64 indexed maxStalePeriod);
43
+
44
+ /// @notice token configs by asset address
45
+ mapping(address => TokenConfig) public tokenConfigs;
46
+
47
+ modifier notNullAddress(address someone) {
48
+ require(someone != address(0), "can't be zero address");
49
+ _;
50
+ }
51
+
52
+ function initialize(address underlyingPythOracle_) public initializer {
53
+ __Ownable_init();
54
+ require(underlyingPythOracle_ != address(0), "pyth oracle cannot be zero address");
55
+ underlyingPythOracle = IPyth(underlyingPythOracle_);
56
+ emit PythOracleSet(underlyingPythOracle_);
57
+ }
58
+
59
+ /**
60
+ * @notice Batch set token configs
61
+ * @param tokenConfigs_ token config array
62
+ */
63
+ function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {
64
+ require(tokenConfigs_.length != 0, "length can't be 0");
65
+ for (uint256 i = 0; i < tokenConfigs_.length; i++) {
66
+ setTokenConfig(tokenConfigs_[i]);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * @notice Set single token config, `maxStalePeriod` cannot be 0 and `vToken` can be zero address
72
+ * @param tokenConfig token config struct
73
+ */
74
+ function setTokenConfig(TokenConfig memory tokenConfig) public onlyOwner notNullAddress(tokenConfig.asset) {
75
+ require(tokenConfig.maxStalePeriod != 0, "max stale period cannot be 0");
76
+ tokenConfigs[tokenConfig.asset] = tokenConfig;
77
+ emit TokenConfigAdded(tokenConfig.asset, tokenConfig.pythId, tokenConfig.maxStalePeriod);
78
+ }
79
+
80
+ /**
81
+ * @notice set the underlying pyth oracle contract address
82
+ * @param underlyingPythOracle_ pyth oracle contract address
83
+ */
84
+ function setUnderlyingPythOracle(IPyth underlyingPythOracle_)
85
+ external
86
+ onlyOwner
87
+ notNullAddress(address(underlyingPythOracle_))
88
+ {
89
+ underlyingPythOracle = underlyingPythOracle_;
90
+ emit PythOracleSet(address(underlyingPythOracle_));
91
+ }
92
+
93
+ /**
94
+ * @notice Get price of underlying asset of the input vToken, under the hood this function
95
+ * get price from Pyth contract, the prices of which are updated externally
96
+ * @param vToken vToken address
97
+ * @return price in 10 decimals
98
+ */
99
+ function getUnderlyingPrice(address vToken) public view override returns (uint256) {
100
+ require(address(underlyingPythOracle) != address(0), "Pyth oracle is zero address");
101
+
102
+ address asset = VBep20Interface(vToken).underlying();
103
+ TokenConfig storage tokenConfig = tokenConfigs[asset];
104
+ require(tokenConfig.asset != address(0), "asset doesn't exist");
105
+
106
+ // if the price is expired after it's compared against `maxStalePeriod`, the following call will revert
107
+ PythStructs.Price memory priceInfo = underlyingPythOracle.getLatestAvailablePriceWithinDuration(
108
+ tokenConfig.pythId,
109
+ tokenConfig.maxStalePeriod
110
+ );
111
+
112
+ uint256 price = int256(priceInfo.price).toUint256();
113
+
114
+ require(price > 0, "Pyth oracle price must be positive");
115
+
116
+ // the price returned from Pyth is price ** 10^expo, which is the real dollar price of the assets
117
+ // we need to multiply it by 1e18 to make the price 18 decimals
118
+ BEP20Interface underlyingToken = BEP20Interface(asset);
119
+ if (priceInfo.expo > 0) {
120
+ return
121
+ price.mul(EXP_SCALE).mul(10**int256(priceInfo.expo).toUint256()) *
122
+ (10**(18 - underlyingToken.decimals()));
123
+ } else {
124
+ return
125
+ price.mul(EXP_SCALE).div(10**int256(-priceInfo.expo).toUint256()) *
126
+ (10**(18 - underlyingToken.decimals()));
127
+ }
128
+ }
129
+ }