@venusprotocol/oracle 1.2.2 → 1.3.0

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 (69) hide show
  1. package/artifacts/build-info/442613ba0e31d357bb61ad07d3e9ccb5.json +1 -0
  2. package/artifacts/build-info/e79aa95060bbee82bc36063535db4019.json +1 -0
  3. package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.dbg.json +4 -0
  4. package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.json +545 -0
  5. package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.dbg.json +1 -1
  6. package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.json +130 -15
  7. package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.dbg.json +1 -1
  8. package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.json +2 -2
  9. package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.dbg.json +1 -1
  10. package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.json +2 -2
  11. package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.dbg.json +1 -1
  12. package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.json +22 -3
  13. package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.dbg.json +1 -1
  14. package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.json +2 -2
  15. package/artifacts/contracts/test/MockPyth.sol/MockPyth.dbg.json +1 -1
  16. package/artifacts/contracts/test/MockPyth.sol/MockPyth.json +305 -212
  17. package/contracts/PriceOracle.sol +16 -0
  18. package/contracts/ResilientOracle.sol +282 -0
  19. package/contracts/interfaces/AggregatorV2V3Interface.sol +60 -0
  20. package/contracts/interfaces/BEP20Interface.sol +97 -0
  21. package/contracts/interfaces/FeedRegistryInterface.sol +17 -0
  22. package/contracts/interfaces/OracleInterface.sol +23 -0
  23. package/contracts/interfaces/PythInterface.sol +252 -0
  24. package/contracts/interfaces/VBep20Interface.sol +11 -0
  25. package/contracts/libraries/PancakeLibrary.sol +81 -0
  26. package/contracts/oracles/BinanceOracle.sol +30 -0
  27. package/contracts/oracles/BoundValidator.sol +97 -0
  28. package/contracts/oracles/ChainlinkOracle.sol +172 -0
  29. package/contracts/oracles/PythOracle.sol +129 -0
  30. package/contracts/oracles/TwapOracle.sol +235 -0
  31. package/contracts/oracles/mocks/MockBinanceFeedRegistry.sol +32 -0
  32. package/contracts/oracles/mocks/MockBinanceOracle.sol +27 -0
  33. package/contracts/oracles/mocks/MockChainlinkOracle.sol +26 -0
  34. package/contracts/oracles/mocks/MockPythOracle.sol +31 -0
  35. package/contracts/oracles/mocks/MockTwapOracle.sol +30 -0
  36. package/contracts/test/BEP20Harness.sol +21 -0
  37. package/contracts/test/MockPyth.sol +123 -0
  38. package/contracts/test/MockSimpleOracle.sol +41 -0
  39. package/contracts/test/MockV3Aggregator.sol +91 -0
  40. package/contracts/test/PancakePairHarness.sol +103 -0
  41. package/contracts/test/VBEP20Harness.sol +21 -0
  42. package/deploy/oracles.d.ts +1 -0
  43. package/deploy/oracles.d.ts.map +1 -1
  44. package/deploy/oracles.js +16 -1
  45. package/deploy/oracles.js.map +1 -1
  46. package/deployments/localhost/.chainId +1 -0
  47. package/deployments/localhost/BinanceOracle.json +393 -0
  48. package/deployments/localhost/BinanceOracle_Implementation.json +305 -0
  49. package/deployments/localhost/BinanceOracle_Proxy.json +241 -0
  50. package/deployments/localhost/BoundValidator.json +457 -0
  51. package/deployments/localhost/BoundValidator_Implementation.json +428 -0
  52. package/deployments/localhost/BoundValidator_Proxy.json +237 -0
  53. package/deployments/localhost/ChainlinkOracle.json +370 -0
  54. package/deployments/localhost/ChainlinkOracle_Implementation.json +273 -0
  55. package/deployments/localhost/ChainlinkOracle_Proxy.json +237 -0
  56. package/deployments/localhost/DefaultProxyAdmin.json +257 -0
  57. package/deployments/localhost/PivotTwapOracle.json +393 -0
  58. package/deployments/localhost/PivotTwapOracle_Implementation.json +304 -0
  59. package/deployments/localhost/PivotTwapOracle_Proxy.json +241 -0
  60. package/deployments/localhost/PythOracle.json +393 -0
  61. package/deployments/localhost/PythOracle_Implementation.json +309 -0
  62. package/deployments/localhost/PythOracle_Proxy.json +241 -0
  63. package/deployments/localhost/ResilientOracle.json +700 -0
  64. package/deployments/localhost/ResilientOracle_Implementation.json +746 -0
  65. package/deployments/localhost/ResilientOracle_Proxy.json +241 -0
  66. package/deployments/localhost/solcInputs/0e89febeebc7444140de8e67c9067d2c.json +78 -0
  67. package/deployments/localhost/solcInputs/468ec7a31e2db8855c82fb8141193271.json +54 -0
  68. package/deployments/localhost/solcInputs/50629170e50dc9fec79dac585e95ac05.json +138 -0
  69. package/package.json +3 -2
@@ -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.getPriceNoOlderThan(
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
+ }
@@ -0,0 +1,235 @@
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 "../libraries/PancakeLibrary.sol";
7
+ import "../interfaces/OracleInterface.sol";
8
+ import "../interfaces/BEP20Interface.sol";
9
+ import "../interfaces/VBep20Interface.sol";
10
+
11
+ struct Observation {
12
+ uint256 timestamp;
13
+ uint256 acc;
14
+ }
15
+
16
+ struct TokenConfig {
17
+ /// @notice asset address, which can't be zero address and can be used for existance check
18
+ address asset;
19
+ /// @notice Decimals of underlying asset
20
+ uint256 baseUnit;
21
+ /// @notice The address of pancake pair
22
+ address pancakePool;
23
+ /// @notice Whether the token is paired with WBNB
24
+ bool isBnbBased;
25
+ /// @notice A flag identifies whether the pancake pair is reversed
26
+ /// e.g. XVS-WBNB is not reversed, while WBNB-XVS is.
27
+ bool isReversedPool;
28
+ /// @notice TWAP update period in second, which is the minimum time in seconds required to update TWAP window
29
+ uint256 anchorPeriod;
30
+ }
31
+
32
+ contract TwapOracle is OwnableUpgradeable, TwapInterface {
33
+ using FixedPoint for *;
34
+
35
+ /// @notice WBNB address
36
+ address public WBNB;
37
+
38
+ /// @notice the base unit of WBNB and BUSD, which are the paired tokens for all assets
39
+ uint256 public constant bnbBaseUnit = 1e18;
40
+ uint256 public constant busdBaseUnit = 1e18;
41
+
42
+ uint256 public constant expScale = 1e18;
43
+
44
+ /// @notice Configs by token
45
+ mapping(address => TokenConfig) public tokenConfigs;
46
+
47
+ /// @notice The current price observation of TWAP. With old and current observations
48
+ /// we can calculate the TWAP between this range
49
+ mapping(address => Observation) public newObservations;
50
+
51
+ /// @notice The old price observation of TWAP
52
+ mapping(address => Observation) public oldObservations;
53
+
54
+ /// @notice Stored price by token
55
+ mapping(address => uint256) public prices;
56
+
57
+ /// @notice Emit this event when TWAP window is updated
58
+ event TwapWindowUpdated(
59
+ address indexed asset,
60
+ uint256 oldTimestamp,
61
+ uint256 oldAcc,
62
+ uint256 newTimestamp,
63
+ uint256 newAcc
64
+ );
65
+
66
+ /// @notice Emit this event when TWAP price is updated
67
+ event AnchorPriceUpdated(address indexed asset, uint256 price, uint256 oldTimestamp, uint256 newTimestamp);
68
+
69
+ /// @notice Emit this event when new token configs are added
70
+ event TokenConfigAdded(address indexed asset, address indexed pancakePool, uint256 indexed anchorPeriod);
71
+
72
+ modifier notNullAddress(address someone) {
73
+ require(someone != address(0), "can't be zero address");
74
+ _;
75
+ }
76
+
77
+ function initialize(address WBNB_) public initializer {
78
+ __Ownable_init();
79
+ require(WBNB_ != address(0), "WBNB can't be zero address");
80
+ WBNB = WBNB_;
81
+ }
82
+
83
+ /**
84
+ * @notice Add multiple token configs at the same time
85
+ * @param configs config array
86
+ */
87
+ function setTokenConfigs(TokenConfig[] memory configs) external onlyOwner {
88
+ require(configs.length > 0, "length can't be 0");
89
+ for (uint8 i = 0; i < configs.length; i++) {
90
+ setTokenConfig(configs[i]);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * @notice Add single token configs
96
+ * @param config token config struct
97
+ */
98
+ function setTokenConfig(TokenConfig memory config)
99
+ public
100
+ onlyOwner
101
+ notNullAddress(config.asset)
102
+ notNullAddress(config.pancakePool)
103
+ {
104
+ require(config.anchorPeriod > 0, "anchor period must be positive");
105
+ require(config.baseUnit > 0, "base unit must be positive");
106
+ uint256 cumulativePrice = currentCumulativePrice(config);
107
+
108
+ // Initialize observation data
109
+ oldObservations[config.asset].timestamp = block.timestamp;
110
+ newObservations[config.asset].timestamp = block.timestamp;
111
+ oldObservations[config.asset].acc = cumulativePrice;
112
+ newObservations[config.asset].acc = cumulativePrice;
113
+ tokenConfigs[config.asset] = config;
114
+ emit TokenConfigAdded(config.asset, config.pancakePool, config.anchorPeriod);
115
+ }
116
+
117
+ /**
118
+ * @notice Get the underlying TWAP price of input vToken
119
+ * @param vToken vToken address
120
+ * @return price in USD, with 18 decimals
121
+ */
122
+ function getUnderlyingPrice(address vToken) external view override returns (uint256) {
123
+ address asset = VBep20Interface(vToken).underlying();
124
+ require(tokenConfigs[asset].asset != address(0), "asset not exist");
125
+
126
+ uint256 price = prices[asset];
127
+
128
+ // if price is 0, it means the price hasn't been updated yet and it's meaningless, revert
129
+ require(price > 0, "TWAP price must be positive");
130
+
131
+ BEP20Interface underlyingToken = BEP20Interface(VBep20Interface(vToken).underlying());
132
+ return (price * (10**(18 - underlyingToken.decimals())));
133
+ }
134
+
135
+ /**
136
+ * @notice Fetches the current token/WBNB and token/BUSD price accumulator from pancakeswap.
137
+ * @return cumulative price of target token regardless of pair order
138
+ */
139
+ function currentCumulativePrice(TokenConfig memory config) public view returns (uint256) {
140
+ (uint256 price0, uint256 price1, ) = PancakeOracleLibrary.currentCumulativePrices(config.pancakePool);
141
+ if (config.isReversedPool) {
142
+ return price1;
143
+ } else {
144
+ return price0;
145
+ }
146
+ }
147
+
148
+ function updateTwap(address vToken) public returns (uint256) {
149
+ address asset = VBep20Interface(vToken).underlying();
150
+ require(tokenConfigs[asset].asset != address(0), "asset not exist");
151
+ // Update & fetch WBNB price first, so we can calculate the price of WBNB paired token
152
+ if (asset != WBNB && tokenConfigs[asset].isBnbBased) {
153
+ require(tokenConfigs[WBNB].asset != address(0), "WBNB not exist");
154
+ _updateTwapInternal(tokenConfigs[WBNB]);
155
+ }
156
+ return _updateTwapInternal(tokenConfigs[asset]);
157
+ }
158
+
159
+ /**
160
+ * @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.
161
+ * @return price in USD, with 18 decimals
162
+ */
163
+ function _updateTwapInternal(TokenConfig memory config) internal virtual returns (uint256) {
164
+ // pokeWindowValues already handled reversed pool cases,
165
+ // priceAverage will always be Token/BNB or Token/BUSD TWAP price.
166
+ (uint256 nowCumulativePrice, uint256 oldCumulativePrice, uint256 oldTimestamp) = pokeWindowValues(config);
167
+
168
+ // This should be impossible, but better safe than sorry
169
+ require(block.timestamp > oldTimestamp, "now must come after before");
170
+ uint256 timeElapsed = block.timestamp - oldTimestamp;
171
+
172
+ // Calculate Pancakge TWAP
173
+ FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(
174
+ uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)
175
+ );
176
+ // TWAP price with 1e18 decimal mantissa
177
+ uint256 priceAverageMantissa = priceAverage.decode112with18();
178
+
179
+ // To cancel the decimals in cumulative price, we need to mulitply the average price with
180
+ // tokenBaseUnit / (wbnbBaseUnit or busdBaseUnit, which is 1e18)
181
+ uint256 pairedTokenBaseUnit = config.isBnbBased ? bnbBaseUnit : busdBaseUnit;
182
+ uint256 anchorPriceMantissa = (priceAverageMantissa * config.baseUnit) / pairedTokenBaseUnit;
183
+
184
+ // if this token is paired with BNB, convert its price to USD
185
+ if (config.isBnbBased) {
186
+ uint256 bnbPrice = prices[WBNB];
187
+ require(bnbPrice != 0, "bnb price is invalid");
188
+ anchorPriceMantissa = (anchorPriceMantissa * bnbPrice) / bnbBaseUnit;
189
+ }
190
+
191
+ require(anchorPriceMantissa != 0, "twap price cannot be 0");
192
+
193
+ emit AnchorPriceUpdated(config.asset, anchorPriceMantissa, oldTimestamp, block.timestamp);
194
+
195
+ // save anchor price, which is 1e18 decimals
196
+ prices[config.asset] = anchorPriceMantissa;
197
+
198
+ return anchorPriceMantissa;
199
+ }
200
+
201
+ /**
202
+ * @notice Update new and old observations of lagging window if period elapsed.
203
+ * @return cumulative price & old observation
204
+ */
205
+ function pokeWindowValues(TokenConfig memory config)
206
+ internal
207
+ returns (
208
+ uint256,
209
+ uint256,
210
+ uint256
211
+ )
212
+ {
213
+ uint256 cumulativePrice = currentCumulativePrice(config);
214
+
215
+ Observation memory newObservation = newObservations[config.asset];
216
+
217
+ // Update new and old observations if elapsed time is greater than or equal to anchor period
218
+ uint256 timeElapsed = block.timestamp - newObservation.timestamp;
219
+ if (timeElapsed >= config.anchorPeriod) {
220
+ oldObservations[config.asset].timestamp = newObservation.timestamp;
221
+ oldObservations[config.asset].acc = newObservation.acc;
222
+
223
+ newObservations[config.asset].timestamp = block.timestamp;
224
+ newObservations[config.asset].acc = cumulativePrice;
225
+ emit TwapWindowUpdated(
226
+ config.asset,
227
+ newObservation.timestamp,
228
+ block.timestamp,
229
+ newObservation.acc,
230
+ cumulativePrice
231
+ );
232
+ }
233
+ return (cumulativePrice, oldObservations[config.asset].acc, oldObservations[config.asset].timestamp);
234
+ }
235
+ }
@@ -0,0 +1,32 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.10;
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(string memory base, string memory quote)
14
+ external
15
+ view
16
+ override
17
+ returns (
18
+ uint80 roundId,
19
+ int256 answer,
20
+ uint256 startedAt,
21
+ uint256 updatedAt,
22
+ uint80 answeredInRound
23
+ )
24
+ {
25
+ quote;
26
+ return (0, int256(assetPrices[base]), 0, 0, 0);
27
+ }
28
+
29
+ function decimalsByName(string memory base, string memory quote) external view override returns (uint8) {
30
+ return 8;
31
+ }
32
+ }
@@ -0,0 +1,27 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity ^0.8.10;
3
+
4
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
5
+ import "../../interfaces/VBep20Interface.sol";
6
+ import "../../interfaces/FeedRegistryInterface.sol";
7
+
8
+ contract MockBinanceOracle is OwnableUpgradeable {
9
+ mapping(address => uint256) public assetPrices;
10
+
11
+ FeedRegistryInterface public feedRegistry;
12
+
13
+ constructor() {}
14
+
15
+ function initialize(FeedRegistryInterface feed) public initializer {
16
+ __Ownable_init();
17
+ feedRegistry = feed;
18
+ }
19
+
20
+ function setPrice(address asset, uint256 price) external {
21
+ assetPrices[asset] = price;
22
+ }
23
+
24
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
25
+ return assetPrices[vToken];
26
+ }
27
+ }
@@ -0,0 +1,26 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity ^0.8.10;
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 initialize() public initializer {
15
+ __Ownable_init();
16
+ }
17
+
18
+ function setPrice(address asset, uint256 price) external {
19
+ assetPrices[asset] = price;
20
+ }
21
+
22
+ //https://compound.finance/docs/prices
23
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
24
+ return assetPrices[vToken];
25
+ }
26
+ }
@@ -0,0 +1,31 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity ^0.8.10;
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 initialize(address underlyingPythOracle_) public initializer {
18
+ __Ownable_init();
19
+ require(underlyingPythOracle_ != address(0), "pyth oracle cannot be zero address");
20
+ underlyingPythOracle = IPyth(underlyingPythOracle_);
21
+ }
22
+
23
+ function setPrice(address asset, uint256 price) external {
24
+ assetPrices[asset] = price;
25
+ }
26
+
27
+ //https://compound.finance/docs/prices
28
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
29
+ return assetPrices[vToken];
30
+ }
31
+ }
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: BSD-3-Clause
2
+ pragma solidity ^0.8.10;
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 initialize(address vBNB_) public initializer {
17
+ __Ownable_init();
18
+ require(vBNB_ != address(0), "vBNB can't be zero address");
19
+ vBNB = vBNB_;
20
+ }
21
+
22
+ function setPrice(address asset, uint256 price) external {
23
+ assetPrices[asset] = price;
24
+ }
25
+
26
+ //https://compound.finance/docs/prices
27
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
28
+ return assetPrices[vToken];
29
+ }
30
+ }
@@ -0,0 +1,21 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+ pragma experimental ABIEncoderV2;
4
+
5
+ import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
6
+
7
+ contract BEP20Harness is ERC20 {
8
+ uint8 public decimalsInternal = 18;
9
+
10
+ constructor(
11
+ string memory name_,
12
+ string memory symbol_,
13
+ uint8 decimals_
14
+ ) ERC20(name_, symbol_) {
15
+ decimalsInternal = decimals_;
16
+ }
17
+
18
+ function decimals() public view virtual override returns (uint8) {
19
+ return decimalsInternal;
20
+ }
21
+ }
@@ -0,0 +1,123 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ pragma solidity ^0.8.0;
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
+ function queryPriceFeed(bytes32 id) public view override returns (PythStructs.PriceFeed memory priceFeed) {
19
+ require(priceFeeds[id].id != 0, "no price feed found for the given price id");
20
+ return priceFeeds[id];
21
+ }
22
+
23
+ // simply update price feeds
24
+ function updatePriceFeedsHarness(PythStructs.PriceFeed[] calldata feeds) external {
25
+ require(feeds.length > 0, "feeds length must > 0");
26
+ for (uint256 i = 0; i < feeds.length; ++i) {
27
+ priceFeeds[feeds[i].id] = feeds[i];
28
+ }
29
+ }
30
+
31
+ function priceFeedExists(bytes32 id) public view override returns (bool) {
32
+ return (priceFeeds[id].id != 0);
33
+ }
34
+
35
+ function getValidTimePeriod() public view override returns (uint256) {
36
+ return validTimePeriod;
37
+ }
38
+
39
+ // Takes an array of encoded price feeds and stores them.
40
+ // You can create this data either by calling createPriceFeedData or
41
+ // by using web3.js or ethers abi utilities.
42
+ function updatePriceFeeds(bytes[] calldata updateData) public payable override {
43
+ uint256 requiredFee = getUpdateFee(updateData.length);
44
+ require(msg.value >= requiredFee, "Insufficient paid fee amount");
45
+
46
+ if (msg.value > requiredFee) {
47
+ (bool success, ) = payable(msg.sender).call{ value: msg.value - requiredFee }("");
48
+ require(success, "failed to transfer update fee");
49
+ }
50
+
51
+ uint256 freshPrices = 0;
52
+
53
+ // Chain ID is id of the source chain that the price update comes from. Since it is just a mock contract
54
+ // We set it to 1.
55
+ uint16 chainId = 1;
56
+
57
+ for (uint256 i = 0; i < updateData.length; i++) {
58
+ PythStructs.PriceFeed memory priceFeed = abi.decode(updateData[i], (PythStructs.PriceFeed));
59
+
60
+ bool fresh = false;
61
+ uint256 lastPublishTime = priceFeeds[priceFeed.id].price.publishTime;
62
+
63
+ if (lastPublishTime < priceFeed.price.publishTime) {
64
+ // Price information is more recent than the existing price information.
65
+ fresh = true;
66
+ priceFeeds[priceFeed.id] = priceFeed;
67
+ freshPrices += 1;
68
+ }
69
+
70
+ emit PriceFeedUpdate(
71
+ priceFeed.id,
72
+ fresh,
73
+ chainId,
74
+ sequenceNumber,
75
+ priceFeed.price.publishTime,
76
+ lastPublishTime,
77
+ priceFeed.price.price,
78
+ priceFeed.price.conf
79
+ );
80
+ }
81
+
82
+ // In the real contract, the input of this function contains multiple batches that each contain multiple prices.
83
+ // This event is emitted when a batch is processed. In this mock contract we consider
84
+ // there is only one batch of prices.
85
+ // Each batch has (chainId, sequenceNumber) as it's unique identifier. Here chainId
86
+ // is set to 1 and an increasing sequence number is used.
87
+ emit BatchPriceFeedUpdate(chainId, sequenceNumber, updateData.length, freshPrices);
88
+ sequenceNumber += 1;
89
+
90
+ // There is only 1 batch of prices
91
+ emit UpdatePriceFeeds(msg.sender, 1, requiredFee);
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
+ }