@venusprotocol/oracle 1.0.0-dev.1

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.
Files changed (78) hide show
  1. package/LICENSE +11 -0
  2. package/README.md +117 -0
  3. package/contracts/ResilientOracle.sol +376 -0
  4. package/contracts/interfaces/FeedRegistryInterface.sol +14 -0
  5. package/contracts/interfaces/OracleInterface.sol +22 -0
  6. package/contracts/interfaces/PublicResolverInterface.sol +7 -0
  7. package/contracts/interfaces/PythInterface.sol +249 -0
  8. package/contracts/interfaces/SIDRegistryInterface.sol +7 -0
  9. package/contracts/interfaces/VBep20Interface.sol +11 -0
  10. package/contracts/libraries/PancakeLibrary.sol +68 -0
  11. package/contracts/oracles/BinanceOracle.sol +125 -0
  12. package/contracts/oracles/BoundValidator.sol +149 -0
  13. package/contracts/oracles/ChainlinkOracle.sol +214 -0
  14. package/contracts/oracles/PythOracle.sol +174 -0
  15. package/contracts/oracles/TwapOracle.sol +309 -0
  16. package/contracts/oracles/mocks/MockBinanceFeedRegistry.sol +29 -0
  17. package/contracts/oracles/mocks/MockBinanceOracle.sol +22 -0
  18. package/contracts/oracles/mocks/MockChainlinkOracle.sol +27 -0
  19. package/contracts/oracles/mocks/MockPythOracle.sol +32 -0
  20. package/contracts/oracles/mocks/MockTwapOracle.sol +31 -0
  21. package/contracts/test/AccessControlManager.sol +6 -0
  22. package/contracts/test/BEP20Harness.sol +16 -0
  23. package/contracts/test/MockPyth.sol +123 -0
  24. package/contracts/test/MockSimpleOracle.sol +41 -0
  25. package/contracts/test/MockV3Aggregator.sol +76 -0
  26. package/contracts/test/PancakePairHarness.sol +90 -0
  27. package/contracts/test/VBEP20Harness.sol +20 -0
  28. package/deploy/1-deploy-oracles.ts +195 -0
  29. package/deploy/2-configure-feeds.ts +324 -0
  30. package/deployments/.gitkeep +0 -0
  31. package/deployments/bscmainnet/.chainId +1 -0
  32. package/deployments/bscmainnet/BinanceOracle.json +329 -0
  33. package/deployments/bscmainnet/BinanceOracle_Implementation.json +259 -0
  34. package/deployments/bscmainnet/BinanceOracle_Proxy.json +227 -0
  35. package/deployments/bscmainnet/BoundValidator.json +621 -0
  36. package/deployments/bscmainnet/BoundValidator_Implementation.json +714 -0
  37. package/deployments/bscmainnet/BoundValidator_Proxy.json +251 -0
  38. package/deployments/bscmainnet/ChainlinkOracle.json +683 -0
  39. package/deployments/bscmainnet/ChainlinkOracle_Implementation.json +826 -0
  40. package/deployments/bscmainnet/ChainlinkOracle_Proxy.json +237 -0
  41. package/deployments/bscmainnet/DefaultProxyAdmin.json +257 -0
  42. package/deployments/bscmainnet/PythOracle.json +681 -0
  43. package/deployments/bscmainnet/PythOracle_Implementation.json +798 -0
  44. package/deployments/bscmainnet/PythOracle_Proxy.json +264 -0
  45. package/deployments/bscmainnet/ResilientOracle.json +832 -0
  46. package/deployments/bscmainnet/ResilientOracle_Implementation.json +1047 -0
  47. package/deployments/bscmainnet/ResilientOracle_Proxy.json +237 -0
  48. package/deployments/bscmainnet/TwapOracle.json +900 -0
  49. package/deployments/bscmainnet/TwapOracle_Implementation.json +1124 -0
  50. package/deployments/bscmainnet/TwapOracle_Proxy.json +251 -0
  51. package/deployments/bscmainnet/solcInputs/0e89febeebc7444140de8e67c9067d2c.json +78 -0
  52. package/deployments/bscmainnet/solcInputs/68ea814c0d6925581f2bda5deba8ce4a.json +60 -0
  53. package/deployments/bscmainnet/solcInputs/8658c669dade0e9ab80874eab3bf3468.json +117 -0
  54. package/deployments/bsctestnet/.chainId +1 -0
  55. package/deployments/bsctestnet/BinanceOracle.json +571 -0
  56. package/deployments/bsctestnet/BinanceOracle_Implementation.json +629 -0
  57. package/deployments/bsctestnet/BinanceOracle_Proxy.json +251 -0
  58. package/deployments/bsctestnet/BoundValidator.json +621 -0
  59. package/deployments/bsctestnet/BoundValidator_Implementation.json +714 -0
  60. package/deployments/bsctestnet/BoundValidator_Proxy.json +251 -0
  61. package/deployments/bsctestnet/ChainlinkOracle.json +697 -0
  62. package/deployments/bsctestnet/ChainlinkOracle_Implementation.json +826 -0
  63. package/deployments/bsctestnet/ChainlinkOracle_Proxy.json +251 -0
  64. package/deployments/bsctestnet/DefaultProxyAdmin.json +257 -0
  65. package/deployments/bsctestnet/PythOracle.json +681 -0
  66. package/deployments/bsctestnet/PythOracle_Implementation.json +798 -0
  67. package/deployments/bsctestnet/PythOracle_Proxy.json +264 -0
  68. package/deployments/bsctestnet/ResilientOracle.json +846 -0
  69. package/deployments/bsctestnet/ResilientOracle_Implementation.json +1047 -0
  70. package/deployments/bsctestnet/ResilientOracle_Proxy.json +251 -0
  71. package/deployments/bsctestnet/TwapOracle.json +887 -0
  72. package/deployments/bsctestnet/TwapOracle_Implementation.json +1111 -0
  73. package/deployments/bsctestnet/TwapOracle_Proxy.json +251 -0
  74. package/deployments/bsctestnet/solcInputs/0e89febeebc7444140de8e67c9067d2c.json +78 -0
  75. package/deployments/bsctestnet/solcInputs/4769dd98af512bf3b6b6504ad0c3bd74.json +78 -0
  76. package/deployments/bsctestnet/solcInputs/f35da22a430a956ee338e720b5898e3d.json +126 -0
  77. package/networks/mainnet.json +1 -0
  78. package/package.json +127 -0
@@ -0,0 +1,249 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2021 Pyth Data Foundation
3
+ pragma solidity 0.8.13;
4
+
5
+ contract PythStructs {
6
+ // A price with a degree of uncertainty, represented as a price +- a confidence interval.
7
+ //
8
+ // The confidence interval roughly corresponds to the standard error of a normal distribution.
9
+ // Both the price and confidence are stored in a fixed-point numeric representation,
10
+ // `x * (10^expo)`, where `expo` is the exponent.
11
+ //
12
+ // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how
13
+ // to how this price safely.
14
+ struct Price {
15
+ // Price
16
+ int64 price;
17
+ // Confidence interval around the price
18
+ uint64 conf;
19
+ // Price exponent
20
+ int32 expo;
21
+ // Unix timestamp describing when the price was published
22
+ uint256 publishTime;
23
+ }
24
+
25
+ // PriceFeed represents a current aggregate price from pyth publisher feeds.
26
+ struct PriceFeed {
27
+ // The price ID.
28
+ bytes32 id;
29
+ // Latest available price
30
+ Price price;
31
+ // Latest available exponentially-weighted moving average price
32
+ Price emaPrice;
33
+ }
34
+ }
35
+
36
+ /// @title Consume prices from the Pyth Network (https://pyth.network/).
37
+ /// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices
38
+ /// for how to consume prices safely.
39
+ /// @author Pyth Data Association
40
+ interface IPyth {
41
+ /// @dev Emitted when an update for price feed with `id` is processed successfully.
42
+ /// @param id The Pyth Price Feed ID.
43
+ /// @param fresh True if the price update is more recent and stored.
44
+ /// @param chainId ID of the source chain that the batch price update containing this price.
45
+ /// This value comes from Wormhole, and you can find the corresponding chains
46
+ /// at https://docs.wormholenetwork.com/wormhole/contracts.
47
+ /// @param sequenceNumber Sequence number of the batch price update containing this price.
48
+ /// @param lastPublishTime Publish time of the previously stored price.
49
+ /// @param publishTime Publish time of the given price update.
50
+ /// @param price Price of the given price update.
51
+ /// @param conf Confidence interval of the given price update.
52
+ event PriceFeedUpdate(
53
+ bytes32 indexed id,
54
+ bool indexed fresh,
55
+ uint16 chainId,
56
+ uint64 sequenceNumber,
57
+ uint256 lastPublishTime,
58
+ uint256 publishTime,
59
+ int64 price,
60
+ uint64 conf
61
+ );
62
+
63
+ /// @dev Emitted when a batch price update is processed successfully.
64
+ /// @param chainId ID of the source chain that the batch price update comes from.
65
+ /// @param sequenceNumber Sequence number of the batch price update.
66
+ /// @param batchSize Number of prices within the batch price update.
67
+ /// @param freshPricesInBatch Number of prices that were more recent and were stored.
68
+ event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber, uint256 batchSize, uint256 freshPricesInBatch);
69
+
70
+ /// @dev Emitted when a call to `updatePriceFeeds` is processed successfully.
71
+ /// @param sender Sender of the call (`msg.sender`).
72
+ /// @param batchCount Number of batches that this function processed.
73
+ /// @param fee Amount of paid fee for updating the prices.
74
+ event UpdatePriceFeeds(address indexed sender, uint256 batchCount, uint256 fee);
75
+
76
+ /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time
77
+ function getValidTimePeriod() external view returns (uint256 validTimePeriod);
78
+
79
+ /// @notice Returns the price and confidence interval.
80
+ /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.
81
+ /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.
82
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
83
+ function getPrice(bytes32 id) external view returns (PythStructs.Price memory price);
84
+
85
+ /// @notice Returns the exponentially-weighted moving average price and confidence interval.
86
+ /// @dev Reverts if the EMA price is not available.
87
+ /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.
88
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
89
+ function getEmaPrice(bytes32 id) external view returns (PythStructs.Price memory price);
90
+
91
+ /// @notice Returns the price of a price feed without any sanity checks.
92
+ /// @dev This function returns the most recent price update in this contract without any recency checks.
93
+ /// This function is unsafe as the returned price update may be arbitrarily far in the past.
94
+ ///
95
+ /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
96
+ /// sufficiently recent for their application. If you are considering using this function, it may be
97
+ /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.
98
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
99
+ function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
100
+
101
+ /// @notice Returns the price that is no older than `age` seconds of the current time.
102
+ /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in
103
+ /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
104
+ /// recently.
105
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
106
+ function getPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);
107
+
108
+ /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.
109
+ /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.
110
+ /// However, if the price is not recent this function returns the latest available price.
111
+ ///
112
+ /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
113
+ /// the returned price is recent or useful for any particular application.
114
+ ///
115
+ /// Users of this function should check the `publishTime` in the price to ensure that the returned price is
116
+ /// sufficiently recent for their application. If you are considering using this function, it may be
117
+ /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.
118
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
119
+ function getEmaPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
120
+
121
+ /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds
122
+ /// of the current time.
123
+ /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in
124
+ /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
125
+ /// recently.
126
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
127
+ function getEmaPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);
128
+
129
+ /// @notice Update price feeds with given update messages.
130
+ /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
131
+ /// `getUpdateFee` with the length of the `updateData` array.
132
+ /// Prices will be updated if they are more recent than the current stored prices.
133
+ /// The call will succeed even if the update is not the most recent.
134
+ /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
135
+ /// @param updateData Array of price update data.
136
+ function updatePriceFeeds(bytes[] calldata updateData) external payable;
137
+
138
+ /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
139
+ /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
140
+ /// given `publishTimes` for the price feeds and does not read the actual price
141
+ /// update publish time within `updateData`.
142
+ ///
143
+ /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
144
+ /// `getUpdateFee` with the length of the `updateData` array.
145
+ ///
146
+ /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime
147
+ /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have
148
+ /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.
149
+ /// Otherwise, it calls updatePriceFeeds method to update the prices.
150
+ ///
151
+ /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.
152
+ /// @param updateData Array of price update data.
153
+ /// @param priceIds Array of price ids.
154
+ /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`
155
+ function updatePriceFeedsIfNecessary(
156
+ bytes[] calldata updateData,
157
+ bytes32[] calldata priceIds,
158
+ uint64[] calldata publishTimes
159
+ ) external payable;
160
+
161
+ /// @notice Returns the required fee to update an array of price updates.
162
+ /// @param updateDataSize Number of price updates.
163
+ /// @return feeAmount The required fee in Wei.
164
+ function getUpdateFee(uint256 updateDataSize) external view returns (uint256 feeAmount);
165
+ }
166
+
167
+ abstract contract AbstractPyth is IPyth {
168
+ /// @notice Returns the price feed with given id.
169
+ /// @dev Reverts if the price does not exist.
170
+ /// @param id The Pyth Price Feed ID of which to fetch the PriceFeed.
171
+ function queryPriceFeed(bytes32 id) public view virtual returns (PythStructs.PriceFeed memory priceFeed);
172
+
173
+ /// @notice Returns true if a price feed with the given id exists.
174
+ /// @param id The Pyth Price Feed ID of which to check its existence.
175
+ function priceFeedExists(bytes32 id) public view virtual returns (bool exists);
176
+
177
+ function getValidTimePeriod() public view virtual override returns (uint256 validTimePeriod);
178
+
179
+ function getPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {
180
+ return getPriceNoOlderThan(id, getValidTimePeriod());
181
+ }
182
+
183
+ function getEmaPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {
184
+ return getEmaPriceNoOlderThan(id, getValidTimePeriod());
185
+ }
186
+
187
+ function getPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {
188
+ PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);
189
+ return priceFeed.price;
190
+ }
191
+
192
+ function getPriceNoOlderThan(
193
+ bytes32 id,
194
+ uint256 age
195
+ ) public view override returns (PythStructs.Price memory price) {
196
+ price = getPriceUnsafe(id);
197
+
198
+ require(diff(block.timestamp, price.publishTime) <= age, "no price available which is recent enough");
199
+
200
+ return price;
201
+ }
202
+
203
+ function getEmaPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {
204
+ PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);
205
+ return priceFeed.emaPrice;
206
+ }
207
+
208
+ function getEmaPriceNoOlderThan(
209
+ bytes32 id,
210
+ uint256 age
211
+ ) public view override returns (PythStructs.Price memory price) {
212
+ price = getEmaPriceUnsafe(id);
213
+
214
+ require(diff(block.timestamp, price.publishTime) <= age, "no ema price available which is recent enough");
215
+
216
+ return price;
217
+ }
218
+
219
+ function diff(uint256 x, uint256 y) internal pure returns (uint256) {
220
+ if (x > y) {
221
+ return x - y;
222
+ } else {
223
+ return y - x;
224
+ }
225
+ }
226
+
227
+ // Access modifier is overridden to public to be able to call it locally.
228
+ function updatePriceFeeds(bytes[] calldata updateData) public payable virtual override;
229
+
230
+ function updatePriceFeedsIfNecessary(
231
+ bytes[] calldata updateData,
232
+ bytes32[] calldata priceIds,
233
+ uint64[] calldata publishTimes
234
+ ) external payable override {
235
+ require(priceIds.length == publishTimes.length, "priceIds and publishTimes arrays should have same length");
236
+
237
+ bool updateNeeded = false;
238
+ for (uint256 i = 0; i < priceIds.length; i++) {
239
+ if (!priceFeedExists(priceIds[i]) || queryPriceFeed(priceIds[i]).price.publishTime < publishTimes[i]) {
240
+ updateNeeded = true;
241
+ break;
242
+ }
243
+ }
244
+
245
+ require(updateNeeded, "no prices in the submitted batch have fresh prices, so this update will have no effect");
246
+
247
+ updatePriceFeeds(updateData);
248
+ }
249
+ }
@@ -0,0 +1,7 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ // SPDX-FileCopyrightText: 2022 Venus
3
+ pragma solidity 0.8.13;
4
+
5
+ interface SIDRegistryInterface {
6
+ function resolver(bytes32 node) external view returns (address);
7
+ }
@@ -0,0 +1,11 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
5
+
6
+ interface VBep20Interface is IERC20Metadata {
7
+ /**
8
+ * @notice Underlying asset for this VToken
9
+ */
10
+ function underlying() external view returns (address);
11
+ }
@@ -0,0 +1,68 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ interface IPancakePair {
5
+ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
6
+
7
+ function price0CumulativeLast() external view returns (uint256);
8
+
9
+ function price1CumulativeLast() external view returns (uint256);
10
+ }
11
+
12
+ library FixedPoint {
13
+ // range: [0, 2**112 - 1]
14
+ // resolution: 1 / 2**112
15
+ struct uq112x112 {
16
+ uint224 _x;
17
+ }
18
+
19
+ // returns a uq112x112 which represents the ratio of the numerator to the denominator
20
+ // equivalent to encode(numerator).div(denominator)
21
+ function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
22
+ require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
23
+ return uq112x112((uint224(numerator) << 112) / denominator);
24
+ }
25
+
26
+ // decode a uq112x112 into a uint with 18 decimals of precision
27
+ function decode112with18(uq112x112 memory self) internal pure returns (uint256) {
28
+ // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
29
+ // instead, get close to:
30
+ // (x * 1e18) >> 112
31
+ // without risk of overflowing, e.g.:
32
+ // (x) / 2 ** (112 - lg(1e18))
33
+ return uint256(self._x) / 5192296858534827;
34
+ }
35
+ }
36
+
37
+ // library with helper methods for oracles that are concerned with computing average prices
38
+ library PancakeOracleLibrary {
39
+ using FixedPoint for *;
40
+
41
+ // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
42
+ function currentBlockTimestamp() internal view returns (uint32) {
43
+ return uint32(block.timestamp % 2 ** 32);
44
+ }
45
+
46
+ // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
47
+ function currentCumulativePrices(
48
+ address pair
49
+ ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) {
50
+ blockTimestamp = currentBlockTimestamp();
51
+ price0Cumulative = IPancakePair(pair).price0CumulativeLast();
52
+ price1Cumulative = IPancakePair(pair).price1CumulativeLast();
53
+
54
+ // if time has elapsed since the last update on the pair, mock the accumulated price values
55
+ (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPancakePair(pair).getReserves();
56
+ if (blockTimestampLast != blockTimestamp) {
57
+ unchecked {
58
+ // subtraction overflow is desired
59
+ uint32 timeElapsed = blockTimestamp - blockTimestampLast;
60
+ // addition overflow is desired
61
+ // counterfactual
62
+ price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
63
+ // counterfactual
64
+ price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
65
+ }
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,125 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
5
+ import "../interfaces/VBep20Interface.sol";
6
+ import "../interfaces/SIDRegistryInterface.sol";
7
+ import "../interfaces/FeedRegistryInterface.sol";
8
+ import "../interfaces/PublicResolverInterface.sol";
9
+ import "@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol";
10
+
11
+ contract BinanceOracle is AccessControlledV8 {
12
+ address public sidRegistryAddress;
13
+
14
+ /// @notice vBNB address
15
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
16
+ address public immutable vBnb;
17
+
18
+ /// @notice VAI address
19
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
20
+ address public immutable vai;
21
+
22
+ /// @notice Max stale period configuration for assets
23
+ mapping(string => uint256) public maxStalePeriod;
24
+
25
+ event MaxStalePeriodAdded(string indexed asset, uint256 maxStalePeriod);
26
+
27
+ /// @notice Constructor for the implementation contract. Sets immutable variables.
28
+ /// @param vBnbAddress The address of the vBNB
29
+ /// @param vaiAddress The address of the VAI
30
+ /// @custom:oz-upgrades-unsafe-allow constructor
31
+ constructor(address vBnbAddress, address vaiAddress) {
32
+ if (vBnbAddress == address(0)) revert("vBNB can't be zero address");
33
+ if (vaiAddress == address(0)) revert("VAI can't be zero address");
34
+ vBnb = vBnbAddress;
35
+ vai = vaiAddress;
36
+ _disableInitializers();
37
+ }
38
+
39
+ /**
40
+ * @notice Used to set the max stale period of an asset
41
+ * @param symbol The symbol of the asset
42
+ * @param _maxStalePeriod The max stake period
43
+ */
44
+ function setMaxStalePeriod(string memory symbol, uint256 _maxStalePeriod) external {
45
+ _checkAccessAllowed("setMaxStalePeriod(string,uint256)");
46
+ if (_maxStalePeriod == 0) revert("stale period can't be zero");
47
+ if (compare(symbol, "")) revert("symbol cannot be empty");
48
+
49
+ maxStalePeriod[symbol] = _maxStalePeriod;
50
+ emit MaxStalePeriodAdded(symbol, _maxStalePeriod);
51
+ }
52
+
53
+ /**
54
+ * @notice Sets the contracts required to fetch prices
55
+ * @param _sidRegistryAddress Address of SID registry
56
+ * @param _accessControlManager Address of the access control manager contract
57
+ */
58
+ function initialize(address _sidRegistryAddress, address _accessControlManager) public initializer {
59
+ sidRegistryAddress = _sidRegistryAddress;
60
+ __AccessControlled_init(_accessControlManager);
61
+ }
62
+
63
+ /**
64
+ * @notice Uses Space ID to fetch the feed registry address
65
+ * @return feedRegistryAddress Address of binance oracle feed registry.
66
+ */
67
+ function getFeedRegistryAddress() public view returns (address) {
68
+ bytes32 nodeHash = 0x94fe3821e0768eb35012484db4df61890f9a6ca5bfa984ef8ff717e73139faff;
69
+
70
+ SIDRegistryInterface sidRegistry = SIDRegistryInterface(sidRegistryAddress);
71
+ address publicResolverAddress = sidRegistry.resolver(nodeHash);
72
+ PublicResolverInterface publicResolver = PublicResolverInterface(publicResolverAddress);
73
+
74
+ return publicResolver.addr(nodeHash);
75
+ }
76
+
77
+ /**
78
+ * @notice Gets the price of a vToken from the binance oracle
79
+ * @param vToken Address of the vToken
80
+ * @return Price in USD
81
+ */
82
+ function getUnderlyingPrice(VBep20Interface vToken) public view returns (uint256) {
83
+ string memory symbol;
84
+ uint256 decimals;
85
+
86
+ // VBNB token doesn't have `underlying` method
87
+ if (address(vToken) == vBnb) {
88
+ symbol = "BNB";
89
+ decimals = 18;
90
+ } else if (address(vToken) == vai) {
91
+ symbol = "VAI";
92
+ decimals = 18;
93
+ } else {
94
+ IERC20Metadata underlyingToken = IERC20Metadata(vToken.underlying());
95
+ symbol = underlyingToken.symbol();
96
+ decimals = underlyingToken.decimals();
97
+ }
98
+
99
+ if (compare(symbol, "WBNB")) {
100
+ symbol = "BNB";
101
+ }
102
+
103
+ FeedRegistryInterface feedRegistry = FeedRegistryInterface(getFeedRegistryAddress());
104
+
105
+ (, int256 answer, , uint256 updatedAt, ) = feedRegistry.latestRoundDataByName(symbol, "USD");
106
+ if (answer <= 0) revert("invalid binance oracle price");
107
+ if (block.timestamp < updatedAt) revert("updatedAt exceeds block time");
108
+
109
+ uint256 deltaTime = block.timestamp - updatedAt;
110
+ if (deltaTime > maxStalePeriod[symbol]) revert("binance oracle price expired");
111
+
112
+ uint256 decimalDelta = feedRegistry.decimalsByName(symbol, "USD");
113
+ return (uint256(answer) * (10 ** (18 - decimalDelta))) * (10 ** (18 - decimals));
114
+ }
115
+
116
+ /**
117
+ * @notice Used to compare if two strings are equal or not
118
+ * @param str1 The first string
119
+ * @param str2 The second string
120
+ * @return equal Returns true if both are equal or else false.
121
+ */
122
+ function compare(string memory str1, string memory str2) internal pure returns (bool) {
123
+ return keccak256(abi.encodePacked(str1)) == keccak256(abi.encodePacked(str2));
124
+ }
125
+ }
@@ -0,0 +1,149 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "../interfaces/VBep20Interface.sol";
5
+ import "../interfaces/OracleInterface.sol";
6
+ import "@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol";
7
+
8
+ struct ValidateConfig {
9
+ /// @notice asset address
10
+ address asset;
11
+ /// @notice Upper bound of deviation between reported price and anchor price,
12
+ /// beyond which the reported price will be invalidated
13
+ uint256 upperBoundRatio;
14
+ /// @notice Lower bound of deviation between reported price and anchor price,
15
+ /// below which the reported price will be invalidated
16
+ uint256 lowerBoundRatio;
17
+ }
18
+
19
+ // BoundValidator provides some common functions and can be used
20
+ // to wrap up other contracts to form pivot oracles
21
+ contract BoundValidator is AccessControlledV8, BoundValidatorInterface {
22
+ /// @notice validation configs by asset
23
+ mapping(address => ValidateConfig) public validateConfigs;
24
+
25
+ /// @notice vBNB address
26
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
27
+ address public immutable vBnb;
28
+
29
+ /// @notice VAI address
30
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
31
+ address public immutable vai;
32
+
33
+ /// @notice Set this as asset address for BNB. This is the underlying for vBNB
34
+ address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
35
+
36
+ /// @notice Emit this event when new validation configs are added
37
+ event ValidateConfigAdded(address indexed asset, uint256 indexed upperBound, uint256 indexed lowerBound);
38
+
39
+ /// @notice Constructor for the implementation contract. Sets immutable variables.
40
+ /// @param vBnbAddress The address of the vBNB
41
+ /// @param vaiAddress The address of the VAI
42
+ /// @custom:oz-upgrades-unsafe-allow constructor
43
+ constructor(address vBnbAddress, address vaiAddress) {
44
+ if (vBnbAddress == address(0)) revert("vBNB can't be zero address");
45
+ if (vaiAddress == address(0)) revert("VAI can't be zero address");
46
+ vBnb = vBnbAddress;
47
+ vai = vaiAddress;
48
+ _disableInitializers();
49
+ }
50
+
51
+ /**
52
+ * @notice Add multiple validation configs at the same time
53
+ * @param configs Array of validation configs
54
+ * @custom:access Only Governance
55
+ * @custom:error Zero length error is thrown if length of the config array is 0
56
+ * @custom:event Emits ValidateConfigAdded for each validation config that is successfully set
57
+ */
58
+ function setValidateConfigs(ValidateConfig[] memory configs) external virtual {
59
+ _checkAccessAllowed("setValidateConfigs(ValidateConfig[])");
60
+
61
+ uint256 length = configs.length;
62
+ if (length == 0) revert("invalid validate config length");
63
+ for (uint256 i; i < length; ++i) {
64
+ setValidateConfig(configs[i]);
65
+ }
66
+ }
67
+
68
+ /**
69
+ * @notice Initializes the owner of the contract
70
+ * @param accessControlManager_ Address of the access control manager contract
71
+ */
72
+ function initialize(address accessControlManager_) public initializer {
73
+ __AccessControlled_init(accessControlManager_);
74
+ }
75
+
76
+ /**
77
+ * @notice Add a single validation config
78
+ * @param config Validation config struct
79
+ * @custom:access Only Governance
80
+ * @custom:error Null address error is thrown if asset address is null
81
+ * @custom:error Range error thrown if bound ratio is not positive
82
+ * @custom:error Range error thrown if lower bound is greater than upper bound
83
+ * @custom:event Emits ValidateConfigAdded when a validation config is successfully set
84
+ */
85
+ function setValidateConfig(ValidateConfig memory config) public virtual {
86
+ _checkAccessAllowed("setValidateConfig(ValidateConfig)");
87
+
88
+ if (config.asset == address(0)) revert("asset can't be zero address");
89
+ if (config.upperBoundRatio == 0 || config.lowerBoundRatio == 0) revert("bound must be positive");
90
+ if (config.upperBoundRatio <= config.lowerBoundRatio) revert("upper bound must be higher than lowner bound");
91
+ validateConfigs[config.asset] = config;
92
+ emit ValidateConfigAdded(config.asset, config.upperBoundRatio, config.lowerBoundRatio);
93
+ }
94
+
95
+ /**
96
+ * @notice Test reported asset price against anchor price
97
+ * @param vToken vToken address
98
+ * @param reportedPrice The price to be tested
99
+ * @custom:error Missing error thrown if asset config is not set
100
+ * @custom:error Price error thrown if anchor price is not valid
101
+ */
102
+ function validatePriceWithAnchorPrice(
103
+ address vToken,
104
+ uint256 reportedPrice,
105
+ uint256 anchorPrice
106
+ ) public view virtual override returns (bool) {
107
+ address asset = _getUnderlyingAsset(vToken);
108
+
109
+ if (validateConfigs[asset].upperBoundRatio == 0) revert("validation config not exist");
110
+ if (anchorPrice == 0) revert("anchor price is not valid");
111
+ return _isWithinAnchor(asset, reportedPrice, anchorPrice);
112
+ }
113
+
114
+ /**
115
+ * @notice Test whether the reported price is within the valid bounds
116
+ * @param asset Asset address
117
+ * @param reportedPrice The price to be tested
118
+ * @param anchorPrice The reported price must be within the the valid bounds of this price
119
+ */
120
+ function _isWithinAnchor(address asset, uint256 reportedPrice, uint256 anchorPrice) internal view returns (bool) {
121
+ if (reportedPrice != 0) {
122
+ uint256 anchorRatio = (anchorPrice * 100e16) / reportedPrice;
123
+ uint256 upperBoundAnchorRatio = validateConfigs[asset].upperBoundRatio;
124
+ uint256 lowerBoundAnchorRatio = validateConfigs[asset].lowerBoundRatio;
125
+ return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
126
+ }
127
+ return false;
128
+ }
129
+
130
+ /**
131
+ * @dev This function returns the underlying asset of a vToken
132
+ * @param vToken vToken address
133
+ * @return asset underlying asset address
134
+ */
135
+ function _getUnderlyingAsset(address vToken) internal view returns (address asset) {
136
+ if (address(vToken) == vBnb) {
137
+ asset = BNB_ADDR;
138
+ } else if (address(vToken) == vai) {
139
+ asset = vai;
140
+ } else {
141
+ asset = VBep20Interface(vToken).underlying();
142
+ }
143
+ }
144
+
145
+ // BoundValidator is to get inherited, so it's a good practice to add some storage gaps like
146
+ // OpenZepplin proposed in their contracts: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
147
+ // solhint-disable-next-line
148
+ uint256[49] private __gap;
149
+ }