@venusprotocol/oracle 1.2.3 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/artifacts/build-info/442613ba0e31d357bb61ad07d3e9ccb5.json +1 -0
- package/artifacts/build-info/e79aa95060bbee82bc36063535db4019.json +1 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.dbg.json +4 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/AbstractPyth.json +545 -0
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/IPyth.json +130 -15
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.dbg.json +1 -1
- package/artifacts/contracts/interfaces/PythInterface.sol/PythStructs.json +2 -2
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/PythOracle.sol/PythOracle.json +2 -2
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockBinanceOracle.sol/MockBinanceOracle.json +22 -3
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.dbg.json +1 -1
- package/artifacts/contracts/oracles/mocks/MockPythOracle.sol/MockPythOracle.json +2 -2
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.dbg.json +1 -1
- package/artifacts/contracts/test/MockPyth.sol/MockPyth.json +305 -212
- package/contracts/interfaces/PythInterface.sol +147 -75
- package/contracts/oracles/PythOracle.sol +1 -1
- package/contracts/oracles/mocks/MockBinanceOracle.sol +5 -1
- package/contracts/test/MockPyth.sol +90 -55
- package/deploy/oracles.d.ts +1 -0
- package/deploy/oracles.d.ts.map +1 -1
- package/deploy/oracles.js +16 -1
- package/deploy/oracles.js.map +1 -1
- package/deployments/localhost/.chainId +1 -0
- package/deployments/localhost/BinanceOracle.json +393 -0
- package/deployments/localhost/BinanceOracle_Implementation.json +305 -0
- package/deployments/localhost/BinanceOracle_Proxy.json +241 -0
- package/deployments/localhost/BoundValidator.json +457 -0
- package/deployments/localhost/BoundValidator_Implementation.json +428 -0
- package/deployments/localhost/BoundValidator_Proxy.json +237 -0
- package/deployments/localhost/ChainlinkOracle.json +370 -0
- package/deployments/localhost/ChainlinkOracle_Implementation.json +273 -0
- package/deployments/localhost/ChainlinkOracle_Proxy.json +237 -0
- package/deployments/localhost/DefaultProxyAdmin.json +257 -0
- package/deployments/localhost/PivotTwapOracle.json +393 -0
- package/deployments/localhost/PivotTwapOracle_Implementation.json +304 -0
- package/deployments/localhost/PivotTwapOracle_Proxy.json +241 -0
- package/deployments/localhost/PythOracle.json +393 -0
- package/deployments/localhost/PythOracle_Implementation.json +309 -0
- package/deployments/localhost/PythOracle_Proxy.json +241 -0
- package/deployments/localhost/ResilientOracle.json +700 -0
- package/deployments/localhost/ResilientOracle_Implementation.json +746 -0
- package/deployments/localhost/ResilientOracle_Proxy.json +241 -0
- package/deployments/localhost/solcInputs/0e89febeebc7444140de8e67c9067d2c.json +78 -0
- package/deployments/localhost/solcInputs/468ec7a31e2db8855c82fb8141193271.json +54 -0
- package/deployments/localhost/solcInputs/50629170e50dc9fec79dac585e95ac05.json +138 -0
- package/package.json +1 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
{
|
|
2
|
+
"language": "Solidity",
|
|
3
|
+
"sources": {
|
|
4
|
+
"contracts/ResilientOracle.sol": {
|
|
5
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport \"./interfaces/OracleInterface.sol\";\n\ncontract ResilientOracle is OwnableUpgradeable, PausableUpgradeable, ResilientOracleInterface {\n uint256 public constant INVALID_PRICE = 0;\n\n BoundValidatorInterface public boundValidator;\n\n /**\n * @dev oracle role, we have 3 roles at the moment\n * MAIN: The most trustworthy price source\n * PIVOT: Not so trustworthy price source, 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 vToken address\n address vToken;\n /// @notice `oracles` stores the oracles in the order of: [main, pivot, fallback],\n /// it can be indexed with enum OracleRole value\n address[3] oracles;\n /// @notice `enableFlagsForOracles` stores the oracle enable statuses\n /// for each oracle in the same order as `oracles`\n bool[3] enableFlagsForOracles;\n }\n\n mapping(address => TokenConfig) private tokenConfigs;\n\n event GlobalEnable(bool indexed isEnable);\n event TokenConfigAdded(\n address indexed token,\n address indexed mainOracle,\n address indexed pivotOracle,\n address fallbackOracle\n );\n event OracleSet(address indexed vToken, address indexed oracle, uint256 indexed role);\n event OracleEnabled(address indexed vToken, uint256 indexed role, bool indexed enable);\n\n modifier notNullAddress(address someone) {\n require(someone != address(0), \"can't be zero address\");\n _;\n }\n\n /**\n * @notice Check whether token config exist by checking whether vToken is zero address\n * @dev vToken can't be set to zero, so it's suitable to be used to check\n * @param vToken vtoken address\n */\n modifier checkTokenConfigExistance(address vToken) {\n require(tokenConfigs[vToken].vToken != address(0), \"token config must exist\");\n _;\n }\n\n function initialize(BoundValidatorInterface _boundValidator) public initializer {\n require(address(_boundValidator) != address(0), \"invaliud bound validator address\");\n boundValidator = _boundValidator;\n\n __Ownable_init();\n __Pausable_init();\n }\n\n /**\n * @notice Pause protocol\n */\n function pause() external onlyOwner {\n _pause();\n }\n\n /**\n * @notice Unpause protocol\n */\n function unpause() external onlyOwner {\n _unpause();\n }\n\n /**\n * @dev Get token config by vToken address\n * @param vToken vtoken address\n */\n function getTokenConfig(address vToken) external view returns (TokenConfig memory) {\n return tokenConfigs[vToken];\n }\n\n /**\n * @notice Get oracle & enabling status by vToken address\n * @param vToken vtoken address\n * @param role oracle role\n */\n function getOracle(address vToken, OracleRole role) public view returns (address oracle, bool enabled) {\n oracle = tokenConfigs[vToken].oracles[uint256(role)];\n enabled = tokenConfigs[vToken].enableFlagsForOracles[uint256(role)];\n }\n\n /**\n * @notice Batch set token configs\n * @param tokenConfigs_ token config array\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {\n require(tokenConfigs_.length != 0, \"length can't be 0\");\n for (uint256 i = 0; i < tokenConfigs_.length; i++) {\n setTokenConfig(tokenConfigs_[i]);\n }\n }\n\n /**\n * @notice Set single token configs, vToken MUST HAVE NOT be added before, and main oracle MUST NOT be zero address\n * @param tokenConfig token config struct\n */\n function setTokenConfig(TokenConfig memory tokenConfig)\n public\n onlyOwner\n notNullAddress(tokenConfig.vToken)\n notNullAddress(tokenConfig.oracles[uint256(OracleRole.MAIN)])\n {\n tokenConfigs[tokenConfig.vToken] = tokenConfig;\n emit TokenConfigAdded(\n tokenConfig.vToken,\n tokenConfig.oracles[uint256(OracleRole.MAIN)],\n tokenConfig.oracles[uint256(OracleRole.PIVOT)],\n tokenConfig.oracles[uint256(OracleRole.FALLBACK)]\n );\n }\n\n /**\n * @notice Set oracle of any type for the input vToken, input vToken MUST exist\n * @param vToken vToken address\n * @param oracle oracle address\n * @param role oracle role\n */\n function setOracle(\n address vToken,\n address oracle,\n OracleRole role\n ) external onlyOwner notNullAddress(vToken) checkTokenConfigExistance(vToken) {\n require(!(oracle == address(0) && role == OracleRole.MAIN), \"can't set zero address to main oracle\");\n tokenConfigs[vToken].oracles[uint256(role)] = oracle;\n emit OracleSet(vToken, oracle, uint256(role));\n }\n\n /**\n * @notice Enable/disable oracle for the input vToken, input vToken MUST exist\n * @param vToken vToken address\n * @param role oracle role\n * @param enable expected status\n */\n function enableOracle(\n address vToken,\n OracleRole role,\n bool enable\n ) external onlyOwner notNullAddress(vToken) checkTokenConfigExistance(vToken) {\n tokenConfigs[vToken].enableFlagsForOracles[uint256(role)] = enable;\n emit OracleEnabled(vToken, uint256(role), enable);\n }\n\n /**\n * @notice Currently it calls the updateTwap\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) returns (uint256 _price) {} catch {}\n }\n }\n\n /**\n * @notice Get price of underlying asset of the input vToken, check flow:\n * - check the global pausing status\n * - check price from main oracle against pivot oracle\n * - check price from fallback oracle against pivot oracle or main oracle if fails\n * @param vToken vToken address\n * @return price USD price in 18 decimals\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n require(!paused(), \"resilient oracle is paused\");\n\n uint256 price = _getMainOraclePrice(vToken);\n if (price == INVALID_PRICE) {\n price = _getFallbackOraclePrice(vToken);\n }\n\n require(price != INVALID_PRICE, \"invalid resilient oracle price\");\n return price;\n }\n\n /**\n * @notice This function won't revert when price is 0, because the fallback oracle may come to play later\n * @param vToken vToken address\n * @return price USD price in 18 decimals\n */\n function _getMainOraclePrice(address vToken) internal view returns (uint256) {\n uint256 price = INVALID_PRICE;\n\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 price = mainOraclePrice;\n\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getUnderlyingPrice(vToken) returns (uint256 pivotPrice) {\n if (pivotPrice != INVALID_PRICE) {\n bool isPriceValid = boundValidator.validatePriceWithAnchorPrice(vToken, price, pivotPrice);\n if (!isPriceValid) {\n return INVALID_PRICE;\n }\n }\n } catch {}\n }\n } catch {}\n }\n\n return price;\n }\n\n /**\n * @notice This function won't revert when price is 0, because the getUnderlyingPrice checks if pirce is > 0\n * @param vToken vToken address\n * @return price USD price in 18 decimals\n */\n function _getFallbackOraclePrice(address vToken) internal view returns (uint256) {\n uint256 price = INVALID_PRICE;\n bool compareWithMain = false;\n\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 price = fallbackOraclePrice;\n\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(vToken, OracleRole.PIVOT);\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getUnderlyingPrice(vToken) returns (uint256 pivotPrice) {\n if (pivotPrice != INVALID_PRICE) {\n bool isPriceValid = boundValidator.validatePriceWithAnchorPrice(vToken, price, pivotPrice);\n if (!isPriceValid) {\n compareWithMain = true;\n }\n } else {\n compareWithMain = true;\n }\n } catch {\n compareWithMain = true;\n }\n } else {\n compareWithMain = true;\n }\n } catch {}\n }\n\n if (compareWithMain) {\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 bool isPriceValid = boundValidator.validatePriceWithAnchorPrice(vToken, price, mainOraclePrice);\n if (!isPriceValid) {\n return INVALID_PRICE;\n } else {\n price = mainOraclePrice;\n }\n } catch {\n price = INVALID_PRICE;\n }\n } else {\n price = INVALID_PRICE;\n }\n }\n\n return price;\n }\n}\n"
|
|
6
|
+
},
|
|
7
|
+
"contracts/interfaces/OracleInterface.sol": {
|
|
8
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\ninterface OracleInterface {\n function getUnderlyingPrice(address vToken) external view returns (uint256);\n}\n\ninterface ResilientOracleInterface is OracleInterface {\n function updatePrice(address vToken) external;\n}\n\ninterface TwapInterface is OracleInterface {\n function updateTwap(address vToken) external returns (uint256);\n}\n\ninterface BoundValidatorInterface {\n function validatePriceWithAnchorPrice(\n address vToken,\n uint256 reporterPrice,\n uint256 anchorPrice\n ) external view returns (bool);\n}\n"
|
|
9
|
+
},
|
|
10
|
+
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
|
|
11
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
|
|
12
|
+
},
|
|
13
|
+
"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": {
|
|
14
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n function __Pausable_init() internal onlyInitializing {\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal onlyInitializing {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n"
|
|
15
|
+
},
|
|
16
|
+
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
|
|
17
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"
|
|
18
|
+
},
|
|
19
|
+
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
|
|
20
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n"
|
|
21
|
+
},
|
|
22
|
+
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
|
|
23
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
|
|
24
|
+
},
|
|
25
|
+
"contracts/oracles/mocks/MockTwapOracle.sol": {
|
|
26
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../../interfaces/VBep20Interface.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 initialize(address vBNB_) public initializer {\n __Ownable_init();\n require(vBNB_ != address(0), \"vBNB can't be zero address\");\n vBNB = vBNB_;\n }\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n //https://compound.finance/docs/prices\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n return assetPrices[vToken];\n }\n}\n"
|
|
27
|
+
},
|
|
28
|
+
"contracts/interfaces/VBep20Interface.sol": {
|
|
29
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"./BEP20Interface.sol\";\n\ninterface VBep20Interface is BEP20Interface {\n /**\n * @notice Underlying asset for this VToken\n */\n function underlying() external view returns (address);\n}\n"
|
|
30
|
+
},
|
|
31
|
+
"contracts/interfaces/BEP20Interface.sol": {
|
|
32
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\ninterface BEP20Interface {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the token decimals.\n */\n function decimals() external view returns (uint8);\n\n /**\n * @dev Returns the token symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the token name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the bep token owner.\n */\n function getOwner() external view returns (address);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address _owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
|
|
33
|
+
},
|
|
34
|
+
"contracts/oracles/mocks/MockPythOracle.sol": {
|
|
35
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.10;\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 initialize(address underlyingPythOracle_) public initializer {\n __Ownable_init();\n require(underlyingPythOracle_ != address(0), \"pyth oracle cannot be zero address\");\n underlyingPythOracle = IPyth(underlyingPythOracle_);\n }\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n //https://compound.finance/docs/prices\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n return assetPrices[vToken];\n }\n}\n"
|
|
36
|
+
},
|
|
37
|
+
"contracts/oracles/PythOracle.sol": {
|
|
38
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/utils/math/SafeMath.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/utils/math/SignedMath.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../interfaces/PythInterface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/BEP20Interface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\n\nstruct TokenConfig {\n bytes32 pythId;\n address asset;\n uint64 maxStalePeriod;\n}\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 OwnableUpgradeable, OracleInterface {\n using SafeMath for uint256;\n\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 /// @notice price decimals\n uint256 public constant EXP_SCALE = 1e18;\n\n /// @notice the actual pyth oracle address fetch & store the prices\n IPyth public underlyingPythOracle;\n\n /// @notice emit when setting a new pyth oracle address\n event PythOracleSet(address indexed newPythOracle);\n\n /// @notice emit when token config added\n event TokenConfigAdded(address indexed vToken, bytes32 indexed pythId, uint64 indexed maxStalePeriod);\n\n /// @notice token configs by asset address\n mapping(address => TokenConfig) public tokenConfigs;\n\n modifier notNullAddress(address someone) {\n require(someone != address(0), \"can't be zero address\");\n _;\n }\n\n function initialize(address underlyingPythOracle_) public initializer {\n __Ownable_init();\n require(underlyingPythOracle_ != address(0), \"pyth oracle cannot be zero address\");\n underlyingPythOracle = IPyth(underlyingPythOracle_);\n emit PythOracleSet(underlyingPythOracle_);\n }\n\n /**\n * @notice Batch set token configs\n * @param tokenConfigs_ token config array\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {\n require(tokenConfigs_.length != 0, \"length can't be 0\");\n for (uint256 i = 0; i < tokenConfigs_.length; i++) {\n setTokenConfig(tokenConfigs_[i]);\n }\n }\n\n /**\n * @notice Set single token config, `maxStalePeriod` cannot be 0 and `vToken` can be zero address\n * @param tokenConfig token config struct\n */\n function setTokenConfig(TokenConfig memory tokenConfig) public onlyOwner notNullAddress(tokenConfig.asset) {\n require(tokenConfig.maxStalePeriod != 0, \"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 set the underlying pyth oracle contract address\n * @param underlyingPythOracle_ pyth oracle contract address\n */\n function setUnderlyingPythOracle(IPyth underlyingPythOracle_)\n external\n onlyOwner\n notNullAddress(address(underlyingPythOracle_))\n {\n underlyingPythOracle = underlyingPythOracle_;\n emit PythOracleSet(address(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 in 10 decimals\n */\n function getUnderlyingPrice(address vToken) public view override returns (uint256) {\n require(address(underlyingPythOracle) != address(0), \"Pyth oracle is zero address\");\n\n address asset = VBep20Interface(vToken).underlying();\n TokenConfig storage tokenConfig = tokenConfigs[asset];\n require(tokenConfig.asset != address(0), \"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.getLatestAvailablePriceWithinDuration(\n tokenConfig.pythId,\n tokenConfig.maxStalePeriod\n );\n\n uint256 price = int256(priceInfo.price).toUint256();\n\n require(price > 0, \"Pyth oracle price must be positive\");\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 BEP20Interface underlyingToken = BEP20Interface(asset);\n if (priceInfo.expo > 0) {\n return\n price.mul(EXP_SCALE).mul(10**int256(priceInfo.expo).toUint256()) *\n (10**(18 - underlyingToken.decimals()));\n } else {\n return\n price.mul(EXP_SCALE).div(10**int256(-priceInfo.expo).toUint256()) *\n (10**(18 - underlyingToken.decimals()));\n }\n }\n}\n"
|
|
39
|
+
},
|
|
40
|
+
"contracts/interfaces/PythInterface.sol": {
|
|
41
|
+
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity ^0.8.0;\n\ncontract PythStructs {\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 }\n\n // PriceFeed represents a current aggregate price from pyth publisher feeds.\n struct PriceFeed {\n // The price ID.\n bytes32 id;\n // Product account key.\n bytes32 productId;\n // The current price.\n int64 price;\n // Confidence interval around the price.\n uint64 conf;\n // Price exponent.\n int32 expo;\n // Status of price.\n PriceStatus status;\n // Maximum number of allowed publishers that can contribute to a price.\n uint32 maxNumPublishers;\n // Number of publishers that made up current aggregate.\n uint32 numPublishers;\n // Exponentially moving average price.\n int64 emaPrice;\n // Exponentially moving average confidence interval.\n uint64 emaConf;\n // Unix timestamp describing when the price was published\n uint64 publishTime;\n // Price of previous price with TRADING status\n int64 prevPrice;\n // Confidence interval of previous price with TRADING status\n uint64 prevConf;\n // Unix timestamp describing when the previous price with TRADING status was published\n uint64 prevPublishTime;\n }\n\n /* PriceStatus represents the availability status of a price feed.\n UNKNOWN: The price feed is not currently updating for an unknown reason.\n TRADING: The price feed is updating as expected.\n HALTED: The price feed is not currently updating because trading in the product has been halted.\n AUCTION: The price feed is not currently updating because an auction is setting the price.\n */\n enum PriceStatus {\n UNKNOWN,\n TRADING,\n HALTED,\n AUCTION\n }\n}\n\n/// @title Consume prices from the Pyth Network (https://pyth.network/).\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,\n /// you can find the corresponding chains 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 Current price of the given price update.\n /// @param conf Current 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 uint64 lastPublishTime,\n uint64 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 current price and confidence interval.\n /// @dev Reverts if the current price is not available.\n /// @param id The Pyth Price Feed ID of which to fetch the current price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getCurrentPrice(bytes32 id) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponential moving average price and confidence interval.\n /// @dev Reverts if the current exponential moving average price is not available.\n /// @param id The Pyth Price Feed ID of which to fetch the current 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 latest available price, along with the timestamp when it was generated.\n /// @dev This function returns the same price as `getCurrentPrice` in the case where a price was available\n /// at the time this `PriceFeed` was published (`publish_time`). However, if a price was not available\n /// at that time, this function returns the price from the latest time at which the price was available.\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 returned timestamp 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 `getCurrentPrice` or `getLatestAvailablePriceWithinDuration`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n /// @return publishTime - the UNIX timestamp of when this price was computed.\n function getLatestAvailablePriceUnsafe(bytes32 id)\n external\n view\n returns (PythStructs.Price memory price, uint64 publishTime);\n\n /// @notice Returns the latest price as long as it was updated within `duration` seconds of the current time.\n /// @dev This function is a sanity-checked version of `getLatestAvailablePriceUnchecked` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n function getLatestAvailablePriceWithinDuration(bytes32 id, uint64 duration)\n external\n view\n 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[] memory 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\n /// does not read the actual price 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[] memory updateData,\n bytes32[] memory priceIds,\n uint64[] memory 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"
|
|
42
|
+
},
|
|
43
|
+
"@openzeppelin/contracts/utils/math/SafeMath.sol": {
|
|
44
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)\n\npragma solidity ^0.8.0;\n\n// CAUTION\n// This version of SafeMath should only be used with Solidity 0.8 or later,\n// because it relies on the compiler's built in overflow checks.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations.\n *\n * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler\n * now has built in overflow checking.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n uint256 c = a + b;\n if (c < a) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b > a) return (false, 0);\n return (true, a - b);\n }\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, with an overflow flag.\n *\n * _Available since v3.4._\n */\n function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) return (true, 0);\n uint256 c = a * b;\n if (c / a != b) return (false, 0);\n return (true, c);\n }\n }\n\n /**\n * @dev Returns the division of two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a / b);\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.\n *\n * _Available since v3.4._\n */\n function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {\n unchecked {\n if (b == 0) return (false, 0);\n return (true, a % b);\n }\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n return a + b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return a - b;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n return a * b;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator.\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return a / b;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return a % b;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {trySub}.\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b <= a, errorMessage);\n return a - b;\n }\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers, reverting with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a / b;\n }\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * reverting with custom message when dividing by zero.\n *\n * CAUTION: This function is deprecated because it requires allocating memory for the error\n * message unnecessarily. For custom revert reasons use {tryMod}.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n unchecked {\n require(b > 0, errorMessage);\n return a % b;\n }\n }\n}\n"
|
|
45
|
+
},
|
|
46
|
+
"@openzeppelin/contracts/utils/math/SignedMath.sol": {
|
|
47
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n /**\n * @dev Returns the largest of two signed numbers.\n */\n function max(int256 a, int256 b) internal pure returns (int256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two signed numbers.\n */\n function min(int256 a, int256 b) internal pure returns (int256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two signed numbers without overflow.\n * The result is rounded towards zero.\n */\n function average(int256 a, int256 b) internal pure returns (int256) {\n // Formula from the book \"Hacker's Delight\"\n int256 x = (a & b) + ((a ^ b) >> 1);\n return x + (int256(uint256(x) >> 255) & (a ^ b));\n }\n\n /**\n * @dev Returns the absolute unsigned value of a signed value.\n */\n function abs(int256 n) internal pure returns (uint256) {\n unchecked {\n // must be unchecked in order to support `n = type(int256).min`\n return uint256(n >= 0 ? n : -n);\n }\n }\n}\n"
|
|
48
|
+
},
|
|
49
|
+
"@openzeppelin/contracts/utils/math/SafeCast.sol": {
|
|
50
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248) {\n require(value >= type(int248).min && value <= type(int248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return int248(value);\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240) {\n require(value >= type(int240).min && value <= type(int240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return int240(value);\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232) {\n require(value >= type(int232).min && value <= type(int232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return int232(value);\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224) {\n require(value >= type(int224).min && value <= type(int224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return int224(value);\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216) {\n require(value >= type(int216).min && value <= type(int216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return int216(value);\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208) {\n require(value >= type(int208).min && value <= type(int208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return int208(value);\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200) {\n require(value >= type(int200).min && value <= type(int200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return int200(value);\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192) {\n require(value >= type(int192).min && value <= type(int192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return int192(value);\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184) {\n require(value >= type(int184).min && value <= type(int184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return int184(value);\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176) {\n require(value >= type(int176).min && value <= type(int176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return int176(value);\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168) {\n require(value >= type(int168).min && value <= type(int168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return int168(value);\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160) {\n require(value >= type(int160).min && value <= type(int160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return int160(value);\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152) {\n require(value >= type(int152).min && value <= type(int152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return int152(value);\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144) {\n require(value >= type(int144).min && value <= type(int144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return int144(value);\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136) {\n require(value >= type(int136).min && value <= type(int136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return int136(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120) {\n require(value >= type(int120).min && value <= type(int120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return int120(value);\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112) {\n require(value >= type(int112).min && value <= type(int112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return int112(value);\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104) {\n require(value >= type(int104).min && value <= type(int104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return int104(value);\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96) {\n require(value >= type(int96).min && value <= type(int96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return int96(value);\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88) {\n require(value >= type(int88).min && value <= type(int88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return int88(value);\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80) {\n require(value >= type(int80).min && value <= type(int80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return int80(value);\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72) {\n require(value >= type(int72).min && value <= type(int72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return int72(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56) {\n require(value >= type(int56).min && value <= type(int56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return int56(value);\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48) {\n require(value >= type(int48).min && value <= type(int48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return int48(value);\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40) {\n require(value >= type(int40).min && value <= type(int40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return int40(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24) {\n require(value >= type(int24).min && value <= type(int24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return int24(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n"
|
|
51
|
+
},
|
|
52
|
+
"contracts/oracles/TwapOracle.sol": {
|
|
53
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../libraries/PancakeLibrary.sol\";\nimport \"../interfaces/OracleInterface.sol\";\nimport \"../interfaces/BEP20Interface.sol\";\nimport \"../interfaces/VBep20Interface.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 TWAP update period in second, which is the minimum time in seconds required to update TWAP window\n uint256 anchorPeriod;\n}\n\ncontract TwapOracle is OwnableUpgradeable, TwapInterface {\n using FixedPoint for *;\n\n /// @notice WBNB address\n address public WBNB;\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 uint256 public constant expScale = 1e18;\n\n /// @notice Configs by token\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice The current price observation of TWAP. With old and current observations\n /// we can calculate the TWAP between this range\n mapping(address => Observation) public newObservations;\n\n /// @notice The old price observation of TWAP\n mapping(address => Observation) public oldObservations;\n\n /// @notice Stored price by token\n mapping(address => uint256) public prices;\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 require(someone != address(0), \"can't be zero address\");\n _;\n }\n\n function initialize(address WBNB_) public initializer {\n __Ownable_init();\n require(WBNB_ != address(0), \"WBNB can't be zero address\");\n WBNB = WBNB_;\n }\n\n /**\n * @notice Add multiple token configs at the same time\n * @param configs config array\n */\n function setTokenConfigs(TokenConfig[] memory configs) external onlyOwner {\n require(configs.length > 0, \"length can't be 0\");\n for (uint8 i = 0; i < configs.length; i++) {\n setTokenConfig(configs[i]);\n }\n }\n\n /**\n * @notice Add single token configs\n * @param config token config struct\n */\n function setTokenConfig(TokenConfig memory config)\n public\n onlyOwner\n notNullAddress(config.asset)\n notNullAddress(config.pancakePool)\n {\n require(config.anchorPeriod > 0, \"anchor period must be positive\");\n require(config.baseUnit > 0, \"base unit must be positive\");\n uint256 cumulativePrice = currentCumulativePrice(config);\n\n // Initialize observation data\n oldObservations[config.asset].timestamp = block.timestamp;\n newObservations[config.asset].timestamp = block.timestamp;\n oldObservations[config.asset].acc = cumulativePrice;\n newObservations[config.asset].acc = cumulativePrice;\n tokenConfigs[config.asset] = config;\n emit TokenConfigAdded(config.asset, config.pancakePool, config.anchorPeriod);\n }\n\n /**\n * @notice Get the underlying TWAP price of input vToken\n * @param vToken vToken address\n * @return price in USD, with 18 decimals\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n address asset = VBep20Interface(vToken).underlying();\n require(tokenConfigs[asset].asset != address(0), \"asset not exist\");\n\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 require(price > 0, \"TWAP price must be positive\");\n\n BEP20Interface underlyingToken = BEP20Interface(VBep20Interface(vToken).underlying());\n return (price * (10**(18 - underlyingToken.decimals())));\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 function updateTwap(address vToken) public returns (uint256) {\n address asset = VBep20Interface(vToken).underlying();\n require(tokenConfigs[asset].asset != address(0), \"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 require(tokenConfigs[WBNB].asset != address(0), \"WBNB not exist\");\n _updateTwapInternal(tokenConfigs[WBNB]);\n }\n return _updateTwapInternal(tokenConfigs[asset]);\n }\n\n /**\n * @notice Fetches the current token/BUSD price from PancakeSwap, with 18 decimals of precision.\n * @return price in USD, with 18 decimals\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 // This should be impossible, but better safe than sorry\n require(block.timestamp > oldTimestamp, \"now must come after before\");\n uint256 timeElapsed = block.timestamp - oldTimestamp;\n\n // Calculate Pancakge 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 require(bnbPrice != 0, \"bnb price is invalid\");\n anchorPriceMantissa = (anchorPriceMantissa * bnbPrice) / bnbBaseUnit;\n }\n\n require(anchorPriceMantissa != 0, \"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 Update new and old observations of lagging window if period elapsed.\n * @return cumulative price & old observation\n */\n function pokeWindowValues(TokenConfig memory config)\n internal\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n uint256 cumulativePrice = currentCumulativePrice(config);\n\n Observation memory newObservation = newObservations[config.asset];\n\n // Update new and old observations if elapsed time is greater than or equal to anchor period\n uint256 timeElapsed = block.timestamp - newObservation.timestamp;\n if (timeElapsed >= config.anchorPeriod) {\n oldObservations[config.asset].timestamp = newObservation.timestamp;\n oldObservations[config.asset].acc = newObservation.acc;\n\n newObservations[config.asset].timestamp = block.timestamp;\n newObservations[config.asset].acc = cumulativePrice;\n emit TwapWindowUpdated(\n config.asset,\n newObservation.timestamp,\n block.timestamp,\n newObservation.acc,\n cumulativePrice\n );\n }\n return (cumulativePrice, oldObservations[config.asset].acc, oldObservations[config.asset].timestamp);\n }\n}\n"
|
|
54
|
+
},
|
|
55
|
+
"contracts/libraries/PancakeLibrary.sol": {
|
|
56
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\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(address pair)\n internal\n view\n returns (\n uint256 price0Cumulative,\n uint256 price1Cumulative,\n uint32 blockTimestamp\n )\n {\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\ninterface IPancakePair {\n function getReserves()\n external\n view\n returns (\n uint112 reserve0,\n uint112 reserve1,\n uint32 blockTimestampLast\n );\n\n function price0CumulativeLast() external view returns (uint256);\n\n function price1CumulativeLast() external view returns (uint256);\n}\n"
|
|
57
|
+
},
|
|
58
|
+
"contracts/test/MockSimpleOracle.sol": {
|
|
59
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/OracleInterface.sol\";\n\ncontract MockSimpleOracle is OracleInterface {\n mapping(address => uint256) public prices;\n\n constructor() {\n //\n }\n\n function setPrice(address vToken, uint256 price) public {\n prices[vToken] = price;\n }\n\n function getUnderlyingPrice(address vToken) external view returns (uint256) {\n return prices[vToken];\n }\n}\n\ncontract MockBoundValidator is BoundValidatorInterface {\n mapping(address => bool) public validateResults;\n bool public twapUpdated;\n\n constructor() {\n //\n }\n\n function setValidateResult(address vToken, bool pass) public {\n validateResults[vToken] = pass;\n }\n\n function validatePriceWithAnchorPrice(\n address vToken,\n uint256 reporterPrice,\n uint256 anchorPrice\n ) external view returns (bool) {\n return validateResults[vToken];\n }\n}\n"
|
|
60
|
+
},
|
|
61
|
+
"contracts/oracles/ChainlinkOracle.sol": {
|
|
62
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/AggregatorV2V3Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\n\nstruct TokenConfig {\n /// @notice underlying token address, which can't be zero address and can be used for existance check\n address asset;\n /// @notice chainlink feed address\n address feed;\n /// @notice expiration period of this asset\n uint256 maxStalePeriod;\n}\n\ncontract ChainlinkOracle is OwnableUpgradeable, OracleInterface {\n /// @notice VAI token is considered $1 constantly in oracle for now\n uint256 public constant VAI_VALUE = 1e18;\n\n /// @notice TODO: might be removed some day, it's for enabling us to force set the prices to\n /// certain values in some urgent conditions\n mapping(address => uint256) public prices;\n\n /// @notice token config by assets\n mapping(address => TokenConfig) public tokenConfigs;\n\n /// @notice emit when forced price is set\n event PricePosted(\n address asset,\n uint256 previousPriceMantissa,\n uint256 requestedPriceMantissa,\n uint256 newPriceMantissa\n );\n\n /// @notice emit when token config is added\n event TokenConfigAdded(address asset, address feed, uint256 maxStalePeriod);\n\n modifier notNullAddress(address someone) {\n require(someone != address(0), \"can't be zero address\");\n _;\n }\n\n function initialize() public initializer {\n __Ownable_init();\n }\n\n /**\n * @notice Get the Chainlink price of underlying asset of input vToken, revert when vToken is zero address\n * @param vToken vToken address\n * @return price in USD, with 18 decimals\n */\n function getUnderlyingPrice(address vToken) public view override returns (uint256) {\n string memory symbol = VBep20Interface(vToken).symbol();\n // VBNB token doesn't have `underlying` method, so it has to skip `_getUnderlyingPriceInternal\n // method and directly goes into `_getChainlinkPrice`\n if (_compareStrings(symbol, \"vBNB\")) {\n return _getChainlinkPrice(vToken);\n // VAI price is constantly 1 at the moment, but not guarantee in the future\n } else if (_compareStrings(symbol, \"VAI\")) {\n return VAI_VALUE;\n // @TODO: This is some history code, keep it here in case of messing up\n } else {\n return _getUnderlyingPriceInternal(VBep20Interface(vToken));\n }\n }\n\n /**\n * @notice Get the Chainlink price of underlying asset of input vToken or cached price when it's been set\n * @dev The decimals of underlying tokens is considered to ensure the returned prices are in 18 decimals\n * @param vToken vToken address\n * @return price in USD, with 18 decimals\n */\n function _getUnderlyingPriceInternal(VBep20Interface vToken) internal view returns (uint256 price) {\n VBep20Interface token = VBep20Interface(vToken.underlying());\n\n if (prices[address(token)] != 0) {\n price = prices[address(token)];\n } else {\n price = _getChainlinkPrice(address(vToken));\n }\n\n uint256 decimalDelta = uint256(18) - uint256(token.decimals());\n return price * (10**decimalDelta);\n }\n\n /**\n * @notice Get the Chainlink price of underlying asset of input vToken, revert if token config doesn't exit\n * @dev The decimals of feeds are considered\n * @param vToken vToken address\n * @return price in USD, with 18 decimals\n */\n function _getChainlinkPrice(address vToken)\n internal\n view\n notNullAddress(tokenConfigs[VBep20Interface(vToken).underlying()].asset)\n returns (uint256)\n {\n address asset = VBep20Interface(vToken).underlying();\n\n TokenConfig storage tokenConfig = tokenConfigs[asset];\n AggregatorV2V3Interface feed = AggregatorV2V3Interface(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 = uint256(18) - feed.decimals();\n\n (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();\n require(answer > 0, \"chainlink price must be positive\");\n\n require(block.timestamp > updatedAt, \"updatedAt exceeds block time\");\n uint256 deltaTime = block.timestamp - updatedAt;\n require(deltaTime <= maxStalePeriod, \"chainlink price expired\");\n\n return uint256(answer) * (10**decimalDelta);\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 */\n function setUnderlyingPrice(VBep20Interface vToken, uint256 underlyingPriceMantissa) external onlyOwner {\n address asset = address(vToken.underlying());\n emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);\n prices[asset] = underlyingPriceMantissa;\n }\n\n /**\n * @notice Set the forced prices of the input token\n * @param asset asset address\n * @param price price in 18 decimals\n */\n function setDirectPrice(address asset, uint256 price) external onlyOwner {\n emit PricePosted(asset, prices[asset], price, price);\n prices[asset] = price;\n }\n\n /**\n * @notice Add multiple token configs at the same time\n * @param tokenConfigs_ config array\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external onlyOwner {\n require(tokenConfigs_.length > 0, \"length can't be 0\");\n for (uint256 i = 0; i < tokenConfigs_.length; i++) {\n setTokenConfig(tokenConfigs_[i]);\n }\n }\n\n /**\n * @notice Add single token config, vToken & feed cannot be zero address, and maxStalePeriod must be positive\n * @param tokenConfig token config struct\n */\n function setTokenConfig(TokenConfig memory tokenConfig)\n public\n onlyOwner\n notNullAddress(tokenConfig.asset)\n notNullAddress(tokenConfig.feed)\n {\n require(tokenConfig.maxStalePeriod > 0, \"stale period can't be zero\");\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(tokenConfig.asset, tokenConfig.feed, tokenConfig.maxStalePeriod);\n }\n\n function _compareStrings(string memory a, string memory b) internal pure returns (bool) {\n return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n }\n}\n"
|
|
63
|
+
},
|
|
64
|
+
"contracts/interfaces/AggregatorV2V3Interface.sol": {
|
|
65
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\n/**\n * @title The V2 & V3 Aggregator Interface\n * @notice Solidity V0.5 does not allow interfaces to inherit from other\n * interfaces so this contract is a combination of v0.5 AggregatorInterface.sol\n * and v0.5 AggregatorV3Interface.sol.\n */\ninterface AggregatorV2V3Interface {\n //\n // V2 Interface:\n //\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 timestamp);\n event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n\n //\n // V3 Interface:\n //\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 // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\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"
|
|
66
|
+
},
|
|
67
|
+
"contracts/oracles/mocks/MockChainlinkOracle.sol": {
|
|
68
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.10;\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 initialize() public initializer {\n __Ownable_init();\n }\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n //https://compound.finance/docs/prices\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n return assetPrices[vToken];\n }\n}\n"
|
|
69
|
+
},
|
|
70
|
+
"contracts/test/MockV3Aggregator.sol": {
|
|
71
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport \"../interfaces/AggregatorV2V3Interface.sol\";\n\n/**\n * @title MockV3Aggregator\n * @notice Based on the FluxAggregator contract\n * @notice Use this contract when you need to test\n * other contract's ability to read data from an\n * aggregator contract, but how the aggregator got\n * its answer is unimportant\n */\ncontract MockV3Aggregator is AggregatorV2V3Interface {\n uint256 public constant version = 0;\n\n uint8 public decimals;\n int256 public latestAnswer;\n uint256 public latestTimestamp;\n uint256 public latestRound;\n\n mapping(uint256 => int256) public getAnswer;\n mapping(uint256 => uint256) public getTimestamp;\n mapping(uint256 => uint256) private getStartedAt;\n\n constructor(uint8 _decimals, int256 _initialAnswer) {\n decimals = _decimals;\n updateAnswer(_initialAnswer);\n }\n\n function updateAnswer(int256 _answer) public {\n latestAnswer = _answer;\n latestTimestamp = block.timestamp;\n latestRound++;\n getAnswer[latestRound] = _answer;\n getTimestamp[latestRound] = block.timestamp;\n getStartedAt[latestRound] = block.timestamp;\n }\n\n function updateRoundData(\n uint80 _roundId,\n int256 _answer,\n uint256 _timestamp,\n uint256 _startedAt\n ) public {\n latestRound = _roundId;\n latestAnswer = _answer;\n latestTimestamp = _timestamp;\n getAnswer[latestRound] = _answer;\n getTimestamp[latestRound] = _timestamp;\n getStartedAt[latestRound] = _startedAt;\n }\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 return (_roundId, getAnswer[_roundId], getStartedAt[_roundId], getTimestamp[_roundId], _roundId);\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 return (\n uint80(latestRound),\n getAnswer[latestRound],\n getStartedAt[latestRound],\n getTimestamp[latestRound],\n uint80(latestRound)\n );\n }\n\n function description() external pure returns (string memory) {\n return \"v0.6/tests/MockV3Aggregator.sol\";\n }\n}\n"
|
|
72
|
+
},
|
|
73
|
+
"contracts/oracles/BoundValidator.sol": {
|
|
74
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../interfaces/BEP20Interface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/OracleInterface.sol\";\n\nstruct 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// BoundValidator provides some common functions and can be used\n// to wrap up other contracts to form pivot oracles\ncontract BoundValidator is OwnableUpgradeable, BoundValidatorInterface {\n /// @notice validation configs by asset\n mapping(address => ValidateConfig) public validateConfigs;\n\n /// @notice Emit this event when new validate configs are added\n event ValidateConfigAdded(address indexed asset, uint256 indexed upperBound, uint256 indexed lowerBound);\n\n function initialize() public initializer {\n __Ownable_init();\n }\n\n /**\n * @notice Add multiple validation configs at the same time\n * @param configs config array\n */\n function setValidateConfigs(ValidateConfig[] memory configs) external virtual onlyOwner {\n require(configs.length > 0, \"invalid validate config length\");\n for (uint8 i = 0; i < configs.length; i++) {\n setValidateConfig(configs[i]);\n }\n }\n\n /**\n * @notice Add single validation config\n * @param config config struct\n */\n function setValidateConfig(ValidateConfig memory config) public virtual onlyOwner {\n require(config.asset != address(0), \"asset can't be zero address\");\n require(config.upperBoundRatio > 0 && config.lowerBoundRatio > 0, \"bound must be positive\");\n require(config.upperBoundRatio > config.lowerBoundRatio, \"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 reported asset price against anchor price\n * @param vToken vToken address\n * @param reporterPrice the price to be tested\n */\n function validatePriceWithAnchorPrice(\n address vToken,\n uint256 reporterPrice,\n uint256 anchorPrice\n ) public view virtual override returns (bool) {\n address asset = VBep20Interface(vToken).underlying();\n\n require(validateConfigs[asset].upperBoundRatio != 0, \"validation config not exist\");\n require(anchorPrice != 0, \"anchor price is not valid\");\n return _isWithinAnchor(asset, reporterPrice, anchorPrice);\n }\n\n /**\n * @notice Test whether the reported price is within the predefined bounds\n * @param asset asset address\n * @param reporterPrice the price to be tested\n * @param anchorPrice anchor price as testing anchor\n */\n function _isWithinAnchor(\n address asset,\n uint256 reporterPrice,\n uint256 anchorPrice\n ) internal view returns (bool) {\n if (reporterPrice > 0) {\n uint256 anchorRatio = (anchorPrice * 100e16) / reporterPrice;\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 // BoundValidator is to get inherited, so it's a good practice to add some storage gaps like\n // OpenZepplin proposed in their contracts: https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n uint256[49] private __gap;\n}\n"
|
|
75
|
+
},
|
|
76
|
+
"contracts/oracles/BinanceOracle.sol": {
|
|
77
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"../interfaces/FeedRegistryInterface.sol\";\nimport \"../interfaces/VBep20Interface.sol\";\nimport \"../interfaces/BEP20Interface.sol\";\n\ncontract BinanceOracle is Initializable {\n FeedRegistryInterface public feedRegistry;\n\n function initialize(FeedRegistryInterface feed) public initializer {\n feedRegistry = feed;\n }\n\n function getUnderlyingPrice(VBep20Interface vToken) public view returns (uint256) {\n BEP20Interface underlyingToken = BEP20Interface(vToken.underlying());\n\n string memory symbol = underlyingToken.symbol();\n\n if (keccak256(bytes(symbol)) == keccak256(bytes(\"WBNB\"))) {\n symbol = \"BNB\";\n }\n\n (, int256 answer, , , ) = feedRegistry.latestRoundDataByName(symbol, \"USD\");\n\n uint256 decimalDelta = feedRegistry.decimalsByName(symbol, \"USD\");\n return (uint256(answer) * (10**(18 - decimalDelta))) * (10**(18 - underlyingToken.decimals()));\n }\n}\n"
|
|
78
|
+
},
|
|
79
|
+
"contracts/interfaces/FeedRegistryInterface.sol": {
|
|
80
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\ninterface FeedRegistryInterface {\n function latestRoundDataByName(string memory base, string memory quote)\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 decimalsByName(string memory base, string memory quote) external view returns (uint8);\n}\n"
|
|
81
|
+
},
|
|
82
|
+
"contracts/oracles/mocks/MockBinanceFeedRegistry.sol": {
|
|
83
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.10;\n\nimport \"../../interfaces/FeedRegistryInterface.sol\";\n\ncontract MockBinanceFeedRegistry is FeedRegistryInterface {\n mapping(string => uint256) public assetPrices;\n\n function setAssetPrice(string memory base, uint256 price) external {\n assetPrices[base] = price;\n }\n\n function latestRoundDataByName(string memory base, string memory quote)\n external\n view\n override\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n )\n {\n quote;\n return (0, int256(assetPrices[base]), 0, 0, 0);\n }\n\n function decimalsByName(string memory base, string memory quote) external view override returns (uint8) {\n return 8;\n }\n}\n"
|
|
84
|
+
},
|
|
85
|
+
"contracts/test/MockPyth.sol": {
|
|
86
|
+
"content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity ^0.8.0;\n\nimport \"../interfaces/PythInterface.sol\";\n\ncontract MockPyth is IPyth {\n mapping(bytes32 => PythStructs.PriceFeed) public priceFeeds;\n\n function queryPriceFeed(bytes32 id) public view returns (PythStructs.PriceFeed memory priceFeed) {\n require(priceFeeds[id].id != 0, \"no price feed found for the given price id\");\n return priceFeeds[id];\n }\n\n // simply update price feeds\n function updatePriceFeedsHarness(PythStructs.PriceFeed[] calldata feeds) external {\n require(feeds.length > 0, \"feeds length must > 0\");\n for (uint256 i = 0; i < feeds.length; ++i) {\n priceFeeds[feeds[i].id] = feeds[i];\n }\n }\n\n // a very simple version get price with timestamp expiration check, just for test\n function getLatestAvailablePriceWithinDuration(bytes32 id, uint64 duration)\n external\n view\n override\n returns (PythStructs.Price memory price)\n {\n PythStructs.PriceFeed memory priceFeed = queryPriceFeed(id);\n\n price.price = priceFeed.price;\n price.conf = priceFeed.conf;\n price.expo = priceFeed.expo;\n uint64 publishTime = priceFeed.publishTime;\n\n require(_diff(block.timestamp, publishTime) <= duration, \"No available price within given duration\");\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 // not implemented\n function updatePriceFeedsIfNecessary(\n bytes[] memory updateData,\n bytes32[] memory priceIds,\n uint64[] memory publishTimes\n ) external payable {\n updateData;\n priceIds;\n publishTimes;\n }\n\n function getUpdateFee(uint256 updateDataSize) external pure override returns (uint256 feeAmount) {\n updateDataSize;\n return 0;\n }\n\n function updatePriceFeeds(bytes[] memory updateData) external payable {\n updateData;\n }\n\n function getCurrentPrice(bytes32 id) external pure override returns (PythStructs.Price memory price) {\n id;\n return PythStructs.Price({ price: 0, conf: 0, expo: 0 });\n }\n\n function getEmaPrice(bytes32 id) external pure override returns (PythStructs.Price memory price) {\n id;\n return PythStructs.Price({ price: 0, conf: 0, expo: 0 });\n }\n\n function getLatestAvailablePriceUnsafe(bytes32 id)\n external\n pure\n override\n returns (PythStructs.Price memory price, uint64 publishTime)\n {\n id;\n return (PythStructs.Price({ price: 0, conf: 0, expo: 0 }), 0);\n }\n}\n"
|
|
87
|
+
},
|
|
88
|
+
"contracts/oracles/mocks/MockBinanceOracle.sol": {
|
|
89
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.10;\n\nimport \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\nimport \"../../interfaces/VBep20Interface.sol\";\n\ncontract MockBinanceOracle is OwnableUpgradeable {\n mapping(address => uint256) public assetPrices;\n\n constructor() {}\n\n function initialize() public initializer {\n __Ownable_init();\n }\n\n function setPrice(address asset, uint256 price) external {\n assetPrices[asset] = price;\n }\n\n function getUnderlyingPrice(address vToken) public view returns (uint256) {\n return assetPrices[vToken];\n }\n}\n"
|
|
90
|
+
},
|
|
91
|
+
"contracts/test/BEP20Harness.sol": {
|
|
92
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract BEP20Harness is ERC20 {\n uint8 public decimalsInternal = 18;\n\n constructor(\n string memory name_,\n string memory symbol_,\n uint8 decimals_\n ) ERC20(name_, symbol_) {\n decimalsInternal = decimals_;\n }\n\n function decimals() public view virtual override returns (uint8) {\n return decimalsInternal;\n }\n}\n"
|
|
93
|
+
},
|
|
94
|
+
"@openzeppelin/contracts/token/ERC20/ERC20.sol": {
|
|
95
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n}\n"
|
|
96
|
+
},
|
|
97
|
+
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
|
|
98
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n"
|
|
99
|
+
},
|
|
100
|
+
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
|
|
101
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
|
|
102
|
+
},
|
|
103
|
+
"@openzeppelin/contracts/utils/Context.sol": {
|
|
104
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
|
|
105
|
+
},
|
|
106
|
+
"contracts/test/VBEP20Harness.sol": {
|
|
107
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\npragma experimental ABIEncoderV2;\n\nimport \"./BEP20Harness.sol\";\n\ncontract VBEP20Harness is BEP20Harness {\n /**\n * @notice Underlying asset for this VToken\n */\n address public underlying;\n\n constructor(\n string memory name_,\n string memory symbol_,\n uint8 decimals,\n address underlying_\n ) BEP20Harness(name_, symbol_, decimals) {\n underlying = underlying_;\n }\n}\n"
|
|
108
|
+
},
|
|
109
|
+
"contracts/test/PancakePairHarness.sol": {
|
|
110
|
+
"content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\n// a library for performing various math operations\n\nlibrary Math {\n function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n z = x < y ? x : y;\n }\n\n // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)\n function sqrt(uint256 y) internal pure returns (uint256 z) {\n if (y > 3) {\n z = y;\n uint256 x = y / 2 + 1;\n while (x < z) {\n z = x;\n x = (y / x + x) / 2;\n }\n } else if (y != 0) {\n z = 1;\n }\n }\n}\n\n// range: [0, 2**112 - 1]\n// resolution: 1 / 2**112\n\nlibrary UQ112x112 {\n //solhint-disable-next-line state-visibility\n uint224 constant Q112 = 2**112;\n\n // encode a uint112 as a UQ112x112\n function encode(uint112 y) internal pure returns (uint224 z) {\n z = uint224(y) * Q112; // never overflows\n }\n\n // divide a UQ112x112 by a uint112, returning a UQ112x112\n function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\n z = x / uint224(y);\n }\n}\n\ncontract PancakePairHarness {\n using UQ112x112 for uint224;\n\n address public token0;\n address public token1;\n\n uint112 private reserve0; // uses single storage slot, accessible via getReserves\n uint112 private reserve1; // uses single storage slot, accessible via getReserves\n uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves\n\n uint256 public price0CumulativeLast;\n uint256 public price1CumulativeLast;\n uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event\n\n function currentBlockTimestamp() external view returns (uint32) {\n return uint32(block.timestamp % 2**32);\n }\n\n function getReserves()\n public\n view\n returns (\n uint112 _reserve0,\n uint112 _reserve1,\n uint32 _blockTimestampLast\n )\n {\n _reserve0 = reserve0;\n _reserve1 = reserve1;\n _blockTimestampLast = blockTimestampLast;\n }\n\n // called once by the factory at time of deployment\n function initialize(address _token0, address _token1) external {\n token0 = _token0;\n token1 = _token1;\n }\n\n // update reserves and, on the first call per block, price accumulators\n function update(\n uint256 balance0,\n uint256 balance1,\n uint112 _reserve0,\n uint112 _reserve1\n ) external {\n require(balance0 <= type(uint112).max && balance1 <= type(uint112).max, \"PancakeV2: OVERFLOW\");\n uint32 blockTimestamp = uint32(block.timestamp % 2**32);\n unchecked {\n uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\n if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\n // * never overflows, and + overflow is desired\n price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\n price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\n }\n }\n reserve0 = uint112(balance0);\n reserve1 = uint112(balance1);\n blockTimestampLast = blockTimestamp;\n }\n}\n"
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
"settings": {
|
|
114
|
+
"optimizer": {
|
|
115
|
+
"enabled": true,
|
|
116
|
+
"runs": 200
|
|
117
|
+
},
|
|
118
|
+
"outputSelection": {
|
|
119
|
+
"*": {
|
|
120
|
+
"*": [
|
|
121
|
+
"storageLayout",
|
|
122
|
+
"abi",
|
|
123
|
+
"evm.bytecode",
|
|
124
|
+
"evm.deployedBytecode",
|
|
125
|
+
"evm.methodIdentifiers",
|
|
126
|
+
"metadata",
|
|
127
|
+
"devdoc",
|
|
128
|
+
"userdoc",
|
|
129
|
+
"evm.gasEstimates"
|
|
130
|
+
],
|
|
131
|
+
"": ["ast"]
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
"metadata": {
|
|
135
|
+
"useLiteralContent": true
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|