@venusprotocol/oracle 1.10.0-dev.3 → 1.10.0-dev.5
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/README.md +2 -2
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol/AggregatorInterface.dbg.json +1 -1
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV2V3Interface.sol/AggregatorV2V3Interface.dbg.json +1 -1
- package/artifacts/@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol/AggregatorV3Interface.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/ERC20.sol/ERC20.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/IERC20.sol/IERC20.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol/IERC20Metadata.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/math/SafeCast.sol/SafeCast.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol/Ownable2StepUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol/OwnableUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol/Initializable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol/PausableUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol/AddressUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol/ContextUpgradeable.dbg.json +1 -1
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlManager.sol/AccessControlManager.dbg.json +1 -1
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol/AccessControlledV8.dbg.json +1 -1
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol/IAccessControlManagerV8.dbg.json +1 -1
- package/artifacts/build-info/cdd56e5e725d884c2b45e24d2c35e787.json +1 -0
- package/artifacts/contracts/ResilientOracle.sol/ResilientOracle.dbg.json +1 -1
- package/artifacts/contracts/interfaces/FeedRegistryInterface.sol/FeedRegistryInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/IStETH.sol/IStETH.dbg.json +1 -1
- package/artifacts/contracts/interfaces/OracleInterface.sol/BoundValidatorInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/OracleInterface.sol/OracleInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/OracleInterface.sol/ResilientOracleInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/OracleInterface.sol/TwapInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PublicResolverInterface.sol/PublicResolverInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.dbg.json +1 -1
- package/artifacts/contracts/interfaces/SIDRegistryInterface.sol/SIDRegistryInterface.dbg.json +1 -1
- package/artifacts/contracts/interfaces/VBep20Interface.sol/VBep20Interface.dbg.json +1 -1
- package/artifacts/contracts/oracles/BinanceOracle.sol/BinanceOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/BoundValidator.sol/BoundValidator.dbg.json +1 -1
- package/artifacts/contracts/oracles/ChainlinkOracle.sol/ChainlinkOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/WstETHOracle.sol/WstETHOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockBinanceFeedRegistry.sol/MockBinanceFeedRegistry.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockChainlinkOracle.sol/MockChainlinkOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.dbg.json +1 -1
- package/artifacts/contracts/test/AccessControlManager.sol/AccessControlManagerScenario.dbg.json +1 -1
- package/artifacts/contracts/test/BEP20Harness.sol/BEP20Harness.dbg.json +1 -1
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.dbg.json +1 -1
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockBoundValidator.dbg.json +1 -1
- package/artifacts/contracts/test/MockSimpleOracle.sol/MockSimpleOracle.dbg.json +1 -1
- package/artifacts/contracts/test/MockV3Aggregator.sol/MockV3Aggregator.dbg.json +1 -1
- package/artifacts/contracts/test/PancakePairHarness.sol/Math.dbg.json +1 -1
- package/artifacts/contracts/test/PancakePairHarness.sol/PancakePairHarness.dbg.json +1 -1
- package/artifacts/contracts/test/PancakePairHarness.sol/UQ112x112.dbg.json +1 -1
- package/artifacts/contracts/test/VBEP20Harness.sol/VBEP20Harness.dbg.json +1 -1
- package/deployments/bscmainnet/solcInputs/aae9f1601b873a5a4704ede73ede10cb.json +0 -3
- package/deployments/bscmainnet/solcInputs/d647123072ba05451b756817f39951df.json +0 -6
- package/deployments/bscmainnet.json +0 -1560
- package/deployments/bscmainnet_addresses.json +1 -4
- package/deployments/bsctestnet/solcInputs/131f58942628e21632de19506977a910.json +0 -3
- package/deployments/bsctestnet/solcInputs/d647123072ba05451b756817f39951df.json +0 -6
- package/deployments/bsctestnet.json +0 -1560
- package/deployments/bsctestnet_addresses.json +1 -4
- package/deployments/ethereum/solcInputs/2675f6933965af498101c80cb5610aca.json +0 -6
- package/deployments/ethereum/solcInputs/61a63fbc062c2591c6768138f59373e1.json +0 -6
- package/deployments/opbnbmainnet/solcInputs/1e37f6e5d619feb70cefe47611ec524e.json +0 -6
- package/deployments/opbnbtestnet/solcInputs/3c996a10e894dc6fe519573ed39fc60f.json +0 -6
- package/deployments/sepolia/solcInputs/61a63fbc062c2591c6768138f59373e1.json +0 -6
- package/deployments/sepolia/solcInputs/f5d4d6aee7a4e630f36ae4eef8377cf3.json +0 -6
- package/dist/deploy/1-deploy-oracles.d.ts.map +1 -1
- package/dist/deploy/1-deploy-oracles.js +0 -24
- package/dist/deploy/1-deploy-oracles.js.map +1 -1
- package/dist/deploy/3-vip-based-configuration.d.ts.map +1 -1
- package/dist/deploy/3-vip-based-configuration.js +0 -1
- package/dist/deploy/3-vip-based-configuration.js.map +1 -1
- package/dist/typechain-types/contracts/index.d.ts +0 -2
- package/dist/typechain-types/contracts/index.d.ts.map +1 -1
- package/dist/typechain-types/contracts/oracles/index.d.ts +0 -1
- package/dist/typechain-types/contracts/oracles/index.d.ts.map +1 -1
- package/dist/typechain-types/contracts/oracles/mocks/index.d.ts +0 -1
- package/dist/typechain-types/contracts/oracles/mocks/index.d.ts.map +1 -1
- package/dist/typechain-types/factories/contracts/index.d.ts +0 -1
- package/dist/typechain-types/factories/contracts/index.d.ts.map +1 -1
- package/dist/typechain-types/factories/contracts/index.js +1 -2
- package/dist/typechain-types/factories/contracts/index.js.map +1 -1
- package/dist/typechain-types/factories/contracts/oracles/index.d.ts +0 -1
- package/dist/typechain-types/factories/contracts/oracles/index.d.ts.map +1 -1
- package/dist/typechain-types/factories/contracts/oracles/index.js +1 -3
- package/dist/typechain-types/factories/contracts/oracles/index.js.map +1 -1
- package/dist/typechain-types/factories/contracts/oracles/mocks/index.d.ts +0 -1
- package/dist/typechain-types/factories/contracts/oracles/mocks/index.d.ts.map +1 -1
- package/dist/typechain-types/factories/contracts/oracles/mocks/index.js +1 -3
- package/dist/typechain-types/factories/contracts/oracles/mocks/index.js.map +1 -1
- package/dist/typechain-types/index.d.ts +0 -6
- package/dist/typechain-types/index.d.ts.map +1 -1
- package/dist/typechain-types/index.js +1 -8
- package/dist/typechain-types/index.js.map +1 -1
- package/package.json +1 -1
- package/artifacts/build-info/1f32e9df7d74fc5f6586169f27f8b186.json +0 -1
- package/artifacts/contracts/libraries/PancakeLibrary.sol/FixedPoint.dbg.json +0 -4
- package/artifacts/contracts/libraries/PancakeLibrary.sol/FixedPoint.json +0 -10
- package/artifacts/contracts/libraries/PancakeLibrary.sol/IPancakePair.dbg.json +0 -4
- package/artifacts/contracts/libraries/PancakeLibrary.sol/IPancakePair.json +0 -60
- package/artifacts/contracts/libraries/PancakeLibrary.sol/PancakeOracleLibrary.dbg.json +0 -4
- package/artifacts/contracts/libraries/PancakeLibrary.sol/PancakeOracleLibrary.json +0 -10
- package/artifacts/contracts/oracles/TwapOracle.sol/TwapOracle.dbg.json +0 -4
- package/artifacts/contracts/oracles/TwapOracle.sol/TwapOracle.json +0 -640
- package/artifacts/contracts/oracles/mocks/MockTwapOracle.sol/MockTwapOracle.dbg.json +0 -4
- package/artifacts/contracts/oracles/mocks/MockTwapOracle.sol/MockTwapOracle.json +0 -163
- package/contracts/libraries/PancakeLibrary.sol +0 -68
- package/contracts/oracles/TwapOracle.sol +0 -300
- package/contracts/oracles/mocks/MockTwapOracle.sol +0 -30
- package/deployments/bscmainnet/TwapOracle.json +0 -887
- package/deployments/bscmainnet/TwapOracle_Implementation.json +0 -1111
- package/deployments/bscmainnet/TwapOracle_Proxy.json +0 -251
- package/deployments/bsctestnet/TwapOracle.json +0 -887
- package/deployments/bsctestnet/TwapOracle_Implementation.json +0 -1111
- package/deployments/bsctestnet/TwapOracle_Proxy.json +0 -251
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/IPancakePair.d.ts +0 -83
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/IPancakePair.d.ts.map +0 -1
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/IPancakePair.js +0 -3
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/IPancakePair.js.map +0 -1
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/index.d.ts +0 -2
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/index.d.ts.map +0 -1
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/index.js +0 -3
- package/dist/typechain-types/contracts/libraries/PancakeLibrary.sol/index.js.map +0 -1
- package/dist/typechain-types/contracts/libraries/index.d.ts +0 -3
- package/dist/typechain-types/contracts/libraries/index.d.ts.map +0 -1
- package/dist/typechain-types/contracts/libraries/index.js +0 -3
- package/dist/typechain-types/contracts/libraries/index.js.map +0 -1
- package/dist/typechain-types/contracts/oracles/TwapOracle.d.ts +0 -450
- package/dist/typechain-types/contracts/oracles/TwapOracle.d.ts.map +0 -1
- package/dist/typechain-types/contracts/oracles/TwapOracle.js +0 -3
- package/dist/typechain-types/contracts/oracles/TwapOracle.js.map +0 -1
- package/dist/typechain-types/contracts/oracles/mocks/MockTwapOracle.d.ts +0 -155
- package/dist/typechain-types/contracts/oracles/mocks/MockTwapOracle.d.ts.map +0 -1
- package/dist/typechain-types/contracts/oracles/mocks/MockTwapOracle.js +0 -3
- package/dist/typechain-types/contracts/oracles/mocks/MockTwapOracle.js.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/IPancakePair__factory.d.ts +0 -47
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/IPancakePair__factory.d.ts.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/IPancakePair__factory.js +0 -66
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/IPancakePair__factory.js.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/index.d.ts +0 -2
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/index.d.ts.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/index.js +0 -6
- package/dist/typechain-types/factories/contracts/libraries/PancakeLibrary.sol/index.js.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/index.d.ts +0 -2
- package/dist/typechain-types/factories/contracts/libraries/index.d.ts.map +0 -1
- package/dist/typechain-types/factories/contracts/libraries/index.js +0 -28
- package/dist/typechain-types/factories/contracts/libraries/index.js.map +0 -1
- package/dist/typechain-types/factories/contracts/oracles/TwapOracle__factory.d.ts +0 -509
- package/dist/typechain-types/factories/contracts/oracles/TwapOracle__factory.d.ts.map +0 -1
- package/dist/typechain-types/factories/contracts/oracles/TwapOracle__factory.js +0 -669
- package/dist/typechain-types/factories/contracts/oracles/TwapOracle__factory.js.map +0 -1
- package/dist/typechain-types/factories/contracts/oracles/mocks/MockTwapOracle__factory.d.ts +0 -139
- package/dist/typechain-types/factories/contracts/oracles/mocks/MockTwapOracle__factory.d.ts.map +0 -1
- package/dist/typechain-types/factories/contracts/oracles/mocks/MockTwapOracle__factory.js +0 -192
- package/dist/typechain-types/factories/contracts/oracles/mocks/MockTwapOracle__factory.js.map +0 -1
|
@@ -88,9 +88,6 @@
|
|
|
88
88
|
"contracts/oracles/PythOracle.sol": {
|
|
89
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\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
90
|
},
|
|
91
|
-
"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\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
|
-
},
|
|
94
91
|
"contracts/ResilientOracle.sol": {
|
|
95
92
|
"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 /// @notice Bound validator contract address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\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,\n address vaiAddress,\n 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
93
|
},
|
|
@@ -109,15 +109,9 @@
|
|
|
109
109
|
"contracts/oracles/mocks/MockPythOracle.sol": {
|
|
110
110
|
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { IPyth } from \"../PythOracle.sol\";\nimport { OracleInterface } from \"../../interfaces/OracleInterface.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 getPrice(address token) public view returns (uint256) {\n return assetPrices[token];\n }\n}\n"
|
|
111
111
|
},
|
|
112
|
-
"contracts/oracles/mocks/MockTwapOracle.sol": {
|
|
113
|
-
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.13;\n\nimport { OwnableUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport { OracleInterface } from \"../../interfaces/OracleInterface.sol\";\n\ncontract MockTwapOracle is OwnableUpgradeable {\n mapping(address => uint256) public assetPrices;\n\n /// @notice vBNB address\n address public vBNB;\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 vBNB_) public initializer {\n __Ownable_init();\n if (vBNB_ == address(0)) revert(\"vBNB can't be zero address\");\n vBNB = vBNB_;\n }\n\n //https://compound.finance/docs/prices\n function getPrice(address token) public view returns (uint256) {\n return assetPrices[token];\n }\n}\n"
|
|
114
|
-
},
|
|
115
112
|
"contracts/oracles/PythOracle.sol": {
|
|
116
113
|
"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 * @title PythOracle\n * @author Venus\n * @notice PythOracle contract reads prices from actual Pyth oracle contract which accepts, verifies and stores\n * the 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 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 asset, 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.\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\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 Set single token config. `maxStalePeriod` cannot be 0 and `asset` cannot 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 /**\n * @notice Gets the price of a asset from the pyth oracle\n * @param asset Address of the asset\n * @return Price in USD\n */\n function getPrice(address asset) public view returns (uint256) {\n uint256 decimals;\n\n if (asset == BNB_ADDR) {\n decimals = 18;\n } else {\n IERC20Metadata token = IERC20Metadata(asset);\n decimals = token.decimals();\n }\n\n return _getPriceInternal(asset, decimals);\n }\n\n function _getPriceInternal(address asset, uint256 decimals) internal view returns (uint256) {\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"
|
|
117
114
|
},
|
|
118
|
-
"contracts/oracles/TwapOracle.sol": {
|
|
119
|
-
"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\n/**\n * @title TwapOracle\n * @author Venus\n * @notice This oracle fetches price of assets from PancakeSwap.\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 asset represented 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 Set this as asset address for BNB. This is the underlying for vBNB\n address public constant BNB_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n /// @notice WBNB address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WBNB;\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 wBnbAddress The address of the WBNB\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address wBnbAddress) notNullAddress(wBnbAddress) {\n WBNB = wBnbAddress;\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 Get the TWAP price for the given asset\n * @param asset asset address\n * @return price asset 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 getPrice(address asset) external view override returns (uint256) {\n uint256 decimals;\n\n if (asset == BNB_ADDR) {\n decimals = 18;\n asset = WBNB;\n } else {\n IERC20Metadata token = IERC20Metadata(asset);\n decimals = token.decimals();\n }\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 - 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 Updates the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return anchorPrice anchor price of the asset\n * @custom:error Missing error is thrown if token config does not exist\n */\n function updateTwap(address asset) public returns (uint256) {\n if (asset == BNB_ADDR) {\n asset = WBNB;\n }\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 Asset 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"
|
|
120
|
-
},
|
|
121
115
|
"contracts/ResilientOracle.sol": {
|
|
122
116
|
"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\n/**\n * @title ResilientOracle\n * @author Venus\n * @notice The Resilient Oracle is the main contract that the protocol uses to fetch prices of assets.\n * \n * DeFi protocols are vulnerable to price oracle failures including oracle manipulation and incorrectly\n * reported prices. If only one oracle is used, this creates a single point of failure and opens a vector\n * for attacking the protocol.\n * \n * The Resilient Oracle uses multiple sources and fallback mechanisms to provide accurate prices and protect\n * the protocol from oracle attacks. Currently it includes integrations with Chainlink, Pyth, Binance Oracle\n * and TWAP (Time-Weighted Average Price) oracles. TWAP uses PancakeSwap as the on-chain price source.\n * \n * For every market (vToken) we configure the main, pivot and fallback oracles. The oracles are configured per \n * vToken's underlying asset address. The main oracle oracle is the most trustworthy price source, the pivot \n * oracle is used as a loose sanity checker and the fallback oracle is used as a backup price source. \n * \n * To validate prices returned from two oracles, we use an upper and lower bound ratio that is set for every\n * market. The upper bound ratio represents the deviation between reported price (the price that’s being\n * validated) and the anchor price (the price we are validating against) above which the reported price will\n * be invalidated. The lower bound ratio presents the deviation between reported price and anchor price below\n * which the reported price will be invalidated. So for oracle price to be considered valid the below statement\n * should be true:\n\n```\nanchorRatio = anchorPrice/reporterPrice\nisValid = anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio\n```\n\n * In most cases, Chainlink is used as the main oracle, TWAP or Pyth oracles are used as the pivot oracle depending\n * on which supports the given market and Binance oracle is used as the fallback oracle. For some markets we may\n * use Pyth or TWAP as the main oracle if the token price is not supported by Chainlink or Binance oracles. \n * \n * For a fetched price to be valid it must be positive and not stagnant. If the price is invalid then we consider the\n * oracle to be stagnant and treat it like it's disabled.\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 /// @notice Bound validator contract address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\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 asset is null address\n * @dev address 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,\n address vaiAddress,\n 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 asset and role.\n * @dev Supplied asset **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 asset. Token config for the input asset **must** exist\n * @dev Configuration for the asset **must** already exist and the asset cannot be 0 address\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 asset = _getUnderlyingAsset(vToken);\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, 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(asset) {} catch {}\n }\n }\n\n /**\n * @notice Updates the pivot oracle price. Currently using TWAP\n * @dev This function should always be called before calling getPrice\n * @param asset asset address\n */\n function updateAssetPrice(address asset) external {\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, 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(asset) {} catch {}\n }\n }\n\n /**\n * @dev Gets token config by asset address\n * @param asset asset address\n * @return tokenConfig Config for the asset\n */\n function getTokenConfig(address asset) external view returns (TokenConfig memory) {\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\n address asset = _getUnderlyingAsset(vToken);\n return _getPrice(asset);\n }\n\n /**\n * @notice Gets price of the asset\n * @param asset asset 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 getPrice(address asset) external view override returns (uint256) {\n if (paused()) revert(\"resilient oracle is paused\");\n return _getPrice(asset);\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 the asset config is set successfully by the authorized account\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 asset address\n * @param asset asset 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 asset, OracleRole role) public view returns (address oracle, bool enabled) {\n oracle = tokenConfigs[asset].oracles[uint256(role)];\n enabled = tokenConfigs[asset].enableFlagsForOracles[uint256(role)];\n }\n\n function _getPrice(address asset) internal view returns (uint256) {\n uint256 pivotPrice = INVALID_PRICE;\n\n // Get pivot oracle price, Invalid price if not available or error\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, OracleRole.PIVOT);\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getPrice(asset) 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 asset,\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(asset, 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(asset, mainPrice, fallbackPrice)\n ) {\n return mainPrice;\n }\n\n revert(\"invalid resilient oracle price\");\n }\n\n /**\n * @notice Gets a price for the provided asset\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 asset asset 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. asset 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 the 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 asset,\n uint256 pivotPrice,\n bool pivotEnabled\n ) internal view returns (uint256, bool) {\n (address mainOracle, bool mainOracleEnabled) = getOracle(asset, OracleRole.MAIN);\n if (mainOracleEnabled && mainOracle != address(0)) {\n try OracleInterface(mainOracle).getPrice(asset) 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(asset, 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 getPrice checks if price is > 0\n * @param asset asset 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 the 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 asset, uint256 pivotPrice) private view returns (uint256, bool) {\n (address fallbackOracle, bool fallbackEnabled) = getOracle(asset, OracleRole.FALLBACK);\n if (fallbackEnabled && fallbackOracle != address(0)) {\n try OracleInterface(fallbackOracle).getPrice(asset) returns (uint256 fallbackOraclePrice) {\n if (pivotPrice == INVALID_PRICE) {\n return (fallbackOraclePrice, false);\n }\n return (\n fallbackOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(asset, 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"
|
|
123
117
|
},
|