@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,309 @@
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 "../libraries/PancakeLibrary.sol";
6
+ import "../interfaces/OracleInterface.sol";
7
+ import "../interfaces/VBep20Interface.sol";
8
+ import "@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol";
9
+
10
+ struct Observation {
11
+ uint256 timestamp;
12
+ uint256 acc;
13
+ }
14
+
15
+ struct TokenConfig {
16
+ /// @notice Asset address, which can't be zero address and can be used for existance check
17
+ address asset;
18
+ /// @notice Decimals of underlying asset
19
+ uint256 baseUnit;
20
+ /// @notice The address of Pancake pair
21
+ address pancakePool;
22
+ /// @notice Whether the token is paired with WBNB
23
+ bool isBnbBased;
24
+ /// @notice A flag identifies whether the Pancake pair is reversed
25
+ /// e.g. XVS-WBNB is not reversed, while WBNB-XVS is.
26
+ bool isReversedPool;
27
+ /// @notice The minimum window in seconds required between TWAP updates
28
+ uint256 anchorPeriod;
29
+ }
30
+
31
+ contract TwapOracle is AccessControlledV8, TwapInterface {
32
+ using FixedPoint for *;
33
+
34
+ /// @notice WBNB address
35
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
36
+ address public immutable WBNB;
37
+
38
+ /// @notice vBNB address
39
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
40
+ address public immutable vBnb;
41
+
42
+ /// @notice VAI address
43
+ /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
44
+ address public immutable vai;
45
+
46
+ /// @notice the base unit of WBNB and BUSD, which are the paired tokens for all assets
47
+ uint256 public constant bnbBaseUnit = 1e18;
48
+ uint256 public constant busdBaseUnit = 1e18;
49
+
50
+ /// @notice Configs by token
51
+ mapping(address => TokenConfig) public tokenConfigs;
52
+
53
+ /// @notice Stored price by token
54
+ mapping(address => uint256) public prices;
55
+
56
+ /// @notice Keeps a record of token observations mapped by address, updated on every updateTwap invocation.
57
+ mapping(address => Observation[]) public observations;
58
+
59
+ /// @notice Observation array index which probably falls in current anchor period mapped by asset address
60
+ mapping(address => uint256) public windowStart;
61
+
62
+ /// @notice Emit this event when TWAP window is updated
63
+ event TwapWindowUpdated(
64
+ address indexed asset,
65
+ uint256 oldTimestamp,
66
+ uint256 oldAcc,
67
+ uint256 newTimestamp,
68
+ uint256 newAcc
69
+ );
70
+
71
+ /// @notice Emit this event when TWAP price is updated
72
+ event AnchorPriceUpdated(address indexed asset, uint256 price, uint256 oldTimestamp, uint256 newTimestamp);
73
+
74
+ /// @notice Emit this event when new token configs are added
75
+ event TokenConfigAdded(address indexed asset, address indexed pancakePool, uint256 indexed anchorPeriod);
76
+
77
+ modifier notNullAddress(address someone) {
78
+ if (someone == address(0)) revert("can't be zero address");
79
+ _;
80
+ }
81
+
82
+ /// @notice Constructor for the implementation contract. Sets immutable variables.
83
+ /// @param vBnbAddress The address of the VBNB
84
+ /// @param wBnbAddress The address of the WBNB
85
+ /// @param vaiAddress The address of the WBNB
86
+ /// @custom:oz-upgrades-unsafe-allow constructor
87
+ constructor(
88
+ address vBnbAddress,
89
+ address wBnbAddress,
90
+ address vaiAddress
91
+ ) notNullAddress(vBnbAddress) notNullAddress(wBnbAddress) notNullAddress(vaiAddress) {
92
+ vBnb = vBnbAddress;
93
+ WBNB = wBnbAddress;
94
+ vai = vaiAddress;
95
+ _disableInitializers();
96
+ }
97
+
98
+ /**
99
+ * @notice Adds multiple token configs at the same time
100
+ * @param configs Config array
101
+ * @custom:error Zero length error thrown, if length of the config array is 0
102
+ */
103
+ function setTokenConfigs(TokenConfig[] memory configs) external {
104
+ _checkAccessAllowed("setTokenConfigs(TokenConfig[])");
105
+ if (configs.length == 0) revert("length can't be 0");
106
+ uint256 numTokenConfigs = configs.length;
107
+ for (uint256 i; i < numTokenConfigs; ++i) {
108
+ setTokenConfig(configs[i]);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * @notice Get the underlying TWAP price for the given vToken
114
+ * @param vToken vToken address
115
+ * @return price Underlying price in USD
116
+ * @custom:error Missing error is thrown if the token config does not exist
117
+ * @custom:error Range error is thrown if TWAP price is not greater than zero
118
+ */
119
+ function getUnderlyingPrice(address vToken) external view override returns (uint256) {
120
+ address asset = _getUnderlyingAsset(vToken);
121
+
122
+ if (tokenConfigs[asset].asset == address(0)) revert("asset not exist");
123
+ uint256 price = prices[asset];
124
+
125
+ // if price is 0, it means the price hasn't been updated yet and it's meaningless, revert
126
+ if (price == 0) revert("TWAP price must be positive");
127
+ return (price * (10 ** (18 - IERC20Metadata(asset).decimals())));
128
+ }
129
+
130
+ /**
131
+ * @notice Initializes the owner of the contract
132
+ * @param accessControlManager_ Address of the access control manager contract
133
+ */
134
+ function initialize(address accessControlManager_) public initializer {
135
+ __AccessControlled_init(accessControlManager_);
136
+ }
137
+
138
+ /**
139
+ * @notice Adds a single token config
140
+ * @param config token config struct
141
+ * @custom:access Only Governance
142
+ * @custom:error Range error is thrown if anchor period is not greater than zero
143
+ * @custom:error Range error is thrown if base unit is not greater than zero
144
+ * @custom:error Value error is thrown if base unit decimals is not the same as asset decimals
145
+ * @custom:error NotNullAddress error is thrown if address of asset is null
146
+ * @custom:error NotNullAddress error is thrown if PancakeSwap pool address is null
147
+ * @custom:event Emits TokenConfigAdded event if new token config are added with
148
+ * asset address, PancakePool address, anchor period address
149
+ */
150
+ function setTokenConfig(
151
+ TokenConfig memory config
152
+ ) public notNullAddress(config.asset) notNullAddress(config.pancakePool) {
153
+ _checkAccessAllowed("setTokenConfig(TokenConfig)");
154
+
155
+ if (config.anchorPeriod == 0) revert("anchor period must be positive");
156
+ if (config.baseUnit == 0) revert("base unit must be positive");
157
+ if (config.baseUnit != 10 ** IERC20Metadata(config.asset).decimals())
158
+ revert("base unit decimals must be same as asset decimals");
159
+
160
+ uint256 cumulativePrice = currentCumulativePrice(config);
161
+
162
+ // Initialize observation data
163
+ observations[config.asset].push(Observation(block.timestamp, cumulativePrice));
164
+ tokenConfigs[config.asset] = config;
165
+ emit TokenConfigAdded(config.asset, config.pancakePool, config.anchorPeriod);
166
+ }
167
+
168
+ /**
169
+ * @notice Updates the current token/BUSD price from PancakeSwap, with 18 decimals of precision.
170
+ * @return anchorPrice anchor price of the underlying asset of the vToken
171
+ * @custom:error Missing error is thrown if token config does not exist
172
+ */
173
+ function updateTwap(address vToken) public returns (uint256) {
174
+ address asset = _getUnderlyingAsset(vToken);
175
+
176
+ if (tokenConfigs[asset].asset == address(0)) revert("asset not exist");
177
+ // Update & fetch WBNB price first, so we can calculate the price of WBNB paired token
178
+ if (asset != WBNB && tokenConfigs[asset].isBnbBased) {
179
+ if (tokenConfigs[WBNB].asset == address(0)) revert("WBNB not exist");
180
+ _updateTwapInternal(tokenConfigs[WBNB]);
181
+ }
182
+ return _updateTwapInternal(tokenConfigs[asset]);
183
+ }
184
+
185
+ /**
186
+ * @notice Fetches the current token/WBNB and token/BUSD price accumulator from PancakeSwap.
187
+ * @return cumulative price of target token regardless of pair order
188
+ */
189
+ function currentCumulativePrice(TokenConfig memory config) public view returns (uint256) {
190
+ (uint256 price0, uint256 price1, ) = PancakeOracleLibrary.currentCumulativePrices(config.pancakePool);
191
+ if (config.isReversedPool) {
192
+ return price1;
193
+ } else {
194
+ return price0;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.
200
+ * @return price Underlying price in USD, with 18 decimals
201
+ * @custom:error Timing error is thrown if current time is not greater than old observation timestamp
202
+ * @custom:error Zero price error is thrown if token is BNB based and price is zero
203
+ * @custom:error Zero price error is thrown if fetched anchorPriceMantissa is zero
204
+ * @custom:event Emits AnchorPriceUpdated event on successful update of observation with assset address,
205
+ * AnchorPrice, old observation timestamp and current timestamp
206
+ */
207
+ function _updateTwapInternal(TokenConfig memory config) internal virtual returns (uint256) {
208
+ // pokeWindowValues already handled reversed pool cases,
209
+ // priceAverage will always be Token/BNB or Token/BUSD *twap** price.
210
+ (uint256 nowCumulativePrice, uint256 oldCumulativePrice, uint256 oldTimestamp) = pokeWindowValues(config);
211
+
212
+ if (block.timestamp == oldTimestamp) return prices[config.asset];
213
+
214
+ // This should be impossible, but better safe than sorry
215
+ if (block.timestamp < oldTimestamp) revert("now must come after before");
216
+
217
+ uint256 timeElapsed = block.timestamp - oldTimestamp;
218
+
219
+ // Calculate Pancake *twap**
220
+ FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
221
+ uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)
222
+ );
223
+ // *twap** price with 1e18 decimal mantissa
224
+ uint256 priceAverageMantissa = priceAverage.decode112with18();
225
+
226
+ // To cancel the decimals in cumulative price, we need to mulitply the average price with
227
+ // tokenBaseUnit / (wbnbBaseUnit or busdBaseUnit, which is 1e18)
228
+ uint256 pairedTokenBaseUnit = config.isBnbBased ? bnbBaseUnit : busdBaseUnit;
229
+ uint256 anchorPriceMantissa = (priceAverageMantissa * config.baseUnit) / pairedTokenBaseUnit;
230
+
231
+ // if this token is paired with BNB, convert its price to USD
232
+ if (config.isBnbBased) {
233
+ uint256 bnbPrice = prices[WBNB];
234
+ if (bnbPrice == 0) revert("bnb price is invalid");
235
+ anchorPriceMantissa = (anchorPriceMantissa * bnbPrice) / bnbBaseUnit;
236
+ }
237
+
238
+ if (anchorPriceMantissa == 0) revert("twap price cannot be 0");
239
+
240
+ emit AnchorPriceUpdated(config.asset, anchorPriceMantissa, oldTimestamp, block.timestamp);
241
+
242
+ // save anchor price, which is 1e18 decimals
243
+ prices[config.asset] = anchorPriceMantissa;
244
+
245
+ return anchorPriceMantissa;
246
+ }
247
+
248
+ /**
249
+ * @notice Appends current observation and pick an observation with a timestamp equal
250
+ * or just greater than the window start timestamp. If one is not available,
251
+ * then pick the last availableobservation. The window start index is updated in both the cases.
252
+ * Only the current observation is saved, prior observations are deleted during this operation.
253
+ * @return Tuple of cumulative price, old observation and timestamp
254
+ * @custom:event Emits TwapWindowUpdated on successful calculation of cumulative price with asset address,
255
+ * new observation timestamp, current timestamp, new observation price and cumulative price
256
+ */
257
+ function pokeWindowValues(
258
+ TokenConfig memory config
259
+ ) internal returns (uint256, uint256 startCumulativePrice, uint256 startCumulativeTimestamp) {
260
+ uint256 cumulativePrice = currentCumulativePrice(config);
261
+ uint256 currentTimestamp = block.timestamp;
262
+ uint256 windowStartTimestamp = currentTimestamp - config.anchorPeriod;
263
+ Observation[] memory storedObservations = observations[config.asset];
264
+
265
+ uint256 storedObservationsLength = storedObservations.length;
266
+ for (
267
+ uint256 windowStartIndex = windowStart[config.asset];
268
+ windowStartIndex < storedObservationsLength;
269
+ ++windowStartIndex
270
+ ) {
271
+ if (
272
+ (storedObservations[windowStartIndex].timestamp >= windowStartTimestamp) ||
273
+ (windowStartIndex == storedObservationsLength - 1)
274
+ ) {
275
+ startCumulativePrice = storedObservations[windowStartIndex].acc;
276
+ startCumulativeTimestamp = storedObservations[windowStartIndex].timestamp;
277
+ windowStart[config.asset] = windowStartIndex;
278
+ break;
279
+ } else {
280
+ delete observations[config.asset][windowStartIndex];
281
+ }
282
+ }
283
+
284
+ observations[config.asset].push(Observation(currentTimestamp, cumulativePrice));
285
+ emit TwapWindowUpdated(
286
+ config.asset,
287
+ startCumulativeTimestamp,
288
+ startCumulativePrice,
289
+ block.timestamp,
290
+ cumulativePrice
291
+ );
292
+ return (cumulativePrice, startCumulativePrice, startCumulativeTimestamp);
293
+ }
294
+
295
+ /**
296
+ * @dev This function returns the underlying asset of a vToken
297
+ * @param vToken vToken address
298
+ * @return asset underlying asset address
299
+ */
300
+ function _getUnderlyingAsset(address vToken) internal view returns (address asset) {
301
+ if (address(vToken) == vBnb) {
302
+ asset = WBNB;
303
+ } else if (address(vToken) == vai) {
304
+ asset = vai;
305
+ } else {
306
+ asset = VBep20Interface(vToken).underlying();
307
+ }
308
+ }
309
+ }
@@ -0,0 +1,29 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "../../interfaces/FeedRegistryInterface.sol";
5
+
6
+ contract MockBinanceFeedRegistry is FeedRegistryInterface {
7
+ mapping(string => uint256) public assetPrices;
8
+
9
+ function setAssetPrice(string memory base, uint256 price) external {
10
+ assetPrices[base] = price;
11
+ }
12
+
13
+ function latestRoundDataByName(
14
+ string memory base,
15
+ string memory quote
16
+ )
17
+ external
18
+ view
19
+ override
20
+ returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
21
+ {
22
+ quote;
23
+ return (0, int256(assetPrices[base]), 0, block.timestamp - 10, 0);
24
+ }
25
+
26
+ function decimalsByName(string memory base, string memory quote) external view override returns (uint8) {
27
+ return 8;
28
+ }
29
+ }
@@ -0,0 +1,22 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
5
+ import "../../interfaces/VBep20Interface.sol";
6
+
7
+ contract MockBinanceOracle is OwnableUpgradeable {
8
+ mapping(address => uint256) public assetPrices;
9
+
10
+ constructor() {}
11
+
12
+ function setPrice(address asset, uint256 price) external {
13
+ assetPrices[asset] = price;
14
+ }
15
+
16
+ function initialize() public initializer {}
17
+
18
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
19
+ address token = VBep20Interface(vToken).underlying();
20
+ return assetPrices[token];
21
+ }
22
+ }
@@ -0,0 +1,27 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
5
+ import "../ChainlinkOracle.sol";
6
+ import "../../interfaces/VBep20Interface.sol";
7
+
8
+ contract MockChainlinkOracle is OwnableUpgradeable {
9
+ mapping(address => uint256) public assetPrices;
10
+
11
+ //set price in 6 decimal precision
12
+ constructor() {}
13
+
14
+ function setPrice(address asset, uint256 price) external {
15
+ assetPrices[asset] = price;
16
+ }
17
+
18
+ function initialize() public initializer {
19
+ __Ownable_init();
20
+ }
21
+
22
+ //https://compound.finance/docs/prices
23
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
24
+ address token = VBep20Interface(vToken).underlying();
25
+ return assetPrices[token];
26
+ }
27
+ }
@@ -0,0 +1,32 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
5
+ import "../PythOracle.sol";
6
+ import "../../interfaces/VBep20Interface.sol";
7
+
8
+ contract MockPythOracle is OwnableUpgradeable {
9
+ mapping(address => uint256) public assetPrices;
10
+
11
+ /// @notice the actual pyth oracle address fetch & store the prices
12
+ IPyth public underlyingPythOracle;
13
+
14
+ //set price in 6 decimal precision
15
+ constructor() {}
16
+
17
+ function setPrice(address asset, uint256 price) external {
18
+ assetPrices[asset] = price;
19
+ }
20
+
21
+ function initialize(address underlyingPythOracle_) public initializer {
22
+ __Ownable_init();
23
+ if (underlyingPythOracle_ == address(0)) revert("pyth oracle cannot be zero address");
24
+ underlyingPythOracle = IPyth(underlyingPythOracle_);
25
+ }
26
+
27
+ //https://compound.finance/docs/prices
28
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
29
+ address token = VBep20Interface(vToken).underlying();
30
+ return assetPrices[token];
31
+ }
32
+ }
@@ -0,0 +1,31 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
5
+ import "../../interfaces/VBep20Interface.sol";
6
+
7
+ contract MockTwapOracle is OwnableUpgradeable {
8
+ mapping(address => uint256) public assetPrices;
9
+
10
+ /// @notice vBNB address
11
+ address public vBNB;
12
+
13
+ //set price in 6 decimal precision
14
+ constructor() {}
15
+
16
+ function setPrice(address asset, uint256 price) external {
17
+ assetPrices[asset] = price;
18
+ }
19
+
20
+ function initialize(address vBNB_) public initializer {
21
+ __Ownable_init();
22
+ if (vBNB_ == address(0)) revert("vBNB can't be zero address");
23
+ vBNB = vBNB_;
24
+ }
25
+
26
+ //https://compound.finance/docs/prices
27
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
28
+ address token = VBep20Interface(vToken).underlying();
29
+ return assetPrices[token];
30
+ }
31
+ }
@@ -0,0 +1,6 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+ import "@openzeppelin/contracts/access/AccessControl.sol";
4
+ import "@venusprotocol/governance-contracts/contracts/Governance/AccessControlManager.sol";
5
+
6
+ contract AccessControlManagerScenario is AccessControlManager {}
@@ -0,0 +1,16 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
5
+
6
+ contract BEP20Harness is ERC20 {
7
+ uint8 public decimalsInternal = 18;
8
+
9
+ constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {
10
+ decimalsInternal = decimals_;
11
+ }
12
+
13
+ function decimals() public view virtual override returns (uint8) {
14
+ return decimalsInternal;
15
+ }
16
+ }
@@ -0,0 +1,123 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "../interfaces/PythInterface.sol";
5
+
6
+ contract MockPyth is AbstractPyth {
7
+ mapping(bytes32 => PythStructs.PriceFeed) priceFeeds;
8
+ uint64 sequenceNumber;
9
+
10
+ uint256 singleUpdateFeeInWei;
11
+ uint256 validTimePeriod;
12
+
13
+ constructor(uint256 _validTimePeriod, uint256 _singleUpdateFeeInWei) {
14
+ singleUpdateFeeInWei = _singleUpdateFeeInWei;
15
+ validTimePeriod = _validTimePeriod;
16
+ }
17
+
18
+ // simply update price feeds
19
+ function updatePriceFeedsHarness(PythStructs.PriceFeed[] calldata feeds) external {
20
+ require(feeds.length > 0, "feeds length must > 0");
21
+ for (uint256 i = 0; i < feeds.length; ++i) {
22
+ priceFeeds[feeds[i].id] = feeds[i];
23
+ }
24
+ }
25
+
26
+ // Takes an array of encoded price feeds and stores them.
27
+ // You can create this data either by calling createPriceFeedData or
28
+ // by using web3.js or ethers abi utilities.
29
+ function updatePriceFeeds(bytes[] calldata updateData) public payable override {
30
+ uint256 requiredFee = getUpdateFee(updateData.length);
31
+ require(msg.value >= requiredFee, "Insufficient paid fee amount");
32
+
33
+ if (msg.value > requiredFee) {
34
+ (bool success, ) = payable(msg.sender).call{ value: msg.value - requiredFee }("");
35
+ require(success, "failed to transfer update fee");
36
+ }
37
+
38
+ uint256 freshPrices = 0;
39
+
40
+ // Chain ID is id of the source chain that the price update comes from. Since it is just a mock contract
41
+ // We set it to 1.
42
+ uint16 chainId = 1;
43
+
44
+ for (uint256 i = 0; i < updateData.length; i++) {
45
+ PythStructs.PriceFeed memory priceFeed = abi.decode(updateData[i], (PythStructs.PriceFeed));
46
+
47
+ bool fresh = false;
48
+ uint256 lastPublishTime = priceFeeds[priceFeed.id].price.publishTime;
49
+
50
+ if (lastPublishTime < priceFeed.price.publishTime) {
51
+ // Price information is more recent than the existing price information.
52
+ fresh = true;
53
+ priceFeeds[priceFeed.id] = priceFeed;
54
+ freshPrices += 1;
55
+ }
56
+
57
+ emit PriceFeedUpdate(
58
+ priceFeed.id,
59
+ fresh,
60
+ chainId,
61
+ sequenceNumber,
62
+ priceFeed.price.publishTime,
63
+ lastPublishTime,
64
+ priceFeed.price.price,
65
+ priceFeed.price.conf
66
+ );
67
+ }
68
+
69
+ // In the real contract, the input of this function contains multiple batches that each contain multiple prices.
70
+ // This event is emitted when a batch is processed. In this mock contract we consider
71
+ // there is only one batch of prices.
72
+ // Each batch has (chainId, sequenceNumber) as it's unique identifier. Here chainId
73
+ // is set to 1 and an increasing sequence number is used.
74
+ emit BatchPriceFeedUpdate(chainId, sequenceNumber, updateData.length, freshPrices);
75
+ sequenceNumber += 1;
76
+
77
+ // There is only 1 batch of prices
78
+ emit UpdatePriceFeeds(msg.sender, 1, requiredFee);
79
+ }
80
+
81
+ function queryPriceFeed(bytes32 id) public view override returns (PythStructs.PriceFeed memory priceFeed) {
82
+ require(priceFeeds[id].id != 0, "no price feed found for the given price id");
83
+ return priceFeeds[id];
84
+ }
85
+
86
+ function priceFeedExists(bytes32 id) public view override returns (bool) {
87
+ return (priceFeeds[id].id != 0);
88
+ }
89
+
90
+ function getValidTimePeriod() public view override returns (uint256) {
91
+ return validTimePeriod;
92
+ }
93
+
94
+ function getUpdateFee(uint256 updateDataSize) public view override returns (uint256 feeAmount) {
95
+ return singleUpdateFeeInWei * updateDataSize;
96
+ }
97
+
98
+ function createPriceFeedUpdateData(
99
+ bytes32 id,
100
+ int64 price,
101
+ uint64 conf,
102
+ int32 expo,
103
+ int64 emaPrice,
104
+ uint64 emaConf,
105
+ uint64 publishTime
106
+ ) public pure returns (bytes memory priceFeedData) {
107
+ PythStructs.PriceFeed memory priceFeed;
108
+
109
+ priceFeed.id = id;
110
+
111
+ priceFeed.price.price = price;
112
+ priceFeed.price.conf = conf;
113
+ priceFeed.price.expo = expo;
114
+ priceFeed.price.publishTime = publishTime;
115
+
116
+ priceFeed.emaPrice.price = emaPrice;
117
+ priceFeed.emaPrice.conf = emaConf;
118
+ priceFeed.emaPrice.expo = expo;
119
+ priceFeed.emaPrice.publishTime = publishTime;
120
+
121
+ priceFeedData = abi.encode(priceFeed);
122
+ }
123
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity 0.8.13;
3
+
4
+ import "../interfaces/OracleInterface.sol";
5
+
6
+ contract MockSimpleOracle is OracleInterface {
7
+ mapping(address => uint256) public prices;
8
+
9
+ constructor() {
10
+ //
11
+ }
12
+
13
+ function getUnderlyingPrice(address vToken) external view returns (uint256) {
14
+ return prices[vToken];
15
+ }
16
+
17
+ function setPrice(address vToken, uint256 price) public {
18
+ prices[vToken] = price;
19
+ }
20
+ }
21
+
22
+ contract MockBoundValidator is BoundValidatorInterface {
23
+ mapping(address => bool) public validateResults;
24
+ bool public twapUpdated;
25
+
26
+ constructor() {
27
+ //
28
+ }
29
+
30
+ function validatePriceWithAnchorPrice(
31
+ address vToken,
32
+ uint256 reporterPrice,
33
+ uint256 anchorPrice
34
+ ) external view returns (bool) {
35
+ return validateResults[vToken];
36
+ }
37
+
38
+ function setValidateResult(address vToken, bool pass) public {
39
+ validateResults[vToken] = pass;
40
+ }
41
+ }