@venusprotocol/oracle 1.1.3 → 1.2.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.
@@ -0,0 +1,220 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+ pragma experimental ABIEncoderV2;
4
+
5
+ import "@openzeppelin/contracts/utils/math/SafeMath.sol";
6
+ import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
7
+ import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
8
+ import "./interfaces/OracleInterface.sol";
9
+
10
+
11
+ contract ResilientOracle is OwnableUpgradeable, PausableUpgradeable {
12
+ using SafeMath for uint256;
13
+
14
+ uint256 public constant INVALID_PRICE = 0;
15
+
16
+ /**
17
+ * @dev oracle role, we have 3 roles at the moment
18
+ * MAIN: The most trustworthy price source
19
+ * PIVOT: Not so trustworthy price source, used as a loose sanity checker
20
+ * FALLBACK: The backup source when main oracle price is invalidated
21
+ */
22
+ enum OracleRole {
23
+ MAIN,
24
+ PIVOT,
25
+ FALLBACK
26
+ }
27
+
28
+ struct TokenConfig {
29
+ /// @notice vToken address
30
+ address vToken;
31
+ /// @notice `oracles` stores the oracles in the order of: [main, pivot, fallback],
32
+ /// it can be indexed with enum OracleRole value
33
+ address[3] oracles;
34
+ /// @notice `enableFlagsForOracles` stores the oracle enable statuses
35
+ /// for each oracle in the same order as `oracles`
36
+ bool[3] enableFlagsForOracles;
37
+ }
38
+
39
+ mapping(address => TokenConfig) private tokenConfigs;
40
+
41
+ event GlobalEnable(bool indexed isEnable);
42
+ event TokenConfigAdded(
43
+ address indexed token,
44
+ address indexed mainOracle,
45
+ address indexed pivotOracle,
46
+ address fallbackOracle
47
+ );
48
+ event OracleSet(address indexed vToken, address indexed oracle, uint indexed role);
49
+ event OracleEnabled(address indexed vToken, uint indexed role, bool indexed enable);
50
+
51
+ modifier notNullAddress(address someone) {
52
+ require(someone != address(0), "can't be zero address");
53
+ _;
54
+ }
55
+
56
+ /**
57
+ * @notice Check whether token config exist by checking whether vToken is zero address
58
+ * @dev vToken can't be set to zero, so it's suitable to be used to check
59
+ * @param vToken vtoken address
60
+ */
61
+ modifier checkTokenConfigExistance(address vToken) {
62
+ require(tokenConfigs[vToken].vToken != address(0), "token config must exist");
63
+ _;
64
+ }
65
+
66
+ function initialize() public initializer {
67
+ __Ownable_init();
68
+ __Pausable_init();
69
+ }
70
+
71
+ /**
72
+ * @notice Pause protocol
73
+ */
74
+ function pause() external onlyOwner() {
75
+ _pause();
76
+ }
77
+
78
+ /**
79
+ * @notice Unpause protocol
80
+ */
81
+ function unpause() external onlyOwner() {
82
+ _unpause();
83
+ }
84
+
85
+ /**
86
+ * @dev Get token config by vToken address
87
+ * @param vToken vtoken address
88
+ */
89
+ function getTokenConfig(address vToken) external view returns (TokenConfig memory) {
90
+ return tokenConfigs[vToken];
91
+ }
92
+
93
+ /**
94
+ * @notice Get oracle & enabling status by vToken address
95
+ * @param vToken vtoken address
96
+ * @param role oracle role
97
+ */
98
+ function getOracle(address vToken, OracleRole role) public view returns (address oracle, bool enabled) {
99
+ oracle = tokenConfigs[vToken].oracles[uint(role)];
100
+ enabled = tokenConfigs[vToken].enableFlagsForOracles[uint(role)];
101
+ }
102
+
103
+ /**
104
+ * @notice Batch set token configs
105
+ * @param tokenConfigs_ token config array
106
+ */
107
+ function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner() {
108
+ require(tokenConfigs_.length != 0, "length can't be 0");
109
+ for (uint256 i = 0; i < tokenConfigs_.length; i++) {
110
+ setTokenConfig(tokenConfigs_[i]);
111
+ }
112
+ }
113
+
114
+ /**
115
+ * @notice Set single token configs, vToken MUST HAVE NOT be added before, and main oracle MUST NOT be zero address
116
+ * @param tokenConfig token config struct
117
+ */
118
+ function setTokenConfig(TokenConfig memory tokenConfig) public
119
+ onlyOwner()
120
+ notNullAddress(tokenConfig.vToken)
121
+ notNullAddress(tokenConfig.oracles[uint(OracleRole.MAIN)])
122
+ {
123
+ tokenConfigs[tokenConfig.vToken] = tokenConfig;
124
+ emit TokenConfigAdded(
125
+ tokenConfig.vToken,
126
+ tokenConfig.oracles[uint(OracleRole.MAIN)],
127
+ tokenConfig.oracles[uint(OracleRole.PIVOT)],
128
+ tokenConfig.oracles[uint(OracleRole.FALLBACK)]
129
+ );
130
+ }
131
+
132
+ /**
133
+ * @notice Set oracle of any type for the input vToken, input vToken MUST exist
134
+ * @param vToken vToken address
135
+ * @param oracle oracle address
136
+ * @param role oracle role
137
+ */
138
+ function setOracle(address vToken, address oracle, OracleRole role) external
139
+ onlyOwner()
140
+ notNullAddress(vToken)
141
+ checkTokenConfigExistance(vToken)
142
+ {
143
+ require(!(oracle == address(0) && role == OracleRole.MAIN), "can't set zero address to main oracle");
144
+ tokenConfigs[vToken].oracles[uint(role)] = oracle;
145
+ emit OracleSet(vToken, oracle, uint(role));
146
+ }
147
+
148
+ /**
149
+ * @notice Enable/disable oracle for the input vToken, input vToken MUST exist
150
+ * @param vToken vToken address
151
+ * @param role oracle role
152
+ * @param enable expected status
153
+ */
154
+ function enableOracle(address vToken, OracleRole role, bool enable) external
155
+ onlyOwner()
156
+ notNullAddress(vToken)
157
+ checkTokenConfigExistance(vToken)
158
+ {
159
+ tokenConfigs[vToken].enableFlagsForOracles[uint(role)] = enable;
160
+ emit OracleEnabled(vToken, uint(role), enable);
161
+ }
162
+
163
+ /**
164
+ * @notice Get price of underlying asset of the input vToken, check flow:
165
+ * - check the global pausing status
166
+ * - check price from main oracle
167
+ * - check price against pivot oracle, if any
168
+ * - if fallback flag is enabled and price is invalidated, fallback
169
+ * @param vToken vToken address
170
+ * @return price USD price in 18 decimals
171
+ */
172
+ function getUnderlyingPrice(address vToken) external view returns (uint256) {
173
+ uint256 price = _getUnderlyingPriceInternal(vToken);
174
+ (address fallbackOracle, bool fallbackEnabled) = getOracle(vToken, OracleRole.FALLBACK);
175
+ if (price == INVALID_PRICE && fallbackEnabled && fallbackOracle != address(0)) {
176
+ uint256 fallbackPrice = OracleInterface(fallbackOracle).getUnderlyingPrice(vToken);
177
+ require(fallbackPrice != INVALID_PRICE, "fallback oracle price must be positive");
178
+ return fallbackPrice;
179
+ }
180
+ // if price is 0 here, it means main oracle price is 0 or got invalidated by pivot oracle
181
+ // and fallback oracle is not active, we revert it
182
+ require(price != INVALID_PRICE, "invalid resilient oracle price");
183
+ return price;
184
+ }
185
+
186
+ /**
187
+ * @notice This function won't revert when price is 0, because the fallback oracle may come to play later
188
+ * @param vToken vToken address
189
+ * @return price USD price in 18 decimals
190
+ */
191
+ function _getUnderlyingPriceInternal(address vToken) internal view returns (uint256) {
192
+ // Global emergency switch
193
+ require(!paused(), "resilient oracle is paused");
194
+
195
+ (address mainOracle, bool mainOracleEnabled) = getOracle(vToken, OracleRole.MAIN);
196
+
197
+ uint price = INVALID_PRICE;
198
+
199
+ if (!mainOracleEnabled) {
200
+ return price;
201
+ }
202
+
203
+ price = OracleInterface(mainOracle).getUnderlyingPrice(vToken);
204
+
205
+ (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);
206
+
207
+ // Price oracle is not mandantory
208
+ if (pivotOracle == address(0) || !pivotOracleEnabled) {
209
+ return price;
210
+ }
211
+
212
+ // Check the price with pivot oracle
213
+ bool pass = PivotOracleInterface(pivotOracle).validatePrice(vToken, price);
214
+ if (!pass) {
215
+ return INVALID_PRICE;
216
+ }
217
+
218
+ return price;
219
+ }
220
+ }
@@ -0,0 +1,60 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ /**
5
+ * @title The V2 & V3 Aggregator Interface
6
+ * @notice Solidity V0.5 does not allow interfaces to inherit from other
7
+ * interfaces so this contract is a combination of v0.5 AggregatorInterface.sol
8
+ * and v0.5 AggregatorV3Interface.sol.
9
+ */
10
+ interface AggregatorV2V3Interface {
11
+ //
12
+ // V2 Interface:
13
+ //
14
+ function latestAnswer() external view returns (int256);
15
+
16
+ function latestTimestamp() external view returns (uint256);
17
+
18
+ function latestRound() external view returns (uint256);
19
+
20
+ function getAnswer(uint256 roundId) external view returns (int256);
21
+
22
+ function getTimestamp(uint256 roundId) external view returns (uint256);
23
+
24
+ event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
25
+ event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
26
+
27
+ //
28
+ // V3 Interface:
29
+ //
30
+ function decimals() external view returns (uint8);
31
+
32
+ function description() external view returns (string memory);
33
+
34
+ function version() external view returns (uint256);
35
+
36
+ // getRoundData and latestRoundData should both raise "No data present"
37
+ // if they do not have data to report, instead of returning unset values
38
+ // which could be misinterpreted as actual reported values.
39
+ function getRoundData(uint80 _roundId)
40
+ external
41
+ view
42
+ returns (
43
+ uint80 roundId,
44
+ int256 answer,
45
+ uint256 startedAt,
46
+ uint256 updatedAt,
47
+ uint80 answeredInRound
48
+ );
49
+
50
+ function latestRoundData()
51
+ external
52
+ view
53
+ returns (
54
+ uint80 roundId,
55
+ int256 answer,
56
+ uint256 startedAt,
57
+ uint256 updatedAt,
58
+ uint80 answeredInRound
59
+ );
60
+ }
@@ -0,0 +1,97 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+
4
+ interface BEP20Interface {
5
+ /**
6
+ * @dev Returns the amount of tokens in existence.
7
+ */
8
+ function totalSupply() external view returns (uint256);
9
+
10
+ /**
11
+ * @dev Returns the token decimals.
12
+ */
13
+ function decimals() external view returns (uint8);
14
+
15
+ /**
16
+ * @dev Returns the token symbol.
17
+ */
18
+ function symbol() external view returns (string memory);
19
+
20
+ /**
21
+ * @dev Returns the token name.
22
+ */
23
+ function name() external view returns (string memory);
24
+
25
+ /**
26
+ * @dev Returns the bep token owner.
27
+ */
28
+ function getOwner() external view returns (address);
29
+
30
+ /**
31
+ * @dev Returns the amount of tokens owned by `account`.
32
+ */
33
+ function balanceOf(address account) external view returns (uint256);
34
+
35
+ /**
36
+ * @dev Moves `amount` tokens from the caller's account to `recipient`.
37
+ *
38
+ * Returns a boolean value indicating whether the operation succeeded.
39
+ *
40
+ * Emits a {Transfer} event.
41
+ */
42
+ function transfer(address recipient, uint256 amount) external returns (bool);
43
+
44
+ /**
45
+ * @dev Returns the remaining number of tokens that `spender` will be
46
+ * allowed to spend on behalf of `owner` through {transferFrom}. This is
47
+ * zero by default.
48
+ *
49
+ * This value changes when {approve} or {transferFrom} are called.
50
+ */
51
+ function allowance(address _owner, address spender) external view returns (uint256);
52
+
53
+ /**
54
+ * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
55
+ *
56
+ * Returns a boolean value indicating whether the operation succeeded.
57
+ *
58
+ * IMPORTANT: Beware that changing an allowance with this method brings the risk
59
+ * that someone may use both the old and the new allowance by unfortunate
60
+ * transaction ordering. One possible solution to mitigate this race
61
+ * condition is to first reduce the spender's allowance to 0 and set the
62
+ * desired value afterwards:
63
+ * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
64
+ *
65
+ * Emits an {Approval} event.
66
+ */
67
+ function approve(address spender, uint256 amount) external returns (bool);
68
+
69
+ /**
70
+ * @dev Moves `amount` tokens from `sender` to `recipient` using the
71
+ * allowance mechanism. `amount` is then deducted from the caller's
72
+ * allowance.
73
+ *
74
+ * Returns a boolean value indicating whether the operation succeeded.
75
+ *
76
+ * Emits a {Transfer} event.
77
+ */
78
+ function transferFrom(
79
+ address sender,
80
+ address recipient,
81
+ uint256 amount
82
+ ) external returns (bool);
83
+
84
+ /**
85
+ * @dev Emitted when `value` tokens are moved from one account (`from`) to
86
+ * another (`to`).
87
+ *
88
+ * Note that `value` may be zero.
89
+ */
90
+ event Transfer(address indexed from, address indexed to, uint256 value);
91
+
92
+ /**
93
+ * @dev Emitted when the allowance of a `spender` for an `owner` is set by
94
+ * a call to {approve}. `value` is the new allowance.
95
+ */
96
+ event Approval(address indexed owner, address indexed spender, uint256 value);
97
+ }
@@ -0,0 +1,15 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+ pragma solidity ^0.8.0;
3
+ pragma experimental ABIEncoderV2;
4
+
5
+
6
+ interface OracleInterface {
7
+ function getUnderlyingPrice(address vToken) external view returns (uint256);
8
+ }
9
+
10
+ interface PivotValidatorInterface {
11
+ function validatePrice(address vToken, uint256 price) external view returns (bool);
12
+ }
13
+
14
+ interface PivotOracleInterface is OracleInterface, PivotValidatorInterface {
15
+ }
@@ -0,0 +1,160 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ pragma solidity ^0.8.0;
3
+
4
+ contract PythStructs {
5
+ //
6
+ // The confidence interval roughly corresponds to the standard error of a normal distribution.
7
+ // Both the price and confidence are stored in a fixed-point numeric representation,
8
+ // `x * (10^expo)`, where `expo` is the exponent.
9
+ //
10
+ // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how
11
+ // to how this price safely.
12
+ struct Price {
13
+ // Price
14
+ int64 price;
15
+ // Confidence interval around the price
16
+ uint64 conf;
17
+ // Price exponent
18
+ int32 expo;
19
+ }
20
+
21
+ // PriceFeed represents a current aggregate price from pyth publisher feeds.
22
+ struct PriceFeed {
23
+ // The price ID.
24
+ bytes32 id;
25
+ // Product account key.
26
+ bytes32 productId;
27
+ // The current price.
28
+ int64 price;
29
+ // Confidence interval around the price.
30
+ uint64 conf;
31
+ // Price exponent.
32
+ int32 expo;
33
+ // Status of price.
34
+ PriceStatus status;
35
+ // Maximum number of allowed publishers that can contribute to a price.
36
+ uint32 maxNumPublishers;
37
+ // Number of publishers that made up current aggregate.
38
+ uint32 numPublishers;
39
+ // Exponentially moving average price.
40
+ int64 emaPrice;
41
+ // Exponentially moving average confidence interval.
42
+ uint64 emaConf;
43
+ // Unix timestamp describing when the price was published
44
+ uint64 publishTime;
45
+ // Price of previous price with TRADING status
46
+ int64 prevPrice;
47
+ // Confidence interval of previous price with TRADING status
48
+ uint64 prevConf;
49
+ // Unix timestamp describing when the previous price with TRADING status was published
50
+ uint64 prevPublishTime;
51
+ }
52
+
53
+ /* PriceStatus represents the availability status of a price feed.
54
+ UNKNOWN: The price feed is not currently updating for an unknown reason.
55
+ TRADING: The price feed is updating as expected.
56
+ HALTED: The price feed is not currently updating because trading in the product has been halted.
57
+ AUCTION: The price feed is not currently updating because an auction is setting the price.
58
+ */
59
+ enum PriceStatus {
60
+ UNKNOWN,
61
+ TRADING,
62
+ HALTED,
63
+ AUCTION
64
+ }
65
+
66
+ }
67
+
68
+ /// @title Consume prices from the Pyth Network (https://pyth.network/).
69
+ /// @author Pyth Data Association
70
+ interface IPyth {
71
+ /// @dev Emitted when an update for price feed with `id` is processed successfully.
72
+ /// @param id The Pyth Price Feed ID.
73
+ /// @param fresh True if the price update is more recent and stored.
74
+ /// @param chainId ID of the source chain that the batch price update containing this price.
75
+ /// This value comes from Wormhole, and you can find the corresponding chains at https://docs.wormholenetwork.com/wormhole/contracts.
76
+ /// @param sequenceNumber Sequence number of the batch price update containing this price.
77
+ /// @param lastPublishTime Publish time of the previously stored price.
78
+ /// @param publishTime Publish time of the given price update.
79
+ /// @param price Current price of the given price update.
80
+ /// @param conf Current confidence interval of the given price update.
81
+ event PriceFeedUpdate(bytes32 indexed id, bool indexed fresh, uint16 chainId, uint64 sequenceNumber, uint64 lastPublishTime, uint64 publishTime, int64 price, uint64 conf);
82
+
83
+ /// @dev Emitted when a batch price update is processed successfully.
84
+ /// @param chainId ID of the source chain that the batch price update comes from.
85
+ /// @param sequenceNumber Sequence number of the batch price update.
86
+ /// @param batchSize Number of prices within the batch price update.
87
+ /// @param freshPricesInBatch Number of prices that were more recent and were stored.
88
+ event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber, uint batchSize, uint freshPricesInBatch);
89
+
90
+ /// @dev Emitted when a call to `updatePriceFeeds` is processed successfully.
91
+ /// @param sender Sender of the call (`msg.sender`).
92
+ /// @param batchCount Number of batches that this function processed.
93
+ /// @param fee Amount of paid fee for updating the prices.
94
+ event UpdatePriceFeeds(address indexed sender, uint batchCount, uint fee);
95
+
96
+ /// @notice Returns the current price and confidence interval.
97
+ /// @dev Reverts if the current price is not available.
98
+ /// @param id The Pyth Price Feed ID of which to fetch the current price and confidence interval.
99
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
100
+ function getCurrentPrice(bytes32 id) external view returns (PythStructs.Price memory price);
101
+
102
+ /// @notice Returns the exponential moving average price and confidence interval.
103
+ /// @dev Reverts if the current exponential moving average price is not available.
104
+ /// @param id The Pyth Price Feed ID of which to fetch the current price and confidence interval.
105
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
106
+ function getEmaPrice(bytes32 id) external view returns (PythStructs.Price memory price);
107
+
108
+ /// @notice Returns the latest available price, along with the timestamp when it was generated.
109
+ /// @dev This function returns the same price as `getCurrentPrice` in the case where a price was available
110
+ /// at the time this `PriceFeed` was published (`publish_time`). However, if a price was not available
111
+ /// at that time, this function returns the price from the latest time at which the price was available.
112
+ ///
113
+ /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that
114
+ /// the returned price is recent or useful for any particular application.
115
+ ///
116
+ /// Users of this function should check the returned timestamp to ensure that the returned price is
117
+ /// sufficiently recent for their application. If you are considering using this function, it may be
118
+ /// safer / easier to use either `getCurrentPrice` or `getLatestAvailablePriceWithinDuration`.
119
+ /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.
120
+ /// @return publishTime - the UNIX timestamp of when this price was computed.
121
+ function getLatestAvailablePriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price, uint64 publishTime);
122
+
123
+ /// @notice Returns the latest price as long as it was updated within `duration` seconds of the current time.
124
+ /// @dev This function is a sanity-checked version of `getLatestAvailablePriceUnchecked` which is useful in
125
+ /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently
126
+ /// recently.
127
+ function getLatestAvailablePriceWithinDuration(bytes32 id, uint64 duration) external view returns (PythStructs.Price memory price);
128
+
129
+ /// @notice Update price feeds with given update messages.
130
+ /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling
131
+ /// `getUpdateFee` with the length of the `updateData` array.
132
+ /// Prices will be updated if they are more recent than the current stored prices.
133
+ /// The call will succeed even if the update is not the most recent.
134
+ /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.
135
+ /// @param updateData Array of price update data.
136
+ function updatePriceFeeds(bytes[] memory updateData) external payable;
137
+
138
+ /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is
139
+ /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the
140
+ /// given `publishTimes` for the price feeds and does not read the actual price 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(bytes[] memory updateData, bytes32[] memory priceIds, uint64[] memory publishTimes) external payable;
155
+
156
+ /// @notice Returns the required fee to update an array of price updates.
157
+ /// @param updateDataSize Number of price updates.
158
+ /// @return feeAmount The required fee in Wei.
159
+ function getUpdateFee(uint updateDataSize) external view returns (uint feeAmount);
160
+ }
@@ -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,64 @@
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 (uint) {
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 uint(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(
40
+ address pair
41
+ ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
42
+ blockTimestamp = currentBlockTimestamp();
43
+ price0Cumulative = IPancakePair(pair).price0CumulativeLast();
44
+ price1Cumulative = IPancakePair(pair).price1CumulativeLast();
45
+
46
+ // if time has elapsed since the last update on the pair, mock the accumulated price values
47
+ (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPancakePair(pair).getReserves();
48
+ if (blockTimestampLast != blockTimestamp) {
49
+ // subtraction overflow is desired
50
+ uint32 timeElapsed = blockTimestamp - blockTimestampLast;
51
+ // addition overflow is desired
52
+ // counterfactual
53
+ price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
54
+ // counterfactual
55
+ price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
56
+ }
57
+ }
58
+ }
59
+
60
+ interface IPancakePair {
61
+ function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
62
+ function price0CumulativeLast() external view returns (uint);
63
+ function price1CumulativeLast() external view returns (uint);
64
+ }