@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.
- package/contracts/ResilientOracle.sol +220 -0
- package/contracts/interfaces/AggregatorV2V3Interface.sol +60 -0
- package/contracts/interfaces/BEP20Interface.sol +97 -0
- package/contracts/interfaces/OracleInterface.sol +15 -0
- package/contracts/interfaces/PythInterface.sol +160 -0
- package/contracts/interfaces/VBep20Interface.sol +11 -0
- package/contracts/libraries/PancakeLibrary.sol +64 -0
- package/contracts/oracles/BoundValidator.sol +96 -0
- package/contracts/oracles/ChainlinkOracle.sol +178 -0
- package/contracts/oracles/PivotPythOracle.sol +18 -0
- package/contracts/oracles/PivotTwapOracle.sol +18 -0
- package/contracts/oracles/PythOracle.sol +129 -0
- package/contracts/oracles/TwapOracle.sol +234 -0
- package/contracts/oracles/mocks/MockChainlinkOracle.sol +26 -0
- package/contracts/oracles/mocks/MockPivotTwapOracle.sol +31 -0
- package/contracts/oracles/mocks/MockPythOracle.sol +31 -0
- package/contracts/test/BEP20Harness.sol +21 -0
- package/contracts/test/MockBoundValidator.sol +10 -0
- package/contracts/test/MockPyth.sol +78 -0
- package/contracts/test/MockSimpleOracle.sol +37 -0
- package/contracts/test/MockV3Aggregator.sol +91 -0
- package/contracts/test/PancakePairHarness.sol +113 -0
- package/contracts/test/VBEP20Harness.sol +22 -0
- package/package.json +4 -3
|
@@ -0,0 +1,96 @@
|
|
|
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 "@openzeppelin/contracts/utils/math/SafeMath.sol";
|
|
7
|
+
|
|
8
|
+
struct ValidateConfig {
|
|
9
|
+
/// @notice vToken address
|
|
10
|
+
address vToken;
|
|
11
|
+
/// @notice upper bound of deviation between reported price and anchor price,
|
|
12
|
+
/// beyond which the reported price will be invalidated
|
|
13
|
+
uint256 upperBoundRatio;
|
|
14
|
+
/// @notice lower bound of deviation between reported price and anchor price,
|
|
15
|
+
/// below which the reported price will be invalidated
|
|
16
|
+
uint256 lowerBoundRatio;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// BoundValidator provides some common functions and can be used
|
|
20
|
+
// to wrap up other contracts to form pivot oracles
|
|
21
|
+
contract BoundValidator is OwnableUpgradeable {
|
|
22
|
+
using SafeMath for uint256;
|
|
23
|
+
|
|
24
|
+
/// @notice validation configs by token
|
|
25
|
+
mapping(address => ValidateConfig) public validateConfigs;
|
|
26
|
+
|
|
27
|
+
/// @notice Emit this event when new validate configs are added
|
|
28
|
+
event ValidateConfigAdded(
|
|
29
|
+
address indexed vToken,
|
|
30
|
+
uint256 indexed upperBound,
|
|
31
|
+
uint256 indexed lowerBound
|
|
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
|
+
{
|
|
51
|
+
require(config.vToken != address(0), "vToken can't be zero address");
|
|
52
|
+
require(config.upperBoundRatio > 0 && config.lowerBoundRatio > 0, "bound must be positive");
|
|
53
|
+
require(config.upperBoundRatio > config.lowerBoundRatio, "upper bound must be higher than lowner bound");
|
|
54
|
+
validateConfigs[config.vToken] = config;
|
|
55
|
+
emit ValidateConfigAdded(
|
|
56
|
+
config.vToken,
|
|
57
|
+
config.upperBoundRatio,
|
|
58
|
+
config.lowerBoundRatio
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @notice Test reported vToken underlying price against anchor price
|
|
64
|
+
* @param vToken vToken address
|
|
65
|
+
* @param reporterPrice the price to be tested
|
|
66
|
+
*/
|
|
67
|
+
function validatePriceWithAnchorPrice(
|
|
68
|
+
address vToken,
|
|
69
|
+
uint256 reporterPrice,
|
|
70
|
+
uint256 anchorPrice) public view virtual returns (bool)
|
|
71
|
+
{
|
|
72
|
+
require(validateConfigs[vToken].upperBoundRatio != 0, "validation config not exist");
|
|
73
|
+
require(anchorPrice != 0, "anchor price is not valid");
|
|
74
|
+
return _isWithinAnchor(vToken, reporterPrice, anchorPrice);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @notice Test whether the reported price is within the predefined bounds
|
|
79
|
+
* @param vToken vToken address
|
|
80
|
+
* @param reporterPrice the price to be tested
|
|
81
|
+
* @param anchorPrice anchor price as testing anchor
|
|
82
|
+
*/
|
|
83
|
+
function _isWithinAnchor(address vToken, uint256 reporterPrice, uint256 anchorPrice) internal view returns (bool) {
|
|
84
|
+
if (reporterPrice > 0) {
|
|
85
|
+
uint256 anchorRatio = anchorPrice.mul(100e16).div(reporterPrice);
|
|
86
|
+
uint256 upperBoundAnchorRatio = validateConfigs[vToken].upperBoundRatio;
|
|
87
|
+
uint256 lowerBoundAnchorRatio = validateConfigs[vToken].lowerBoundRatio;
|
|
88
|
+
return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// BoundValidator is to get inherited, so it's a good practice to add some storage gaps like
|
|
94
|
+
// OpenZepplin proposed in their contracts: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
|
|
95
|
+
uint256[49] private __gap;
|
|
96
|
+
}
|
|
@@ -0,0 +1,178 @@
|
|
|
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 "@openzeppelin/contracts/utils/math/SafeMath.sol";
|
|
7
|
+
import "../interfaces/VBep20Interface.sol";
|
|
8
|
+
import "../interfaces/AggregatorV2V3Interface.sol";
|
|
9
|
+
import "../interfaces/OracleInterface.sol";
|
|
10
|
+
|
|
11
|
+
struct TokenConfig {
|
|
12
|
+
/// @notice vToken address, which can't be zero address and can be used for existance check
|
|
13
|
+
address vToken;
|
|
14
|
+
/// @notice chainlink feed address
|
|
15
|
+
address feed;
|
|
16
|
+
/// @notice expiration period of this asset
|
|
17
|
+
uint256 maxStalePeriod;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
contract ChainlinkOracle is OwnableUpgradeable, OracleInterface {
|
|
21
|
+
using SafeMath for uint256;
|
|
22
|
+
|
|
23
|
+
/// @notice VAI token is considered $1 constantly in oracle for now
|
|
24
|
+
uint256 public constant VAI_VALUE = 1e18;
|
|
25
|
+
|
|
26
|
+
/// @notice TODO: might be removed some day, it's for enabling us to force set the prices to
|
|
27
|
+
/// certain values in some urgent conditions
|
|
28
|
+
mapping(address => uint256) public prices;
|
|
29
|
+
|
|
30
|
+
/// @notice token config by assets
|
|
31
|
+
mapping(address => TokenConfig) public tokenConfigs;
|
|
32
|
+
|
|
33
|
+
/// @notice emit when forced price is set
|
|
34
|
+
event PricePosted(
|
|
35
|
+
address asset,
|
|
36
|
+
uint256 previousPriceMantissa,
|
|
37
|
+
uint256 requestedPriceMantissa,
|
|
38
|
+
uint256 newPriceMantissa
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
/// @notice emit when token config is added
|
|
42
|
+
event TokenConfigAdded(address vToken, address feed, uint256 maxStalePeriod);
|
|
43
|
+
|
|
44
|
+
modifier notNullAddress(address someone) {
|
|
45
|
+
require(someone != address(0), "can't be zero address");
|
|
46
|
+
_;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function initialize() public initializer {
|
|
50
|
+
__Ownable_init();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @notice Get the Chainlink price of underlying asset of input vToken, revert when vToken is zero address
|
|
55
|
+
* @param vToken vToken address
|
|
56
|
+
* @return price in USD, with 18 decimals
|
|
57
|
+
*/
|
|
58
|
+
function getUnderlyingPrice(address vToken) public view override
|
|
59
|
+
returns (uint256)
|
|
60
|
+
{
|
|
61
|
+
string memory symbol = VBep20Interface(vToken).symbol();
|
|
62
|
+
// VBNB token doesn't have `underlying` method, so it has to skip `_getUnderlyingPriceInternal
|
|
63
|
+
// method and directly goes into `_getChainlinkPrice`
|
|
64
|
+
if (_compareStrings(symbol, "vBNB")) {
|
|
65
|
+
return _getChainlinkPrice(vToken);
|
|
66
|
+
// VAI price is constantly 1 at the moment, but not guarantee in the future
|
|
67
|
+
} else if (_compareStrings(symbol, "VAI")) {
|
|
68
|
+
return VAI_VALUE;
|
|
69
|
+
// @TODO: This is some history code, keep it here in case of messing up
|
|
70
|
+
} else if (_compareStrings(symbol, "XVS")) {
|
|
71
|
+
return prices[address(vToken)];
|
|
72
|
+
} else {
|
|
73
|
+
return _getUnderlyingPriceInternal(VBep20Interface(vToken));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* @notice Get the Chainlink price of underlying asset of input vToken or cached price when it's been set
|
|
79
|
+
* @dev The decimals of underlying tokens is considered to ensure the returned prices are in 18 decimals
|
|
80
|
+
* @param vToken vToken address
|
|
81
|
+
* @return price in USD, with 18 decimals
|
|
82
|
+
*/
|
|
83
|
+
function _getUnderlyingPriceInternal(VBep20Interface vToken) internal view returns (uint256 price) {
|
|
84
|
+
VBep20Interface token = VBep20Interface(vToken.underlying());
|
|
85
|
+
|
|
86
|
+
if (prices[address(token)] != 0) {
|
|
87
|
+
price = prices[address(token)];
|
|
88
|
+
} else {
|
|
89
|
+
price = _getChainlinkPrice(address(vToken));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
uint256 decimalDelta = uint256(18).sub(uint256(token.decimals()));
|
|
93
|
+
return price.mul(10**decimalDelta);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @notice Get the Chainlink price of underlying asset of input vToken, revert if token config doesn't exit
|
|
98
|
+
* @dev The decimals of feeds are considered
|
|
99
|
+
* @param vToken vToken address
|
|
100
|
+
* @return price in USD, with 18 decimals
|
|
101
|
+
*/
|
|
102
|
+
function _getChainlinkPrice(address vToken)
|
|
103
|
+
internal view
|
|
104
|
+
notNullAddress(tokenConfigs[address(vToken)].vToken)
|
|
105
|
+
returns (uint256)
|
|
106
|
+
{
|
|
107
|
+
TokenConfig storage tokenConfig = tokenConfigs[vToken];
|
|
108
|
+
AggregatorV2V3Interface feed = AggregatorV2V3Interface(tokenConfig.feed);
|
|
109
|
+
|
|
110
|
+
// note: maxStalePeriod cannot be 0
|
|
111
|
+
uint256 maxStalePeriod = tokenConfig.maxStalePeriod;
|
|
112
|
+
|
|
113
|
+
// Chainlink USD-denominated feeds store answers at 8 decimals, mostly
|
|
114
|
+
uint256 decimalDelta = uint256(18).sub(feed.decimals());
|
|
115
|
+
|
|
116
|
+
(, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
|
|
117
|
+
require(answer > 0, "chainlink price must be positive");
|
|
118
|
+
|
|
119
|
+
uint256 deltaTime = block.timestamp.sub(updatedAt, "updatedAt exceeds block time");
|
|
120
|
+
require(deltaTime <= maxStalePeriod, "chainlink price expired");
|
|
121
|
+
|
|
122
|
+
return uint256(answer).mul(10**decimalDelta);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* @notice Set the forced prices of the underlying token of input vToken
|
|
127
|
+
* @param vToken vToken address
|
|
128
|
+
* @param underlyingPriceMantissa price in 18 decimals
|
|
129
|
+
*/
|
|
130
|
+
function setUnderlyingPrice(VBep20Interface vToken, uint256 underlyingPriceMantissa) external onlyOwner() {
|
|
131
|
+
address asset = address(vToken.underlying());
|
|
132
|
+
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
|
|
133
|
+
prices[asset] = underlyingPriceMantissa;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* @notice Set the forced prices of the input token
|
|
138
|
+
* @param asset asset address
|
|
139
|
+
* @param price price in 18 decimals
|
|
140
|
+
*/
|
|
141
|
+
function setDirectPrice(address asset, uint256 price) external onlyOwner() {
|
|
142
|
+
emit PricePosted(asset, prices[asset], price, price);
|
|
143
|
+
prices[asset] = price;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* @notice Add multiple token configs at the same time
|
|
148
|
+
* @param tokenConfigs_ config array
|
|
149
|
+
*/
|
|
150
|
+
function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner() {
|
|
151
|
+
require(tokenConfigs_.length > 0, "length can't be 0");
|
|
152
|
+
for (uint256 i = 0; i < tokenConfigs_.length; i++) {
|
|
153
|
+
setTokenConfig(tokenConfigs_[i]);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @notice Add single token config, vToken & feed cannot be zero address, and maxStalePeriod must be positive
|
|
159
|
+
* @param tokenConfig token config struct
|
|
160
|
+
*/
|
|
161
|
+
function setTokenConfig(TokenConfig memory tokenConfig) public
|
|
162
|
+
onlyOwner()
|
|
163
|
+
notNullAddress(tokenConfig.vToken)
|
|
164
|
+
notNullAddress(tokenConfig.feed)
|
|
165
|
+
{
|
|
166
|
+
require(tokenConfig.maxStalePeriod > 0, "stale period can't be zero");
|
|
167
|
+
tokenConfigs[tokenConfig.vToken] = tokenConfig;
|
|
168
|
+
emit TokenConfigAdded(
|
|
169
|
+
tokenConfig.vToken,
|
|
170
|
+
tokenConfig.feed,
|
|
171
|
+
tokenConfig.maxStalePeriod
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function _compareStrings(string memory a, string memory b) internal pure returns (bool) {
|
|
176
|
+
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
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 "./BoundValidator.sol";
|
|
7
|
+
import "./PythOracle.sol";
|
|
8
|
+
|
|
9
|
+
contract PivotPythOracle is PythOracle, BoundValidator, PivotOracleInterface {
|
|
10
|
+
/**
|
|
11
|
+
* @notice Test reported vToken underlying price against stored TWAP
|
|
12
|
+
* @param vToken vToken address
|
|
13
|
+
* @param reporterPrice the price to be tested
|
|
14
|
+
*/
|
|
15
|
+
function validatePrice(address vToken, uint256 reporterPrice) external view override returns (bool) {
|
|
16
|
+
return validatePriceWithAnchorPrice(vToken, reporterPrice, getUnderlyingPrice(vToken));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
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 "./BoundValidator.sol";
|
|
7
|
+
import "./TwapOracle.sol";
|
|
8
|
+
|
|
9
|
+
contract PivotTwapOracle is TwapOracle, BoundValidator, PivotOracleInterface {
|
|
10
|
+
/**
|
|
11
|
+
* @notice Test reported vToken underlying price against stored TWAP
|
|
12
|
+
* @param vToken vToken address
|
|
13
|
+
* @param reporterPrice the price to be tested
|
|
14
|
+
*/
|
|
15
|
+
function validatePrice(address vToken, uint256 reporterPrice) external view override returns (bool) {
|
|
16
|
+
return validatePriceWithAnchorPrice(vToken, reporterPrice, prices[vToken]);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -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
|
+
|
|
11
|
+
struct TokenConfig {
|
|
12
|
+
bytes32 pythId;
|
|
13
|
+
address vToken;
|
|
14
|
+
uint64 maxStalePeriod;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* PythOracle contract reads prices from actual Pyth oracle contract which accepts/verifies and stores the
|
|
19
|
+
* updated prices from external sources
|
|
20
|
+
*/
|
|
21
|
+
contract PythOracle is OwnableUpgradeable, OracleInterface {
|
|
22
|
+
using SafeMath for uint256;
|
|
23
|
+
|
|
24
|
+
// To calculate 10 ** n(which is a signed type)
|
|
25
|
+
using SignedMath for int256;
|
|
26
|
+
|
|
27
|
+
// To cast int64/int8 types from Pyth to unsigned types
|
|
28
|
+
using SafeCast for int256;
|
|
29
|
+
|
|
30
|
+
/// @notice price decimals
|
|
31
|
+
uint256 public constant EXP_SCALE = 1e18;
|
|
32
|
+
|
|
33
|
+
/// @notice the actual pyth oracle address fetch & store the prices
|
|
34
|
+
IPyth public underlyingPythOracle;
|
|
35
|
+
|
|
36
|
+
/// @notice emit when setting a new pyth oracle address
|
|
37
|
+
event PythOracleSet(address indexed newPythOracle);
|
|
38
|
+
|
|
39
|
+
/// @notice emit when token config added
|
|
40
|
+
event TokenConfigAdded(
|
|
41
|
+
address indexed vToken,
|
|
42
|
+
bytes32 indexed pythId,
|
|
43
|
+
uint64 indexed maxStalePeriod
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
/// @notice token configs by vToken address
|
|
47
|
+
mapping(address => TokenConfig) public tokenConfigs;
|
|
48
|
+
|
|
49
|
+
modifier notNullAddress(address someone) {
|
|
50
|
+
require(someone != address(0), "can't be zero address");
|
|
51
|
+
_;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function initialize(address underlyingPythOracle_) public initializer {
|
|
55
|
+
__Ownable_init();
|
|
56
|
+
require(underlyingPythOracle_ != address(0), "pyth oracle cannot be zero address");
|
|
57
|
+
underlyingPythOracle = IPyth(underlyingPythOracle_);
|
|
58
|
+
emit PythOracleSet(underlyingPythOracle_);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @notice Batch set token configs
|
|
63
|
+
* @param tokenConfigs_ token config array
|
|
64
|
+
*/
|
|
65
|
+
function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner() {
|
|
66
|
+
require(tokenConfigs_.length != 0, "length can't be 0");
|
|
67
|
+
for (uint256 i = 0; i < tokenConfigs_.length; i++) {
|
|
68
|
+
setTokenConfig(tokenConfigs_[i]);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @notice Set single token config, `maxStalePeriod` cannot be 0 and `vToken` can be zero address
|
|
74
|
+
* @param tokenConfig token config struct
|
|
75
|
+
*/
|
|
76
|
+
function setTokenConfig(TokenConfig memory tokenConfig) public
|
|
77
|
+
onlyOwner()
|
|
78
|
+
notNullAddress(tokenConfig.vToken)
|
|
79
|
+
{
|
|
80
|
+
require(tokenConfig.maxStalePeriod != 0, "max stale period cannot be 0");
|
|
81
|
+
tokenConfigs[tokenConfig.vToken] = tokenConfig;
|
|
82
|
+
emit TokenConfigAdded(tokenConfig.vToken, tokenConfig.pythId, tokenConfig.maxStalePeriod);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @notice set the underlying pyth oracle contract address
|
|
87
|
+
* @param underlyingPythOracle_ pyth oracle contract address
|
|
88
|
+
*/
|
|
89
|
+
function setUnderlyingPythOracle(IPyth underlyingPythOracle_)
|
|
90
|
+
external
|
|
91
|
+
onlyOwner()
|
|
92
|
+
notNullAddress(address(underlyingPythOracle_))
|
|
93
|
+
{
|
|
94
|
+
underlyingPythOracle = underlyingPythOracle_;
|
|
95
|
+
emit PythOracleSet(address(underlyingPythOracle_));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @notice Get price of underlying asset of the input vToken, under the hood this function
|
|
100
|
+
* get price from Pyth contract, the prices of which are updated externally
|
|
101
|
+
* @param vToken vToken address
|
|
102
|
+
* @return price in 10 decimals
|
|
103
|
+
*/
|
|
104
|
+
function getUnderlyingPrice(address vToken) public view override returns (uint256) {
|
|
105
|
+
require(address(underlyingPythOracle) != address(0), "Pyth oracle is zero address");
|
|
106
|
+
TokenConfig storage tokenConfig = tokenConfigs[vToken];
|
|
107
|
+
require(tokenConfig.vToken != address(0), "vToken doesn't exist");
|
|
108
|
+
|
|
109
|
+
// if the price is expired after it's compared against `maxStalePeriod`, the following call will revert
|
|
110
|
+
PythStructs.Price memory priceInfo = underlyingPythOracle.getLatestAvailablePriceWithinDuration(
|
|
111
|
+
tokenConfig.pythId,
|
|
112
|
+
tokenConfig.maxStalePeriod
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
uint256 price = int256(priceInfo.price).toUint256();
|
|
116
|
+
|
|
117
|
+
require(price > 0, "Pyth oracle price must be positive");
|
|
118
|
+
|
|
119
|
+
// the price returned from Pyth is price ** 10^expo, which is the real dollar price of the assets
|
|
120
|
+
// we need to multiply it by 1e18 to make the price 18 decimals
|
|
121
|
+
if (priceInfo.expo > 0) {
|
|
122
|
+
return price.mul(EXP_SCALE).mul(10 ** int256(priceInfo.expo).toUint256());
|
|
123
|
+
} else {
|
|
124
|
+
return price.mul(EXP_SCALE).div(10 ** int256(-priceInfo.expo).toUint256());
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
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 "@openzeppelin/contracts/utils/math/SafeMath.sol";
|
|
7
|
+
import "../libraries/PancakeLibrary.sol";
|
|
8
|
+
import "../interfaces/OracleInterface.sol";
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
struct Observation {
|
|
12
|
+
uint256 timestamp;
|
|
13
|
+
uint256 acc;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
struct TokenConfig {
|
|
17
|
+
/// @notice vToken address, which can't be zero address and can be used for existance check
|
|
18
|
+
address vToken;
|
|
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, OracleInterface {
|
|
33
|
+
using SafeMath for uint256;
|
|
34
|
+
using FixedPoint for *;
|
|
35
|
+
|
|
36
|
+
/// @notice vBNB address
|
|
37
|
+
address public vBNB;
|
|
38
|
+
|
|
39
|
+
/// @notice the base unit of WBNB and BUSD, which are the paired tokens for all assets
|
|
40
|
+
uint256 public constant bnbBaseUnit = 1e18;
|
|
41
|
+
uint256 public constant busdBaseUnit = 1e18;
|
|
42
|
+
|
|
43
|
+
uint256 public constant expScale = 1e18;
|
|
44
|
+
|
|
45
|
+
/// @notice Configs by token
|
|
46
|
+
mapping(address => TokenConfig) public tokenConfigs;
|
|
47
|
+
|
|
48
|
+
/// @notice The current price observation of TWAP. With old and current observations
|
|
49
|
+
/// we can calculate the TWAP between this range
|
|
50
|
+
mapping(address => Observation) public newObservations;
|
|
51
|
+
|
|
52
|
+
/// @notice The old price observation of TWAP
|
|
53
|
+
mapping(address => Observation) public oldObservations;
|
|
54
|
+
|
|
55
|
+
/// @notice Stored price by token
|
|
56
|
+
mapping(address => uint256) public prices;
|
|
57
|
+
|
|
58
|
+
/// @notice Emit this event when TWAP window is updated
|
|
59
|
+
event TwapWindowUpdated(
|
|
60
|
+
address indexed vToken,
|
|
61
|
+
uint256 oldTimestamp,
|
|
62
|
+
uint256 oldAcc,
|
|
63
|
+
uint256 newTimestamp,
|
|
64
|
+
uint256 newAcc);
|
|
65
|
+
|
|
66
|
+
/// @notice Emit this event when TWAP price is updated
|
|
67
|
+
event AnchorPriceUpdated(
|
|
68
|
+
address indexed vToken,
|
|
69
|
+
uint256 price,
|
|
70
|
+
uint256 oldTimestamp,
|
|
71
|
+
uint256 newTimestamp
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
/// @notice Emit this event when new token configs are added
|
|
75
|
+
event TokenConfigAdded(
|
|
76
|
+
address indexed vToken,
|
|
77
|
+
address indexed pancakePool,
|
|
78
|
+
uint256 indexed anchorPeriod
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
modifier notNullAddress(address someone) {
|
|
82
|
+
require(someone != address(0), "can't be zero address");
|
|
83
|
+
_;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function initialize(address vBNB_) public initializer {
|
|
87
|
+
__Ownable_init();
|
|
88
|
+
require(vBNB_ != address(0), "vBNB can't be zero address");
|
|
89
|
+
vBNB = vBNB_;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* @notice Add multiple token configs at the same time
|
|
94
|
+
* @param configs config array
|
|
95
|
+
*/
|
|
96
|
+
function setTokenConfigs(TokenConfig[] memory configs) external onlyOwner() {
|
|
97
|
+
require(configs.length > 0, "length can't be 0");
|
|
98
|
+
for (uint8 i = 0; i < configs.length; i++) {
|
|
99
|
+
setTokenConfig(configs[i]);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @notice Add single token configs
|
|
105
|
+
* @param config token config struct
|
|
106
|
+
*/
|
|
107
|
+
function setTokenConfig(TokenConfig memory config) public
|
|
108
|
+
onlyOwner()
|
|
109
|
+
notNullAddress(config.vToken)
|
|
110
|
+
notNullAddress(config.pancakePool)
|
|
111
|
+
{
|
|
112
|
+
require(config.anchorPeriod > 0, "anchor period must be positive");
|
|
113
|
+
require(config.baseUnit > 0, "base unit must be positive");
|
|
114
|
+
uint256 cumulativePrice = currentCumulativePrice(config);
|
|
115
|
+
|
|
116
|
+
// Initialize observation data
|
|
117
|
+
oldObservations[config.vToken].timestamp = block.timestamp;
|
|
118
|
+
newObservations[config.vToken].timestamp = block.timestamp;
|
|
119
|
+
oldObservations[config.vToken].acc = cumulativePrice;
|
|
120
|
+
newObservations[config.vToken].acc = cumulativePrice;
|
|
121
|
+
tokenConfigs[config.vToken] = config;
|
|
122
|
+
emit TokenConfigAdded(
|
|
123
|
+
config.vToken,
|
|
124
|
+
config.pancakePool,
|
|
125
|
+
config.anchorPeriod
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* @notice Get the underlying TWAP price of input vToken
|
|
131
|
+
* @param vToken vToken address
|
|
132
|
+
* @return price in USD, with 18 decimals
|
|
133
|
+
*/
|
|
134
|
+
function getUnderlyingPrice(address vToken) external override view returns (uint256) {
|
|
135
|
+
require(tokenConfigs[vToken].vToken != address(0), "vToken not exist");
|
|
136
|
+
uint256 price = prices[vToken];
|
|
137
|
+
|
|
138
|
+
// if price is 0, it means the price hasn't been updated yet and it's meaningless, revert
|
|
139
|
+
require(price > 0, "TWAP price must be positive");
|
|
140
|
+
return price;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* @notice Fetches the current token/WBNB and token/BUSD price accumulator from pancakeswap.
|
|
145
|
+
* @return cumulative price of target token regardless of pair order
|
|
146
|
+
*/
|
|
147
|
+
function currentCumulativePrice(TokenConfig memory config) public view returns (uint256) {
|
|
148
|
+
(uint256 price0, uint256 price1,) = PancakeOracleLibrary.currentCumulativePrices(config.pancakePool);
|
|
149
|
+
if (config.isReversedPool) {
|
|
150
|
+
return price1;
|
|
151
|
+
} else {
|
|
152
|
+
return price0;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function updateTwap(address vToken) public returns (uint256) {
|
|
157
|
+
require(tokenConfigs[vToken].vToken != address(0), "vTokne not exist");
|
|
158
|
+
// Update & fetch WBNB price first, so we can calculate the price of WBNB paired token
|
|
159
|
+
if (vToken != vBNB && tokenConfigs[vToken].isBnbBased) {
|
|
160
|
+
updateTwap(vBNB);
|
|
161
|
+
}
|
|
162
|
+
return _updateTwapInternal(tokenConfigs[vToken]);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.
|
|
167
|
+
* @return price in USD, with 18 decimals
|
|
168
|
+
*/
|
|
169
|
+
function _updateTwapInternal(TokenConfig memory config) internal virtual returns (uint256) {
|
|
170
|
+
// pokeWindowValues already handled reversed pool cases,
|
|
171
|
+
// priceAverage will always be Token/BNB or Token/BUSD TWAP price.
|
|
172
|
+
(uint256 nowCumulativePrice, uint256 oldCumulativePrice, uint256 oldTimestamp) = pokeWindowValues(config);
|
|
173
|
+
|
|
174
|
+
// This should be impossible, but better safe than sorry
|
|
175
|
+
require(block.timestamp > oldTimestamp, "now must come after before");
|
|
176
|
+
uint256 timeElapsed = block.timestamp.sub(oldTimestamp);
|
|
177
|
+
|
|
178
|
+
// Calculate Pancakge TWAP
|
|
179
|
+
FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224(
|
|
180
|
+
nowCumulativePrice.sub(oldCumulativePrice).div(timeElapsed)
|
|
181
|
+
));
|
|
182
|
+
// TWAP price with 1e18 decimal mantissa
|
|
183
|
+
uint256 priceAverageMantissa = priceAverage.decode112with18();
|
|
184
|
+
|
|
185
|
+
// To cancel the decimals in cumulative price, we need to mulitply the average price with
|
|
186
|
+
// tokenBaseUnit / (wbnbBaseUnit or busdBaseUnit, which is 1e18)
|
|
187
|
+
uint256 pairedTokenBaseUnit = config.isBnbBased ? bnbBaseUnit : busdBaseUnit;
|
|
188
|
+
uint256 anchorPriceMantissa = priceAverageMantissa.mul(config.baseUnit).div(pairedTokenBaseUnit);
|
|
189
|
+
|
|
190
|
+
// if this token is paired with BNB, convert its price to USD
|
|
191
|
+
if (config.isBnbBased) {
|
|
192
|
+
uint256 bnbPrice = prices[vBNB];
|
|
193
|
+
require(bnbPrice != 0, "bnb price is invalid");
|
|
194
|
+
anchorPriceMantissa = anchorPriceMantissa.mul(bnbPrice).div(bnbBaseUnit);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
require(anchorPriceMantissa != 0, "twap price cannot be 0");
|
|
198
|
+
|
|
199
|
+
emit AnchorPriceUpdated(config.vToken, anchorPriceMantissa, oldTimestamp, block.timestamp);
|
|
200
|
+
|
|
201
|
+
// save anchor price, which is 1e18 decimals
|
|
202
|
+
prices[config.vToken] = anchorPriceMantissa;
|
|
203
|
+
|
|
204
|
+
return anchorPriceMantissa;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* @notice Update new and old observations of lagging window if period elapsed.
|
|
209
|
+
* @return cumulative price & old observation
|
|
210
|
+
*/
|
|
211
|
+
function pokeWindowValues(TokenConfig memory config) internal returns (uint256, uint256, uint256) {
|
|
212
|
+
uint256 cumulativePrice = currentCumulativePrice(config);
|
|
213
|
+
|
|
214
|
+
Observation memory newObservation = newObservations[config.vToken];
|
|
215
|
+
|
|
216
|
+
// Update new and old observations if elapsed time is greater than or equal to anchor period
|
|
217
|
+
uint256 timeElapsed = block.timestamp.sub(newObservation.timestamp);
|
|
218
|
+
if (timeElapsed >= config.anchorPeriod) {
|
|
219
|
+
oldObservations[config.vToken].timestamp = newObservation.timestamp;
|
|
220
|
+
oldObservations[config.vToken].acc = newObservation.acc;
|
|
221
|
+
|
|
222
|
+
newObservations[config.vToken].timestamp = block.timestamp;
|
|
223
|
+
newObservations[config.vToken].acc = cumulativePrice;
|
|
224
|
+
emit TwapWindowUpdated(
|
|
225
|
+
config.vToken,
|
|
226
|
+
newObservation.timestamp,
|
|
227
|
+
block.timestamp,
|
|
228
|
+
newObservation.acc,
|
|
229
|
+
cumulativePrice
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
return (cumulativePrice, oldObservations[config.vToken].acc, oldObservations[config.vToken].timestamp);
|
|
233
|
+
}
|
|
234
|
+
}
|