@venusprotocol/oracle 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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,23 @@
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 MockBinanceOracle is OwnableUpgradeable {
8
+ mapping(address => uint256) public assetPrices;
9
+
10
+ constructor() {}
11
+
12
+ function initialize() public initializer {
13
+ __Ownable_init();
14
+ }
15
+
16
+ function setPrice(address asset, uint256 price) external {
17
+ assetPrices[asset] = price;
18
+ }
19
+
20
+ function getUnderlyingPrice(address vToken) public view returns (uint256) {
21
+ return assetPrices[vToken];
22
+ }
23
+ }
@@ -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,88 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ pragma solidity ^0.8.0;
3
+
4
+ import "../interfaces/PythInterface.sol";
5
+
6
+ contract MockPyth is IPyth {
7
+ mapping(bytes32 => PythStructs.PriceFeed) public priceFeeds;
8
+
9
+ function queryPriceFeed(bytes32 id) public view returns (PythStructs.PriceFeed memory priceFeed) {
10
+ require(priceFeeds[id].id != 0, "no price feed found for the given price id");
11
+ return priceFeeds[id];
12
+ }
13
+
14
+ // simply update price feeds
15
+ function updatePriceFeedsHarness(PythStructs.PriceFeed[] calldata feeds) external {
16
+ require(feeds.length > 0, "feeds length must > 0");
17
+ for (uint256 i = 0; i < feeds.length; ++i) {
18
+ priceFeeds[feeds[i].id] = feeds[i];
19
+ }
20
+ }
21
+
22
+ // a very simple version get price with timestamp expiration check, just for test
23
+ function getLatestAvailablePriceWithinDuration(bytes32 id, uint64 duration)
24
+ external
25
+ view
26
+ override
27
+ returns (PythStructs.Price memory price)
28
+ {
29
+ PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);
30
+
31
+ price.price = priceFeed.price;
32
+ price.conf = priceFeed.conf;
33
+ price.expo = priceFeed.expo;
34
+ uint64 publishTime = priceFeed.publishTime;
35
+
36
+ require(_diff(block.timestamp, publishTime) <= duration, "No available price within given duration");
37
+
38
+ return price;
39
+ }
40
+
41
+ function _diff(uint256 x, uint256 y) internal pure returns (uint256) {
42
+ if (x > y) {
43
+ return x - y;
44
+ } else {
45
+ return y - x;
46
+ }
47
+ }
48
+
49
+ // not implemented
50
+ function updatePriceFeedsIfNecessary(
51
+ bytes[] memory updateData,
52
+ bytes32[] memory priceIds,
53
+ uint64[] memory publishTimes
54
+ ) external payable {
55
+ updateData;
56
+ priceIds;
57
+ publishTimes;
58
+ }
59
+
60
+ function getUpdateFee(uint256 updateDataSize) external pure override returns (uint256 feeAmount) {
61
+ updateDataSize;
62
+ return 0;
63
+ }
64
+
65
+ function updatePriceFeeds(bytes[] memory updateData) external payable {
66
+ updateData;
67
+ }
68
+
69
+ function getCurrentPrice(bytes32 id) external pure override returns (PythStructs.Price memory price) {
70
+ id;
71
+ return PythStructs.Price({ price: 0, conf: 0, expo: 0 });
72
+ }
73
+
74
+ function getEmaPrice(bytes32 id) external pure override returns (PythStructs.Price memory price) {
75
+ id;
76
+ return PythStructs.Price({ price: 0, conf: 0, expo: 0 });
77
+ }
78
+
79
+ function getLatestAvailablePriceUnsafe(bytes32 id)
80
+ external
81
+ pure
82
+ override
83
+ returns (PythStructs.Price memory price, uint64 publishTime)
84
+ {
85
+ id;
86
+ return (PythStructs.Price({ price: 0, conf: 0, expo: 0 }), 0);
87
+ }
88
+ }
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
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 setPrice(address vToken, uint256 price) public {
14
+ prices[vToken] = price;
15
+ }
16
+
17
+ function getUnderlyingPrice(address vToken) external view returns (uint256) {
18
+ return prices[vToken];
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 setValidateResult(address vToken, bool pass) public {
31
+ validateResults[vToken] = pass;
32
+ }
33
+
34
+ function validatePriceWithAnchorPrice(
35
+ address vToken,
36
+ uint256 reporterPrice,
37
+ uint256 anchorPrice
38
+ ) external view returns (bool) {
39
+ return validateResults[vToken];
40
+ }
41
+ }
@@ -0,0 +1,91 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ import "../interfaces/AggregatorV2V3Interface.sol";
5
+
6
+ /**
7
+ * @title MockV3Aggregator
8
+ * @notice Based on the FluxAggregator contract
9
+ * @notice Use this contract when you need to test
10
+ * other contract's ability to read data from an
11
+ * aggregator contract, but how the aggregator got
12
+ * its answer is unimportant
13
+ */
14
+ contract MockV3Aggregator is AggregatorV2V3Interface {
15
+ uint256 public constant version = 0;
16
+
17
+ uint8 public decimals;
18
+ int256 public latestAnswer;
19
+ uint256 public latestTimestamp;
20
+ uint256 public latestRound;
21
+
22
+ mapping(uint256 => int256) public getAnswer;
23
+ mapping(uint256 => uint256) public getTimestamp;
24
+ mapping(uint256 => uint256) private getStartedAt;
25
+
26
+ constructor(uint8 _decimals, int256 _initialAnswer) {
27
+ decimals = _decimals;
28
+ updateAnswer(_initialAnswer);
29
+ }
30
+
31
+ function updateAnswer(int256 _answer) public {
32
+ latestAnswer = _answer;
33
+ latestTimestamp = block.timestamp;
34
+ latestRound++;
35
+ getAnswer[latestRound] = _answer;
36
+ getTimestamp[latestRound] = block.timestamp;
37
+ getStartedAt[latestRound] = block.timestamp;
38
+ }
39
+
40
+ function updateRoundData(
41
+ uint80 _roundId,
42
+ int256 _answer,
43
+ uint256 _timestamp,
44
+ uint256 _startedAt
45
+ ) public {
46
+ latestRound = _roundId;
47
+ latestAnswer = _answer;
48
+ latestTimestamp = _timestamp;
49
+ getAnswer[latestRound] = _answer;
50
+ getTimestamp[latestRound] = _timestamp;
51
+ getStartedAt[latestRound] = _startedAt;
52
+ }
53
+
54
+ function getRoundData(uint80 _roundId)
55
+ external
56
+ view
57
+ returns (
58
+ uint80 roundId,
59
+ int256 answer,
60
+ uint256 startedAt,
61
+ uint256 updatedAt,
62
+ uint80 answeredInRound
63
+ )
64
+ {
65
+ return (_roundId, getAnswer[_roundId], getStartedAt[_roundId], getTimestamp[_roundId], _roundId);
66
+ }
67
+
68
+ function latestRoundData()
69
+ external
70
+ view
71
+ returns (
72
+ uint80 roundId,
73
+ int256 answer,
74
+ uint256 startedAt,
75
+ uint256 updatedAt,
76
+ uint80 answeredInRound
77
+ )
78
+ {
79
+ return (
80
+ uint80(latestRound),
81
+ getAnswer[latestRound],
82
+ getStartedAt[latestRound],
83
+ getTimestamp[latestRound],
84
+ uint80(latestRound)
85
+ );
86
+ }
87
+
88
+ function description() external pure returns (string memory) {
89
+ return "v0.6/tests/MockV3Aggregator.sol";
90
+ }
91
+ }