@venusprotocol/oracle 1.0.0-dev.1 → 1.0.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/@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol/AggregatorInterface.dbg.json +4 -0
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol/AggregatorInterface.json +138 -0
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol/AggregatorV2V3Interface.dbg.json +4 -0
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol/AggregatorV2V3Interface.json +249 -0
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol/AggregatorV3Interface.dbg.json +4 -0
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol/AggregatorV3Interface.json +122 -0
- package/artifacts/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.json +215 -0
- package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.json +183 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/ERC20.sol/ERC20.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/ERC20.sol/ERC20.json +297 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/IERC20.sol/IERC20.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/IERC20.sol/IERC20.json +194 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol/IERC20Metadata.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol/IERC20Metadata.json +233 -0
- package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.json +10 -0
- package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.json +10 -0
- package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.json +30 -0
- package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.json +30 -0
- package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.json +10 -0
- package/artifacts/@openzeppelin/contracts/utils/math/SafeCast.sol/SafeCast.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/math/SafeCast.sol/SafeCast.json +10 -0
- package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.json +10 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol/Ownable2StepUpgradeable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol/Ownable2StepUpgradeable.json +115 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol/OwnableUpgradeable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol/OwnableUpgradeable.json +76 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol/Initializable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol/Initializable.json +24 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol/PausableUpgradeable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol/PausableUpgradeable.json +63 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol/AddressUpgradeable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol/AddressUpgradeable.json +10 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol/ContextUpgradeable.dbg.json +4 -0
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol/ContextUpgradeable.json +24 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlManager.sol/AccessControlManager.dbg.json +4 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlManager.sol/AccessControlManager.json +369 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol/AccessControlledV8.dbg.json +4 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol/AccessControlledV8.json +181 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol/IAccessControlManagerV8.dbg.json +4 -0
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol/IAccessControlManagerV8.json +282 -0
- package/artifacts/build-info/0137d0ff3ae413641739f9f6322cc2b3.json +1 -0
- package/artifacts/contracts/ResilientOracle.sol/ResilientOracle.dbg.json +4 -0
- package/artifacts/contracts/ResilientOracle.sol/ResilientOracle.json +617 -0
- package/artifacts/contracts/interfaces/FeedRegistryInterface.sol/FeedRegistryInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/FeedRegistryInterface.sol/FeedRegistryInterface.json +79 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/BoundValidatorInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/BoundValidatorInterface.json +40 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/OracleInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/OracleInterface.json +30 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/ResilientOracleInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/ResilientOracleInterface.json +43 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/TwapInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/OracleInterface.sol/TwapInterface.json +49 -0
- package/artifacts/contracts/interfaces/PublicResolverInterface.sol/PublicResolverInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/PublicResolverInterface.sol/PublicResolverInterface.json +30 -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 +4 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.json +446 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.dbg.json +4 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.json +10 -0
- package/artifacts/contracts/interfaces/SIDRegistryInterface.sol/SIDRegistryInterface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/SIDRegistryInterface.sol/SIDRegistryInterface.json +30 -0
- package/artifacts/contracts/interfaces/VBep20Interface.sol/VBep20Interface.dbg.json +4 -0
- package/artifacts/contracts/interfaces/VBep20Interface.sol/VBep20Interface.json +246 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/FixedPoint.dbg.json +4 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/FixedPoint.json +10 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/IPancakePair.dbg.json +4 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/IPancakePair.json +60 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/PancakeOracleLibrary.dbg.json +4 -0
- package/artifacts/contracts/libraries/PancakeLibrary.sol/PancakeOracleLibrary.json +10 -0
- package/artifacts/contracts/oracles/BinanceOracle.sol/BinanceOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/BinanceOracle.sol/BinanceOracle.json +342 -0
- package/artifacts/contracts/oracles/BoundValidator.sol/BoundValidator.dbg.json +4 -0
- package/artifacts/contracts/oracles/BoundValidator.sol/BoundValidator.json +392 -0
- package/artifacts/contracts/oracles/ChainlinkOracle.sol/ChainlinkOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/ChainlinkOracle.sol/ChainlinkOracle.json +462 -0
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.json +445 -0
- package/artifacts/contracts/oracles/TwapOracle.sol/TwapOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/TwapOracle.sol/TwapOracle.json +663 -0
- package/artifacts/contracts/oracles/mocks/MockBinanceFeedRegistry.sol/MockBinanceFeedRegistry.dbg.json +4 -0
- package/artifacts/contracts/oracles/mocks/MockBinanceFeedRegistry.sol/MockBinanceFeedRegistry.json +116 -0
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.json +144 -0
- package/artifacts/contracts/oracles/mocks/MockChainlinkOracle.sol/MockChainlinkOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/mocks/MockChainlinkOracle.sol/MockChainlinkOracle.json +144 -0
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.json +163 -0
- package/artifacts/contracts/oracles/mocks/MockTwapOracle.sol/MockTwapOracle.dbg.json +4 -0
- package/artifacts/contracts/oracles/mocks/MockTwapOracle.sol/MockTwapOracle.json +163 -0
- package/artifacts/contracts/test/AccessControlManager.sol/AccessControlManagerScenario.dbg.json +4 -0
- package/artifacts/contracts/test/AccessControlManager.sol/AccessControlManagerScenario.json +364 -0
- package/artifacts/contracts/test/BEP20Harness.sol/BEP20Harness.dbg.json +4 -0
- package/artifacts/contracts/test/BEP20Harness.sol/BEP20Harness.json +328 -0
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.dbg.json +4 -0
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.json +684 -0
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockBoundValidator.dbg.json +4 -0
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockBoundValidator.json +95 -0
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockSimpleOracle.dbg.json +4 -0
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockSimpleOracle.json +72 -0
- package/artifacts/contracts/test/MockV3Aggregator.sol/MockV3Aggregator.dbg.json +4 -0
- package/artifacts/contracts/test/MockV3Aggregator.sol/MockV3Aggregator.json +306 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/Math.dbg.json +4 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/Math.json +10 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/PancakePairHarness.dbg.json +4 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/PancakePairHarness.json +158 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/UQ112x112.dbg.json +4 -0
- package/artifacts/contracts/test/PancakePairHarness.sol/UQ112x112.json +10 -0
- package/artifacts/contracts/test/VBEP20Harness.sol/VBEP20Harness.dbg.json +4 -0
- package/artifacts/contracts/test/VBEP20Harness.sol/VBEP20Harness.json +346 -0
- package/contracts/ResilientOracle.sol +35 -27
- package/contracts/interfaces/PythInterface.sol +4 -1
- package/contracts/oracles/BinanceOracle.sol +29 -24
- package/contracts/oracles/BoundValidator.sol +41 -44
- package/contracts/oracles/ChainlinkOracle.sol +44 -40
- package/contracts/oracles/PythOracle.sol +39 -34
- package/contracts/oracles/TwapOracle.sol +69 -65
- package/contracts/test/BEP20Harness.sol +4 -0
- package/contracts/test/MockPyth.sol +9 -2
- package/deployments/bscmainnet/BinanceOracle.json +279 -37
- package/deployments/bscmainnet/BinanceOracle_Implementation.json +399 -29
- package/deployments/bscmainnet/BinanceOracle_Proxy.json +58 -34
- package/deployments/bscmainnet/BoundValidator.json +50 -50
- package/deployments/bscmainnet/BoundValidator_Implementation.json +47 -55
- package/deployments/bscmainnet/BoundValidator_Proxy.json +46 -46
- package/deployments/bscmainnet/ChainlinkOracle.json +57 -49
- package/deployments/bscmainnet/ChainlinkOracle_Implementation.json +48 -54
- package/deployments/bscmainnet/ChainlinkOracle_Proxy.json +53 -39
- package/deployments/bscmainnet/DefaultProxyAdmin.json +16 -16
- package/deployments/bscmainnet/PythOracle.json +64 -57
- package/deployments/bscmainnet/PythOracle_Implementation.json +57 -51
- package/deployments/bscmainnet/PythOracle_Proxy.json +54 -53
- package/deployments/bscmainnet/ResilientOracle.json +57 -48
- package/deployments/bscmainnet/ResilientOracle_Implementation.json +67 -70
- package/deployments/bscmainnet/ResilientOracle_Proxy.json +54 -40
- package/deployments/bscmainnet/TwapOracle.json +69 -82
- package/deployments/bscmainnet/TwapOracle_Implementation.json +85 -98
- package/deployments/bscmainnet/TwapOracle_Proxy.json +46 -46
- package/deployments/bscmainnet/solcInputs/{8658c669dade0e9ab80874eab3bf3468.json → aae9f1601b873a5a4704ede73ede10cb.json} +37 -19
- package/deployments/bsctestnet/BinanceOracle.json +35 -35
- package/deployments/bsctestnet/BinanceOracle_Implementation.json +31 -31
- package/deployments/bsctestnet/BinanceOracle_Proxy.json +33 -33
- package/deployments/bsctestnet/BoundValidator.json +36 -36
- package/deployments/bsctestnet/BoundValidator_Implementation.json +44 -52
- package/deployments/bsctestnet/BoundValidator_Proxy.json +33 -33
- package/deployments/bsctestnet/ChainlinkOracle.json +36 -42
- package/deployments/bsctestnet/ChainlinkOracle_Implementation.json +42 -48
- package/deployments/bsctestnet/ChainlinkOracle_Proxy.json +33 -33
- package/deployments/bsctestnet/DefaultProxyAdmin.json +11 -11
- package/deployments/bsctestnet/PythOracle.json +48 -41
- package/deployments/bsctestnet/PythOracle_Implementation.json +51 -45
- package/deployments/bsctestnet/PythOracle_Proxy.json +39 -38
- package/deployments/bsctestnet/ResilientOracle.json +36 -41
- package/deployments/bsctestnet/ResilientOracle_Implementation.json +63 -66
- package/deployments/bsctestnet/ResilientOracle_Proxy.json +34 -34
- package/deployments/bsctestnet/TwapOracle.json +56 -56
- package/deployments/bsctestnet/TwapOracle_Implementation.json +81 -81
- package/deployments/bsctestnet/TwapOracle_Proxy.json +33 -33
- package/deployments/bsctestnet/solcInputs/{f35da22a430a956ee338e720b5898e3d.json → 131f58942628e21632de19506977a910.json} +7 -13
- package/deployments/bsctestnet/solcInputs/{4769dd98af512bf3b6b6504ad0c3bd74.json → 144b49e8aec3add79553ba273ea32d00.json} +4 -10
- package/deployments/bsctestnet/solcInputs/503f2e4e766f3be923fadf8030a5470f.json +78 -0
- package/deployments/bsctestnet/solcInputs/b39d33092f7dd383ae3a042566194132.json +75 -0
- package/dist/deploy/1-deploy-oracles.d.ts +5 -0
- package/dist/deploy/1-deploy-oracles.d.ts.map +1 -0
- package/dist/deploy/1-deploy-oracles.js +186 -0
- package/dist/deploy/1-deploy-oracles.js.map +1 -0
- package/dist/deploy/2-configure-feeds.d.ts +15 -0
- package/dist/deploy/2-configure-feeds.d.ts.map +1 -0
- package/dist/deploy/2-configure-feeds.js +300 -0
- package/dist/deploy/2-configure-feeds.js.map +1 -0
- package/dist/hardhat.config.d.ts +13 -0
- package/dist/hardhat.config.d.ts.map +1 -0
- package/dist/hardhat.config.js +158 -0
- package/dist/hardhat.config.js.map +1 -0
- package/package.json +2 -15
- package/deploy/1-deploy-oracles.ts +0 -195
- package/deploy/2-configure-feeds.ts +0 -324
- package/deployments/bscmainnet/solcInputs/68ea814c0d6925581f2bda5deba8ce4a.json +0 -60
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"address": "
|
|
2
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
3
3
|
"abi": [
|
|
4
4
|
{
|
|
5
5
|
"inputs": [
|
|
@@ -133,35 +133,35 @@
|
|
|
133
133
|
"type": "receive"
|
|
134
134
|
}
|
|
135
135
|
],
|
|
136
|
-
"transactionHash": "
|
|
136
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
137
137
|
"receipt": {
|
|
138
138
|
"to": null,
|
|
139
139
|
"from": "0x8BDA9f9E1fEF0DFd404Fef338D9fE4c543d172e1",
|
|
140
|
-
"contractAddress": "
|
|
140
|
+
"contractAddress": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
141
141
|
"transactionIndex": 0,
|
|
142
|
-
"gasUsed": "
|
|
143
|
-
"logsBloom": "
|
|
144
|
-
"blockHash": "
|
|
145
|
-
"transactionHash": "
|
|
142
|
+
"gasUsed": "696602",
|
|
143
|
+
"logsBloom": "0x00000000000000000000000000000000400000000000000000800000000000000000000000000000000004000000000000000000000000000000000000008000000000000000000000000000000002000001040000000080000000000000000000000000020000000000000200000800000000800000000000000000000000400000000000000000000000000000000080000000000080000000000000804000000000000000000010000000000400000000000000800000000000000000200000000020000000000200000000040000000000000400000000000000000020000000000000000000000000000000000000000800000000000000000000000000",
|
|
144
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae",
|
|
145
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
146
146
|
"logs": [
|
|
147
147
|
{
|
|
148
148
|
"transactionIndex": 0,
|
|
149
|
-
"blockNumber":
|
|
150
|
-
"transactionHash": "
|
|
151
|
-
"address": "
|
|
149
|
+
"blockNumber": 30137623,
|
|
150
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
151
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
152
152
|
"topics": [
|
|
153
153
|
"0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b",
|
|
154
|
-
"
|
|
154
|
+
"0x000000000000000000000000a65d9c3593b8ca0ef4c475e16eb93f92ca81f98b"
|
|
155
155
|
],
|
|
156
156
|
"data": "0x",
|
|
157
157
|
"logIndex": 0,
|
|
158
|
-
"blockHash": "
|
|
158
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae"
|
|
159
159
|
},
|
|
160
160
|
{
|
|
161
161
|
"transactionIndex": 0,
|
|
162
|
-
"blockNumber":
|
|
163
|
-
"transactionHash": "
|
|
164
|
-
"address": "
|
|
162
|
+
"blockNumber": 30137623,
|
|
163
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
164
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
165
165
|
"topics": [
|
|
166
166
|
"0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0",
|
|
167
167
|
"0x0000000000000000000000000000000000000000000000000000000000000000",
|
|
@@ -169,47 +169,47 @@
|
|
|
169
169
|
],
|
|
170
170
|
"data": "0x",
|
|
171
171
|
"logIndex": 1,
|
|
172
|
-
"blockHash": "
|
|
172
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae"
|
|
173
173
|
},
|
|
174
174
|
{
|
|
175
175
|
"transactionIndex": 0,
|
|
176
|
-
"blockNumber":
|
|
177
|
-
"transactionHash": "
|
|
178
|
-
"address": "
|
|
176
|
+
"blockNumber": 30137623,
|
|
177
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
178
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
179
179
|
"topics": ["0x66fd58e82f7b31a2a5c30e0888f3093efe4e111b00cd2b0c31fe014601293aa0"],
|
|
180
180
|
"data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045f8a08f534f34a97187626e05d4b6648eeaa9aa",
|
|
181
181
|
"logIndex": 2,
|
|
182
|
-
"blockHash": "
|
|
182
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae"
|
|
183
183
|
},
|
|
184
184
|
{
|
|
185
185
|
"transactionIndex": 0,
|
|
186
|
-
"blockNumber":
|
|
187
|
-
"transactionHash": "
|
|
188
|
-
"address": "
|
|
186
|
+
"blockNumber": 30137623,
|
|
187
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
188
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
189
189
|
"topics": ["0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498"],
|
|
190
190
|
"data": "0x0000000000000000000000000000000000000000000000000000000000000001",
|
|
191
191
|
"logIndex": 3,
|
|
192
|
-
"blockHash": "
|
|
192
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae"
|
|
193
193
|
},
|
|
194
194
|
{
|
|
195
195
|
"transactionIndex": 0,
|
|
196
|
-
"blockNumber":
|
|
197
|
-
"transactionHash": "
|
|
198
|
-
"address": "
|
|
196
|
+
"blockNumber": 30137623,
|
|
197
|
+
"transactionHash": "0x3efb22545b047f193a166c3fe9575bb2ec0142f23bdbb87a63eb9a4805ecbc18",
|
|
198
|
+
"address": "0x3eeE05d929D1E9816185B1b6d8c470eC192b4432",
|
|
199
199
|
"topics": ["0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f"],
|
|
200
|
-
"data": "
|
|
200
|
+
"data": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ef480a5654b231ff7d80a0681f938f3db71a6ca6",
|
|
201
201
|
"logIndex": 4,
|
|
202
|
-
"blockHash": "
|
|
202
|
+
"blockHash": "0x6e074a9560e1a6b6abc2011ef72c0a87dbfada6a95c5f34624def3b2c13585ae"
|
|
203
203
|
}
|
|
204
204
|
],
|
|
205
|
-
"blockNumber":
|
|
206
|
-
"cumulativeGasUsed": "
|
|
205
|
+
"blockNumber": 30137623,
|
|
206
|
+
"cumulativeGasUsed": "696602",
|
|
207
207
|
"status": 1,
|
|
208
208
|
"byzantium": true
|
|
209
209
|
},
|
|
210
210
|
"args": [
|
|
211
|
-
"
|
|
212
|
-
"
|
|
211
|
+
"0xA65d9c3593B8ca0EF4C475E16Eb93f92Ca81F98B",
|
|
212
|
+
"0xef480a5654b231ff7d80A0681F938f3Db71a6Ca6",
|
|
213
213
|
"0xc4d66de800000000000000000000000045f8a08f534f34a97187626e05d4b6648eeaa9aa"
|
|
214
214
|
],
|
|
215
215
|
"numDeployments": 1,
|
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"language": "Solidity",
|
|
3
3
|
"sources": {
|
|
4
|
-
"@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol": {
|
|
5
|
-
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorInterface {\n function latestAnswer() external view returns (int256);\n\n function latestTimestamp() external view returns (uint256);\n\n function latestRound() external view returns (uint256);\n\n function getAnswer(uint256 roundId) external view returns (int256);\n\n function getTimestamp(uint256 roundId) external view returns (uint256);\n\n event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);\n\n event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n}\n"
|
|
6
|
-
},
|
|
7
|
-
"@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol": {
|
|
8
|
-
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./AggregatorInterface.sol\";\nimport \"./AggregatorV3Interface.sol\";\n\ninterface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}\n"
|
|
9
|
-
},
|
|
10
4
|
"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
|
|
11
5
|
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n function decimals() external view returns (uint8);\n\n function description() external view returns (string memory);\n\n function version() external view returns (uint256);\n\n function getRoundData(uint80 _roundId)\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n}\n"
|
|
12
6
|
},
|
|
@@ -59,7 +53,7 @@
|
|
|
59
53
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\n// SPDX-FileCopyrightText: 2022 Venus\npragma solidity 0.8.13;\n\ninterface PublicResolverInterface {\n function addr(bytes32 node) external view returns (address payable);\n}\n"
|
|
60
54
|
},
|
|
61
55
|
"contracts/interfaces/PythInterface.sol": {
|
|
62
|
-
"content": "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2021 Pyth Data Foundation\npragma solidity 0.8.13;\n\ncontract PythStructs {\n // A price with a degree of uncertainty, represented as a price +- a confidence interval.\n //\n // The confidence interval roughly corresponds to the standard error of a normal distribution.\n // Both the price and confidence are stored in a fixed-point numeric representation,\n // `x * (10^expo)`, where `expo` is the exponent.\n //\n // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how\n // to how this price safely.\n struct Price {\n // Price\n int64 price;\n // Confidence interval around the price\n uint64 conf;\n // Price exponent\n int32 expo;\n // Unix timestamp describing when the price was published\n uint256 publishTime;\n }\n\n // PriceFeed represents a current aggregate price from pyth publisher feeds.\n struct PriceFeed {\n // The price ID.\n bytes32 id;\n // Latest available price\n Price price;\n // Latest available exponentially-weighted moving average price\n Price emaPrice;\n }\n}\n\n/// @title Consume prices from the Pyth Network (https://pyth.network/).\n/// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices\n/// for how to consume prices safely.\n/// @author Pyth Data Association\ninterface IPyth {\n /// @dev Emitted when an update for price feed with `id` is processed successfully.\n /// @param id The Pyth Price Feed ID.\n /// @param fresh True if the price update is more recent and stored.\n /// @param chainId ID of the source chain that the batch price update containing this price.\n /// This value comes from Wormhole, and you can find the corresponding chains\n /// at https://docs.wormholenetwork.com/wormhole/contracts.\n /// @param sequenceNumber Sequence number of the batch price update containing this price.\n /// @param lastPublishTime Publish time of the previously stored price.\n /// @param publishTime Publish time of the given price update.\n /// @param price Price of the given price update.\n /// @param conf Confidence interval of the given price update.\n event PriceFeedUpdate(\n bytes32 indexed id,\n bool indexed fresh,\n uint16 chainId,\n uint64 sequenceNumber,\n uint256 lastPublishTime,\n uint256 publishTime,\n int64 price,\n uint64 conf\n );\n\n /// @dev Emitted when a batch price update is processed successfully.\n /// @param chainId ID of the source chain that the batch price update comes from.\n /// @param sequenceNumber Sequence number of the batch price update.\n /// @param batchSize Number of prices within the batch price update.\n /// @param freshPricesInBatch Number of prices that were more recent and were stored.\n event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber, uint256 batchSize, uint256 freshPricesInBatch);\n\n /// @dev Emitted when a call to `updatePriceFeeds` is processed successfully.\n /// @param sender Sender of the call (`msg.sender`).\n /// @param batchCount Number of batches that this function processed.\n /// @param fee Amount of paid fee for updating the prices.\n event UpdatePriceFeeds(address indexed sender, uint256 batchCount, uint256 fee);\n\n /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time\n function getValidTimePeriod() external view returns (uint256 validTimePeriod);\n\n /// @notice Returns the price and confidence interval.\n /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.\n /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPrice(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price and confidence interval.\n /// @dev Reverts if the EMA price is not available.\n /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPrice(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price of a price feed without any sanity checks.\n /// @dev This function returns the most recent price update in this contract without any recency checks.\n /// This function is unsafe as the returned price update may be arbitrarily far in the past.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price that is no older than `age` seconds of the current time.\n /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.\n /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.\n /// However, if the price is not recent this function returns the latest available price.\n ///\n /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that\n /// the returned price is recent or useful for any particular application.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds\n /// of the current time.\n /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);\n\n /// @notice Update price feeds with given update messages.\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n /// Prices will be updated if they are more recent than the current stored prices.\n /// The call will succeed even if the update is not the most recent.\n /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n function updatePriceFeeds(bytes[] calldata updateData) external payable;\n\n /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is\n /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the\n /// given `publishTimes` for the price feeds and does not read the actual price\n /// update publish time within `updateData`.\n ///\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n ///\n /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime\n /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have\n /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.\n /// Otherwise, it calls updatePriceFeeds method to update the prices.\n ///\n /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n /// @param priceIds Array of price ids.\n /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`\n function updatePriceFeedsIfNecessary(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64[] calldata publishTimes\n ) external payable;\n\n /// @notice Returns the required fee to update an array of price updates.\n /// @param updateDataSize Number of price updates.\n /// @return feeAmount The required fee in Wei.\n function getUpdateFee(uint256 updateDataSize) external view returns (uint256 feeAmount);\n}\n\nabstract contract AbstractPyth is IPyth {\n /// @notice Returns the price feed with given id.\n /// @dev Reverts if the price does not exist.\n /// @param id The Pyth Price Feed ID of which to fetch the PriceFeed.\n function queryPriceFeed(bytes32 id) public view virtual returns (PythStructs.PriceFeed memory priceFeed);\n\n /// @notice Returns true if a price feed with the given id exists.\n /// @param id The Pyth Price Feed ID of which to check its existence.\n function priceFeedExists(bytes32 id) public view virtual returns (bool exists);\n\n function getValidTimePeriod() public view virtual override returns (uint256 validTimePeriod);\n\n function getPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {\n return getPriceNoOlderThan(id, getValidTimePeriod());\n }\n\n function getEmaPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {\n return getEmaPriceNoOlderThan(id, getValidTimePeriod());\n }\n\n function getPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {\n PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);\n return priceFeed.price;\n }\n\n function getPriceNoOlderThan(\n bytes32 id,\n uint256 age\n ) public view override returns (PythStructs.Price memory price) {\n price = getPriceUnsafe(id);\n\n require(diff(block.timestamp, price.publishTime) <= age, \"no price available which is recent enough\");\n\n return price;\n }\n\n function getEmaPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {\n PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);\n return priceFeed.emaPrice;\n }\n\n function getEmaPriceNoOlderThan(\n bytes32 id,\n uint256 age\n ) public view override returns (PythStructs.Price memory price) {\n price = getEmaPriceUnsafe(id);\n\n require(diff(block.timestamp, price.publishTime) <= age, \"no ema price available which is recent enough\");\n\n return price;\n }\n\n function diff(uint256 x, uint256 y) internal pure returns (uint256) {\n if (x > y) {\n return x - y;\n } else {\n return y - x;\n }\n }\n\n // Access modifier is overridden to public to be able to call it locally.\n function updatePriceFeeds(bytes[] calldata updateData) public payable virtual override;\n\n function updatePriceFeedsIfNecessary(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64[] calldata publishTimes\n ) external payable override {\n require(priceIds.length == publishTimes.length, \"priceIds and publishTimes arrays should have same length\");\n\n bool updateNeeded = false;\n for (uint256 i = 0; i < priceIds.length; i++) {\n if (!priceFeedExists(priceIds[i]) || queryPriceFeed(priceIds[i]).price.publishTime < publishTimes[i]) {\n updateNeeded = true;\n break;\n }\n }\n\n require(updateNeeded, \"no prices in the submitted batch have fresh prices, so this update will have no effect\");\n\n updatePriceFeeds(updateData);\n }\n}\n"
|
|
56
|
+
"content": "// SPDX-License-Identifier: Apache-2.0\n// SPDX-FileCopyrightText: 2021 Pyth Data Foundation\npragma solidity 0.8.13;\n\ncontract PythStructs {\n // A price with a degree of uncertainty, represented as a price +- a confidence interval.\n //\n // The confidence interval roughly corresponds to the standard error of a normal distribution.\n // Both the price and confidence are stored in a fixed-point numeric representation,\n // `x * (10^expo)`, where `expo` is the exponent.\n //\n // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how\n // to how this price safely.\n struct Price {\n // Price\n int64 price;\n // Confidence interval around the price\n uint64 conf;\n // Price exponent\n int32 expo;\n // Unix timestamp describing when the price was published\n uint256 publishTime;\n }\n\n // PriceFeed represents a current aggregate price from pyth publisher feeds.\n struct PriceFeed {\n // The price ID.\n bytes32 id;\n // Latest available price\n Price price;\n // Latest available exponentially-weighted moving average price\n Price emaPrice;\n }\n}\n\n/// @title Consume prices from the Pyth Network (https://pyth.network/).\n/// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices\n/// for how to consume prices safely.\n/// @author Pyth Data Association\ninterface IPyth {\n /// @dev Emitted when an update for price feed with `id` is processed successfully.\n /// @param id The Pyth Price Feed ID.\n /// @param fresh True if the price update is more recent and stored.\n /// @param chainId ID of the source chain that the batch price update containing this price.\n /// This value comes from Wormhole, and you can find the corresponding chains\n /// at https://docs.wormholenetwork.com/wormhole/contracts.\n /// @param sequenceNumber Sequence number of the batch price update containing this price.\n /// @param lastPublishTime Publish time of the previously stored price.\n /// @param publishTime Publish time of the given price update.\n /// @param price Price of the given price update.\n /// @param conf Confidence interval of the given price update.\n event PriceFeedUpdate(\n bytes32 indexed id,\n bool indexed fresh,\n uint16 chainId,\n uint64 sequenceNumber,\n uint256 lastPublishTime,\n uint256 publishTime,\n int64 price,\n uint64 conf\n );\n\n /// @dev Emitted when a batch price update is processed successfully.\n /// @param chainId ID of the source chain that the batch price update comes from.\n /// @param sequenceNumber Sequence number of the batch price update.\n /// @param batchSize Number of prices within the batch price update.\n /// @param freshPricesInBatch Number of prices that were more recent and were stored.\n event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber, uint256 batchSize, uint256 freshPricesInBatch);\n\n /// @dev Emitted when a call to `updatePriceFeeds` is processed successfully.\n /// @param sender Sender of the call (`msg.sender`).\n /// @param batchCount Number of batches that this function processed.\n /// @param fee Amount of paid fee for updating the prices.\n event UpdatePriceFeeds(address indexed sender, uint256 batchCount, uint256 fee);\n\n /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time\n function getValidTimePeriod() external view returns (uint256 validTimePeriod);\n\n /// @notice Returns the price and confidence interval.\n /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.\n /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPrice(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price and confidence interval.\n /// @dev Reverts if the EMA price is not available.\n /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPrice(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price of a price feed without any sanity checks.\n /// @dev This function returns the most recent price update in this contract without any recency checks.\n /// This function is unsafe as the returned price update may be arbitrarily far in the past.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price that is no older than `age` seconds of the current time.\n /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.\n /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.\n /// However, if the price is not recent this function returns the latest available price.\n ///\n /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that\n /// the returned price is recent or useful for any particular application.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceUnsafe(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds\n /// of the current time.\n /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceNoOlderThan(bytes32 id, uint256 age) external view returns (PythStructs.Price memory price);\n\n /// @notice Update price feeds with given update messages.\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n /// Prices will be updated if they are more recent than the current stored prices.\n /// The call will succeed even if the update is not the most recent.\n /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n function updatePriceFeeds(bytes[] calldata updateData) external payable;\n\n /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is\n /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the\n /// given `publishTimes` for the price feeds and does not read the actual price\n /// update publish time within `updateData`.\n ///\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n ///\n /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime\n /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have\n /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.\n /// Otherwise, it calls updatePriceFeeds method to update the prices.\n ///\n /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n /// @param priceIds Array of price ids.\n /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`\n function updatePriceFeedsIfNecessary(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64[] calldata publishTimes\n ) external payable;\n\n /// @notice Returns the required fee to update an array of price updates.\n /// @param updateDataSize Number of price updates.\n /// @return feeAmount The required fee in Wei.\n function getUpdateFee(uint256 updateDataSize) external view returns (uint256 feeAmount);\n}\n\nabstract contract AbstractPyth is IPyth {\n /// @notice Returns the price feed with given id.\n /// @dev Reverts if the price does not exist.\n /// @param id The Pyth Price Feed ID of which to fetch the PriceFeed.\n function queryPriceFeed(bytes32 id) public view virtual returns (PythStructs.PriceFeed memory priceFeed);\n\n /// @notice Returns true if a price feed with the given id exists.\n /// @param id The Pyth Price Feed ID of which to check its existence.\n function priceFeedExists(bytes32 id) public view virtual returns (bool exists);\n\n function getValidTimePeriod() public view virtual override returns (uint256 validTimePeriod);\n\n function getPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {\n return getPriceNoOlderThan(id, getValidTimePeriod());\n }\n\n function getEmaPrice(bytes32 id) external view override returns (PythStructs.Price memory price) {\n return getEmaPriceNoOlderThan(id, getValidTimePeriod());\n }\n\n function getPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {\n PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);\n return priceFeed.price;\n }\n\n function getPriceNoOlderThan(\n bytes32 id,\n uint256 age\n ) public view override returns (PythStructs.Price memory price) {\n price = getPriceUnsafe(id);\n\n require(diff(block.timestamp, price.publishTime) <= age, \"no price available which is recent enough\");\n\n return price;\n }\n\n function getEmaPriceUnsafe(bytes32 id) public view override returns (PythStructs.Price memory price) {\n PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);\n return priceFeed.emaPrice;\n }\n\n function getEmaPriceNoOlderThan(\n bytes32 id,\n uint256 age\n ) public view override returns (PythStructs.Price memory price) {\n price = getEmaPriceUnsafe(id);\n\n require(diff(block.timestamp, price.publishTime) <= age, \"no ema price available which is recent enough\");\n\n return price;\n }\n\n function diff(uint256 x, uint256 y) internal pure returns (uint256) {\n if (x > y) {\n return x - y;\n } else {\n return y - x;\n }\n }\n\n // Access modifier is overridden to public to be able to call it locally.\n function updatePriceFeeds(bytes[] calldata updateData) public payable virtual override;\n\n function updatePriceFeedsIfNecessary(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64[] calldata publishTimes\n ) external payable override {\n require(priceIds.length == publishTimes.length, \"priceIds and publishTimes arrays should have same length\");\n\n bool updateNeeded = false;\n for (uint256 i = 0; i < priceIds.length; ) {\n if (!priceFeedExists(priceIds[i]) || queryPriceFeed(priceIds[i]).price.publishTime < publishTimes[i]) {\n updateNeeded = true;\n break;\n }\n unchecked {\n i++;\n }\n }\n\n require(updateNeeded, \"no prices in the submitted batch have fresh prices, so this update will have no effect\");\n\n updatePriceFeeds(updateData);\n }\n}\n"
|
|
63
57
|
},
|
|
64
58
|
"contracts/interfaces/SIDRegistryInterface.sol": {
|
|
65
59
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\n// SPDX-FileCopyrightText: 2022 Venus\npragma solidity 0.8.13;\n\ninterface SIDRegistryInterface {\n function resolver(bytes32 node) external view returns (address);\n}\n"
|
|
@@ -71,13 +65,13 @@
|
|
|
71
65
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\ninterface IPancakePair {\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n\n function price0CumulativeLast() external view returns (uint256);\n\n function price1CumulativeLast() external view returns (uint256);\n}\n\nlibrary FixedPoint {\n // range: [0, 2**112 - 1]\n // resolution: 1 / 2**112\n struct uq112x112 {\n uint224 _x;\n }\n\n // returns a uq112x112 which represents the ratio of the numerator to the denominator\n // equivalent to encode(numerator).div(denominator)\n function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {\n require(denominator > 0, \"FixedPoint: DIV_BY_ZERO\");\n return uq112x112((uint224(numerator) << 112) / denominator);\n }\n\n // decode a uq112x112 into a uint with 18 decimals of precision\n function decode112with18(uq112x112 memory self) internal pure returns (uint256) {\n // we only have 256 - 224 = 32 bits to spare, so scaling up by ~60 bits is dangerous\n // instead, get close to:\n // (x * 1e18) >> 112\n // without risk of overflowing, e.g.:\n // (x) / 2 ** (112 - lg(1e18))\n return uint256(self._x) / 5192296858534827;\n }\n}\n\n// library with helper methods for oracles that are concerned with computing average prices\nlibrary PancakeOracleLibrary {\n using FixedPoint for *;\n\n // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]\n function currentBlockTimestamp() internal view returns (uint32) {\n return uint32(block.timestamp % 2 ** 32);\n }\n\n // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.\n function currentCumulativePrices(\n address pair\n ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) {\n blockTimestamp = currentBlockTimestamp();\n price0Cumulative = IPancakePair(pair).price0CumulativeLast();\n price1Cumulative = IPancakePair(pair).price1CumulativeLast();\n\n // if time has elapsed since the last update on the pair, mock the accumulated price values\n (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IPancakePair(pair).getReserves();\n if (blockTimestampLast != blockTimestamp) {\n unchecked {\n // subtraction overflow is desired\n uint32 timeElapsed = blockTimestamp - blockTimestampLast;\n // addition overflow is desired\n // counterfactual\n price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;\n // counterfactual\n price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;\n }\n }\n }\n}\n"
|
|
72
66
|
},
|
|
73
67
|
"contracts/oracles/BinanceOracle.sol": {
|
|
74
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts
|
|
68
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/SIDRegistryInterface.sol\";\nimport \"../interfaces/FeedRegistryInterface.sol\";\nimport \"../interfaces/PublicResolverInterface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\ncontract BinanceOracle is AccessControlledV8, OracleInterface {\n address public sidRegistryAddress;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Max stale period configuration for assets\n mapping(string => uint256) public maxStalePeriod;\n\n event MaxStalePeriodAdded(string indexed asset, uint256 maxStalePeriod);\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address vBnbAddress, address vaiAddress) {\n if (vBnbAddress == address(0)) revert(\"vBNB can't be zero address\");\n if (vaiAddress == address(0)) revert(\"VAI can't be zero address\");\n vBnb = vBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Used to set the max stale period of an asset\n * @param symbol The symbol of the asset\n * @param _maxStalePeriod The max stake period\n */\n function setMaxStalePeriod(string memory symbol, uint256 _maxStalePeriod) external {\n _checkAccessAllowed(\"setMaxStalePeriod(string,uint256)\");\n if (_maxStalePeriod == 0) revert(\"stale period can't be zero\");\n if (bytes(symbol).length == 0) revert(\"symbol cannot be empty\");\n\n maxStalePeriod[symbol] = _maxStalePeriod;\n emit MaxStalePeriodAdded(symbol, _maxStalePeriod);\n }\n\n /**\n * @notice Sets the contracts required to fetch prices\n * @param _sidRegistryAddress Address of SID registry\n * @param _accessControlManager Address of the access control manager contract\n */\n function initialize(address _sidRegistryAddress, address _accessControlManager) external initializer {\n sidRegistryAddress = _sidRegistryAddress;\n __AccessControlled_init(_accessControlManager);\n }\n\n /**\n * @notice Gets the price of a vToken from the binance oracle\n * @param vToken Address of the vToken\n * @return Price in USD\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n string memory symbol;\n uint256 decimals;\n\n // VBNB token doesn't have `underlying` method\n if (vToken == vBnb) {\n symbol = \"BNB\";\n decimals = 18;\n } else if (vToken == vai) {\n symbol = \"VAI\";\n decimals = 18;\n } else {\n IERC20Metadata underlyingToken = IERC20Metadata(VBep20Interface(vToken).underlying());\n symbol = underlyingToken.symbol();\n decimals = underlyingToken.decimals();\n }\n\n if (compare(symbol, \"WBNB\")) {\n symbol = \"BNB\";\n }\n\n FeedRegistryInterface feedRegistry = FeedRegistryInterface(getFeedRegistryAddress());\n\n (, int256 answer, , uint256 updatedAt, ) = feedRegistry.latestRoundDataByName(symbol, \"USD\");\n if (answer <= 0) revert(\"invalid binance oracle price\");\n if (block.timestamp < updatedAt) revert(\"updatedAt exceeds block time\");\n\n uint256 deltaTime;\n unchecked {\n deltaTime = block.timestamp - updatedAt;\n }\n\n if (deltaTime > maxStalePeriod[symbol]) revert(\"binance oracle price expired\");\n\n uint256 decimalDelta = feedRegistry.decimalsByName(symbol, \"USD\");\n return (uint256(answer) * (10 ** (18 - decimalDelta))) * (10 ** (18 - decimals));\n }\n\n /**\n * @notice Uses Space ID to fetch the feed registry address\n * @return feedRegistryAddress Address of binance oracle feed registry.\n */\n function getFeedRegistryAddress() public view returns (address) {\n bytes32 nodeHash = 0x94fe3821e0768eb35012484db4df61890f9a6ca5bfa984ef8ff717e73139faff;\n\n SIDRegistryInterface sidRegistry = SIDRegistryInterface(sidRegistryAddress);\n address publicResolverAddress = sidRegistry.resolver(nodeHash);\n PublicResolverInterface publicResolver = PublicResolverInterface(publicResolverAddress);\n\n return publicResolver.addr(nodeHash);\n }\n\n /**\n * @notice Used to compare if two strings are equal or not\n * @param str1 The first string\n * @param str2 The second string\n * @return equal Returns true if both are equal or else false.\n */\n function compare(string memory str1, string memory str2) private pure returns (bool) {\n return keccak256(bytes(str1)) == keccak256(bytes(str2));\n }\n}\n"
|
|
75
69
|
},
|
|
76
70
|
"contracts/oracles/BoundValidator.sol": {
|
|
77
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\
|
|
71
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\n// BoundValidator provides some common functions and can be used\n// to wrap up other contracts to form pivot oracles\ncontract BoundValidator is AccessControlledV8, BoundValidatorInterface {\n struct ValidateConfig {\n /// @notice asset address\n address asset;\n /// @notice Upper bound of deviation between reported price and anchor price,\n /// beyond which the reported price will be invalidated\n uint256 upperBoundRatio;\n /// @notice Lower bound of deviation between reported price and anchor price,\n /// below which the reported price will be invalidated\n uint256 lowerBoundRatio;\n }\n\n /// @notice validation configs by asset\n mapping(address => ValidateConfig) public validateConfigs;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for BNB. This is the underlying for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n /// @notice Emit this event when new validation configs are added\n event ValidateConfigAdded(address indexed asset, uint256 indexed upperBound, uint256 indexed lowerBound);\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address vBnbAddress, address vaiAddress) {\n if (vBnbAddress == address(0)) revert(\"vBNB can't be zero address\");\n if (vaiAddress == address(0)) revert(\"VAI can't be zero address\");\n vBnb = vBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Add multiple validation configs at the same time\n * @param configs Array of validation configs\n * @custom:access Only Governance\n * @custom:error Zero length error is thrown if length of the config array is 0\n * @custom:event Emits ValidateConfigAdded for each validation config that is successfully set\n */\n function setValidateConfigs(ValidateConfig[] memory configs) external {\n uint256 length = configs.length;\n if (length == 0) revert(\"invalid validate config length\");\n for (uint256 i; i < length; ) {\n setValidateConfig(configs[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Initializes the owner of the contract\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) external initializer {\n __AccessControlled_init(accessControlManager_);\n }\n\n /**\n * @notice Test reported asset price against anchor price\n * @param vToken vToken address\n * @param reportedPrice The price to be tested\n * @custom:error Missing error thrown if asset config is not set\n * @custom:error Price error thrown if anchor price is not valid\n */\n function validatePriceWithAnchorPrice(\n address vToken,\n uint256 reportedPrice,\n uint256 anchorPrice\n ) external view override returns (bool) {\n address asset = _getUnderlyingAsset(vToken);\n\n if (validateConfigs[asset].upperBoundRatio == 0) revert(\"validation config not exist\");\n if (anchorPrice == 0) revert(\"anchor price is not valid\");\n return _isWithinAnchor(asset, reportedPrice, anchorPrice);\n }\n\n /**\n * @notice Add a single validation config\n * @param config Validation config struct\n * @custom:access Only Governance\n * @custom:error Null address error is thrown if asset address is null\n * @custom:error Range error thrown if bound ratio is not positive\n * @custom:error Range error thrown if lower bound is greater than or equal to upper bound\n * @custom:event Emits ValidateConfigAdded when a validation config is successfully set\n */\n function setValidateConfig(ValidateConfig memory config) public {\n _checkAccessAllowed(\"setValidateConfig(ValidateConfig)\");\n\n if (config.asset == address(0)) revert(\"asset can't be zero address\");\n if (config.upperBoundRatio == 0 || config.lowerBoundRatio == 0) revert(\"bound must be positive\");\n if (config.upperBoundRatio <= config.lowerBoundRatio) revert(\"upper bound must be higher than lowner bound\");\n validateConfigs[config.asset] = config;\n emit ValidateConfigAdded(config.asset, config.upperBoundRatio, config.lowerBoundRatio);\n }\n\n /**\n * @notice Test whether the reported price is within the valid bounds\n * @param asset Asset address\n * @param reportedPrice The price to be tested\n * @param anchorPrice The reported price must be within the the valid bounds of this price\n */\n function _isWithinAnchor(address asset, uint256 reportedPrice, uint256 anchorPrice) private view returns (bool) {\n if (reportedPrice != 0) {\n uint256 anchorRatio = (anchorPrice * 100e16) / reportedPrice;\n uint256 upperBoundAnchorRatio = validateConfigs[asset].upperBoundRatio;\n uint256 lowerBoundAnchorRatio = validateConfigs[asset].lowerBoundRatio;\n return anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio;\n }\n return false;\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) private view returns (address asset) {\n if (address(vToken) == vBnb) {\n asset = BNB_ADDR;\n } else if (address(vToken) == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
78
72
|
},
|
|
79
73
|
"contracts/oracles/ChainlinkOracle.sol": {
|
|
80
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"@chainlink/contracts/src/v0.8/interfaces/
|
|
74
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\ncontract ChainlinkOracle is AccessControlledV8, OracleInterface {\n struct TokenConfig {\n /// @notice Underlying token address, which can't be a null address\n /// @notice Used to check if a token is supported\n /// @notice 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB for BNB\n address asset;\n /// @notice Chainlink feed address\n address feed;\n /// @notice Price expiration period of this asset\n uint256 maxStalePeriod;\n }\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for BNB. This is the underlying address for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n /// @notice Manually set an override price, useful under extenuating conditions such as price feed failure\n mapping(address => uint256) public prices;\n\n /// @notice Token config by assets\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice Emit when a price is manually set\n event PricePosted(address indexed asset, uint256 previousPriceMantissa, uint256 newPriceMantissa);\n\n /// @notice Emit when a token config is added\n event TokenConfigAdded(address indexed asset, address feed, uint256 maxStalePeriod);\n\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address vBnbAddress, address vaiAddress) notNullAddress(vBnbAddress) notNullAddress(vaiAddress) {\n vBnb = vBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Set the forced prices of the underlying token of input vToken\n * @param vToken vToken address\n * @param underlyingPriceMantissa price in 18 decimals\n * @custom:access Only Governance\n * @custom:error NotNullAddress thrown if address of vToken is null\n * @custom:event Emits PricePosted event on succesfully setup of underlying price\n */\n function setUnderlyingPrice(\n VBep20Interface vToken,\n uint256 underlyingPriceMantissa\n ) external notNullAddress(address(vToken)) {\n _checkAccessAllowed(\"setUnderlyingPrice(address,uint256)\");\n\n address asset = address(vToken) == vBnb ? BNB_ADDR : address(vToken.underlying());\n uint256 previousPriceMantissa = prices[asset];\n prices[asset] = underlyingPriceMantissa;\n emit PricePosted(asset, previousPriceMantissa, prices[asset]);\n }\n\n /**\n * @notice Manually set the price of a given asset\n * @param asset Asset address\n * @param price Underlying price in 18 decimals\n * @custom:access Only Governance\n * @custom:event Emits PricePosted event on succesfully setup of underlying price\n */\n function setDirectPrice(address asset, uint256 price) external notNullAddress(asset) {\n _checkAccessAllowed(\"setDirectPrice(address,uint256)\");\n\n uint256 previousPriceMantissa = prices[asset];\n prices[asset] = price;\n emit PricePosted(asset, previousPriceMantissa, price);\n }\n\n /**\n * @notice Add multiple token configs at the same time\n * @param tokenConfigs_ config array\n * @custom:access Only Governance\n * @custom:error Zero length error thrown, if length of the array in parameter is 0\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external {\n if (tokenConfigs_.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = tokenConfigs_.length;\n for (uint256 i; i < numTokenConfigs; ) {\n setTokenConfig(tokenConfigs_[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Initializes the owner of the contract\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) external initializer {\n __AccessControlled_init(accessControlManager_);\n }\n\n /**\n * @notice Gets the Chainlink price for the underlying asset of a given vToken, revert when vToken is a null address\n * @param vToken vToken address\n * @return price Underlying price in USD\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n return _getUnderlyingPriceInternal(VBep20Interface(vToken));\n }\n\n /**\n * @notice Add single token config. vToken & feed cannot be null addresses and maxStalePeriod must be positive\n * @param tokenConfig Token config struct\n * @custom:access Only Governance\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error NotNullAddress error is thrown if token feed address is null\n * @custom:error Range error is thrown if maxStale period of token is not greater than zero\n * @custom:event Emits TokenConfigAdded event on succesfully setting of the token config\n */\n function setTokenConfig(\n TokenConfig memory tokenConfig\n ) public notNullAddress(tokenConfig.asset) notNullAddress(tokenConfig.feed) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n if (tokenConfig.maxStalePeriod == 0) revert(\"stale period can't be zero\");\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(tokenConfig.asset, tokenConfig.feed, tokenConfig.maxStalePeriod);\n }\n\n /**\n * @notice Gets the Chainlink price for the underlying asset of a given vToken\n * or the manually set price if it's been set\n * @dev The decimals of the underlying token are considered to ensure the returned price\n * has 18 decimals of precision\n * @param vToken vToken address\n * @return price Underlying price in USD\n */\n function _getUnderlyingPriceInternal(VBep20Interface vToken) private view returns (uint256 price) {\n address token;\n uint256 decimals;\n\n // vBNB token doesn't have `underlying` method\n if (address(vToken) == vBnb) {\n token = BNB_ADDR;\n decimals = 18;\n } else if (address(vToken) == vai) {\n token = vai;\n decimals = 18;\n } else {\n token = vToken.underlying();\n decimals = VBep20Interface(token).decimals();\n }\n\n uint256 tokenPrice = prices[token];\n if (tokenPrice != 0) {\n price = tokenPrice;\n } else {\n price = _getChainlinkPrice(token);\n }\n\n uint256 decimalDelta = 18 - uint256(decimals);\n return price * (10 ** decimalDelta);\n }\n\n /**\n * @notice Get the Chainlink price for the underlying asset of a given vToken, revert if token config doesn't exist\n * @dev The precision of the price feed is used to ensure the returned price has 18 decimals of precision\n * @param asset Underlying asset address\n * @return price Underlying price in USD, with 18 decimals of precision\n * @custom:error NotNullAddress error is thrown if the asset address is null\n * @custom:error Price error is thrown if the Chainlink price of asset is not greater than zero\n * @custom:error Timing error is thrown if current timestamp is less than the last updatedAt timestamp\n * @custom:error Timing error is thrown if time difference between current time and last updated time\n * is greater than maxStalePeriod\n */\n function _getChainlinkPrice(\n address asset\n ) private view notNullAddress(tokenConfigs[asset].asset) returns (uint256) {\n TokenConfig memory tokenConfig = tokenConfigs[asset];\n AggregatorV3Interface feed = AggregatorV3Interface(tokenConfig.feed);\n\n // note: maxStalePeriod cannot be 0\n uint256 maxStalePeriod = tokenConfig.maxStalePeriod;\n\n // Chainlink USD-denominated feeds store answers at 8 decimals, mostly\n uint256 decimalDelta = 18 - feed.decimals();\n\n (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();\n if (answer <= 0) revert(\"chainlink price must be positive\");\n if (block.timestamp < updatedAt) revert(\"updatedAt exceeds block time\");\n\n uint256 deltaTime;\n unchecked {\n deltaTime = block.timestamp - updatedAt;\n }\n\n if (deltaTime > maxStalePeriod) revert(\"chainlink price expired\");\n\n return uint256(answer) * (10 ** decimalDelta);\n }\n}\n"
|
|
81
75
|
},
|
|
82
76
|
"contracts/oracles/mocks/MockChainlinkOracle.sol": {
|
|
83
77
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../ChainlinkOracle.sol\";\nimport \"../../interfaces/VBep20Interface.sol\";\n\ncontract MockChainlinkOracle is OwnableUpgradeable {\n mapping(address => uint256) public assetPrices;\n\n //set price in 6 decimal precision\n constructor() {}\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n function initialize() public initializer {\n __Ownable_init();\n }\n\n //https://compound.finance/docs/prices\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n address token = VBep20Interface(vToken).underlying();\n return assetPrices[token];\n }\n}\n"
|
|
@@ -86,13 +80,13 @@
|
|
|
86
80
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../PythOracle.sol\";\nimport \"../../interfaces/VBep20Interface.sol\";\n\ncontract MockPythOracle is OwnableUpgradeable {\n mapping(address => uint256) public assetPrices;\n\n /// @notice the actual pyth oracle address fetch & store the prices\n IPyth public underlyingPythOracle;\n\n //set price in 6 decimal precision\n constructor() {}\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n function initialize(address underlyingPythOracle_) public initializer {\n __Ownable_init();\n if (underlyingPythOracle_ == address(0)) revert(\"pyth oracle cannot be zero address\");\n underlyingPythOracle = IPyth(underlyingPythOracle_);\n }\n\n //https://compound.finance/docs/prices\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n address token = VBep20Interface(vToken).underlying();\n return assetPrices[token];\n }\n}\n"
|
|
87
81
|
},
|
|
88
82
|
"contracts/oracles/PythOracle.sol": {
|
|
89
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/utils/math/SignedMath.sol\";\nimport \"../interfaces/PythInterface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\
|
|
83
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/utils/math/SignedMath.sol\";\nimport \"../interfaces/PythInterface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\n/**\n * PythOracle contract reads prices from actual Pyth oracle contract which accepts, verifies and stores the\n * updated prices from external sources\n */\ncontract PythOracle is AccessControlledV8, OracleInterface {\n // To calculate 10 ** n(which is a signed type)\n using SignedMath for int256;\n\n // To cast int64/int8 types from Pyth to unsigned types\n using SafeCast for int256;\n\n struct TokenConfig {\n bytes32 pythId;\n address asset;\n uint64 maxStalePeriod;\n }\n\n /// @notice Exponent scale (decimal precision) of prices\n uint256 public constant EXP_SCALE = 1e18;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for BNB. This is the underlying for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n /// @notice The actual pyth oracle address fetch & store the prices\n IPyth public underlyingPythOracle;\n\n /// @notice Token configs by asset address\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice Emit when setting a new pyth oracle address\n event PythOracleSet(address indexed oldPythOracle, address indexed newPythOracle);\n\n /// @notice Emit when a token config is added\n event TokenConfigAdded(address indexed vToken, bytes32 indexed pythId, uint64 indexed maxStalePeriod);\n\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address vBnbAddress, address vaiAddress) notNullAddress(vBnbAddress) notNullAddress(vaiAddress) {\n vBnb = vBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Batch set token configs\n * @param tokenConfigs_ Token config array\n * @custom:access Only Governance\n * @custom:error Zero length error is thrown if length of the array in parameter is 0\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external {\n if (tokenConfigs_.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = tokenConfigs_.length;\n for (uint256 i; i < numTokenConfigs; ) {\n setTokenConfig(tokenConfigs_[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Set the underlying Pyth oracle contract address\n * @param underlyingPythOracle_ Pyth oracle contract address\n * @custom:access Only Governance\n * @custom:error NotNullAddress error thrown if underlyingPythOracle_ address is zero\n * @custom:event Emits PythOracleSet event with address of Pyth oracle.\n */\n function setUnderlyingPythOracle(\n IPyth underlyingPythOracle_\n ) external notNullAddress(address(underlyingPythOracle_)) {\n _checkAccessAllowed(\"setUnderlyingPythOracle(address)\");\n IPyth oldUnderlyingPythOracle = underlyingPythOracle;\n underlyingPythOracle = underlyingPythOracle_;\n emit PythOracleSet(address(oldUnderlyingPythOracle), address(underlyingPythOracle_));\n }\n\n /**\n * @notice Initializes the owner of the contract and sets required contracts\n * @param underlyingPythOracle_ Address of the Pyth oracle\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(\n address underlyingPythOracle_,\n address accessControlManager_\n ) external initializer notNullAddress(underlyingPythOracle_) {\n __AccessControlled_init(accessControlManager_);\n\n underlyingPythOracle = IPyth(underlyingPythOracle_);\n emit PythOracleSet(address(0), underlyingPythOracle_);\n }\n\n /**\n * @notice Get price of underlying asset of the input vToken, under the hood this function\n * get price from Pyth contract, the prices of which are updated externally\n * @param vToken vToken address\n * @return price Underlying price with a precision of 18 decimals\n * @custom:error Zero address error thrown if underlyingPythOracle address is null\n * @custom:error Zero address error thrown if asset address is null\n * @custom:error Range error thrown if price of Pyth oracle is not greater than zero\n */\n function getUnderlyingPrice(\n address vToken\n ) external view override notNullAddress(address(underlyingPythOracle)) returns (uint256) {\n address asset;\n uint256 decimals;\n\n // VBNB token doesn't have `underlying` method\n if (vToken == vBnb) {\n asset = BNB_ADDR;\n decimals = 18;\n } else if (vToken == vai) {\n asset = vai;\n decimals = 18;\n } else {\n asset = VBep20Interface(vToken).underlying();\n decimals = VBep20Interface(asset).decimals();\n }\n\n TokenConfig storage tokenConfig = tokenConfigs[asset];\n if (tokenConfig.asset == address(0)) revert(\"asset doesn't exist\");\n\n // if the price is expired after it's compared against `maxStalePeriod`, the following call will revert\n PythStructs.Price memory priceInfo = underlyingPythOracle.getPriceNoOlderThan(\n tokenConfig.pythId,\n tokenConfig.maxStalePeriod\n );\n\n uint256 price = int256(priceInfo.price).toUint256();\n\n if (price == 0) revert(\"invalid pyth oracle price\");\n\n // the price returned from Pyth is price ** 10^expo, which is the real dollar price of the assets\n // we need to multiply it by 1e18 to make the price 18 decimals\n if (priceInfo.expo > 0) {\n return price * EXP_SCALE * (10 ** int256(priceInfo.expo).toUint256()) * (10 ** (18 - decimals));\n } else {\n return ((price * EXP_SCALE) / (10 ** int256(-priceInfo.expo).toUint256())) * (10 ** (18 - decimals));\n }\n }\n\n /**\n * @notice Set single token config. `maxStalePeriod` cannot be 0 and `vToken` can be a null address\n * @param tokenConfig Token config struct\n * @custom:access Only Governance\n * @custom:error Range error is thrown if max stale period is zero\n * @custom:error NotNullAddress error is thrown if asset address is null\n */\n function setTokenConfig(TokenConfig memory tokenConfig) public notNullAddress(tokenConfig.asset) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n if (tokenConfig.maxStalePeriod == 0) revert(\"max stale period cannot be 0\");\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(tokenConfig.asset, tokenConfig.pythId, tokenConfig.maxStalePeriod);\n }\n}\n"
|
|
90
84
|
},
|
|
91
85
|
"contracts/oracles/TwapOracle.sol": {
|
|
92
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../libraries/PancakeLibrary.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\nstruct Observation {\n uint256 timestamp;\n uint256 acc;\n}\n\nstruct TokenConfig {\n /// @notice Asset address, which can't be zero address and can be used for existance check\n address asset;\n /// @notice Decimals of underlying asset\n uint256 baseUnit;\n /// @notice The address of Pancake pair\n address pancakePool;\n /// @notice Whether the token is paired with WBNB\n bool isBnbBased;\n /// @notice A flag identifies whether the Pancake pair is reversed\n /// e.g. XVS-WBNB is not reversed, while WBNB-XVS is.\n bool isReversedPool;\n /// @notice The minimum window in seconds required between TWAP updates\n uint256 anchorPeriod;\n}\n\ncontract TwapOracle is AccessControlledV8, TwapInterface {\n using FixedPoint for *;\n\n /// @notice WBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WBNB;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice the base unit of WBNB and BUSD, which are the paired tokens for all assets\n uint256 public constant bnbBaseUnit = 1e18;\n uint256 public constant busdBaseUnit = 1e18;\n\n /// @notice Configs by token\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice Stored price by token\n mapping(address => uint256) public prices;\n\n /// @notice Keeps a record of token observations mapped by address, updated on every updateTwap invocation.\n mapping(address => Observation[]) public observations;\n\n /// @notice Observation array index which probably falls in current anchor period mapped by asset address\n mapping(address => uint256) public windowStart;\n\n /// @notice Emit this event when TWAP window is updated\n event TwapWindowUpdated(\n address indexed asset,\n uint256 oldTimestamp,\n uint256 oldAcc,\n uint256 newTimestamp,\n uint256 newAcc\n );\n\n /// @notice Emit this event when TWAP price is updated\n event AnchorPriceUpdated(address indexed asset, uint256 price, uint256 oldTimestamp, uint256 newTimestamp);\n\n /// @notice Emit this event when new token configs are added\n event TokenConfigAdded(address indexed asset, address indexed pancakePool, uint256 indexed anchorPeriod);\n\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the VBNB\n /// @param wBnbAddress The address of the WBNB\n /// @param vaiAddress The address of the WBNB\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address vBnbAddress,\n address wBnbAddress,\n address vaiAddress\n ) notNullAddress(vBnbAddress) notNullAddress(wBnbAddress) notNullAddress(vaiAddress) {\n vBnb = vBnbAddress;\n WBNB = wBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Adds multiple token configs at the same time\n * @param configs Config array\n * @custom:error Zero length error thrown, if length of the config array is 0\n */\n function setTokenConfigs(TokenConfig[] memory configs) external {\n _checkAccessAllowed(\"setTokenConfigs(TokenConfig[])\");\n if (configs.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = configs.length;\n for (uint256 i; i < numTokenConfigs; ++i) {\n setTokenConfig(configs[i]);\n }\n }\n\n /**\n * @notice Get the underlying TWAP price for the given vToken\n * @param vToken vToken address\n * @return price Underlying price in USD\n * @custom:error Missing error is thrown if the token config does not exist\n * @custom:error Range error is thrown if TWAP price is not greater than zero\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n address asset = _getUnderlyingAsset(vToken);\n\n if (tokenConfigs[asset].asset == address(0)) revert(\"asset not exist\");\n uint256 price = prices[asset];\n\n // if price is 0, it means the price hasn't been updated yet and it's meaningless, revert\n if (price == 0) revert(\"TWAP price must be positive\");\n return (price * (10 ** (18 - IERC20Metadata(asset).decimals())));\n }\n\n /**\n * @notice Initializes the owner of the contract\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) public initializer {\n __AccessControlled_init(accessControlManager_);\n }\n\n /**\n * @notice Adds a single token config\n * @param config token config struct\n * @custom:access Only Governance\n * @custom:error Range error is thrown if anchor period is not greater than zero\n * @custom:error Range error is thrown if base unit is not greater than zero\n * @custom:error Value error is thrown if base unit decimals is not the same as asset decimals\n * @custom:error NotNullAddress error is thrown if address of asset is null\n * @custom:error NotNullAddress error is thrown if PancakeSwap pool address is null\n * @custom:event Emits TokenConfigAdded event if new token config are added with\n * asset address, PancakePool address, anchor period address\n */\n function setTokenConfig(\n TokenConfig memory config\n ) public notNullAddress(config.asset) notNullAddress(config.pancakePool) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n if (config.anchorPeriod == 0) revert(\"anchor period must be positive\");\n if (config.baseUnit == 0) revert(\"base unit must be positive\");\n if (config.baseUnit != 10 ** IERC20Metadata(config.asset).decimals())\n revert(\"base unit decimals must be same as asset decimals\");\n\n uint256 cumulativePrice = currentCumulativePrice(config);\n\n // Initialize observation data\n observations[config.asset].push(Observation(block.timestamp, cumulativePrice));\n tokenConfigs[config.asset] = config;\n emit TokenConfigAdded(config.asset, config.pancakePool, config.anchorPeriod);\n }\n\n /**\n * @notice Updates the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return anchorPrice anchor price of the underlying asset of the vToken\n * @custom:error Missing error is thrown if token config does not exist\n */\n function updateTwap(address vToken) public returns (uint256) {\n address asset = _getUnderlyingAsset(vToken);\n\n if (tokenConfigs[asset].asset == address(0)) revert(\"asset not exist\");\n // Update & fetch WBNB price first, so we can calculate the price of WBNB paired token\n if (asset != WBNB && tokenConfigs[asset].isBnbBased) {\n if (tokenConfigs[WBNB].asset == address(0)) revert(\"WBNB not exist\");\n _updateTwapInternal(tokenConfigs[WBNB]);\n }\n return _updateTwapInternal(tokenConfigs[asset]);\n }\n\n /**\n * @notice Fetches the current token/WBNB and token/BUSD price accumulator from PancakeSwap.\n * @return cumulative price of target token regardless of pair order\n */\n function currentCumulativePrice(TokenConfig memory config) public view returns (uint256) {\n (uint256 price0, uint256 price1, ) = PancakeOracleLibrary.currentCumulativePrices(config.pancakePool);\n if (config.isReversedPool) {\n return price1;\n } else {\n return price0;\n }\n }\n\n /**\n * @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return price Underlying price in USD, with 18 decimals\n * @custom:error Timing error is thrown if current time is not greater than old observation timestamp\n * @custom:error Zero price error is thrown if token is BNB based and price is zero\n * @custom:error Zero price error is thrown if fetched anchorPriceMantissa is zero\n * @custom:event Emits AnchorPriceUpdated event on successful update of observation with assset address,\n * AnchorPrice, old observation timestamp and current timestamp\n */\n function _updateTwapInternal(TokenConfig memory config) internal virtual returns (uint256) {\n // pokeWindowValues already handled reversed pool cases,\n // priceAverage will always be Token/BNB or Token/BUSD *twap** price.\n (uint256 nowCumulativePrice, uint256 oldCumulativePrice, uint256 oldTimestamp) = pokeWindowValues(config);\n\n if (block.timestamp == oldTimestamp) return prices[config.asset];\n\n // This should be impossible, but better safe than sorry\n if (block.timestamp < oldTimestamp) revert(\"now must come after before\");\n\n uint256 timeElapsed = block.timestamp - oldTimestamp;\n\n // Calculate Pancake *twap**\n FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(\n uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)\n );\n // *twap** price with 1e18 decimal mantissa\n uint256 priceAverageMantissa = priceAverage.decode112with18();\n\n // To cancel the decimals in cumulative price, we need to mulitply the average price with\n // tokenBaseUnit / (wbnbBaseUnit or busdBaseUnit, which is 1e18)\n uint256 pairedTokenBaseUnit = config.isBnbBased ? bnbBaseUnit : busdBaseUnit;\n uint256 anchorPriceMantissa = (priceAverageMantissa * config.baseUnit) / pairedTokenBaseUnit;\n\n // if this token is paired with BNB, convert its price to USD\n if (config.isBnbBased) {\n uint256 bnbPrice = prices[WBNB];\n if (bnbPrice == 0) revert(\"bnb price is invalid\");\n anchorPriceMantissa = (anchorPriceMantissa * bnbPrice) / bnbBaseUnit;\n }\n\n if (anchorPriceMantissa == 0) revert(\"twap price cannot be 0\");\n\n emit AnchorPriceUpdated(config.asset, anchorPriceMantissa, oldTimestamp, block.timestamp);\n\n // save anchor price, which is 1e18 decimals\n prices[config.asset] = anchorPriceMantissa;\n\n return anchorPriceMantissa;\n }\n\n /**\n * @notice Appends current observation and pick an observation with a timestamp equal\n * or just greater than the window start timestamp. If one is not available,\n * then pick the last availableobservation. The window start index is updated in both the cases.\n * Only the current observation is saved, prior observations are deleted during this operation.\n * @return Tuple of cumulative price, old observation and timestamp\n * @custom:event Emits TwapWindowUpdated on successful calculation of cumulative price with asset address,\n * new observation timestamp, current timestamp, new observation price and cumulative price\n */\n function pokeWindowValues(\n TokenConfig memory config\n ) internal returns (uint256, uint256 startCumulativePrice, uint256 startCumulativeTimestamp) {\n uint256 cumulativePrice = currentCumulativePrice(config);\n uint256 currentTimestamp = block.timestamp;\n uint256 windowStartTimestamp = currentTimestamp - config.anchorPeriod;\n Observation[] memory storedObservations = observations[config.asset];\n\n uint256 storedObservationsLength = storedObservations.length;\n for (\n uint256 windowStartIndex = windowStart[config.asset];\n windowStartIndex < storedObservationsLength;\n ++windowStartIndex\n ) {\n if (\n (storedObservations[windowStartIndex].timestamp >= windowStartTimestamp) ||\n (windowStartIndex == storedObservationsLength - 1)\n ) {\n startCumulativePrice = storedObservations[windowStartIndex].acc;\n startCumulativeTimestamp = storedObservations[windowStartIndex].timestamp;\n windowStart[config.asset] = windowStartIndex;\n break;\n } else {\n delete observations[config.asset][windowStartIndex];\n }\n }\n\n observations[config.asset].push(Observation(currentTimestamp, cumulativePrice));\n emit TwapWindowUpdated(\n config.asset,\n startCumulativeTimestamp,\n startCumulativePrice,\n block.timestamp,\n cumulativePrice\n );\n return (cumulativePrice, startCumulativePrice, startCumulativeTimestamp);\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) internal view returns (address asset) {\n if (address(vToken) == vBnb) {\n asset = WBNB;\n } else if (address(vToken) == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
86
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../libraries/PancakeLibrary.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\ncontract TwapOracle is AccessControlledV8, TwapInterface {\n using FixedPoint for *;\n\n struct Observation {\n uint256 timestamp;\n uint256 acc;\n }\n\n struct TokenConfig {\n /// @notice Asset address, which can't be zero address and can be used for existance check\n address asset;\n /// @notice Decimals of underlying asset respresented as 1e{decimals}\n uint256 baseUnit;\n /// @notice The address of Pancake pair\n address pancakePool;\n /// @notice Whether the token is paired with WBNB\n bool isBnbBased;\n /// @notice A flag identifies whether the Pancake pair is reversed\n /// e.g. XVS-WBNB is reversed, while WBNB-XVS is not.\n bool isReversedPool;\n /// @notice The minimum window in seconds required between TWAP updates\n uint256 anchorPeriod;\n }\n\n /// @notice WBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WBNB;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice the base unit of WBNB and BUSD, which are the paired tokens for all assets\n uint256 public constant BNB_BASE_UNIT = 1e18;\n uint256 public constant BUSD_BASE_UNIT = 1e18;\n\n /// @notice Configs by token\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice Stored price by token\n mapping(address => uint256) public prices;\n\n /// @notice Keeps a record of token observations mapped by address, updated on every updateTwap invocation.\n mapping(address => Observation[]) public observations;\n\n /// @notice Observation array index which probably falls in current anchor period mapped by asset address\n mapping(address => uint256) public windowStart;\n\n /// @notice Emit this event when TWAP window is updated\n event TwapWindowUpdated(\n address indexed asset,\n uint256 oldTimestamp,\n uint256 oldAcc,\n uint256 newTimestamp,\n uint256 newAcc\n );\n\n /// @notice Emit this event when TWAP price is updated\n event AnchorPriceUpdated(address indexed asset, uint256 price, uint256 oldTimestamp, uint256 newTimestamp);\n\n /// @notice Emit this event when new token configs are added\n event TokenConfigAdded(address indexed asset, address indexed pancakePool, uint256 indexed anchorPeriod);\n\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the VBNB\n /// @param wBnbAddress The address of the WBNB\n /// @param vaiAddress The address of the WBNB\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address vBnbAddress,\n address wBnbAddress,\n address vaiAddress\n ) notNullAddress(vBnbAddress) notNullAddress(wBnbAddress) notNullAddress(vaiAddress) {\n vBnb = vBnbAddress;\n WBNB = wBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Adds multiple token configs at the same time\n * @param configs Config array\n * @custom:error Zero length error thrown, if length of the config array is 0\n */\n function setTokenConfigs(TokenConfig[] memory configs) external {\n if (configs.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = configs.length;\n for (uint256 i; i < numTokenConfigs; ) {\n setTokenConfig(configs[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Initializes the owner of the contract\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) external initializer {\n __AccessControlled_init(accessControlManager_);\n }\n\n /**\n * @notice Updates the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return anchorPrice anchor price of the underlying asset of the vToken\n * @custom:error Missing error is thrown if token config does not exist\n */\n function updateTwap(address vToken) external returns (uint256) {\n address asset = _getUnderlyingAsset(vToken);\n\n if (tokenConfigs[asset].asset == address(0)) revert(\"asset not exist\");\n // Update & fetch WBNB price first, so we can calculate the price of WBNB paired token\n if (asset != WBNB && tokenConfigs[asset].isBnbBased) {\n if (tokenConfigs[WBNB].asset == address(0)) revert(\"WBNB not exist\");\n _updateTwapInternal(tokenConfigs[WBNB]);\n }\n return _updateTwapInternal(tokenConfigs[asset]);\n }\n\n /**\n * @notice Get the underlying TWAP price for the given vToken\n * @param vToken vToken address\n * @return price Underlying price in USD\n * @custom:error Missing error is thrown if the token config does not exist\n * @custom:error Range error is thrown if TWAP price is not greater than zero\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n address asset = _getUnderlyingAsset(vToken);\n\n if (tokenConfigs[asset].asset == address(0)) revert(\"asset not exist\");\n uint256 price = prices[asset];\n\n // if price is 0, it means the price hasn't been updated yet and it's meaningless, revert\n if (price == 0) revert(\"TWAP price must be positive\");\n return (price * (10 ** (18 - IERC20Metadata(asset).decimals())));\n }\n\n /**\n * @notice Adds a single token config\n * @param config token config struct\n * @custom:access Only Governance\n * @custom:error Range error is thrown if anchor period is not greater than zero\n * @custom:error Range error is thrown if base unit is not greater than zero\n * @custom:error Value error is thrown if base unit decimals is not the same as asset decimals\n * @custom:error NotNullAddress error is thrown if address of asset is null\n * @custom:error NotNullAddress error is thrown if PancakeSwap pool address is null\n * @custom:event Emits TokenConfigAdded event if new token config are added with\n * asset address, PancakePool address, anchor period address\n */\n function setTokenConfig(\n TokenConfig memory config\n ) public notNullAddress(config.asset) notNullAddress(config.pancakePool) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n if (config.anchorPeriod == 0) revert(\"anchor period must be positive\");\n if (config.baseUnit != 10 ** IERC20Metadata(config.asset).decimals())\n revert(\"base unit decimals must be same as asset decimals\");\n\n uint256 cumulativePrice = currentCumulativePrice(config);\n\n // Initialize observation data\n observations[config.asset].push(Observation(block.timestamp, cumulativePrice));\n tokenConfigs[config.asset] = config;\n emit TokenConfigAdded(config.asset, config.pancakePool, config.anchorPeriod);\n }\n\n /**\n * @notice Fetches the current token/WBNB and token/BUSD price accumulator from PancakeSwap.\n * @return cumulative price of target token regardless of pair order\n */\n function currentCumulativePrice(TokenConfig memory config) public view returns (uint256) {\n (uint256 price0, uint256 price1, ) = PancakeOracleLibrary.currentCumulativePrices(config.pancakePool);\n if (config.isReversedPool) {\n return price1;\n } else {\n return price0;\n }\n }\n\n /**\n * @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return price Underlying price in USD, with 18 decimals\n * @custom:error Timing error is thrown if current time is not greater than old observation timestamp\n * @custom:error Zero price error is thrown if token is BNB based and price is zero\n * @custom:error Zero price error is thrown if fetched anchorPriceMantissa is zero\n * @custom:event Emits AnchorPriceUpdated event on successful update of observation with assset address,\n * AnchorPrice, old observation timestamp and current timestamp\n */\n function _updateTwapInternal(TokenConfig memory config) private returns (uint256) {\n // pokeWindowValues already handled reversed pool cases,\n // priceAverage will always be Token/BNB or Token/BUSD *twap** price.\n (uint256 nowCumulativePrice, uint256 oldCumulativePrice, uint256 oldTimestamp) = pokeWindowValues(config);\n\n if (block.timestamp == oldTimestamp) return prices[config.asset];\n\n // This should be impossible, but better safe than sorry\n if (block.timestamp < oldTimestamp) revert(\"now must come after before\");\n\n uint256 timeElapsed;\n unchecked {\n timeElapsed = block.timestamp - oldTimestamp;\n }\n\n // Calculate Pancake *twap**\n FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(\n uint224((nowCumulativePrice - oldCumulativePrice) / timeElapsed)\n );\n // *twap** price with 1e18 decimal mantissa\n uint256 priceAverageMantissa = priceAverage.decode112with18();\n\n // To cancel the decimals in cumulative price, we need to mulitply the average price with\n // tokenBaseUnit / (BNB_BASE_UNIT or BUSD_BASE_UNIT, which is 1e18)\n uint256 pairedTokenBaseUnit = config.isBnbBased ? BNB_BASE_UNIT : BUSD_BASE_UNIT;\n uint256 anchorPriceMantissa = (priceAverageMantissa * config.baseUnit) / pairedTokenBaseUnit;\n\n // if this token is paired with BNB, convert its price to USD\n if (config.isBnbBased) {\n uint256 bnbPrice = prices[WBNB];\n if (bnbPrice == 0) revert(\"bnb price is invalid\");\n anchorPriceMantissa = (anchorPriceMantissa * bnbPrice) / BNB_BASE_UNIT;\n }\n\n if (anchorPriceMantissa == 0) revert(\"twap price cannot be 0\");\n\n emit AnchorPriceUpdated(config.asset, anchorPriceMantissa, oldTimestamp, block.timestamp);\n\n // save anchor price, which is 1e18 decimals\n prices[config.asset] = anchorPriceMantissa;\n\n return anchorPriceMantissa;\n }\n\n /**\n * @notice Appends current observation and pick an observation with a timestamp equal\n * or just greater than the window start timestamp. If one is not available,\n * then pick the last availableobservation. The window start index is updated in both the cases.\n * Only the current observation is saved, prior observations are deleted during this operation.\n * @return Tuple of cumulative price, old observation and timestamp\n * @custom:event Emits TwapWindowUpdated on successful calculation of cumulative price with asset address,\n * new observation timestamp, current timestamp, new observation price and cumulative price\n */\n function pokeWindowValues(\n TokenConfig memory config\n ) private returns (uint256, uint256 startCumulativePrice, uint256 startCumulativeTimestamp) {\n uint256 cumulativePrice = currentCumulativePrice(config);\n uint256 currentTimestamp = block.timestamp;\n uint256 windowStartTimestamp = currentTimestamp - config.anchorPeriod;\n Observation[] memory storedObservations = observations[config.asset];\n\n uint256 storedObservationsLength = storedObservations.length;\n for (uint256 windowStartIndex = windowStart[config.asset]; windowStartIndex < storedObservationsLength; ) {\n if (\n (storedObservations[windowStartIndex].timestamp >= windowStartTimestamp) ||\n (windowStartIndex == storedObservationsLength - 1)\n ) {\n startCumulativePrice = storedObservations[windowStartIndex].acc;\n startCumulativeTimestamp = storedObservations[windowStartIndex].timestamp;\n windowStart[config.asset] = windowStartIndex;\n break;\n } else {\n delete observations[config.asset][windowStartIndex];\n }\n\n unchecked {\n ++windowStartIndex;\n }\n }\n\n observations[config.asset].push(Observation(currentTimestamp, cumulativePrice));\n emit TwapWindowUpdated(\n config.asset,\n startCumulativeTimestamp,\n startCumulativePrice,\n block.timestamp,\n cumulativePrice\n );\n return (cumulativePrice, startCumulativePrice, startCumulativeTimestamp);\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) private view returns (address asset) {\n if (vToken == vBnb) {\n asset = WBNB;\n } else if (vToken == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
93
87
|
},
|
|
94
88
|
"contracts/ResilientOracle.sol": {
|
|
95
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\n// SPDX-FileCopyrightText: 2022 Venus\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport \"./interfaces/VBep20Interface.sol\";\nimport \"./interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\ncontract ResilientOracle is PausableUpgradeable, AccessControlledV8, ResilientOracleInterface {\n /**\n * @dev Oracle roles:\n * **main**: The most trustworthy price source\n * **pivot**: Price oracle used as a loose sanity checker\n * **fallback**: The backup source when main oracle price is invalidated\n */\n enum OracleRole {\n MAIN,\n PIVOT,\n FALLBACK\n }\n\n struct TokenConfig {\n /// @notice asset address\n address asset;\n /// @notice `oracles` stores the oracles based on their role in the following order:\n /// [main, pivot, fallback],\n /// It can be indexed with the corresponding enum OracleRole value\n address[3] oracles;\n /// @notice `enableFlagsForOracles` stores the enabled state\n /// for each oracle in the same order as `oracles`\n bool[3] enableFlagsForOracles;\n }\n\n uint256 public constant INVALID_PRICE = 0;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for BNB. This is the underlying for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n BoundValidatorInterface public boundValidator;\n\n mapping(address => TokenConfig) private tokenConfigs;\n\n event TokenConfigAdded(\n address indexed asset,\n address indexed mainOracle,\n address indexed pivotOracle,\n address fallbackOracle\n );\n\n /// Event emitted when an oracle is set\n event OracleSet(address indexed asset, address indexed oracle, uint256 indexed role);\n\n /// Event emitted when an oracle is enabled or disabled\n event OracleEnabled(address indexed asset, uint256 indexed role, bool indexed enable);\n\n /**\n * @notice Checks whether an address is null or not\n */\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /**\n * @notice Checks whether token config exists by checking whether vToken is null address\n * @dev vToken can't be null, so it's suitable to be used to check the validity of the config\n * @param asset asset address\n */\n modifier checkTokenConfigExistence(address asset) {\n if (tokenConfigs[asset].asset == address(0)) revert(\"token config must exist\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address vBnbAddress, address vaiAddress) notNullAddress(vBnbAddress) {\n vBnb = vBnbAddress;\n vai = vaiAddress;\n _disableInitializers();\n }\n\n /**\n * @notice Pauses oracle\n * @custom:access Only Governance\n */\n function pause() external {\n _checkAccessAllowed(\"pause()\");\n _pause();\n }\n\n /**\n * @notice Unpauses oracle\n * @custom:access Only Governance\n */\n function unpause() external {\n _checkAccessAllowed(\"unpause()\");\n _unpause();\n }\n\n /**\n * @notice Batch sets token configs\n * @param tokenConfigs_ Token config array\n * @custom:access Only Governance\n * @custom:error Throws a length error if the lenght of the token configs array is 0\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external {\n _checkAccessAllowed(\"setTokenConfigs(TokenConfig[])\");\n if (tokenConfigs_.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = tokenConfigs_.length;\n for (uint256 i; i < numTokenConfigs; ++i) {\n setTokenConfig(tokenConfigs_[i]);\n }\n }\n\n /**\n * @notice Sets oracle for a given vToken and role.\n * @dev Supplied vToken **must** exist and main oracle may not be null\n * @param asset Asset address\n * @param oracle Oracle address\n * @param role Oracle role\n * @custom:access Only Governance\n * @custom:error Null address error if main-role oracle address is null\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n * @custom:event Emits OracleSet event with asset address, oracle address and role of the oracle for the asset\n */\n function setOracle(\n address asset,\n address oracle,\n OracleRole role\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"setOracle(address,address,OracleRole)\");\n if (oracle == address(0) && role == OracleRole.MAIN) revert(\"can't set zero address to main oracle\");\n tokenConfigs[asset].oracles[uint256(role)] = oracle;\n emit OracleSet(asset, oracle, uint256(role));\n }\n\n /**\n * @notice Enables/ disables oracle for the input vToken, input vToken **must** exist\n * @param asset Asset address\n * @param role Oracle role\n * @param enable Enabled boolean of the oracle\n * @custom:access Only Governance\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n */\n function enableOracle(\n address asset,\n OracleRole role,\n bool enable\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"enableOracle(address,OracleRole,bool)\");\n tokenConfigs[asset].enableFlagsForOracles[uint256(role)] = enable;\n emit OracleEnabled(asset, uint256(role), enable);\n }\n\n /**\n * @notice Updates the pivot oracle price. Currently using TWAP\n * @dev This function should always be called before calling getUnderlyingPrice\n * @param vToken vToken address\n */\n function updatePrice(address vToken) external override {\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n if (pivotOracle != address(0) && pivotOracleEnabled) {\n //if **pivot** oracle is PythOrcle it will revert so we need to catch the revert\n try TwapInterface(pivotOracle).updateTwap(vToken) {} catch {}\n }\n }\n\n /**\n * @dev Gets token config by vToken address\n * @param vToken vToken address\n * @return tokenConfig Config for the vToken\n */\n function getTokenConfig(address vToken) external view returns (TokenConfig memory) {\n address asset = _getUnderlyingAsset(vToken);\n return tokenConfigs[asset];\n }\n\n /**\n * @notice Gets price of the underlying asset for a given vToken. Validation flow:\n * - Check if the oracle is paused globally\n * - Validate price from main oracle against pivot oracle\n * - Validate price from fallback oracle against pivot oracle or main oracle if the first validation failed\n * In the case that the pivot oracle is not available but main price is available and validation is successful,\n * main oracle price is returned.\n * @param vToken vToken address\n * @return price USD price in scaled decimal places.\n * @custom:error Paused error is thrown when resilent oracle is paused\n * @custom:error Invalid resilient oracle price error is thrown if fetched prices from oracle is invalid\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n if (paused()) revert(\"resilient oracle is paused\");\n uint256 pivotPrice = INVALID_PRICE;\n\n // Get pivot oracle price, Invalid price if not available or error\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getUnderlyingPrice(vToken) returns (uint256 pricePivot) {\n pivotPrice = pricePivot;\n } catch {}\n }\n\n // Compare main price and pivot price, return main price and if validation was successful\n // note: In case pivot oracle is not available but main price is available and\n // validation is successful, the main oracle price is returned.\n (uint256 mainPrice, bool validatedPivotMain) = _getMainOraclePrice(\n vToken,\n pivotPrice,\n pivotOracleEnabled && pivotOracle != address(0)\n );\n if (mainPrice != INVALID_PRICE && validatedPivotMain) return mainPrice;\n\n // Compare fallback and pivot if main oracle comparision fails with pivot\n // Return fallback price when fallback price is validated successfully with pivot oracle\n (uint256 fallbackPrice, bool validatedPivotFallback) = _getFallbackOraclePrice(vToken, pivotPrice);\n if (fallbackPrice != INVALID_PRICE && validatedPivotFallback) return fallbackPrice;\n\n // Lastly compare main price and fallback price\n if (\n mainPrice != INVALID_PRICE &&\n fallbackPrice != INVALID_PRICE &&\n boundValidator.validatePriceWithAnchorPrice(vToken, fallbackPrice, mainPrice)\n ) {\n return mainPrice;\n }\n\n revert(\"invalid resilient oracle price\");\n }\n\n /**\n * @notice Initializes the contract admin and sets the BoundValidator contract address\n * @param _boundValidator Address of the bound validator contract\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(BoundValidatorInterface _boundValidator, address accessControlManager_) public initializer {\n if (address(_boundValidator) == address(0)) revert(\"invalid bound validator address\");\n boundValidator = _boundValidator;\n\n __AccessControlled_init(accessControlManager_);\n __Pausable_init();\n }\n\n /**\n * @notice Sets/resets single token configs.\n * @dev main oracle **must not** be a null address\n * @param tokenConfig Token config struct\n * @custom:access Only Governance\n * @custom:error NotNullAddress is thrown if asset address is null\n * @custom:error NotNullAddress is thrown if main-role oracle address for asset is null\n * @custom:event Emits TokenConfigAdded event when vToken config is set successfully by governnace\n */\n function setTokenConfig(\n TokenConfig memory tokenConfig\n ) public notNullAddress(tokenConfig.asset) notNullAddress(tokenConfig.oracles[uint256(OracleRole.MAIN)]) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(\n tokenConfig.asset,\n tokenConfig.oracles[uint256(OracleRole.MAIN)],\n tokenConfig.oracles[uint256(OracleRole.PIVOT)],\n tokenConfig.oracles[uint256(OracleRole.FALLBACK)]\n );\n }\n\n /**\n * @notice Gets oracle and enabled status by vToken address\n * @param vToken vToken address\n * @param role Oracle role\n * @return oracle Oracle address based on role\n * @return enabled Enabled flag of the oracle based on token config\n */\n function getOracle(address vToken, OracleRole role) public view returns (address oracle, bool enabled) {\n address asset = _getUnderlyingAsset(vToken);\n\n oracle = tokenConfigs[asset].oracles[uint256(role)];\n enabled = tokenConfigs[asset].enableFlagsForOracles[uint256(role)];\n }\n\n /**\n * @notice Gets underlying asset price for the provided vToken\n * @dev This function won't revert when price is 0, because the fallback oracle may still be\n * able to fetch a correct price\n * @param vToken vToken address\n * @param pivotPrice Pivot oracle price\n * @param pivotEnabled If pivot oracle is not empty and enabled\n * @return price USD price in scaled decimals\n * e.g. vToken decimals is 8 then price is returned as 10**18 * 10**(18-8) = 10**28 decimals\n * @return pivotValidated Boolean representing if the validation of main oracle price\n * and pivot oracle price were successful\n * @custom:error Invalid price error is thrown if main oracle fails to fetch price of underlying asset\n * @custom:error Invalid price error is thrown if main oracle is not enabled or main oracle\n * address is null\n */\n function _getMainOraclePrice(\n address vToken,\n uint256 pivotPrice,\n bool pivotEnabled\n ) internal view returns (uint256, bool) {\n (address mainOracle, bool mainOracleEnabled) = getOracle(vToken, OracleRole.MAIN);\n if (mainOracleEnabled && mainOracle != address(0)) {\n try OracleInterface(mainOracle).getUnderlyingPrice(vToken) returns (uint256 mainOraclePrice) {\n if (!pivotEnabled) {\n return (mainOraclePrice, true);\n }\n if (pivotPrice == INVALID_PRICE) {\n return (mainOraclePrice, false);\n }\n return (\n mainOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(vToken, mainOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function won't revert when the price is 0 because getUnderlyingPrice checks if price is > 0\n * @param vToken vToken address\n * @return price USD price in 18 decimals\n * @return pivotValidated Boolean representing if the validation of fallback oracle price\n * and pivot oracle price were successfull\n * @custom:error Invalid price error is thrown if fallback oracle fails to fetch price of underlying asset\n * @custom:error Invalid price error is thrown if fallback oracle is not enabled or fallback oracle\n * address is null\n */\n function _getFallbackOraclePrice(address vToken, uint256 pivotPrice) internal view returns (uint256, bool) {\n (address fallbackOracle, bool fallbackEnabled) = getOracle(vToken, OracleRole.FALLBACK);\n if (fallbackEnabled && fallbackOracle != address(0)) {\n try OracleInterface(fallbackOracle).getUnderlyingPrice(vToken) returns (uint256 fallbackOraclePrice) {\n if (pivotPrice == INVALID_PRICE) {\n return (fallbackOraclePrice, false);\n }\n return (\n fallbackOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(vToken, fallbackOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) internal view returns (address asset) {\n if (address(vToken) == vBnb) {\n asset = BNB_ADDR;\n } else if (address(vToken) == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
89
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\n// SPDX-FileCopyrightText: 2022 Venus\npragma solidity 0.8.13;\n\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport \"./interfaces/VBep20Interface.sol\";\nimport \"./interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\ncontract ResilientOracle is PausableUpgradeable, AccessControlledV8, ResilientOracleInterface {\n /**\n * @dev Oracle roles:\n * **main**: The most trustworthy price source\n * **pivot**: Price oracle used as a loose sanity checker\n * **fallback**: The backup source when main oracle price is invalidated\n */\n enum OracleRole {\n MAIN,\n PIVOT,\n FALLBACK\n }\n\n struct TokenConfig {\n /// @notice asset address\n address asset;\n /// @notice `oracles` stores the oracles based on their role in the following order:\n /// [main, pivot, fallback],\n /// It can be indexed with the corresponding enum OracleRole value\n address[3] oracles;\n /// @notice `enableFlagsForOracles` stores the enabled state\n /// for each oracle in the same order as `oracles`\n bool[3] enableFlagsForOracles;\n }\n\n uint256 public constant INVALID_PRICE = 0;\n\n /// @notice vBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBnb;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for BNB. This is the underlying for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n BoundValidatorInterface public immutable boundValidator;\n\n mapping(address => TokenConfig) private tokenConfigs;\n\n event TokenConfigAdded(\n address indexed asset,\n address indexed mainOracle,\n address indexed pivotOracle,\n address fallbackOracle\n );\n\n /// Event emitted when an oracle is set\n event OracleSet(address indexed asset, address indexed oracle, uint256 indexed role);\n\n /// Event emitted when an oracle is enabled or disabled\n event OracleEnabled(address indexed asset, uint256 indexed role, bool indexed enable);\n\n /**\n * @notice Checks whether an address is null or not\n */\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /**\n * @notice Checks whether token config exists by checking whether vToken is null address\n * @dev vToken can't be null, so it's suitable to be used to check the validity of the config\n * @param asset asset address\n */\n modifier checkTokenConfigExistence(address asset) {\n if (tokenConfigs[asset].asset == address(0)) revert(\"token config must exist\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param vBnbAddress The address of the vBNB\n /// @param vaiAddress The address of the VAI\n /// @param _boundValidator Address of the bound validator contract\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address vBnbAddress, address vaiAddress, BoundValidatorInterface _boundValidator\n ) notNullAddress(vBnbAddress) notNullAddress(vaiAddress) notNullAddress(address(_boundValidator)) {\n vBnb = vBnbAddress;\n vai = vaiAddress;\n boundValidator = _boundValidator;\n\n _disableInitializers();\n }\n\n /**\n * @notice Initializes the contract admin and sets the BoundValidator contract address\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) external initializer {\n __AccessControlled_init(accessControlManager_);\n __Pausable_init();\n }\n\n /**\n * @notice Pauses oracle\n * @custom:access Only Governance\n */\n function pause() external {\n _checkAccessAllowed(\"pause()\");\n _pause();\n }\n\n /**\n * @notice Unpauses oracle\n * @custom:access Only Governance\n */\n function unpause() external {\n _checkAccessAllowed(\"unpause()\");\n _unpause();\n }\n\n /**\n * @notice Batch sets token configs\n * @param tokenConfigs_ Token config array\n * @custom:access Only Governance\n * @custom:error Throws a length error if the length of the token configs array is 0\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external {\n if (tokenConfigs_.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = tokenConfigs_.length;\n for (uint256 i; i < numTokenConfigs; ) {\n setTokenConfig(tokenConfigs_[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Sets oracle for a given vToken and role.\n * @dev Supplied vToken **must** exist and main oracle may not be null\n * @param asset Asset address\n * @param oracle Oracle address\n * @param role Oracle role\n * @custom:access Only Governance\n * @custom:error Null address error if main-role oracle address is null\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n * @custom:event Emits OracleSet event with asset address, oracle address and role of the oracle for the asset\n */\n function setOracle(\n address asset,\n address oracle,\n OracleRole role\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"setOracle(address,address,uint8)\");\n if (oracle == address(0) && role == OracleRole.MAIN) revert(\"can't set zero address to main oracle\");\n tokenConfigs[asset].oracles[uint256(role)] = oracle;\n emit OracleSet(asset, oracle, uint256(role));\n }\n\n /**\n * @notice Enables/ disables oracle for the input vToken, input vToken **must** exist\n * @param asset Asset address\n * @param role Oracle role\n * @param enable Enabled boolean of the oracle\n * @custom:access Only Governance\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n */\n function enableOracle(\n address asset,\n OracleRole role,\n bool enable\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"enableOracle(address,uint8,bool)\");\n tokenConfigs[asset].enableFlagsForOracles[uint256(role)] = enable;\n emit OracleEnabled(asset, uint256(role), enable);\n }\n\n /**\n * @notice Updates the TWAP pivot oracle price.\n * @dev This function should always be called before calling getUnderlyingPrice\n * @param vToken vToken address\n */\n function updatePrice(address vToken) external override {\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n if (pivotOracle != address(0) && pivotOracleEnabled) {\n //if pivot oracle is not TwapOracle it will revert so we need to catch the revert\n try TwapInterface(pivotOracle).updateTwap(vToken) {} catch {}\n }\n }\n\n /**\n * @dev Gets token config by vToken address\n * @param vToken vToken address\n * @return tokenConfig Config for the vToken\n */\n function getTokenConfig(address vToken) external view returns (TokenConfig memory) {\n address asset = _getUnderlyingAsset(vToken);\n return tokenConfigs[asset];\n }\n\n /**\n * @notice Gets price of the underlying asset for a given vToken. Validation flow:\n * - Check if the oracle is paused globally\n * - Validate price from main oracle against pivot oracle\n * - Validate price from fallback oracle against pivot oracle if the first validation failed\n * - Validate price from main oracle against fallback oracle if the second validation failed\n * In the case that the pivot oracle is not available but main price is available and validation is successful,\n * main oracle price is returned.\n * @param vToken vToken address\n * @return price USD price in scaled decimal places.\n * @custom:error Paused error is thrown when resilent oracle is paused\n * @custom:error Invalid resilient oracle price error is thrown if fetched prices from oracle is invalid\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n if (paused()) revert(\"resilient oracle is paused\");\n uint256 pivotPrice = INVALID_PRICE;\n\n // Get pivot oracle price, Invalid price if not available or error\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getUnderlyingPrice(vToken) returns (uint256 pricePivot) {\n pivotPrice = pricePivot;\n } catch {}\n }\n\n // Compare main price and pivot price, return main price and if validation was successful\n // note: In case pivot oracle is not available but main price is available and\n // validation is successful, the main oracle price is returned.\n (uint256 mainPrice, bool validatedPivotMain) = _getMainOraclePrice(\n vToken,\n pivotPrice,\n pivotOracleEnabled && pivotOracle != address(0)\n );\n if (mainPrice != INVALID_PRICE && validatedPivotMain) return mainPrice;\n\n // Compare fallback and pivot if main oracle comparision fails with pivot\n // Return fallback price when fallback price is validated successfully with pivot oracle\n (uint256 fallbackPrice, bool validatedPivotFallback) = _getFallbackOraclePrice(vToken, pivotPrice);\n if (fallbackPrice != INVALID_PRICE && validatedPivotFallback) return fallbackPrice;\n\n // Lastly compare main price and fallback price\n if (\n mainPrice != INVALID_PRICE &&\n fallbackPrice != INVALID_PRICE &&\n boundValidator.validatePriceWithAnchorPrice(vToken, mainPrice, fallbackPrice)\n ) {\n return mainPrice;\n }\n\n revert(\"invalid resilient oracle price\");\n }\n\n /**\n * @notice Sets/resets single token configs.\n * @dev main oracle **must not** be a null address\n * @param tokenConfig Token config struct\n * @custom:access Only Governance\n * @custom:error NotNullAddress is thrown if asset address is null\n * @custom:error NotNullAddress is thrown if main-role oracle address for asset is null\n * @custom:event Emits TokenConfigAdded event when vToken config is set successfully by governnace\n */\n function setTokenConfig(\n TokenConfig memory tokenConfig\n ) public notNullAddress(tokenConfig.asset) notNullAddress(tokenConfig.oracles[uint256(OracleRole.MAIN)]) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(\n tokenConfig.asset,\n tokenConfig.oracles[uint256(OracleRole.MAIN)],\n tokenConfig.oracles[uint256(OracleRole.PIVOT)],\n tokenConfig.oracles[uint256(OracleRole.FALLBACK)]\n );\n }\n\n /**\n * @notice Gets oracle and enabled status by vToken address\n * @param vToken vToken address\n * @param role Oracle role\n * @return oracle Oracle address based on role\n * @return enabled Enabled flag of the oracle based on token config\n */\n function getOracle(address vToken, OracleRole role) public view returns (address oracle, bool enabled) {\n address asset = _getUnderlyingAsset(vToken);\n\n oracle = tokenConfigs[asset].oracles[uint256(role)];\n enabled = tokenConfigs[asset].enableFlagsForOracles[uint256(role)];\n }\n\n /**\n * @notice Gets underlying asset price for the provided vToken\n * @dev This function won't revert when price is 0, because the fallback oracle may still be\n * able to fetch a correct price\n * @param vToken vToken address\n * @param pivotPrice Pivot oracle price\n * @param pivotEnabled If pivot oracle is not empty and enabled\n * @return price USD price in scaled decimals\n * e.g. vToken decimals is 8 then price is returned as 10**18 * 10**(18-8) = 10**28 decimals\n * @return pivotValidated Boolean representing if the validation of main oracle price\n * and pivot oracle price were successful\n * @custom:error Invalid price error is thrown if main oracle fails to fetch price of underlying asset\n * @custom:error Invalid price error is thrown if main oracle is not enabled or main oracle\n * address is null\n */\n function _getMainOraclePrice(\n address vToken,\n uint256 pivotPrice,\n bool pivotEnabled\n ) private view returns (uint256, bool) {\n (address mainOracle, bool mainOracleEnabled) = getOracle(vToken, OracleRole.MAIN);\n if (mainOracleEnabled && mainOracle != address(0)) {\n try OracleInterface(mainOracle).getUnderlyingPrice(vToken) returns (uint256 mainOraclePrice) {\n if (!pivotEnabled) {\n return (mainOraclePrice, true);\n }\n if (pivotPrice == INVALID_PRICE) {\n return (mainOraclePrice, false);\n }\n return (\n mainOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(vToken, mainOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function won't revert when the price is 0 because getUnderlyingPrice checks if price is > 0\n * @param vToken vToken address\n * @return price USD price in 18 decimals\n * @return pivotValidated Boolean representing if the validation of fallback oracle price\n * and pivot oracle price were successfull\n * @custom:error Invalid price error is thrown if fallback oracle fails to fetch price of underlying asset\n * @custom:error Invalid price error is thrown if fallback oracle is not enabled or fallback oracle\n * address is null\n */\n function _getFallbackOraclePrice(address vToken, uint256 pivotPrice) private view returns (uint256, bool) {\n (address fallbackOracle, bool fallbackEnabled) = getOracle(vToken, OracleRole.FALLBACK);\n if (fallbackEnabled && fallbackOracle != address(0)) {\n try OracleInterface(fallbackOracle).getUnderlyingPrice(vToken) returns (uint256 fallbackOraclePrice) {\n if (pivotPrice == INVALID_PRICE) {\n return (fallbackOraclePrice, false);\n }\n return (\n fallbackOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(vToken, fallbackOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) private view returns (address asset) {\n if (address(vToken) == vBnb) {\n asset = BNB_ADDR;\n } else if (address(vToken) == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
96
90
|
}
|
|
97
91
|
},
|
|
98
92
|
"settings": {
|