@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.
- package/artifacts/build-info/442613ba0e31d357bb61ad07d3e9ccb5.json +1 -0
- package/artifacts/build-info/e79aa95060bbee82bc36063535db4019.json +1 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.dbg.json +4 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.json +545 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.json +130 -15
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.json +2 -2
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.json +2 -2
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.json +22 -3
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.json +2 -2
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.dbg.json +1 -1
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.json +305 -212
- package/contracts/PriceOracle.sol +16 -0
- package/contracts/ResilientOracle.sol +282 -0
- package/contracts/interfaces/AggregatorV2V3Interface.sol +60 -0
- package/contracts/interfaces/BEP20Interface.sol +97 -0
- package/contracts/interfaces/FeedRegistryInterface.sol +17 -0
- package/contracts/interfaces/OracleInterface.sol +23 -0
- package/contracts/interfaces/PythInterface.sol +252 -0
- package/contracts/interfaces/VBep20Interface.sol +11 -0
- package/contracts/libraries/PancakeLibrary.sol +81 -0
- package/contracts/oracles/BinanceOracle.sol +30 -0
- package/contracts/oracles/BoundValidator.sol +97 -0
- package/contracts/oracles/ChainlinkOracle.sol +172 -0
- package/contracts/oracles/PythOracle.sol +129 -0
- package/contracts/oracles/TwapOracle.sol +235 -0
- package/contracts/oracles/mocks/MockBinanceFeedRegistry.sol +32 -0
- package/contracts/oracles/mocks/MockBinanceOracle.sol +27 -0
- package/contracts/oracles/mocks/MockChainlinkOracle.sol +26 -0
- package/contracts/oracles/mocks/MockPythOracle.sol +31 -0
- package/contracts/oracles/mocks/MockTwapOracle.sol +30 -0
- package/contracts/test/BEP20Harness.sol +21 -0
- package/contracts/test/MockPyth.sol +123 -0
- package/contracts/test/MockSimpleOracle.sol +41 -0
- package/contracts/test/MockV3Aggregator.sol +91 -0
- package/contracts/test/PancakePairHarness.sol +103 -0
- package/contracts/test/VBEP20Harness.sol +21 -0
- package/deploy/oracles.d.ts +1 -0
- package/deploy/oracles.d.ts.map +1 -1
- package/deploy/oracles.js +16 -1
- package/deploy/oracles.js.map +1 -1
- package/deployments/localhost/.chainId +1 -0
- package/deployments/localhost/BinanceOracle.json +393 -0
- package/deployments/localhost/BinanceOracle_Implementation.json +305 -0
- package/deployments/localhost/BinanceOracle_Proxy.json +241 -0
- package/deployments/localhost/BoundValidator.json +457 -0
- package/deployments/localhost/BoundValidator_Implementation.json +428 -0
- package/deployments/localhost/BoundValidator_Proxy.json +237 -0
- package/deployments/localhost/ChainlinkOracle.json +370 -0
- package/deployments/localhost/ChainlinkOracle_Implementation.json +273 -0
- package/deployments/localhost/ChainlinkOracle_Proxy.json +237 -0
- package/deployments/localhost/DefaultProxyAdmin.json +257 -0
- package/deployments/localhost/PivotTwapOracle.json +393 -0
- package/deployments/localhost/PivotTwapOracle_Implementation.json +304 -0
- package/deployments/localhost/PivotTwapOracle_Proxy.json +241 -0
- package/deployments/localhost/PythOracle.json +393 -0
- package/deployments/localhost/PythOracle_Implementation.json +309 -0
- package/deployments/localhost/PythOracle_Proxy.json +241 -0
- package/deployments/localhost/ResilientOracle.json +700 -0
- package/deployments/localhost/ResilientOracle_Implementation.json +746 -0
- package/deployments/localhost/ResilientOracle_Proxy.json +241 -0
- package/deployments/localhost/solcInputs/0e89febeebc7444140de8e67c9067d2c.json +78 -0
- package/deployments/localhost/solcInputs/468ec7a31e2db8855c82fb8141193271.json +54 -0
- package/deployments/localhost/solcInputs/50629170e50dc9fec79dac585e95ac05.json +138 -0
- package/package.json +3 -2
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
pragma solidity ^0.8.0;
|
|
3
|
+
|
|
4
|
+
contract PythStructs {
|
|
5
|
+
// A price with a degree of uncertainty, represented as a price +- a confidence interval.
|
|
6
|
+
//
|
|
7
|
+
// The confidence interval roughly corresponds to the standard error of a normal distribution.
|
|
8
|
+
// Both the price and confidence are stored in a fixed-point numeric representation,
|
|
9
|
+
// `x * (10^expo)`, where `expo` is the exponent.
|
|
10
|
+
//
|
|
11
|
+
// Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how
|
|
12
|
+
// to how this price safely.
|
|
13
|
+
struct Price {
|
|
14
|
+
// Price
|
|
15
|
+
int64 price;
|
|
16
|
+
// Confidence interval around the price
|
|
17
|
+
uint64 conf;
|
|
18
|
+
// Price exponent
|
|
19
|
+
int32 expo;
|
|
20
|
+
// Unix timestamp describing when the price was published
|
|
21
|
+
uint256 publishTime;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// PriceFeed represents a current aggregate price from pyth publisher feeds.
|
|
25
|
+
struct PriceFeed {
|
|
26
|
+
// The price ID.
|
|
27
|
+
bytes32 id;
|
|
28
|
+
// Latest available price
|
|
29
|
+
Price price;
|
|
30
|
+
// Latest available exponentially-weighted moving average price
|
|
31
|
+
Price emaPrice;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// @title Consume prices from the Pyth Network (https://pyth.network/).
|
|
36
|
+
/// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices
|
|
37
|
+
/// for how to consume prices safely.
|
|
38
|
+
/// @author Pyth Data Association
|
|
39
|
+
interface IPyth {
|
|
40
|
+
/// @dev Emitted when an update for price feed with `id` is processed successfully.
|
|
41
|
+
/// @param id The Pyth Price Feed ID.
|
|
42
|
+
/// @param fresh True if the price update is more recent and stored.
|
|
43
|
+
/// @param chainId ID of the source chain that the batch price update containing this price.
|
|
44
|
+
/// This value comes from Wormhole, and you can find the corresponding chains
|
|
45
|
+
/// at https://docs.wormholenetwork.com/wormhole/contracts.
|
|
46
|
+
/// @param sequenceNumber Sequence number of the batch price update containing this price.
|
|
47
|
+
/// @param lastPublishTime Publish time of the previously stored price.
|
|
48
|
+
/// @param publishTime Publish time of the given price update.
|
|
49
|
+
/// @param price Price of the given price update.
|
|
50
|
+
/// @param conf Confidence interval of the given price update.
|
|
51
|
+
event PriceFeedUpdate(
|
|
52
|
+
bytes32 indexed id,
|
|
53
|
+
bool indexed fresh,
|
|
54
|
+
uint16 chainId,
|
|
55
|
+
uint64 sequenceNumber,
|
|
56
|
+
uint256 lastPublishTime,
|
|
57
|
+
uint256 publishTime,
|
|
58
|
+
int64 price,
|
|
59
|
+
uint64 conf
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
/// @dev Emitted when a batch price update is processed successfully.
|
|
63
|
+
/// @param chainId ID of the source chain that the batch price update comes from.
|
|
64
|
+
/// @param sequenceNumber Sequence number of the batch price update.
|
|
65
|
+
/// @param batchSize Number of prices within the batch price update.
|
|
66
|
+
/// @param freshPricesInBatch Number of prices that were more recent and were stored.
|
|
67
|
+
event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber, uint256 batchSize, uint256 freshPricesInBatch);
|
|
68
|
+
|
|
69
|
+
/// @dev Emitted when a call to `updatePriceFeeds` is processed successfully.
|
|
70
|
+
/// @param sender Sender of the call (`msg.sender`).
|
|
71
|
+
/// @param batchCount Number of batches that this function processed.
|
|
72
|
+
/// @param fee Amount of paid fee for updating the prices.
|
|
73
|
+
event UpdatePriceFeeds(address indexed sender, uint256 batchCount, uint256 fee);
|
|
74
|
+
|
|
75
|
+
/// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time
|
|
76
|
+
function getValidTimePeriod() external view returns (uint256 validTimePeriod);
|
|
77
|
+
|
|
78
|
+
/// @notice Returns the price and confidence interval.
|
|
79
|
+
/// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.
|
|
80
|
+
/// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.
|
|
81
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
82
|
+
function getPrice(bytes32 id) external view returns (PythStructs.Price memory price);
|
|
83
|
+
|
|
84
|
+
/// @notice Returns the exponentially-weighted moving average price and confidence interval.
|
|
85
|
+
/// @dev Reverts if the EMA price is not available.
|
|
86
|
+
/// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.
|
|
87
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
88
|
+
function getEmaPrice(bytes32 id) external view returns (PythStructs.Price memory price);
|
|
89
|
+
|
|
90
|
+
/// @notice Returns the price of a price feed without any sanity checks.
|
|
91
|
+
/// @dev This function returns the most recent price update in this contract without any recency checks.
|
|
92
|
+
/// This function is unsafe as the returned price update may be arbitrarily far in the past.
|
|
93
|
+
///
|
|
94
|
+
/// Users of this function should check the `publishTime` in the price to ensure that the returned price is
|
|
95
|
+
/// sufficiently recent for their application. If you are considering using this function, it may be
|
|
96
|
+
/// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.
|
|
97
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
98
|
+
function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
|
|
99
|
+
|
|
100
|
+
/// @notice Returns the price that is no older than `age` seconds of the current time.
|
|
101
|
+
/// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in
|
|
102
|
+
/// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
|
|
103
|
+
/// recently.
|
|
104
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
105
|
+
function getPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);
|
|
106
|
+
|
|
107
|
+
/// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.
|
|
108
|
+
/// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.
|
|
109
|
+
/// However, if the price is not recent this function returns the latest available price.
|
|
110
|
+
///
|
|
111
|
+
/// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
|
|
112
|
+
/// the returned price is recent or useful for any particular application.
|
|
113
|
+
///
|
|
114
|
+
/// Users of this function should check the `publishTime` in the price to ensure that the returned price is
|
|
115
|
+
/// sufficiently recent for their application. If you are considering using this function, it may be
|
|
116
|
+
/// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.
|
|
117
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
118
|
+
function getEmaPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);
|
|
119
|
+
|
|
120
|
+
/// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds
|
|
121
|
+
/// of the current time.
|
|
122
|
+
/// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in
|
|
123
|
+
/// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
|
|
124
|
+
/// recently.
|
|
125
|
+
/// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
|
|
126
|
+
function getEmaPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);
|
|
127
|
+
|
|
128
|
+
/// @notice Update price feeds with given update messages.
|
|
129
|
+
/// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
|
|
130
|
+
/// `getUpdateFee` with the length of the `updateData` array.
|
|
131
|
+
/// Prices will be updated if they are more recent than the current stored prices.
|
|
132
|
+
/// The call will succeed even if the update is not the most recent.
|
|
133
|
+
/// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
|
|
134
|
+
/// @param updateData Array of price update data.
|
|
135
|
+
function updatePriceFeeds(bytes[] calldata updateData) external payable;
|
|
136
|
+
|
|
137
|
+
/// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
|
|
138
|
+
/// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
|
|
139
|
+
/// given `publishTimes` for the price feeds and does not read the actual price
|
|
140
|
+
/// update publish time within `updateData`.
|
|
141
|
+
///
|
|
142
|
+
/// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
|
|
143
|
+
/// `getUpdateFee` with the length of the `updateData` array.
|
|
144
|
+
///
|
|
145
|
+
/// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime
|
|
146
|
+
/// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have
|
|
147
|
+
/// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.
|
|
148
|
+
/// Otherwise, it calls updatePriceFeeds method to update the prices.
|
|
149
|
+
///
|
|
150
|
+
/// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.
|
|
151
|
+
/// @param updateData Array of price update data.
|
|
152
|
+
/// @param priceIds Array of price ids.
|
|
153
|
+
/// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`
|
|
154
|
+
function updatePriceFeedsIfNecessary(
|
|
155
|
+
bytes[] calldata updateData,
|
|
156
|
+
bytes32[] calldata priceIds,
|
|
157
|
+
uint64[] calldata publishTimes
|
|
158
|
+
) external payable;
|
|
159
|
+
|
|
160
|
+
/// @notice Returns the required fee to update an array of price updates.
|
|
161
|
+
/// @param updateDataSize Number of price updates.
|
|
162
|
+
/// @return feeAmount The required fee in Wei.
|
|
163
|
+
function getUpdateFee(uint256 updateDataSize) external view returns (uint256 feeAmount);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
abstract contract AbstractPyth is IPyth {
|
|
167
|
+
/// @notice Returns the price feed with given id.
|
|
168
|
+
/// @dev Reverts if the price does not exist.
|
|
169
|
+
/// @param id The Pyth Price Feed ID of which to fetch the PriceFeed.
|
|
170
|
+
function queryPriceFeed(bytes32 id) public view virtual returns (PythStructs.PriceFeed memory priceFeed);
|
|
171
|
+
|
|
172
|
+
/// @notice Returns true if a price feed with the given id exists.
|
|
173
|
+
/// @param id The Pyth Price Feed ID of which to check its existence.
|
|
174
|
+
function priceFeedExists(bytes32 id) public view virtual returns (bool exists);
|
|
175
|
+
|
|
176
|
+
function getValidTimePeriod() public view virtual override returns (uint256 validTimePeriod);
|
|
177
|
+
|
|
178
|
+
function getPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {
|
|
179
|
+
return getPriceNoOlderThan(id, getValidTimePeriod());
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function getEmaPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {
|
|
183
|
+
return getEmaPriceNoOlderThan(id, getValidTimePeriod());
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function getPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {
|
|
187
|
+
PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);
|
|
188
|
+
return priceFeed.price;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function getPriceNoOlderThan(bytes32 id, uint256 age)
|
|
192
|
+
public
|
|
193
|
+
view
|
|
194
|
+
override
|
|
195
|
+
returns (PythStructs.Price memory price)
|
|
196
|
+
{
|
|
197
|
+
price = getPriceUnsafe(id);
|
|
198
|
+
|
|
199
|
+
require(diff(block.timestamp, price.publishTime) <= age, "no price available which is recent enough");
|
|
200
|
+
|
|
201
|
+
return price;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function getEmaPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {
|
|
205
|
+
PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);
|
|
206
|
+
return priceFeed.emaPrice;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function getEmaPriceNoOlderThan(bytes32 id, uint256 age)
|
|
210
|
+
public
|
|
211
|
+
view
|
|
212
|
+
override
|
|
213
|
+
returns (PythStructs.Price memory price)
|
|
214
|
+
{
|
|
215
|
+
price = getEmaPriceUnsafe(id);
|
|
216
|
+
|
|
217
|
+
require(diff(block.timestamp, price.publishTime) <= age, "no ema price available which is recent enough");
|
|
218
|
+
|
|
219
|
+
return price;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function diff(uint256 x, uint256 y) internal pure returns (uint256) {
|
|
223
|
+
if (x > y) {
|
|
224
|
+
return x - y;
|
|
225
|
+
} else {
|
|
226
|
+
return y - x;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Access modifier is overridden to public to be able to call it locally.
|
|
231
|
+
function updatePriceFeeds(bytes[] calldata updateData) public payable virtual override;
|
|
232
|
+
|
|
233
|
+
function updatePriceFeedsIfNecessary(
|
|
234
|
+
bytes[] calldata updateData,
|
|
235
|
+
bytes32[] calldata priceIds,
|
|
236
|
+
uint64[] calldata publishTimes
|
|
237
|
+
) external payable override {
|
|
238
|
+
require(priceIds.length == publishTimes.length, "priceIds and publishTimes arrays should have same length");
|
|
239
|
+
|
|
240
|
+
bool updateNeeded = false;
|
|
241
|
+
for (uint256 i = 0; i < priceIds.length; i++) {
|
|
242
|
+
if (!priceFeedExists(priceIds[i]) || queryPriceFeed(priceIds[i]).price.publishTime < publishTimes[i]) {
|
|
243
|
+
updateNeeded = true;
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
require(updateNeeded, "no prices in the submitted batch have fresh prices, so this update will have no effect");
|
|
249
|
+
|
|
250
|
+
updatePriceFeeds(updateData);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// SPDX-License-Identifier: UNLICENSED
|
|
2
|
+
pragma solidity ^0.8.0;
|
|
3
|
+
|
|
4
|
+
import "./BEP20Interface.sol";
|
|
5
|
+
|
|
6
|
+
interface VBep20Interface is BEP20Interface {
|
|
7
|
+
/**
|
|
8
|
+
* @notice Underlying asset for this VToken
|
|
9
|
+
*/
|
|
10
|
+
function underlying() external view returns (address);
|
|
11
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// SPDX-License-Identifier: UNLICENSED
|
|
2
|
+
pragma solidity ^0.8.0;
|
|
3
|
+
|
|
4
|
+
library FixedPoint {
|
|
5
|
+
// range: [0, 2**112 - 1]
|
|
6
|
+
// resolution: 1 / 2**112
|
|
7
|
+
struct uq112x112 {
|
|
8
|
+
uint224 _x;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// returns a uq112x112 which represents the ratio of the numerator to the denominator
|
|
12
|
+
// equivalent to encode(numerator).div(denominator)
|
|
13
|
+
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
|
|
14
|
+
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
|
|
15
|
+
return uq112x112((uint224(numerator) << 112) / denominator);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// decode a uq112x112 into a uint with 18 decimals of precision
|
|
19
|
+
function decode112with18(uq112x112 memory self) internal pure returns (uint256) {
|
|
20
|
+
// we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous
|
|
21
|
+
// instead, get close to:
|
|
22
|
+
// (x * 1e18) >> 112
|
|
23
|
+
// without risk of overflowing, e.g.:
|
|
24
|
+
// (x) / 2 ** (112 - lg(1e18))
|
|
25
|
+
return uint256(self._x) / 5192296858534827;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// library with helper methods for oracles that are concerned with computing average prices
|
|
30
|
+
library PancakeOracleLibrary {
|
|
31
|
+
using FixedPoint for *;
|
|
32
|
+
|
|
33
|
+
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
|
|
34
|
+
function currentBlockTimestamp() internal view returns (uint32) {
|
|
35
|
+
return uint32(block.timestamp % 2**32);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
|
|
39
|
+
function currentCumulativePrices(address pair)
|
|
40
|
+
internal
|
|
41
|
+
view
|
|
42
|
+
returns (
|
|
43
|
+
uint256 price0Cumulative,
|
|
44
|
+
uint256 price1Cumulative,
|
|
45
|
+
uint32 blockTimestamp
|
|
46
|
+
)
|
|
47
|
+
{
|
|
48
|
+
blockTimestamp = currentBlockTimestamp();
|
|
49
|
+
price0Cumulative = IPancakePair(pair).price0CumulativeLast();
|
|
50
|
+
price1Cumulative = IPancakePair(pair).price1CumulativeLast();
|
|
51
|
+
|
|
52
|
+
// if time has elapsed since the last update on the pair, mock the accumulated price values
|
|
53
|
+
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPancakePair(pair).getReserves();
|
|
54
|
+
if (blockTimestampLast != blockTimestamp) {
|
|
55
|
+
unchecked {
|
|
56
|
+
// subtraction overflow is desired
|
|
57
|
+
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
|
|
58
|
+
// addition overflow is desired
|
|
59
|
+
// counterfactual
|
|
60
|
+
price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
|
|
61
|
+
// counterfactual
|
|
62
|
+
price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface IPancakePair {
|
|
69
|
+
function getReserves()
|
|
70
|
+
external
|
|
71
|
+
view
|
|
72
|
+
returns (
|
|
73
|
+
uint112 reserve0,
|
|
74
|
+
uint112 reserve1,
|
|
75
|
+
uint32 blockTimestampLast
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
function price0CumulativeLast() external view returns (uint256);
|
|
79
|
+
|
|
80
|
+
function price1CumulativeLast() external view returns (uint256);
|
|
81
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// SPDX-License-Identifier: UNLICENSED
|
|
2
|
+
pragma solidity ^0.8.10;
|
|
3
|
+
|
|
4
|
+
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
|
|
5
|
+
import "../interfaces/FeedRegistryInterface.sol";
|
|
6
|
+
import "../interfaces/VBep20Interface.sol";
|
|
7
|
+
import "../interfaces/BEP20Interface.sol";
|
|
8
|
+
|
|
9
|
+
contract BinanceOracle is Initializable {
|
|
10
|
+
FeedRegistryInterface public feedRegistry;
|
|
11
|
+
|
|
12
|
+
function initialize(FeedRegistryInterface feed) public initializer {
|
|
13
|
+
feedRegistry = feed;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getUnderlyingPrice(VBep20Interface vToken) public view returns (uint256) {
|
|
17
|
+
BEP20Interface underlyingToken = BEP20Interface(vToken.underlying());
|
|
18
|
+
|
|
19
|
+
string memory symbol = underlyingToken.symbol();
|
|
20
|
+
|
|
21
|
+
if (keccak256(bytes(symbol)) == keccak256(bytes("WBNB"))) {
|
|
22
|
+
symbol = "BNB";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
(, int256 answer, , , ) = feedRegistry.latestRoundDataByName(symbol, "USD");
|
|
26
|
+
|
|
27
|
+
uint256 decimalDelta = feedRegistry.decimalsByName(symbol, "USD");
|
|
28
|
+
return (uint256(answer) * (10**(18 - decimalDelta))) * (10**(18 - underlyingToken.decimals()));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// SPDX-License-Identifier: UNLICENSED
|
|
2
|
+
pragma solidity ^0.8.0;
|
|
3
|
+
pragma experimental ABIEncoderV2;
|
|
4
|
+
|
|
5
|
+
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
|
|
6
|
+
import "../interfaces/BEP20Interface.sol";
|
|
7
|
+
import "../interfaces/VBep20Interface.sol";
|
|
8
|
+
import "../interfaces/OracleInterface.sol";
|
|
9
|
+
|
|
10
|
+
struct ValidateConfig {
|
|
11
|
+
/// @notice asset address
|
|
12
|
+
address asset;
|
|
13
|
+
/// @notice upper bound of deviation between reported price and anchor price,
|
|
14
|
+
/// beyond which the reported price will be invalidated
|
|
15
|
+
uint256 upperBoundRatio;
|
|
16
|
+
/// @notice lower bound of deviation between reported price and anchor price,
|
|
17
|
+
/// below which the reported price will be invalidated
|
|
18
|
+
uint256 lowerBoundRatio;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// BoundValidator provides some common functions and can be used
|
|
22
|
+
// to wrap up other contracts to form pivot oracles
|
|
23
|
+
contract BoundValidator is OwnableUpgradeable, BoundValidatorInterface {
|
|
24
|
+
/// @notice validation configs by asset
|
|
25
|
+
mapping(address => ValidateConfig) public validateConfigs;
|
|
26
|
+
|
|
27
|
+
/// @notice Emit this event when new validate configs are added
|
|
28
|
+
event ValidateConfigAdded(address indexed asset, uint256 indexed upperBound, uint256 indexed lowerBound);
|
|
29
|
+
|
|
30
|
+
function initialize() public initializer {
|
|
31
|
+
__Ownable_init();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @notice Add multiple validation configs at the same time
|
|
36
|
+
* @param configs config array
|
|
37
|
+
*/
|
|
38
|
+
function setValidateConfigs(ValidateConfig[] memory configs) external virtual onlyOwner {
|
|
39
|
+
require(configs.length > 0, "invalid validate config length");
|
|
40
|
+
for (uint8 i = 0; i < configs.length; i++) {
|
|
41
|
+
setValidateConfig(configs[i]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @notice Add single validation config
|
|
47
|
+
* @param config config struct
|
|
48
|
+
*/
|
|
49
|
+
function setValidateConfig(ValidateConfig memory config) public virtual onlyOwner {
|
|
50
|
+
require(config.asset != address(0), "asset can't be zero address");
|
|
51
|
+
require(config.upperBoundRatio > 0 && config.lowerBoundRatio > 0, "bound must be positive");
|
|
52
|
+
require(config.upperBoundRatio > config.lowerBoundRatio, "upper bound must be higher than lowner bound");
|
|
53
|
+
validateConfigs[config.asset] = config;
|
|
54
|
+
emit ValidateConfigAdded(config.asset, config.upperBoundRatio, config.lowerBoundRatio);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @notice Test reported asset price against anchor price
|
|
59
|
+
* @param vToken vToken address
|
|
60
|
+
* @param reporterPrice the price to be tested
|
|
61
|
+
*/
|
|
62
|
+
function validatePriceWithAnchorPrice(
|
|
63
|
+
address vToken,
|
|
64
|
+
uint256 reporterPrice,
|
|
65
|
+
uint256 anchorPrice
|
|
66
|
+
) public view virtual override returns (bool) {
|
|
67
|
+
address asset = VBep20Interface(vToken).underlying();
|
|
68
|
+
|
|
69
|
+
require(validateConfigs[asset].upperBoundRatio != 0, "validation config not exist");
|
|
70
|
+
require(anchorPrice != 0, "anchor price is not valid");
|
|
71
|
+
return _isWithinAnchor(asset, reporterPrice, anchorPrice);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @notice Test whether the reported price is within the predefined bounds
|
|
76
|
+
* @param asset asset address
|
|
77
|
+
* @param reporterPrice the price to be tested
|
|
78
|
+
* @param anchorPrice anchor price as testing anchor
|
|
79
|
+
*/
|
|
80
|
+
function _isWithinAnchor(
|
|
81
|
+
address asset,
|
|
82
|
+
uint256 reporterPrice,
|
|
83
|
+
uint256 anchorPrice
|
|
84
|
+
) internal view returns (bool) {
|
|
85
|
+
if (reporterPrice > 0) {
|
|
86
|
+
uint256 anchorRatio = (anchorPrice * 100e16) / reporterPrice;
|
|
87
|
+
uint256 upperBoundAnchorRatio = validateConfigs[asset].upperBoundRatio;
|
|
88
|
+
uint256 lowerBoundAnchorRatio = validateConfigs[asset].lowerBoundRatio;
|
|
89
|
+
return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
|
|
90
|
+
}
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// BoundValidator is to get inherited, so it's a good practice to add some storage gaps like
|
|
95
|
+
// OpenZepplin proposed in their contracts: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
|
|
96
|
+
uint256[49] private __gap;
|
|
97
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// SPDX-License-Identifier: UNLICENSED
|
|
2
|
+
pragma solidity ^0.8.0;
|
|
3
|
+
pragma experimental ABIEncoderV2;
|
|
4
|
+
|
|
5
|
+
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
|
|
6
|
+
import "../interfaces/VBep20Interface.sol";
|
|
7
|
+
import "../interfaces/AggregatorV2V3Interface.sol";
|
|
8
|
+
import "../interfaces/OracleInterface.sol";
|
|
9
|
+
|
|
10
|
+
struct TokenConfig {
|
|
11
|
+
/// @notice underlying token address, which can't be zero address and can be used for existance check
|
|
12
|
+
address asset;
|
|
13
|
+
/// @notice chainlink feed address
|
|
14
|
+
address feed;
|
|
15
|
+
/// @notice expiration period of this asset
|
|
16
|
+
uint256 maxStalePeriod;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
contract ChainlinkOracle is OwnableUpgradeable, OracleInterface {
|
|
20
|
+
/// @notice VAI token is considered $1 constantly in oracle for now
|
|
21
|
+
uint256 public constant VAI_VALUE = 1e18;
|
|
22
|
+
|
|
23
|
+
/// @notice TODO: might be removed some day, it's for enabling us to force set the prices to
|
|
24
|
+
/// certain values in some urgent conditions
|
|
25
|
+
mapping(address => uint256) public prices;
|
|
26
|
+
|
|
27
|
+
/// @notice token config by assets
|
|
28
|
+
mapping(address => TokenConfig) public tokenConfigs;
|
|
29
|
+
|
|
30
|
+
/// @notice emit when forced price is set
|
|
31
|
+
event PricePosted(
|
|
32
|
+
address asset,
|
|
33
|
+
uint256 previousPriceMantissa,
|
|
34
|
+
uint256 requestedPriceMantissa,
|
|
35
|
+
uint256 newPriceMantissa
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
/// @notice emit when token config is added
|
|
39
|
+
event TokenConfigAdded(address asset, address feed, uint256 maxStalePeriod);
|
|
40
|
+
|
|
41
|
+
modifier notNullAddress(address someone) {
|
|
42
|
+
require(someone != address(0), "can't be zero address");
|
|
43
|
+
_;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function initialize() public initializer {
|
|
47
|
+
__Ownable_init();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @notice Get the Chainlink price of underlying asset of input vToken, revert when vToken is zero address
|
|
52
|
+
* @param vToken vToken address
|
|
53
|
+
* @return price in USD, with 18 decimals
|
|
54
|
+
*/
|
|
55
|
+
function getUnderlyingPrice(address vToken) public view override returns (uint256) {
|
|
56
|
+
string memory symbol = VBep20Interface(vToken).symbol();
|
|
57
|
+
// VBNB token doesn't have `underlying` method, so it has to skip `_getUnderlyingPriceInternal
|
|
58
|
+
// method and directly goes into `_getChainlinkPrice`
|
|
59
|
+
if (_compareStrings(symbol, "vBNB")) {
|
|
60
|
+
return _getChainlinkPrice(vToken);
|
|
61
|
+
// VAI price is constantly 1 at the moment, but not guarantee in the future
|
|
62
|
+
} else if (_compareStrings(symbol, "VAI")) {
|
|
63
|
+
return VAI_VALUE;
|
|
64
|
+
// @TODO: This is some history code, keep it here in case of messing up
|
|
65
|
+
} else {
|
|
66
|
+
return _getUnderlyingPriceInternal(VBep20Interface(vToken));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @notice Get the Chainlink price of underlying asset of input vToken or cached price when it's been set
|
|
72
|
+
* @dev The decimals of underlying tokens is considered to ensure the returned prices are in 18 decimals
|
|
73
|
+
* @param vToken vToken address
|
|
74
|
+
* @return price in USD, with 18 decimals
|
|
75
|
+
*/
|
|
76
|
+
function _getUnderlyingPriceInternal(VBep20Interface vToken) internal view returns (uint256 price) {
|
|
77
|
+
VBep20Interface token = VBep20Interface(vToken.underlying());
|
|
78
|
+
|
|
79
|
+
if (prices[address(token)] != 0) {
|
|
80
|
+
price = prices[address(token)];
|
|
81
|
+
} else {
|
|
82
|
+
price = _getChainlinkPrice(address(vToken));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
uint256 decimalDelta = uint256(18) - uint256(token.decimals());
|
|
86
|
+
return price * (10**decimalDelta);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @notice Get the Chainlink price of underlying asset of input vToken, revert if token config doesn't exit
|
|
91
|
+
* @dev The decimals of feeds are considered
|
|
92
|
+
* @param vToken vToken address
|
|
93
|
+
* @return price in USD, with 18 decimals
|
|
94
|
+
*/
|
|
95
|
+
function _getChainlinkPrice(address vToken)
|
|
96
|
+
internal
|
|
97
|
+
view
|
|
98
|
+
notNullAddress(tokenConfigs[VBep20Interface(vToken).underlying()].asset)
|
|
99
|
+
returns (uint256)
|
|
100
|
+
{
|
|
101
|
+
address asset = VBep20Interface(vToken).underlying();
|
|
102
|
+
|
|
103
|
+
TokenConfig storage tokenConfig = tokenConfigs[asset];
|
|
104
|
+
AggregatorV2V3Interface feed = AggregatorV2V3Interface(tokenConfig.feed);
|
|
105
|
+
|
|
106
|
+
// note: maxStalePeriod cannot be 0
|
|
107
|
+
uint256 maxStalePeriod = tokenConfig.maxStalePeriod;
|
|
108
|
+
|
|
109
|
+
// Chainlink USD-denominated feeds store answers at 8 decimals, mostly
|
|
110
|
+
uint256 decimalDelta = uint256(18) - feed.decimals();
|
|
111
|
+
|
|
112
|
+
(, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
|
|
113
|
+
require(answer > 0, "chainlink price must be positive");
|
|
114
|
+
|
|
115
|
+
require(block.timestamp > updatedAt, "updatedAt exceeds block time");
|
|
116
|
+
uint256 deltaTime = block.timestamp - updatedAt;
|
|
117
|
+
require(deltaTime <= maxStalePeriod, "chainlink price expired");
|
|
118
|
+
|
|
119
|
+
return uint256(answer) * (10**decimalDelta);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @notice Set the forced prices of the underlying token of input vToken
|
|
124
|
+
* @param vToken vToken address
|
|
125
|
+
* @param underlyingPriceMantissa price in 18 decimals
|
|
126
|
+
*/
|
|
127
|
+
function setUnderlyingPrice(VBep20Interface vToken, uint256 underlyingPriceMantissa) external onlyOwner {
|
|
128
|
+
address asset = address(vToken.underlying());
|
|
129
|
+
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
|
|
130
|
+
prices[asset] = underlyingPriceMantissa;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* @notice Set the forced prices of the input token
|
|
135
|
+
* @param asset asset address
|
|
136
|
+
* @param price price in 18 decimals
|
|
137
|
+
*/
|
|
138
|
+
function setDirectPrice(address asset, uint256 price) external onlyOwner {
|
|
139
|
+
emit PricePosted(asset, prices[asset], price, price);
|
|
140
|
+
prices[asset] = price;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* @notice Add multiple token configs at the same time
|
|
145
|
+
* @param tokenConfigs_ config array
|
|
146
|
+
*/
|
|
147
|
+
function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {
|
|
148
|
+
require(tokenConfigs_.length > 0, "length can't be 0");
|
|
149
|
+
for (uint256 i = 0; i < tokenConfigs_.length; i++) {
|
|
150
|
+
setTokenConfig(tokenConfigs_[i]);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* @notice Add single token config, vToken & feed cannot be zero address, and maxStalePeriod must be positive
|
|
156
|
+
* @param tokenConfig token config struct
|
|
157
|
+
*/
|
|
158
|
+
function setTokenConfig(TokenConfig memory tokenConfig)
|
|
159
|
+
public
|
|
160
|
+
onlyOwner
|
|
161
|
+
notNullAddress(tokenConfig.asset)
|
|
162
|
+
notNullAddress(tokenConfig.feed)
|
|
163
|
+
{
|
|
164
|
+
require(tokenConfig.maxStalePeriod > 0, "stale period can't be zero");
|
|
165
|
+
tokenConfigs[tokenConfig.asset] = tokenConfig;
|
|
166
|
+
emit TokenConfigAdded(tokenConfig.asset, tokenConfig.feed, tokenConfig.maxStalePeriod);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function _compareStrings(string memory a, string memory b) internal pure returns (bool) {
|
|
170
|
+
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
|
|
171
|
+
}
|
|
172
|
+
}
|