@venusprotocol/protocol-reserve 3.5.0-dev.7 → 3.5.0-dev.8
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/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/access/Ownable.sol/Ownable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/interfaces/IERC1967.sol/IERC1967.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC1822.sol/IERC1822Proxiable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol/ERC1967Proxy.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol/ERC1967Upgrade.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/Proxy.sol/Proxy.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol/BeaconProxy.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/beacon/IBeacon.sol/IBeacon.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol/UpgradeableBeacon.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol/ProxyAdmin.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol/ITransparentUpgradeableProxy.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/ERC20.sol/ERC20.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/IERC20.sol/IERC20.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol/IERC20Metadata.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/Address.sol/Address.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/StorageSlot.sol/StorageSlot.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol/Ownable2StepUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol/OwnableUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol/Initializable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol/PausableUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol/ReentrancyGuardUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol/IERC20Upgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol/IERC20PermitUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol/SafeERC20Upgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol/AddressUpgradeable.dbg.json +1 -1
- package/artifacts/@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol/ContextUpgradeable.dbg.json +1 -1
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol/AccessControlledV8.dbg.json +1 -1
- package/artifacts/@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol/IAccessControlManagerV8.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/ResilientOracle.sol/ResilientOracle.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol/BoundValidatorInterface.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol/OracleInterface.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol/ResilientOracleInterface.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol/TwapInterface.dbg.json +1 -1
- package/artifacts/@venusprotocol/oracle/contracts/interfaces/VBep20Interface.sol/VBep20Interface.dbg.json +1 -1
- package/artifacts/@venusprotocol/solidity-utilities/contracts/MaxLoopsLimitHelper.sol/MaxLoopsLimitHelper.dbg.json +1 -1
- package/artifacts/build-info/{e9a9c41c1c0114337c3d18db652650e4.json → cb5f4507306da329520f3a92d218c904.json} +1 -1
- package/artifacts/contracts/Interfaces/IComptroller.sol/IComptroller.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IConverterNetwork.sol/IConverterNetwork.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IIncomeDestination.sol/IIncomeDestination.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IPoolRegistry.sol/IPoolRegistry.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IProtocolShareReserve.sol/IProtocolShareReserve.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IRiskFund.sol/IRiskFund.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IRiskFund.sol/IRiskFundGetters.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IRiskFundConverter.sol/IRiskFundConverter.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IShortfall.sol/IShortfall.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/ITokenBuyback.sol/ITokenBuyback.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IVToken.sol/IVToken.dbg.json +1 -1
- package/artifacts/contracts/Interfaces/IXVSVault.sol/IXVSVault.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/ProtocolShareReserve.sol/ProtocolShareReserve.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/RiskFundStorage.sol/MaxLoopsLimitHelpersStorage.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/RiskFundStorage.sol/ReserveHelpersStorage.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/RiskFundStorage.sol/RiskFundV1Storage.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/RiskFundStorage.sol/RiskFundV2Storage.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/RiskFundV2.sol/RiskFundV2.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/TokenBuyback.sol/TokenBuyback.dbg.json +1 -1
- package/artifacts/contracts/ProtocolReserve/TokenBuyback.sol/TokenBuyback.json +2 -2
- package/artifacts/contracts/ProtocolReserve/XVSVaultTreasury.sol/XVSVaultTreasury.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockACM.sol/MockACM.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockArraySorter.sol/MockArraySorter.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockConverter.sol/MockConverter.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockDeflationaryToken.sol/MockDeflatingToken.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockRiskFundConverter.sol/MockRiskFundConverter.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockRouter.sol/MockRouter.dbg.json +1 -1
- package/artifacts/contracts/Test/Mocks/MockToken.sol/MockToken.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/AbstractTokenConverter.sol/AbstractTokenConverter.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/ConverterNetwork.sol/ConverterNetwork.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/IAbstractTokenConverter.sol/IAbstractTokenConverter.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/RiskFundConverter.sol/ILegacyRiskFundPoolState.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/RiskFundConverter.sol/RiskFundConverter.dbg.json +1 -1
- package/artifacts/contracts/TokenConverter/SingleTokenConverter.sol/SingleTokenConverter.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/access/Ownable.sol/Ownable.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/interfaces/draft-IERC1822.sol/IERC1822Proxiable.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Proxy.sol/ERC1967Proxy.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Upgrade.sol/ERC1967Upgrade.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/Proxy.sol/Proxy.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/beacon/IBeacon.sol/IBeacon.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/transparent/ProxyAdmin.sol/ProxyAdmin.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/utils/Address.sol/Address.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/utils/Context.sol/Context.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/openzeppelin/utils/StorageSlot.sol/StorageSlot.dbg.json +1 -1
- package/artifacts/hardhat-deploy/solc_0.8/proxy/OptimizedTransparentUpgradeableProxy.sol/OptimizedTransparentUpgradeableProxy.dbg.json +1 -1
- package/contracts/ProtocolReserve/TokenBuyback.sol +4 -1
- package/deployments/bscmainnet/BTCBTreasuryBuyback.json +42 -42
- package/deployments/bscmainnet/BTCBTreasuryBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/BTCBTreasuryBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/ETHTreasuryBuyback.json +42 -42
- package/deployments/bscmainnet/ETHTreasuryBuyback_Implementation.json +36 -36
- package/deployments/bscmainnet/ETHTreasuryBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/RiskFundBuyback.json +42 -42
- package/deployments/bscmainnet/RiskFundBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/RiskFundBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/UPrimeBuyback.json +42 -42
- package/deployments/bscmainnet/UPrimeBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/UPrimeBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/USDCTreasuryBuyback.json +42 -42
- package/deployments/bscmainnet/USDCTreasuryBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/USDCTreasuryBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/USDTPrimeBuyback.json +42 -42
- package/deployments/bscmainnet/USDTPrimeBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/USDTPrimeBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/USDTTreasuryBuyback.json +42 -42
- package/deployments/bscmainnet/USDTTreasuryBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/USDTTreasuryBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/UTreasuryBuyback.json +42 -42
- package/deployments/bscmainnet/UTreasuryBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/UTreasuryBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/XVSBuyback.json +42 -42
- package/deployments/bscmainnet/XVSBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/XVSBuyback_Proxy.json +41 -41
- package/deployments/bscmainnet/XVSTreasuryBuyback.json +43 -43
- package/deployments/bscmainnet/XVSTreasuryBuyback_Implementation.json +38 -38
- package/deployments/bscmainnet/XVSTreasuryBuyback_Proxy.json +42 -42
- package/deployments/bscmainnet/solcInputs/06a4b2a5158db930e9e8fb8d7fe245af.json +139 -0
- package/deployments/bscmainnet.json +30 -30
- package/deployments/bscmainnet_addresses.json +30 -30
- package/dist/typechain/factories/TokenBuyback__factory.d.ts +1 -1
- package/dist/typechain/factories/TokenBuyback__factory.js +1 -1
- package/package.json +1 -1
- package/typechain/factories/TokenBuyback__factory.ts +1 -1
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
{
|
|
2
|
+
"language": "Solidity",
|
|
3
|
+
"sources": {
|
|
4
|
+
"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol": {
|
|
5
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./OwnableUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides 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} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {\n function __Ownable2Step_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable2Step_init_unchained() internal onlyInitializing {\n }\n address private _pendingOwner;\n\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Returns the address of the pending owner.\n */\n function pendingOwner() public view virtual returns (address) {\n return _pendingOwner;\n }\n\n /**\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual override onlyOwner {\n _pendingOwner = newOwner;\n emit OwnershipTransferStarted(owner(), newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual override {\n delete _pendingOwner;\n super._transferOwnership(newOwner);\n }\n\n /**\n * @dev The new owner accepts the ownership transfer.\n */\n function acceptOwnership() public virtual {\n address sender = _msgSender();\n require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n _transferOwnership(sender);\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"
|
|
6
|
+
},
|
|
7
|
+
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": {
|
|
8
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby disabling 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"
|
|
9
|
+
},
|
|
10
|
+
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
|
|
11
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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 * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\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.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\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 * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\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 * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\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 * Emits an {Initialized} event the first time it is successfully executed.\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 /**\n * @dev Returns the highest version that has been initialized. See {reinitializer}.\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\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/security/ReentrancyGuardUpgradeable.sol": {
|
|
17
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n * `nonReentrant` function in the call stack.\n */\n function _reentrancyGuardEntered() internal view returns (bool) {\n return _status == _ENTERED;\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"
|
|
18
|
+
},
|
|
19
|
+
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol": {
|
|
20
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
|
|
21
|
+
},
|
|
22
|
+
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
|
|
23
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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 IERC20Upgradeable {\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(address from, address to, uint256 amount) external returns (bool);\n}\n"
|
|
24
|
+
},
|
|
25
|
+
"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": {
|
|
26
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n /**\n * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n /**\n * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n */\n function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n /**\n * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n uint256 oldAllowance = token.allowance(address(this), spender);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n }\n\n /**\n * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n */\n function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n }\n }\n\n /**\n * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n * to be set to zero before setting it to a non-zero value, such as USDT.\n */\n function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {\n bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n if (!_callOptionalReturnBool(token, approvalCall)) {\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n _callOptionalReturn(token, approvalCall);\n }\n }\n\n /**\n * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n * Revert on invalid signature.\n */\n function safePermit(\n IERC20PermitUpgradeable token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n *\n * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n */\n function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n // and not revert is the subcall reverts.\n\n (bool success, bytes memory returndata) = address(token).call(data);\n return\n success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));\n }\n}\n"
|
|
27
|
+
},
|
|
28
|
+
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
|
|
29
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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 * Furthermore, `isContract` will also return true if the target contract within\n * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n * which only has an effect at the end of a transaction.\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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, \"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(address target, bytes memory data, uint256 value) 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 (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or 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 _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\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"
|
|
30
|
+
},
|
|
31
|
+
"@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": {
|
|
32
|
+
"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"
|
|
33
|
+
},
|
|
34
|
+
"@openzeppelin/contracts/access/IAccessControl.sol": {
|
|
35
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControl {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\n}\n"
|
|
36
|
+
},
|
|
37
|
+
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
|
|
38
|
+
"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"
|
|
39
|
+
},
|
|
40
|
+
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
|
|
41
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(address from, address to, uint256 amount) external returns (bool);\n}\n"
|
|
42
|
+
},
|
|
43
|
+
"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol": {
|
|
44
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\n\nimport \"./IAccessControlManagerV8.sol\";\n\n/**\n * @title AccessControlledV8\n * @author Venus\n * @notice This contract is helper between access control manager and actual contract. This contract further inherited by other contract (using solidity 0.8.13)\n * to integrate access controlled mechanism. It provides initialise methods and verifying access methods.\n */\nabstract contract AccessControlledV8 is Initializable, Ownable2StepUpgradeable {\n /// @notice Access control manager contract\n IAccessControlManagerV8 internal _accessControlManager;\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 /// @notice Emitted when access control manager contract address is changed\n event NewAccessControlManager(address oldAccessControlManager, address newAccessControlManager);\n\n /// @notice Thrown when the action is prohibited by AccessControlManager\n error Unauthorized(address sender, address calledContract, string methodSignature);\n\n function __AccessControlled_init(address accessControlManager_) internal onlyInitializing {\n __Ownable2Step_init();\n __AccessControlled_init_unchained(accessControlManager_);\n }\n\n function __AccessControlled_init_unchained(address accessControlManager_) internal onlyInitializing {\n _setAccessControlManager(accessControlManager_);\n }\n\n /**\n * @notice Sets the address of AccessControlManager\n * @dev Admin function to set address of AccessControlManager\n * @param accessControlManager_ The new address of the AccessControlManager\n * @custom:event Emits NewAccessControlManager event\n * @custom:access Only Governance\n */\n function setAccessControlManager(address accessControlManager_) external onlyOwner {\n _setAccessControlManager(accessControlManager_);\n }\n\n /**\n * @notice Returns the address of the access control manager contract\n */\n function accessControlManager() external view returns (IAccessControlManagerV8) {\n return _accessControlManager;\n }\n\n /**\n * @dev Internal function to set address of AccessControlManager\n * @param accessControlManager_ The new address of the AccessControlManager\n */\n function _setAccessControlManager(address accessControlManager_) internal {\n require(address(accessControlManager_) != address(0), \"invalid acess control manager address\");\n address oldAccessControlManager = address(_accessControlManager);\n _accessControlManager = IAccessControlManagerV8(accessControlManager_);\n emit NewAccessControlManager(oldAccessControlManager, accessControlManager_);\n }\n\n /**\n * @notice Reverts if the call is not allowed by AccessControlManager\n * @param signature Method signature\n */\n function _checkAccessAllowed(string memory signature) internal view {\n bool isAllowedToCall = _accessControlManager.isAllowedToCall(msg.sender, signature);\n\n if (!isAllowedToCall) {\n revert Unauthorized(msg.sender, address(this), signature);\n }\n }\n}\n"
|
|
45
|
+
},
|
|
46
|
+
"@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol": {
|
|
47
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\n\n/**\n * @title IAccessControlManagerV8\n * @author Venus\n * @notice Interface implemented by the `AccessControlManagerV8` contract.\n */\ninterface IAccessControlManagerV8 is IAccessControl {\n function giveCallPermission(address contractAddress, string calldata functionSig, address accountToPermit) external;\n\n function revokeCallPermission(\n address contractAddress,\n string calldata functionSig,\n address accountToRevoke\n ) external;\n\n function isAllowedToCall(address account, string calldata functionSig) external view returns (bool);\n\n function hasPermission(\n address account,\n address contractAddress,\n string calldata functionSig\n ) external view returns (bool);\n}\n"
|
|
48
|
+
},
|
|
49
|
+
"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol": {
|
|
50
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface OracleInterface {\n function getPrice(address asset) external view returns (uint256);\n}\n\ninterface ResilientOracleInterface is OracleInterface {\n function updatePrice(address vToken) external;\n\n function updateAssetPrice(address asset) external;\n\n function getUnderlyingPrice(address vToken) external view returns (uint256);\n}\n\ninterface TwapInterface is OracleInterface {\n function updateTwap(address asset) external returns (uint256);\n}\n\ninterface BoundValidatorInterface {\n function validatePriceWithAnchorPrice(\n address asset,\n uint256 reporterPrice,\n uint256 anchorPrice\n ) external view returns (bool);\n}\n"
|
|
51
|
+
},
|
|
52
|
+
"@venusprotocol/oracle/contracts/interfaces/VBep20Interface.sol": {
|
|
53
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\ninterface VBep20Interface is IERC20Metadata {\n /**\n * @notice Underlying asset for this VToken\n */\n function underlying() external view returns (address);\n}\n"
|
|
54
|
+
},
|
|
55
|
+
"@venusprotocol/oracle/contracts/ResilientOracle.sol": {
|
|
56
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\n// SPDX-FileCopyrightText: 2022 Venus\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport \"./interfaces/VBep20Interface.sol\";\nimport \"./interfaces/OracleInterface.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\n\n/**\n * @title ResilientOracle\n * @author Venus\n * @notice The Resilient Oracle is the main contract that the protocol uses to fetch prices of assets.\n *\n * DeFi protocols are vulnerable to price oracle failures including oracle manipulation and incorrectly\n * reported prices. If only one oracle is used, this creates a single point of failure and opens a vector\n * for attacking the protocol.\n *\n * The Resilient Oracle uses multiple sources and fallback mechanisms to provide accurate prices and protect\n * the protocol from oracle attacks. Currently it includes integrations with Chainlink, Pyth, Binance Oracle\n * and TWAP (Time-Weighted Average Price) oracles. TWAP uses PancakeSwap as the on-chain price source.\n *\n * For every market (vToken) we configure the main, pivot and fallback oracles. The oracles are configured per\n * vToken's underlying asset address. The main oracle oracle is the most trustworthy price source, the pivot\n * oracle is used as a loose sanity checker and the fallback oracle is used as a backup price source.\n *\n * To validate prices returned from two oracles, we use an upper and lower bound ratio that is set for every\n * market. The upper bound ratio represents the deviation between reported price (the price that’s being\n * validated) and the anchor price (the price we are validating against) above which the reported price will\n * be invalidated. The lower bound ratio presents the deviation between reported price and anchor price below\n * which the reported price will be invalidated. So for oracle price to be considered valid the below statement\n * should be true:\n\n```\nanchorRatio = anchorPrice/reporterPrice\nisValid = anchorRatio <= upperBoundAnchorRatio && anchorRatio >= lowerBoundAnchorRatio\n```\n\n * In most cases, Chainlink is used as the main oracle, TWAP or Pyth oracles are used as the pivot oracle depending\n * on which supports the given market and Binance oracle is used as the fallback oracle. For some markets we may\n * use Pyth or TWAP as the main oracle if the token price is not supported by Chainlink or Binance oracles.\n *\n * For a fetched price to be valid it must be positive and not stagnant. If the price is invalid then we consider the\n * oracle to be stagnant and treat it like it's disabled.\n */\ncontract ResilientOracle is PausableUpgradeable, AccessControlledV8, ResilientOracleInterface {\n /**\n * @dev Oracle roles:\n * **main**: The most trustworthy price source\n * **pivot**: Price oracle used as a loose sanity checker\n * **fallback**: The backup source when main oracle price is invalidated\n */\n enum OracleRole {\n MAIN,\n PIVOT,\n FALLBACK\n }\n\n struct TokenConfig {\n /// @notice asset address\n address asset;\n /// @notice `oracles` stores the oracles based on their role in the following order:\n /// [main, pivot, fallback],\n /// It can be indexed with the corresponding enum OracleRole value\n address[3] oracles;\n /// @notice `enableFlagsForOracles` stores the enabled state\n /// for each oracle in the same order as `oracles`\n bool[3] enableFlagsForOracles;\n }\n\n uint256 public constant INVALID_PRICE = 0;\n\n /// @notice Native market address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable nativeMarket;\n\n /// @notice VAI address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vai;\n\n /// @notice Set this as asset address for Native token on each chain.This is the underlying for vBNB (on bsc)\n /// and can serve as any underlying asset of a market that supports native tokens\n address public constant NATIVE_TOKEN_ADDR = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n /// @notice Bound validator contract address\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n BoundValidatorInterface public immutable boundValidator;\n\n mapping(address => TokenConfig) private tokenConfigs;\n\n event TokenConfigAdded(\n address indexed asset,\n address indexed mainOracle,\n address indexed pivotOracle,\n address fallbackOracle\n );\n\n /// Event emitted when an oracle is set\n event OracleSet(address indexed asset, address indexed oracle, uint256 indexed role);\n\n /// Event emitted when an oracle is enabled or disabled\n event OracleEnabled(address indexed asset, uint256 indexed role, bool indexed enable);\n\n /**\n * @notice Checks whether an address is null or not\n */\n modifier notNullAddress(address someone) {\n if (someone == address(0)) revert(\"can't be zero address\");\n _;\n }\n\n /**\n * @notice Checks whether token config exists by checking whether asset is null address\n * @dev address can't be null, so it's suitable to be used to check the validity of the config\n * @param asset asset address\n */\n modifier checkTokenConfigExistence(address asset) {\n if (tokenConfigs[asset].asset == address(0)) revert(\"token config must exist\");\n _;\n }\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @dev nativeMarketAddress can be address(0) if on the chain we do not support native market\n /// (e.g vETH on ethereum would not be supported, only vWETH)\n /// @param nativeMarketAddress The address of a native market (for bsc it would be vBNB address)\n /// @param vaiAddress The address of the VAI token (if there is VAI on the deployed chain).\n /// Set to address(0) of VAI is not existent.\n /// @param _boundValidator Address of the bound validator contract\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address nativeMarketAddress,\n address vaiAddress,\n BoundValidatorInterface _boundValidator\n ) notNullAddress(address(_boundValidator)) {\n nativeMarket = nativeMarketAddress;\n vai = vaiAddress;\n boundValidator = _boundValidator;\n\n _disableInitializers();\n }\n\n /**\n * @notice Initializes the contract admin and sets the BoundValidator contract address\n * @param accessControlManager_ Address of the access control manager contract\n */\n function initialize(address accessControlManager_) external initializer {\n __AccessControlled_init(accessControlManager_);\n __Pausable_init();\n }\n\n /**\n * @notice Pauses oracle\n * @custom:access Only Governance\n */\n function pause() external {\n _checkAccessAllowed(\"pause()\");\n _pause();\n }\n\n /**\n * @notice Unpauses oracle\n * @custom:access Only Governance\n */\n function unpause() external {\n _checkAccessAllowed(\"unpause()\");\n _unpause();\n }\n\n /**\n * @notice Batch sets token configs\n * @param tokenConfigs_ Token config array\n * @custom:access Only Governance\n * @custom:error Throws a length error if the length of the token configs array is 0\n */\n function setTokenConfigs(TokenConfig[] memory tokenConfigs_) external {\n if (tokenConfigs_.length == 0) revert(\"length can't be 0\");\n uint256 numTokenConfigs = tokenConfigs_.length;\n for (uint256 i; i < numTokenConfigs; ) {\n setTokenConfig(tokenConfigs_[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Sets oracle for a given asset and role.\n * @dev Supplied asset **must** exist and main oracle may not be null\n * @param asset Asset address\n * @param oracle Oracle address\n * @param role Oracle role\n * @custom:access Only Governance\n * @custom:error Null address error if main-role oracle address is null\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n * @custom:event Emits OracleSet event with asset address, oracle address and role of the oracle for the asset\n */\n function setOracle(\n address asset,\n address oracle,\n OracleRole role\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"setOracle(address,address,uint8)\");\n if (oracle == address(0) && role == OracleRole.MAIN) revert(\"can't set zero address to main oracle\");\n tokenConfigs[asset].oracles[uint256(role)] = oracle;\n emit OracleSet(asset, oracle, uint256(role));\n }\n\n /**\n * @notice Enables/ disables oracle for the input asset. Token config for the input asset **must** exist\n * @dev Configuration for the asset **must** already exist and the asset cannot be 0 address\n * @param asset Asset address\n * @param role Oracle role\n * @param enable Enabled boolean of the oracle\n * @custom:access Only Governance\n * @custom:error NotNullAddress error is thrown if asset address is null\n * @custom:error TokenConfigExistance error is thrown if token config is not set\n */\n function enableOracle(\n address asset,\n OracleRole role,\n bool enable\n ) external notNullAddress(asset) checkTokenConfigExistence(asset) {\n _checkAccessAllowed(\"enableOracle(address,uint8,bool)\");\n tokenConfigs[asset].enableFlagsForOracles[uint256(role)] = enable;\n emit OracleEnabled(asset, uint256(role), enable);\n }\n\n /**\n * @notice Updates the TWAP pivot oracle price.\n * @dev This function should always be called before calling getUnderlyingPrice\n * @param vToken vToken address\n */\n function updatePrice(address vToken) external override {\n address asset = _getUnderlyingAsset(vToken);\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, OracleRole.PIVOT);\n if (pivotOracle != address(0) && pivotOracleEnabled) {\n //if pivot oracle is not TwapOracle it will revert so we need to catch the revert\n try TwapInterface(pivotOracle).updateTwap(asset) {} catch {}\n }\n }\n\n /**\n * @notice Updates the pivot oracle price. Currently using TWAP\n * @dev This function should always be called before calling getPrice\n * @param asset asset address\n */\n function updateAssetPrice(address asset) external {\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, OracleRole.PIVOT);\n if (pivotOracle != address(0) && pivotOracleEnabled) {\n //if pivot oracle is not TwapOracle it will revert so we need to catch the revert\n try TwapInterface(pivotOracle).updateTwap(asset) {} catch {}\n }\n }\n\n /**\n * @dev Gets token config by asset address\n * @param asset asset address\n * @return tokenConfig Config for the asset\n */\n function getTokenConfig(address asset) external view returns (TokenConfig memory) {\n return tokenConfigs[asset];\n }\n\n /**\n * @notice Gets price of the underlying asset for a given vToken. Validation flow:\n * - Check if the oracle is paused globally\n * - Validate price from main oracle against pivot oracle\n * - Validate price from fallback oracle against pivot oracle if the first validation failed\n * - Validate price from main oracle against fallback oracle if the second validation failed\n * In the case that the pivot oracle is not available but main price is available and validation is successful,\n * main oracle price is returned.\n * @param vToken vToken address\n * @return price USD price in scaled decimal places.\n * @custom:error Paused error is thrown when resilent oracle is paused\n * @custom:error Invalid resilient oracle price error is thrown if fetched prices from oracle is invalid\n */\n function getUnderlyingPrice(address vToken) external view override returns (uint256) {\n if (paused()) revert(\"resilient oracle is paused\");\n\n address asset = _getUnderlyingAsset(vToken);\n return _getPrice(asset);\n }\n\n /**\n * @notice Gets price of the asset\n * @param asset asset address\n * @return price USD price in scaled decimal places.\n * @custom:error Paused error is thrown when resilent oracle is paused\n * @custom:error Invalid resilient oracle price error is thrown if fetched prices from oracle is invalid\n */\n function getPrice(address asset) external view override returns (uint256) {\n if (paused()) revert(\"resilient oracle is paused\");\n return _getPrice(asset);\n }\n\n /**\n * @notice Sets/resets single token configs.\n * @dev main oracle **must not** be a null address\n * @param tokenConfig Token config struct\n * @custom:access Only Governance\n * @custom:error NotNullAddress is thrown if asset address is null\n * @custom:error NotNullAddress is thrown if main-role oracle address for asset is null\n * @custom:event Emits TokenConfigAdded event when the asset config is set successfully by the authorized account\n */\n function setTokenConfig(\n TokenConfig memory tokenConfig\n ) public notNullAddress(tokenConfig.asset) notNullAddress(tokenConfig.oracles[uint256(OracleRole.MAIN)]) {\n _checkAccessAllowed(\"setTokenConfig(TokenConfig)\");\n\n tokenConfigs[tokenConfig.asset] = tokenConfig;\n emit TokenConfigAdded(\n tokenConfig.asset,\n tokenConfig.oracles[uint256(OracleRole.MAIN)],\n tokenConfig.oracles[uint256(OracleRole.PIVOT)],\n tokenConfig.oracles[uint256(OracleRole.FALLBACK)]\n );\n }\n\n /**\n * @notice Gets oracle and enabled status by asset address\n * @param asset asset address\n * @param role Oracle role\n * @return oracle Oracle address based on role\n * @return enabled Enabled flag of the oracle based on token config\n */\n function getOracle(address asset, OracleRole role) public view returns (address oracle, bool enabled) {\n oracle = tokenConfigs[asset].oracles[uint256(role)];\n enabled = tokenConfigs[asset].enableFlagsForOracles[uint256(role)];\n }\n\n function _getPrice(address asset) internal view returns (uint256) {\n uint256 pivotPrice = INVALID_PRICE;\n\n // Get pivot oracle price, Invalid price if not available or error\n (address pivotOracle, bool pivotOracleEnabled) = getOracle(asset, OracleRole.PIVOT);\n if (pivotOracleEnabled && pivotOracle != address(0)) {\n try OracleInterface(pivotOracle).getPrice(asset) returns (uint256 pricePivot) {\n pivotPrice = pricePivot;\n } catch {}\n }\n\n // Compare main price and pivot price, return main price and if validation was successful\n // note: In case pivot oracle is not available but main price is available and\n // validation is successful, the main oracle price is returned.\n (uint256 mainPrice, bool validatedPivotMain) = _getMainOraclePrice(\n asset,\n pivotPrice,\n pivotOracleEnabled && pivotOracle != address(0)\n );\n if (mainPrice != INVALID_PRICE && validatedPivotMain) return mainPrice;\n\n // Compare fallback and pivot if main oracle comparision fails with pivot\n // Return fallback price when fallback price is validated successfully with pivot oracle\n (uint256 fallbackPrice, bool validatedPivotFallback) = _getFallbackOraclePrice(asset, pivotPrice);\n if (fallbackPrice != INVALID_PRICE && validatedPivotFallback) return fallbackPrice;\n\n // Lastly compare main price and fallback price\n if (\n mainPrice != INVALID_PRICE &&\n fallbackPrice != INVALID_PRICE &&\n boundValidator.validatePriceWithAnchorPrice(asset, mainPrice, fallbackPrice)\n ) {\n return mainPrice;\n }\n\n revert(\"invalid resilient oracle price\");\n }\n\n /**\n * @notice Gets a price for the provided asset\n * @dev This function won't revert when price is 0, because the fallback oracle may still be\n * able to fetch a correct price\n * @param asset asset address\n * @param pivotPrice Pivot oracle price\n * @param pivotEnabled If pivot oracle is not empty and enabled\n * @return price USD price in scaled decimals\n * e.g. asset decimals is 8 then price is returned as 10**18 * 10**(18-8) = 10**28 decimals\n * @return pivotValidated Boolean representing if the validation of main oracle price\n * and pivot oracle price were successful\n * @custom:error Invalid price error is thrown if main oracle fails to fetch price of the asset\n * @custom:error Invalid price error is thrown if main oracle is not enabled or main oracle\n * address is null\n */\n function _getMainOraclePrice(\n address asset,\n uint256 pivotPrice,\n bool pivotEnabled\n ) internal view returns (uint256, bool) {\n (address mainOracle, bool mainOracleEnabled) = getOracle(asset, OracleRole.MAIN);\n if (mainOracleEnabled && mainOracle != address(0)) {\n try OracleInterface(mainOracle).getPrice(asset) returns (uint256 mainOraclePrice) {\n if (!pivotEnabled) {\n return (mainOraclePrice, true);\n }\n if (pivotPrice == INVALID_PRICE) {\n return (mainOraclePrice, false);\n }\n return (\n mainOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(asset, mainOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function won't revert when the price is 0 because getPrice checks if price is > 0\n * @param asset asset address\n * @return price USD price in 18 decimals\n * @return pivotValidated Boolean representing if the validation of fallback oracle price\n * and pivot oracle price were successfully\n * @custom:error Invalid price error is thrown if fallback oracle fails to fetch price of the asset\n * @custom:error Invalid price error is thrown if fallback oracle is not enabled or fallback oracle\n * address is null\n */\n function _getFallbackOraclePrice(address asset, uint256 pivotPrice) private view returns (uint256, bool) {\n (address fallbackOracle, bool fallbackEnabled) = getOracle(asset, OracleRole.FALLBACK);\n if (fallbackEnabled && fallbackOracle != address(0)) {\n try OracleInterface(fallbackOracle).getPrice(asset) returns (uint256 fallbackOraclePrice) {\n if (pivotPrice == INVALID_PRICE) {\n return (fallbackOraclePrice, false);\n }\n return (\n fallbackOraclePrice,\n boundValidator.validatePriceWithAnchorPrice(asset, fallbackOraclePrice, pivotPrice)\n );\n } catch {\n return (INVALID_PRICE, false);\n }\n }\n\n return (INVALID_PRICE, false);\n }\n\n /**\n * @dev This function returns the underlying asset of a vToken\n * @param vToken vToken address\n * @return asset underlying asset address\n */\n function _getUnderlyingAsset(address vToken) private view notNullAddress(vToken) returns (address asset) {\n if (vToken == nativeMarket) {\n asset = NATIVE_TOKEN_ADDR;\n } else if (vToken == vai) {\n asset = vai;\n } else {\n asset = VBep20Interface(vToken).underlying();\n }\n }\n}\n"
|
|
57
|
+
},
|
|
58
|
+
"@venusprotocol/solidity-utilities/contracts/constants.sol": {
|
|
59
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\n/// @dev Base unit for computations, usually used in scaling (multiplications, divisions)\nuint256 constant EXP_SCALE = 1e18;\n\n/// @dev A unit (literal one) in EXP_SCALE, usually used in additions/subtractions\nuint256 constant MANTISSA_ONE = EXP_SCALE;\n\n/// @dev The approximate number of seconds per year\nuint256 constant SECONDS_PER_YEAR = 31_536_000;\n"
|
|
60
|
+
},
|
|
61
|
+
"@venusprotocol/solidity-utilities/contracts/validators.sol": {
|
|
62
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n/// @notice Thrown if the supplied address is a zero address where it is not allowed\nerror ZeroAddressNotAllowed();\n\n/// @notice Thrown if the supplied value is 0 where it is not allowed\nerror ZeroValueNotAllowed();\n\n/// @notice Checks if the provided address is nonzero, reverts otherwise\n/// @param address_ Address to check\n/// @custom:error ZeroAddressNotAllowed is thrown if the provided address is a zero address\nfunction ensureNonzeroAddress(address address_) pure {\n if (address_ == address(0)) {\n revert ZeroAddressNotAllowed();\n }\n}\n\n/// @notice Checks if the provided value is nonzero, reverts otherwise\n/// @param value_ Value to check\n/// @custom:error ZeroValueNotAllowed is thrown if the provided value is 0\nfunction ensureNonzeroValue(uint256 value_) pure {\n if (value_ == 0) {\n revert ZeroValueNotAllowed();\n }\n}\n"
|
|
63
|
+
},
|
|
64
|
+
"contracts/Interfaces/IComptroller.sol": {
|
|
65
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IComptroller {\n function isComptroller() external view returns (bool);\n\n function markets(address) external view returns (bool);\n\n function getAllMarkets() external view returns (address[] memory);\n}\n"
|
|
66
|
+
},
|
|
67
|
+
"contracts/Interfaces/IConverterNetwork.sol": {
|
|
68
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { IAbstractTokenConverter } from \"../TokenConverter/IAbstractTokenConverter.sol\";\n\n/**\n * @title IConverterNetwork\n * @author Venus\n * @notice Interface implemented by `ConverterNetwork`.\n */\ninterface IConverterNetwork {\n /// @notice Adds new converter to the array\n /// @param _tokenConverter Address of the token converter\n function addTokenConverter(IAbstractTokenConverter _tokenConverter) external;\n\n /// @notice Removes converter from the array\n /// @param _tokenConverter Address of the token converter\n function removeTokenConverter(IAbstractTokenConverter _tokenConverter) external;\n\n /// @notice Used to get the array of converters supporting conversions, arranged in descending order based on token balances\n /// @param _tokenAddressIn Address of tokenIn\n /// @param _tokenAddressOut Address of tokenOut\n /// @return converters Array of the conveters on the basis of the tokens pair\n /// @return convertersBalance Array of balances with respect to token out\n function findTokenConverters(address _tokenAddressIn, address _tokenAddressOut)\n external\n returns (address[] memory converters, uint256[] memory convertersBalance);\n\n /// @notice Used to get the array of converters supporting conversions, arranged in descending order based on token balances\n /// @param _tokenAddressIn Address of tokenIn\n /// @param _tokenAddressOut Address of tokenOut\n /// @return converters Array of the conveters on the basis of the tokens pair\n /// @return convertersBalance Array of balances with respect to token out\n function findTokenConvertersForConverters(address _tokenAddressIn, address _tokenAddressOut)\n external\n returns (address[] memory converters, uint256[] memory convertersBalance);\n\n /// @notice This function returns the array containing all the converters addresses\n /// @return Array containing all the converters addresses\n function getAllConverters() external view returns (IAbstractTokenConverter[] memory);\n\n /// @notice This function checks for given address is converter or not\n /// @param _tokenConverter Address of the token converter\n /// @return boolean true if given address is converter otherwise false\n function isTokenConverter(address _tokenConverter) external view returns (bool);\n}\n"
|
|
69
|
+
},
|
|
70
|
+
"contracts/Interfaces/IIncomeDestination.sol": {
|
|
71
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IIncomeDestination {\n function updateAssetsState(address comptroller, address asset) external;\n}\n"
|
|
72
|
+
},
|
|
73
|
+
"contracts/Interfaces/IPoolRegistry.sol": {
|
|
74
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IPoolRegistry {\n /// @notice Get VToken in the Pool for an Asset\n function getVTokenForAsset(address comptroller, address asset) external view returns (address);\n\n /// @notice Get the addresss of the Pools supported that include a market for the provided asset\n function getPoolsSupportedByAsset(address asset) external view returns (address[] memory);\n}\n"
|
|
75
|
+
},
|
|
76
|
+
"contracts/Interfaces/IRiskFund.sol": {
|
|
77
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\n/**\n * @title IRiskFund\n * @author Venus\n * @notice Interface implemented by `RiskFund`.\n */\ninterface IRiskFund {\n function transferReserveForAuction(address comptroller, uint256 amount) external returns (uint256);\n\n function getPoolsBaseAssetReserves(address comptroller) external view returns (uint256);\n}\n\n/**\n * @title IRiskFundGetters\n * @author Venus\n * @notice Interface implemented by `RiskFund` for getter methods.\n */\ninterface IRiskFundGetters {\n function convertibleBaseAsset() external view returns (address);\n}\n"
|
|
78
|
+
},
|
|
79
|
+
"contracts/Interfaces/ITokenBuyback.sol": {
|
|
80
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { IIncomeDestination } from \"./IIncomeDestination.sol\";\n\n/**\n * @title ITokenBuyback\n * @author Venus\n * @notice Interface implemented by `TokenBuyback`.\n */\ninterface ITokenBuyback is IIncomeDestination {\n /// @notice Executes a buyback by swapping accumulated tokens via a DEX router\n /// @param tokenIn Address of the token to swap\n /// @param amountIn Amount of tokenIn to swap\n /// @param minAmountOut Minimum acceptable amount of BASE_ASSET received\n /// @param deadline Unix timestamp after which the swap reverts\n /// @param router Address of the DEX router to use\n /// @param routerCalldata Encoded calldata for the router swap call (must send output to this contract)\n /// @param comptroller Address of the pool's comptroller, echoed in the BuybackExecuted event for off-chain attribution\n function executeBuyback(\n address tokenIn,\n uint256 amountIn,\n uint256 minAmountOut,\n uint256 deadline,\n address router,\n bytes calldata routerCalldata,\n address comptroller\n ) external;\n\n /// @notice Forwards a caller-specified portion of accumulated BASE_ASSET to DESTINATION without swap\n /// @param comptroller Pool comptroller echoed in the BaseAssetForwarded event for off-chain attribution\n /// @param amount Amount of BASE_ASSET to forward\n function forwardBaseAsset(address comptroller, uint256 amount) external;\n\n /// @notice Adds or removes a DEX router from the allowlist\n /// @param router Address of the DEX router\n /// @param allowed Whether the router should be allowed\n function setAllowedRouter(address router, bool allowed) external;\n\n /// @notice Transfers tokens out of the contract (emergency recovery)\n /// @param token Address of the token to sweep\n /// @param to Recipient address\n /// @param amount Amount to transfer\n function sweepToken(\n address token,\n address to,\n uint256 amount\n ) external;\n\n /// @notice Updates the daily USD cap on tokenIn consumption (1e18-scaled)\n function setDailyCapUsd(uint256 newCap) external;\n\n /// @notice Updates the absolute USD slippage threshold for AbnormalSlippage (1e18-scaled)\n function setSlippageEventUsd(uint256 newThreshold) external;\n}\n"
|
|
81
|
+
},
|
|
82
|
+
"contracts/Interfaces/IVToken.sol": {
|
|
83
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IVToken {\n function underlying() external view returns (address);\n}\n"
|
|
84
|
+
},
|
|
85
|
+
"contracts/ProtocolReserve/RiskFundStorage.sol": {
|
|
86
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\n/// @title ReserveHelpersStorage\n/// @author Venus\n/// @dev Reserve helpers storage\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract ReserveHelpersStorage is Ownable2StepUpgradeable {\n /// @notice Deprecated slot for assetReserves mapping\n bytes32 private __deprecatedSlot1;\n\n /// @notice Deprecated slot for the former poolAssetsFunds mapping. The per-pool\n /// accounting ledger was removed: isolated pools are wound down on BSC\n /// and core pool does not auction via Shortfall, so funds now live as a\n /// single balance on this contract and are governed via sweepToken.\n bytes32 private __deprecatedSlotPoolAssetsFunds;\n\n /// @notice Deprecated slot for poolRegistry address\n bytes32 private __deprecatedSlot2;\n /// @notice Deprecated slot for status variable\n bytes32 private __deprecatedSlot3;\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 uint256[46] private __gap;\n}\n\n/// @title MaxLoopsLimitHelpersStorage\n/// @author Venus\n/// @dev Max loop limit helpers storage\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract MaxLoopsLimitHelpersStorage {\n /// @notice Limit for the loops to avoid the DOS\n /// @notice This state is deprecated, using it to prevent storage collision\n uint256 public maxLoopsLimit;\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 uint256[49] private __gap;\n}\n\n/// @title RiskFundV1Storage\n/// @author Venus\n/// @dev Risk fund V1 storage\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract RiskFundV1Storage is ReserveHelpersStorage, MaxLoopsLimitHelpersStorage {\n /// @notice Address of base asset\n address public convertibleBaseAsset;\n /// @notice Address of shortfall contract\n address public shortfall;\n\n /// @notice This state is deprecated, using it to prevent storage collision\n address private pancakeSwapRouter;\n /// @notice This state is deprecated, using it to prevent storage collision\n uint256 private minAmountToConvert;\n}\n\n/// @title RiskFundV2Storage\n/// @author Venus\n/// @dev Risk fund V2 storage\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract RiskFundV2Storage is RiskFundV1Storage, ReentrancyGuardUpgradeable {\n /// @notice Deprecated slot for the former riskFundConverter address used for\n /// per-pool accounting callbacks; the converter callback path was removed\n /// and this slot is retained only to preserve the upgradeable storage\n /// layout. The setter was dropped and the slot is not read by any contract\n /// code.\n bytes32 private __deprecatedSlotRiskFundConverter;\n}\n"
|
|
87
|
+
},
|
|
88
|
+
"contracts/ProtocolReserve/RiskFundV2.sol": {
|
|
89
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { ensureNonzeroAddress, ensureNonzeroValue } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { IRiskFund } from \"../Interfaces/IRiskFund.sol\";\nimport { RiskFundV2Storage } from \"./RiskFundStorage.sol\";\n\n/// @title RiskFundV2\n/// @author Venus\n/// @notice Contract with basic features to hold base asset for different Comptrollers\n/// @dev This contract does not support BNB\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract RiskFundV2 is AccessControlledV8, RiskFundV2Storage, IRiskFund {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Emitted when convertible base asset address is updated\n event ConvertibleBaseAssetUpdated(address indexed oldConvertibleBaseAsset, address indexed newConvertibleBaseAsset);\n\n /// @notice Emitted when shortfall contract address is updated\n event ShortfallContractUpdated(address indexed oldShortfallContract, address indexed newShortfallContract);\n\n /// @notice Emitted when reserves are transferred for auction\n event TransferredReserveForAuction(address indexed comptroller, uint256 amount);\n\n /// @notice Event emitted when tokens are swept\n event SweepToken(address indexed token, address indexed to, uint256 amount);\n\n /// @notice Error is thrown when transferReserveForAuction is called by non shortfall address\n error InvalidShortfallAddress();\n\n /// @notice thrown when amount entered is greater than balance\n error InsufficientBalance();\n\n /// @dev Convertible base asset setter\n /// @param convertibleBaseAsset_ Address of the convertible base asset\n /// @custom:event ConvertibleBaseAssetUpdated emit on success\n /// @custom:error ZeroAddressNotAllowed is thrown when convertible base asset address is zero\n /// @custom:access Only Governance\n function setConvertibleBaseAsset(address convertibleBaseAsset_) external onlyOwner {\n ensureNonzeroAddress(convertibleBaseAsset_);\n emit ConvertibleBaseAssetUpdated(convertibleBaseAsset, convertibleBaseAsset_);\n convertibleBaseAsset = convertibleBaseAsset_;\n }\n\n /// @dev Shortfall contract address setter\n /// @param shortfallContractAddress_ Address of the auction contract\n /// @custom:event ShortfallContractUpdated emit on success\n /// @custom:error ZeroAddressNotAllowed is thrown when shortfall contract address is zero\n /// @custom:access Only Governance\n function setShortfallContractAddress(address shortfallContractAddress_) external onlyOwner {\n ensureNonzeroAddress(shortfallContractAddress_);\n emit ShortfallContractUpdated(shortfall, shortfallContractAddress_);\n shortfall = shortfallContractAddress_;\n }\n\n /// @dev Transfers convertibleBaseAsset to the Shortfall contract for an auction.\n /// Per-pool accounting was removed (isolated pools are wound down and core pool\n /// does not auction), so the call now draws against this contract's raw balance.\n /// The `comptroller` argument is kept for ABI parity with Shortfall.sol and is\n /// echoed in the event only.\n /// @param comptroller Comptroller of the pool (attribution only)\n /// @param amount Amount to be transferred to the shortfall\n /// @return Amount of tokens transferred to the shortfall\n /// @custom:event TransferredReserveForAuction emit on success\n /// @custom:error InvalidShortfallAddress is thrown when caller is not shortfall contract\n /// @custom:error InsufficientBalance is thrown when amount exceeds the contract balance\n /// @custom:access Only Shortfall contract\n function transferReserveForAuction(address comptroller, uint256 amount)\n external\n override\n nonReentrant\n returns (uint256)\n {\n if (msg.sender != shortfall) {\n revert InvalidShortfallAddress();\n }\n\n uint256 balance = IERC20Upgradeable(convertibleBaseAsset).balanceOf(address(this));\n if (amount > balance) {\n revert InsufficientBalance();\n }\n\n IERC20Upgradeable(convertibleBaseAsset).safeTransfer(shortfall, amount);\n emit TransferredReserveForAuction(comptroller, amount);\n\n return amount;\n }\n\n /// @notice Function to sweep any token held by this contract\n /// @param tokenAddress Address of the asset(token)\n /// @param to Address to which assets will be transferred\n /// @param amount Amount to sweep\n /// @custom:event Emits SweepToken event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when tokenAddress/to address is zero\n /// @custom:error ZeroValueNotAllowed is thrown when amount is zero\n /// @custom:error InsufficientBalance is thrown when amount exceeds the contract balance\n /// @custom:access Only Governance\n function sweepToken(\n address tokenAddress,\n address to,\n uint256 amount\n ) external onlyOwner nonReentrant {\n ensureNonzeroAddress(tokenAddress);\n ensureNonzeroAddress(to);\n ensureNonzeroValue(amount);\n\n IERC20Upgradeable token = IERC20Upgradeable(tokenAddress);\n preSweepToken(tokenAddress, amount);\n token.safeTransfer(to, amount);\n\n emit SweepToken(tokenAddress, to, amount);\n }\n\n /// @notice Returns the RiskFund reserves attributed to a comptroller.\n /// @dev Kept on the ABI for compatibility with `Shortfall.sol` which reads this\n /// value during auction sizing. Per-pool accounting was removed alongside the\n /// `poolAssetsFunds` mapping, so this always returns 0 — Shortfall auctions\n /// for isolated pools are not expected to fire post-migration, and returning\n /// 0 is safer than the raw contract balance (prevents any zombie auction\n /// from over-sizing its seizedRiskFund against the global pool).\n /// @param comptroller Comptroller address (unused; retained for ABI parity)\n /// @return Always 0\n function getPoolsBaseAssetReserves(address comptroller) external view returns (uint256) {\n comptroller; // silence unused-parameter warning\n return 0;\n }\n\n /// @dev Operations to perform before sweeping tokens\n /// @param tokenAddress Address of the token\n /// @param amount Amount transferred to address(to)\n /// @custom:error InsufficientBalance is thrown when amount entered is greater than balance\n function preSweepToken(address tokenAddress, uint256 amount) internal view {\n uint256 balance = IERC20Upgradeable(tokenAddress).balanceOf(address(this));\n if (amount > balance) revert InsufficientBalance();\n }\n}\n"
|
|
90
|
+
},
|
|
91
|
+
"contracts/ProtocolReserve/TokenBuyback.sol": {
|
|
92
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { AddressUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\nimport { ensureNonzeroAddress, ensureNonzeroValue } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { ITokenBuyback } from \"../Interfaces/ITokenBuyback.sol\";\n\n/// @title TokenBuyback\n/// @author Venus\n/// @notice Accumulates tokens from ProtocolShareReserve and converts them to a base asset\n/// via DEX swaps triggered by an ACM-authorized operator (finance team cron job).\n/// Replaces the community-driven Token Converter system.\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract TokenBuyback is AccessControlledV8, ReentrancyGuardUpgradeable, ITokenBuyback {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using AddressUpgradeable for address;\n\n /// @notice Address where buyback proceeds are sent\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable DESTINATION;\n\n /// @notice Token that every swap converts into (output of every buyback)\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable BASE_ASSET;\n\n /// @notice Only legitimate caller of updateAssetsState. PSR is the single upstream\n /// income source so pinning the caller here prevents spoofed AssetsReceived\n /// events that could mis-attribute inflows to arbitrary comptrollers.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable PROTOCOL_SHARE_RESERVE;\n\n /// @notice ResilientOracle used to USD-price tokenIn and BASE_ASSET when\n /// enforcing the daily consumption cap and detecting abnormal\n /// swap slippage in executeBuyback.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable RESILIENT_ORACLE;\n\n /// @notice DEX router allowlist\n mapping(address => bool) public allowedRouters;\n\n /// @notice Per-asset balance watermark used to derive the delta received\n /// on each updateAssetsState call. Resynced after every outflow\n /// (executeBuyback, forwardBaseAsset, sweepToken) so inflow deltas\n /// stay correct across interleaved deposits and withdrawals.\n /// @dev Reflects observed `balanceOf(this)` deltas rather than an authenticated\n /// source-of-funds record. Tokens transferred directly to the contract\n /// outside the PSR flow are not distinguished from authenticated PSR\n /// inflows: they get merged into the next AssetsReceived event, can be\n /// consumed by executeBuyback / forwardBaseAsset, and are absorbed into\n /// this watermark when sweepToken resyncs to the post-transfer balance.\n /// Off-chain integrators relying on `AssetsReceived` for source-of-funds\n /// attribution must treat the value as a balance delta only.\n mapping(address => uint256) public assetsReserves;\n\n /// @notice Maximum cumulative USD value of tokenIn consumed via executeBuyback\n /// within a rolling 24h window. Bounds blast radius if the operator key\n /// is compromised. Stored 1e18-scaled.\n uint256 public dailyCapUsd;\n\n /// @notice Absolute USD threshold above which `executeBuyback` emits\n /// AbnormalSlippage. Detects swap economics that diverge from\n /// oracle pricing (e.g. swap routed through an attacker pool).\n /// Event-only; does not revert. Stored 1e18-scaled.\n uint256 public slippageEventUsd;\n\n /// @notice Cumulative USD value of tokenIn consumed, decayed linearly over `WINDOW`\n /// since the last update. Acts as a leaky-bucket accumulator: any rolling\n /// 24h interval's total consumption is bounded by `dailyCapUsd`.\n uint256 public usdConsumedInWindow;\n\n /// @notice Block timestamp at which `usdConsumedInWindow` was last written. Used\n /// to compute the linear decay applied on the next executeBuyback.\n uint256 public lastUpdate;\n\n /// @notice Decay horizon for the leaky-bucket accumulator: after `WINDOW` seconds\n /// of inactivity, `usdConsumedInWindow` decays to 0.\n uint256 internal constant WINDOW = 24 hours;\n\n /// @dev Gap for future storage variables\n uint256[44] private __gap;\n\n /// @notice Emitted when PSR transfers tokens and calls updateAssetsState\n event AssetsReceived(address indexed comptroller, address indexed asset, uint256 amount);\n\n /// @notice Emitted after a successful buyback swap\n event BuybackExecuted(\n address indexed tokenIn,\n uint256 amountIn,\n uint256 amountOut,\n address indexed router,\n address indexed comptroller\n );\n\n /// @notice Emitted when a router is added to or removed from the allowlist\n event RouterAllowlisted(address indexed router, bool allowed);\n\n /// @notice Emitted when BASE_ASSET is forwarded directly to DESTINATION without swap\n event BaseAssetForwarded(address indexed comptroller, uint256 amount);\n\n /// @notice Emitted when tokens are swept from the contract\n event SweepToken(address indexed token, address indexed to, uint256 amount);\n\n /// @notice Emitted when an executeBuyback swap returns less USD value than the input,\n /// beyond the configured slippage threshold. Event-only; the swap still settles.\n event AbnormalSlippage(\n address indexed tokenIn,\n uint256 actualAmountIn,\n uint256 amountOut,\n uint256 usdIn,\n uint256 usdOut\n );\n\n /// @notice Emitted when the daily USD cap is updated\n event DailyCapUpdated(uint256 oldCap, uint256 newCap);\n\n /// @notice Emitted when the slippage event threshold is updated\n event SlippageEventUsdUpdated(uint256 oldThreshold, uint256 newThreshold);\n\n /// @notice Thrown when the router is not on the allowlist\n error RouterNotAllowed(address router);\n\n /// @notice Thrown when requested amount exceeds the contract's token balance\n error InsufficientBalance(address token, uint256 requested, uint256 available);\n\n /// @notice Thrown when swap output is below the minimum required\n error SlippageExceeded(uint256 expected, uint256 actual);\n\n /// @notice Thrown when the deadline has passed\n error DeadlineExpired(uint256 deadline, uint256 blockTimestamp);\n\n /// @notice Thrown when tokenIn equals BASE_ASSET (no swap needed)\n error InvalidTokenIn(address tokenIn);\n\n /// @notice Thrown when updateAssetsState is called by any address other than PROTOCOL_SHARE_RESERVE\n error UnauthorizedCaller(address caller);\n\n /// @notice Thrown when executeBuyback would push cumulative USD consumption past the daily cap\n error DailyCapExceeded(uint256 attempted, uint256 cap);\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n /// @param destination_ Address where buyback proceeds land\n /// @param baseAsset_ Token being bought (output of every swap)\n /// @param protocolShareReserve_ Only address permitted to call updateAssetsState\n /// @param resilientOracle_ ResilientOracle used to USD-price tokenIn and BASE_ASSET\n constructor(\n address destination_,\n address baseAsset_,\n address protocolShareReserve_,\n address resilientOracle_\n ) {\n ensureNonzeroAddress(destination_);\n ensureNonzeroAddress(baseAsset_);\n ensureNonzeroAddress(protocolShareReserve_);\n ensureNonzeroAddress(resilientOracle_);\n DESTINATION = destination_;\n BASE_ASSET = baseAsset_;\n PROTOCOL_SHARE_RESERVE = protocolShareReserve_;\n RESILIENT_ORACLE = resilientOracle_;\n\n _disableInitializers();\n }\n\n /// @param accessControlManager_ Access control manager contract address\n /// @param dailyCapUsd_ Initial daily USD cap on tokenIn consumption (1e18-scaled)\n /// @param slippageEventUsd_ Initial absolute USD slippage threshold for AbnormalSlippage (1e18-scaled)\n function initialize(\n address accessControlManager_,\n uint256 dailyCapUsd_,\n uint256 slippageEventUsd_\n ) public initializer {\n ensureNonzeroValue(dailyCapUsd_);\n ensureNonzeroValue(slippageEventUsd_);\n\n __AccessControlled_init(accessControlManager_);\n __ReentrancyGuard_init();\n\n dailyCapUsd = dailyCapUsd_;\n slippageEventUsd = slippageEventUsd_;\n lastUpdate = block.timestamp;\n }\n\n /// @notice Called by PSR after transferring tokens to this contract\n /// @dev This is a required implementation of IIncomeDestination. PSR transfers tokens\n /// via safeTransfer before calling this function. The contract passively holds\n /// tokens until the cron calls executeBuyback. The emitted event is monitored\n /// by the cron to track which tokens arrived from which pool.\n /// The reported `balanceDifference` is computed as `balanceOf(this) -\n /// assetsReserves[asset]` and therefore reflects the observed balance delta\n /// since the last accounting update, not an authenticated record of PSR\n /// transfer amounts. Tokens transferred directly to the contract outside the\n /// PSR flow will be merged into a subsequent AssetsReceived event under\n /// whichever comptroller PSR happens to be processing at the time. The bias\n /// is one-shot (the watermark resyncs to `balanceOf(this)` on the same call)\n /// and the donated tokens remain recoverable via `sweepToken`.\n /// @param comptroller Address of the pool's comptroller\n /// @param asset Address of the token transferred\n /// @custom:event AssetsReceived emits the received amount\n /// @custom:error UnauthorizedCaller when msg.sender is not PROTOCOL_SHARE_RESERVE\n /// @custom:access Only callable by PROTOCOL_SHARE_RESERVE\n function updateAssetsState(address comptroller, address asset) external override nonReentrant {\n if (msg.sender != PROTOCOL_SHARE_RESERVE) {\n revert UnauthorizedCaller(msg.sender);\n }\n uint256 currentBalance = IERC20Upgradeable(asset).balanceOf(address(this));\n uint256 previousBalance = assetsReserves[asset];\n if (currentBalance > previousBalance) {\n uint256 balanceDifference;\n unchecked {\n balanceDifference = currentBalance - previousBalance;\n }\n assetsReserves[asset] = currentBalance;\n emit AssetsReceived(comptroller, asset, balanceDifference);\n }\n }\n\n /// @notice Executes a buyback by swapping accumulated tokens via a DEX router\n /// @param tokenIn Address of the token to swap\n /// @param amountIn Amount of tokenIn to swap\n /// @param minAmountOut Minimum acceptable amount of BASE_ASSET received\n /// @param deadline Unix timestamp after which the swap reverts\n /// @param router Address of the DEX router (must be on allowlist)\n /// @param routerCalldata Encoded calldata for the router swap call (MUST send output to address(this))\n /// @param comptroller Comptroller address echoed in the BuybackExecuted event for off-chain attribution\n /// @custom:event BuybackExecuted emits on success\n /// @custom:error DeadlineExpired when block.timestamp > deadline\n /// @custom:error InvalidTokenIn when tokenIn equals BASE_ASSET\n /// @custom:error RouterNotAllowed when router is not on the allowlist\n /// @custom:error InsufficientBalance when amountIn exceeds the contract's tokenIn balance\n /// @custom:error SlippageExceeded when amountOut is less than minAmountOut\n /// @custom:access Restricted by ACM\n function executeBuyback(\n address tokenIn,\n uint256 amountIn,\n uint256 minAmountOut,\n uint256 deadline,\n address router,\n bytes calldata routerCalldata,\n address comptroller\n ) external override nonReentrant {\n _checkAccessAllowed(\"executeBuyback(address,uint256,uint256,uint256,address,bytes,address)\");\n _validateBuyback(tokenIn, amountIn, deadline, router);\n\n // Measure BASE_ASSET and tokenIn balances directly on this contract so the\n // delta reflects actual swap consumption regardless of any donation surplus\n // sitting outside the assetsReserves watermark. Router calldata MUST send\n // BASE_ASSET output here.\n uint256 baseAssetBalanceBefore = IERC20Upgradeable(BASE_ASSET).balanceOf(address(this));\n uint256 tokenInBalanceBefore = IERC20Upgradeable(tokenIn).balanceOf(address(this));\n\n IERC20Upgradeable(tokenIn).forceApprove(router, amountIn);\n router.functionCall(routerCalldata);\n IERC20Upgradeable(tokenIn).forceApprove(router, 0);\n\n uint256 tokenInBalanceAfter = IERC20Upgradeable(tokenIn).balanceOf(address(this));\n uint256 amountOut = IERC20Upgradeable(BASE_ASSET).balanceOf(address(this)) - baseAssetBalanceBefore;\n uint256 actualAmountIn = tokenInBalanceBefore - tokenInBalanceAfter;\n\n if (amountOut < minAmountOut) {\n revert SlippageExceeded(minAmountOut, amountOut);\n }\n\n if (amountOut != 0) {\n IERC20Upgradeable(BASE_ASSET).safeTransfer(DESTINATION, amountOut);\n }\n\n assetsReserves[tokenIn] = tokenInBalanceAfter;\n assetsReserves[BASE_ASSET] = IERC20Upgradeable(BASE_ASSET).balanceOf(address(this));\n\n _enforceCapAndDetectSlippage(tokenIn, actualAmountIn, amountOut);\n\n emit BuybackExecuted(tokenIn, actualAmountIn, amountOut, router, comptroller);\n }\n\n /// @notice Forwards a caller-specified portion of accumulated BASE_ASSET to DESTINATION without swap\n /// @dev BASE_ASSET can land here from multiple pools (PSR delivers per pool), so `amount`\n /// lets the operator partition the balance and attribute each portion via the event.\n /// No-op when `amount` is zero.\n /// @param comptroller Comptroller address echoed in the BaseAssetForwarded event for off-chain attribution\n /// @param amount Amount of BASE_ASSET to forward\n /// @custom:event BaseAssetForwarded emits when amount > 0\n /// @custom:error InsufficientBalance when amount exceeds BASE_ASSET balance\n /// @custom:access Restricted by ACM\n function forwardBaseAsset(address comptroller, uint256 amount) external nonReentrant {\n _checkAccessAllowed(\"forwardBaseAsset(address,uint256)\");\n\n if (amount == 0) {\n return;\n }\n\n uint256 balance = IERC20Upgradeable(BASE_ASSET).balanceOf(address(this));\n if (amount > balance) {\n revert InsufficientBalance(BASE_ASSET, amount, balance);\n }\n\n IERC20Upgradeable(BASE_ASSET).safeTransfer(DESTINATION, amount);\n assetsReserves[BASE_ASSET] = IERC20Upgradeable(BASE_ASSET).balanceOf(address(this));\n\n emit BaseAssetForwarded(comptroller, amount);\n }\n\n /// @notice Adds or removes a DEX router from the allowlist\n /// @param router Address of the DEX router\n /// @param allowed Whether the router should be allowed\n /// @custom:event RouterAllowlisted emits on success\n /// @custom:error ZeroAddressNotAllowed is thrown when router address is zero\n /// @custom:access Only Governance\n function setAllowedRouter(address router, bool allowed) external override onlyOwner {\n ensureNonzeroAddress(router);\n allowedRouters[router] = allowed;\n emit RouterAllowlisted(router, allowed);\n }\n\n /// @notice Transfers tokens out of the contract (emergency recovery)\n /// @dev Resyncs `assetsReserves[token]` to the post-transfer balance after the\n /// sweep. This is also the canonical recovery path for tokens transferred\n /// directly to the contract outside the PSR flow: such tokens are not\n /// distinguished from PSR-delivered balances on-chain, so governance can\n /// use this function to drain unsolicited inflows when needed.\n /// @param token Address of the token to sweep\n /// @param to Recipient address\n /// @param amount Amount to transfer\n /// @custom:event SweepToken emits on success\n /// @custom:error ZeroAddressNotAllowed is thrown when token/to address is zero\n /// @custom:error ZeroValueNotAllowed is thrown when amount is zero\n /// @custom:access Only Governance\n function sweepToken(\n address token,\n address to,\n uint256 amount\n ) external override onlyOwner nonReentrant {\n ensureNonzeroAddress(token);\n ensureNonzeroAddress(to);\n ensureNonzeroValue(amount);\n\n IERC20Upgradeable(token).safeTransfer(to, amount);\n assetsReserves[token] = IERC20Upgradeable(token).balanceOf(address(this));\n\n emit SweepToken(token, to, amount);\n }\n\n /// @notice Updates the daily USD cap on tokenIn consumption\n /// @param newCap New cap value (1e18-scaled)\n /// @custom:event DailyCapUpdated emits on success\n /// @custom:access Restricted by ACM\n function setDailyCapUsd(uint256 newCap) external override {\n _checkAccessAllowed(\"setDailyCapUsd(uint256)\");\n ensureNonzeroValue(newCap);\n emit DailyCapUpdated(dailyCapUsd, newCap);\n dailyCapUsd = newCap;\n if (usdConsumedInWindow > newCap) {\n usdConsumedInWindow = newCap;\n }\n }\n\n /// @notice Updates the absolute USD slippage threshold above which AbnormalSlippage is emitted\n /// @param newThreshold New threshold value (1e18-scaled)\n /// @custom:event SlippageEventUsdUpdated emits on success\n /// @custom:access Restricted by ACM\n function setSlippageEventUsd(uint256 newThreshold) external override {\n _checkAccessAllowed(\"setSlippageEventUsd(uint256)\");\n ensureNonzeroValue(newThreshold);\n emit SlippageEventUsdUpdated(slippageEventUsd, newThreshold);\n slippageEventUsd = newThreshold;\n }\n\n /// @dev Enforces the daily USD cap on tokenIn consumption via a leaky-bucket\n /// accumulator with linear decay (rate `dailyCapUsd / WINDOW`), and emits\n /// AbnormalSlippage when the swap returns less USD value than the input by\n /// more than `slippageEventUsd`. The cap reverts; slippage detection is\n /// event-only. Continuous decay (vs a tumbling window) ensures any rolling\n /// 24h interval's total consumption is bounded by `dailyCapUsd`.\n function _enforceCapAndDetectSlippage(\n address tokenIn,\n uint256 actualAmountIn,\n uint256 amountOut\n ) internal {\n ResilientOracleInterface oracle = ResilientOracleInterface(RESILIENT_ORACLE);\n oracle.updateAssetPrice(tokenIn);\n oracle.updateAssetPrice(BASE_ASSET);\n uint256 priceIn = oracle.getPrice(tokenIn);\n uint256 priceBase = oracle.getPrice(BASE_ASSET);\n\n uint256 usdIn = (actualAmountIn * priceIn) / 1e18;\n uint256 usdOut = (amountOut * priceBase) / 1e18;\n\n uint256 elapsed = block.timestamp - lastUpdate;\n uint256 decayed = elapsed >= WINDOW ? 0 : (usdConsumedInWindow * (WINDOW - elapsed)) / WINDOW;\n lastUpdate = block.timestamp;\n\n uint256 newConsumed = decayed + usdIn;\n if (newConsumed > dailyCapUsd) {\n revert DailyCapExceeded(newConsumed, dailyCapUsd);\n }\n\n usdConsumedInWindow = newConsumed;\n\n if (usdIn > usdOut) {\n uint256 usdSlippage = usdIn - usdOut;\n if (usdSlippage > slippageEventUsd) {\n emit AbnormalSlippage(tokenIn, actualAmountIn, amountOut, usdIn, usdOut);\n }\n }\n }\n\n /// @dev Validates executeBuyback inputs before router interaction\n function _validateBuyback(\n address tokenIn,\n uint256 amountIn,\n uint256 deadline,\n address router\n ) internal view {\n if (block.timestamp > deadline) {\n revert DeadlineExpired(deadline, block.timestamp);\n }\n if (tokenIn == BASE_ASSET) {\n revert InvalidTokenIn(tokenIn);\n }\n if (!allowedRouters[router]) {\n revert RouterNotAllowed(router);\n }\n\n ensureNonzeroValue(amountIn);\n\n uint256 tokenInBalance = IERC20Upgradeable(tokenIn).balanceOf(address(this));\n if (amountIn > tokenInBalance) {\n revert InsufficientBalance(tokenIn, amountIn, tokenInBalance);\n }\n }\n}\n"
|
|
93
|
+
},
|
|
94
|
+
"contracts/Test/Mocks/MockConverter.sol": {
|
|
95
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracle } from \"@venusprotocol/oracle/contracts/ResilientOracle.sol\";\n\nimport { AbstractTokenConverter } from \"../../TokenConverter/AbstractTokenConverter.sol\";\nimport { IRiskFundGetters } from \"../../Interfaces/IRiskFund.sol\";\n\ncontract MockConverter is AbstractTokenConverter {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Store the previous state for the asset transferred to ProtocolShareReserve combined(for all pools)\n mapping(address => uint256) public assetsReserves;\n\n /// @notice Store the asset's reserve per pool in the ProtocolShareReserve\n /// @dev Comptroller(pool) -> Asset -> amount\n mapping(address => mapping(address => uint256)) public poolsAssetsReserves;\n\n /// @notice Emitted after updating of the assets reserves\n /// amount -> reserve increased by amount\n event AssetsReservesUpdated(address indexed comptroller, address indexed asset, uint256 amount);\n\n function mockPrivateConversion(\n address comptroller,\n address tokenAddressOut,\n uint256 balanceDiff\n ) external {\n _privateConversion(comptroller, tokenAddressOut, balanceDiff);\n }\n\n function AbstractTokenConverter_init(\n address accessControlManager_,\n ResilientOracle priceOracle_,\n address destinationAddress_,\n uint256 minAmountToConvert_\n ) public initializer {\n __AbstractTokenConverter_init(accessControlManager_, priceOracle_, destinationAddress_, minAmountToConvert_);\n }\n\n function balanceOf(address tokenAddress) public view override returns (uint256 tokenBalance) {\n IERC20Upgradeable token = IERC20Upgradeable(tokenAddress);\n tokenBalance = token.balanceOf(address(this));\n }\n\n function _postPrivateConversionHook(\n address comptroller,\n address tokenAddressIn,\n uint256 convertedTokenInBalance,\n address tokenAddressOut,\n uint256 convertedTokenOutBalance\n ) internal override {\n if (convertedTokenInBalance > 0) {\n assetsReserves[tokenAddressIn] += convertedTokenInBalance;\n poolsAssetsReserves[comptroller][tokenAddressIn] += convertedTokenInBalance;\n emit AssetsReservesUpdated(comptroller, tokenAddressIn, convertedTokenInBalance);\n }\n if (convertedTokenOutBalance > 0) {\n assetsReserves[tokenAddressOut] += convertedTokenOutBalance;\n poolsAssetsReserves[comptroller][tokenAddressOut] += convertedTokenOutBalance;\n emit AssetsReservesUpdated(comptroller, tokenAddressOut, convertedTokenOutBalance);\n }\n }\n\n /// @notice Get base asset address\n function _getDestinationBaseAsset() internal view override returns (address) {\n return IRiskFundGetters(destinationAddress).convertibleBaseAsset();\n }\n}\n"
|
|
96
|
+
},
|
|
97
|
+
"contracts/Test/Mocks/MockRiskFundConverter.sol": {
|
|
98
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { RiskFundConverter } from \"../../TokenConverter/RiskFundConverter.sol\";\n\ncontract MockRiskFundConverter is RiskFundConverter {\n constructor(\n address corePoolComptroller_,\n address vBNB_,\n address nativeWrapped_\n ) RiskFundConverter(corePoolComptroller_, vBNB_, nativeWrapped_) {}\n\n function postConversionHookMock(\n address tokenInAddress,\n address tokenOutAddress,\n uint256 amountIn,\n uint256 amountOut\n ) external {\n super._postConversionHook(tokenInAddress, tokenOutAddress, amountIn, amountOut);\n }\n\n function preTransferHookMock(address tokenOutAddress, uint256 amountOut) external {\n super._preTransferHook(tokenOutAddress, amountOut);\n }\n\n function setAssetsReserves(address asset, uint256 amount) external {\n assetsReserves[asset] = amount;\n }\n\n function setPoolsAssetsReserves(\n address comptroller,\n address asset,\n uint256 amount\n ) external {\n poolsAssetsReserves[comptroller][asset] = amount;\n }\n\n function getPoolsAssetsReserves(address comptroller, address asset) external view returns (uint256) {\n return poolsAssetsReserves[comptroller][asset];\n }\n\n function getAssetsReserves(address asset) external view returns (uint256) {\n return assetsReserves[asset];\n }\n}\n"
|
|
99
|
+
},
|
|
100
|
+
"contracts/Test/Mocks/MockRouter.sol": {
|
|
101
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/// @title MockRouter\n/// @notice Minimal DEX router mock for testing TokenBuyback.\n/// Pulls tokenIn via transferFrom and sends tokenOut to recipient.\n/// `shouldFail` flag lets tests simulate router failures.\n/// `skipTransfer` flag lets tests simulate a router that pulls input but sends no output (amountOut = 0 path).\ncontract MockRouter {\n bool public shouldFail;\n bool public skipTransfer;\n\n error RouterForcedFailure();\n\n function setShouldFail(bool value) external {\n shouldFail = value;\n }\n\n function setSkipTransfer(bool value) external {\n skipTransfer = value;\n }\n\n /// @notice Simulates a DEX swap\n /// @param tokenIn Token pulled from caller\n /// @param amountIn Amount pulled\n /// @param tokenOut Token sent to recipient\n /// @param amountOut Amount sent\n /// @param recipient Where tokenOut is delivered\n function swap(\n address tokenIn,\n uint256 amountIn,\n address tokenOut,\n uint256 amountOut,\n address recipient\n ) external {\n if (shouldFail) {\n revert RouterForcedFailure();\n }\n\n IERC20(tokenIn).transferFrom(msg.sender, address(this), amountIn);\n\n if (!skipTransfer) {\n IERC20(tokenOut).transfer(recipient, amountOut);\n }\n }\n\n /// @notice Fund the router with tokenOut so it can deliver swap output in tests\n function fund(address token, uint256 amount) external {\n IERC20(token).transferFrom(msg.sender, address(this), amount);\n }\n}\n"
|
|
102
|
+
},
|
|
103
|
+
"contracts/TokenConverter/AbstractTokenConverter.sol": {
|
|
104
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracle } from \"@venusprotocol/oracle/contracts/ResilientOracle.sol\";\nimport { ensureNonzeroAddress, ensureNonzeroValue } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\nimport { MANTISSA_ONE, EXP_SCALE } from \"@venusprotocol/solidity-utilities/contracts/constants.sol\";\n\nimport { IAbstractTokenConverter } from \"./IAbstractTokenConverter.sol\";\nimport { IConverterNetwork } from \"../Interfaces/IConverterNetwork.sol\";\n\n/// @title AbstractTokenConverter\n/// @author Venus\n/// @notice Abstract contract will be extended by SingleTokenConverter and RiskFundConverter\n/*\n * This contract specifies four functions for converting tokens, each applicable under following circumstances:\n *\n * Case I: TokenIn -> deflationary token, TokenOut -> deflationary token\n * In this scenario, functions supporting fees can only be utilized to convert tokens which are:\n * a. convertExactTokensSupportingFeeOnTransferTokens\n * b. convertForExactTokensSupportingFeeOnTransferTokens\n *\n * Case II: TokenIn -> deflationary token, TokenOut -> non-deflationary token\n * In this scenario, functions supporting fee can only be utilized to convert tokens which are:\n * similar to Case I.\n *\n * Case III: TokenIn -> non-deflationary token, TokenOut -> deflationary token\n * In this scenario, functions with or without supporting fee can be utilized to convert tokens which are:\n * a. convertExactTokens\n * b. convertForExactTokens\n * c. convertExactTokensSupportingFeeOnTransferTokens\n * d. convertForExactTokensSupportingFeeOnTransferTokens\n *\n * Case IV: TokenIn -> non-deflationary token, TokenOut -> non-deflationary token\n * In this scenario, functions with or without supporting fee can be utilized to convert tokens which are:\n * similar to Case III.\n *\n * ------------------------------------------------------------------------------------------------------------------------------------\n * Example 1:-\n * tokenInAddress - 0xaaaa.....\n * tokenOutAddress - 0xbbbb.....\n * tokenInAmount - 100\n * tokenOutMinAmount - minimum amount desired by the user(let's say 70)\n * Here user can use `convertExactTokens` or `convertExactTokensSupportingFeeOnTransferTokens`, if tokenIn is deflationary\n * then `convertExactTokensSupportingFeeOnTransferTokens` should be used(let's suppose `convertExactTokens` is used).\n * Now first tokenInAddress tokens will be transferred from the user to the contract, on the basis of amount\n * received(as tokenInAddress can be deflationary token) tokenAmountOut will be calculated and will be transferred\n * to the user and if amount sent is less than tokenOutMinAmount, tx will revert. If amount sent is satisfied(let's say\n * 80 or even 70) then at last the actual amount received and the amount that was supposed to be received by the contract will\n * be compared, if they differ then the whole tx will revert as user was supposed to use `convertExactTokensSupportingFeeOnTransferTokens`\n * function for tokenIn as deflationary token.\n *\n * Example 2:-\n * tokenInAddress - 0xaaaa.....\n * tokenOutAddress - 0xbbbb.....\n * tokenInMaxAmount - maximum amount user is willing to provide(let's say 100)\n * tokenOutAmount - 70\n * Here user can use `convertForExactTokens` or `convertForExactTokensSupportingFeeOnTransferTokens`, if tokenIn is deflationary\n * then `convertForExactTokensSupportingFeeOnTransferTokens` should be used(let's suppose `convertForExactTokens` is used),\n * which on the basis of tokenOutAmount provided will calculate tokenInAmount based on the tokens prices and will transfer\n * tokens from the user to the contract, now the actual amount received(as tokenInAddress can be deflationary token) will be\n * compared with tokenInMaxAmount if it is greater, tx will revert. If In amount is satisfied(let's say 90 or even 100) then\n * new tokenOutAmount will be calculated, and tokenOutAddress tokens will be transferred to the user, but at last the\n * old tokenOutAmount and new tokenOutAmount will be compared and if they differ whole tx will revert, because user was\n * supposed to use `convertForExactTokensSupportingFeeOnTransferTokens` function for tokenIn as deflationary token.\n * ------------------------------------------------------------------------------------------------------------------------------------\n *\n * This contract also supports private conversion between the converters:\n * Private conversions:\n * Private conversions is designed in order to convert the maximum amount of tokens received from PSR(to any converter) between\n * existing converters to save incentive and lower the dependency of users for conversion. So Private Conversion will be executed\n * by converters on it's own whenever funds are received from PSR. No incentive will be offered during private conversion.\n *\n * It will execute on updateAssetsState() function call in Converter Contracts. After this function call, converter will first\n * check for the amount received. If base asset is received then it will be directly sent to the destination address and no private\n * conversion will happen otherwise converter will interact with ConverterNetwork contract to find other valid converters who are providing the conversion for:\n *\n * tokenAddressIn: As asset received by that converter on updateAssetsState() function call.\n * tokenAddressOut: As base asset of that converter.\n *\n * ConverterNetwork:\n * This contract will contain all the converters, and will provide valid converters which can perform the execution according to tokenAddressIn\n * and tokenAddressOut provided.\n *\n * findTokenConverters():\n * It will return an array of converter addresses along with their corresponding balances, sorted in descending order based on the converter's balances\n * relative to tokenAddressOut. This function filter the converter addresses on the basis of the conversionAccess(for users).\n *\n * findTokenConvertersForConverters():\n * It will return an array of converter addresses along with their corresponding balances, sorted in descending order based on the converter's balances\n * relative to tokenAddressOut. This function filter the converter addresses on the basis of the conversionAccess(for converters).\n */\n\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\nabstract contract AbstractTokenConverter is AccessControlledV8, IAbstractTokenConverter, ReentrancyGuardUpgradeable {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Maximum incentive could be\n uint256 public constant MAX_INCENTIVE = 0.5e18;\n\n /// @notice Min amount to convert for private conversions. Defined in USD, with 18 decimals\n uint256 public minAmountToConvert;\n\n /// @notice Venus price oracle contract\n ResilientOracle public priceOracle;\n\n /// @notice conversion configurations for the existing pairs\n /// @dev tokenAddressIn => tokenAddressOut => ConversionConfig\n mapping(address => mapping(address => ConversionConfig)) public conversionConfigurations;\n\n /// @notice Address that all incoming tokens are transferred to\n address public destinationAddress;\n\n /// @notice Boolean for if conversion is paused\n bool public conversionPaused;\n\n /// @notice Address of the converterNetwork contract\n IConverterNetwork public converterNetwork;\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 uint256[45] private __gap;\n\n /// @notice Emitted when config is updated for tokens pair\n event ConversionConfigUpdated(\n address indexed tokenAddressIn,\n address indexed tokenAddressOut,\n uint256 oldIncentive,\n uint256 newIncentive,\n ConversionAccessibility oldAccess,\n ConversionAccessibility newAccess\n );\n /// @notice Emitted when price oracle address is updated\n event PriceOracleUpdated(ResilientOracle indexed oldPriceOracle, ResilientOracle indexed priceOracle);\n\n /// @notice Emitted when destination address is updated\n event DestinationAddressUpdated(address indexed oldDestinationAddress, address indexed destinationAddress);\n\n /// @notice Emitted when converterNetwork address is updated\n event ConverterNetworkAddressUpdated(address indexed oldConverterNetwork, address indexed converterNetwork);\n\n /// @notice Emitted when exact amount of tokens are converted for tokens\n event ConvertedExactTokens(\n address indexed sender,\n address indexed receiver,\n address tokenAddressIn,\n address indexed tokenAddressOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /// @notice Emitted when tokens are converted for exact amount of tokens\n event ConvertedForExactTokens(\n address indexed sender,\n address indexed receiver,\n address tokenAddressIn,\n address indexed tokenAddressOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /// @notice Emitted when exact amount of tokens are converted for tokens, for deflationary tokens\n event ConvertedExactTokensSupportingFeeOnTransferTokens(\n address indexed sender,\n address indexed receiver,\n address tokenAddressIn,\n address indexed tokenAddressOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /// @notice Emitted when tokens are converted for exact amount of tokens, for deflationary tokens\n event ConvertedForExactTokensSupportingFeeOnTransferTokens(\n address indexed sender,\n address indexed receiver,\n address tokenAddressIn,\n address indexed tokenAddressOut,\n uint256 amountIn,\n uint256 amountOut\n );\n\n /// @notice Emitted when conversion is paused\n event ConversionPaused(address indexed sender);\n\n /// @notice Emitted when conversion is unpaused\n event ConversionResumed(address indexed sender);\n\n /// @notice Event emitted when tokens are swept\n event SweepToken(address indexed token, address indexed to, uint256 amount);\n\n /// @notice Emitted when minimum amount to convert is updated\n event MinAmountToConvertUpdated(uint256 oldMinAmountToConvert, uint256 newMinAmountToConvert);\n\n /// @notice Thrown when actualAmountOut does not match with amountOutMantissa for convertForExactTokens\n error AmountOutMismatched();\n\n /// @notice Thrown when actualAmountIn does not match with amountInMantissa for convertForExactTokens\n error AmountInMismatched();\n\n /// @notice Thrown when given input amount is zero\n error InsufficientInputAmount();\n\n /// @notice Thrown when given output amount is zero\n error InsufficientOutputAmount();\n\n /// @notice Thrown when conversion is disabled or config does not exist for given pair\n error ConversionConfigNotEnabled();\n\n /// @notice Thrown when conversion is enabled only for private conversions\n error ConversionEnabledOnlyForPrivateConversions();\n\n /// @notice Thrown when address(to) is same as tokenAddressIn or tokenAddressOut\n error InvalidToAddress();\n\n /// @notice Thrown when incentive is higher than the MAX_INCENTIVE\n error IncentiveTooHigh(uint256 incentive, uint256 maxIncentive);\n\n /// @notice Thrown when amountOut is lower than amountOutMin\n error AmountOutLowerThanMinRequired(uint256 amountOutMantissa, uint256 amountOutMinMantissa);\n\n /// @notice Thrown when amountIn is higher than amountInMax\n error AmountInHigherThanMax(uint256 amountInMantissa, uint256 amountInMaxMantissa);\n\n /// @notice Thrown when conversion is paused\n error ConversionTokensPaused();\n\n /// @notice Thrown when conversion is Active\n error ConversionTokensActive();\n\n /// @notice Thrown when tokenInAddress is same as tokeOutAdress OR tokeInAddress is not the base asset of the destination\n error InvalidTokenConfigAddresses();\n\n /// @notice Thrown when contract has less liquidity for tokenAddressOut than amountOutMantissa\n error InsufficientPoolLiquidity();\n\n /// @notice When address of the ConverterNetwork is not set or Zero address\n error InvalidConverterNetwork();\n\n /// @notice Thrown when trying to set non zero incentive for private conversion\n error NonZeroIncentiveForPrivateConversion();\n\n /// @notice Thrown when using convertForExactTokens deflationary tokens\n error DeflationaryTokenNotSupported();\n\n /// @notice Thrown when minimum amount to convert is zero\n error InvalidMinimumAmountToConvert();\n\n /// @notice Thrown when there is a mismatch in the length of input arrays\n error InputLengthMisMatch();\n\n /**\n * @notice Modifier to ensure valid conversion parameters for a token conversion\n * and check if conversion is paused or not\n * @param to The recipient address for the converted tokens\n * @param tokenAddressIn The input token address for the conversion\n * @param tokenAddressOut The output token address for the conversion\n */\n modifier validConversionParameters(\n address to,\n address tokenAddressIn,\n address tokenAddressOut\n ) {\n _checkConversionPaused();\n ensureNonzeroAddress(to);\n if (to == tokenAddressIn || to == tokenAddressOut) {\n revert InvalidToAddress();\n }\n _;\n }\n\n /// @notice Pause conversion of tokens\n /// @custom:event Emits ConversionPaused on success\n /// @custom:error ConversionTokensPaused thrown when conversion is already paused\n /// @custom:access Restricted by ACM\n function pauseConversion() external {\n _checkAccessAllowed(\"pauseConversion()\");\n _checkConversionPaused();\n conversionPaused = true;\n emit ConversionPaused(msg.sender);\n }\n\n /// @notice Resume conversion of tokens.\n /// @custom:event Emits ConversionResumed on success\n /// @custom:error ConversionTokensActive thrown when conversion is already active\n /// @custom:access Restricted by ACM\n function resumeConversion() external {\n _checkAccessAllowed(\"resumeConversion()\");\n if (!conversionPaused) {\n revert ConversionTokensActive();\n }\n\n conversionPaused = false;\n emit ConversionResumed(msg.sender);\n }\n\n /// @notice Sets a new price oracle\n /// @param priceOracle_ Address of the new price oracle to set\n /// @custom:access Only Governance\n function setPriceOracle(ResilientOracle priceOracle_) external onlyOwner {\n _setPriceOracle(priceOracle_);\n }\n\n /// @notice Sets a new destination address\n /// @param destinationAddress_ The new destination address to be set\n /// @custom:access Only Governance\n function setDestination(address destinationAddress_) external onlyOwner {\n _setDestination(destinationAddress_);\n }\n\n /// @notice Sets a converter network contract address\n /// @param converterNetwork_ The converterNetwork address to be set\n /// @custom:access Only Governance\n function setConverterNetwork(IConverterNetwork converterNetwork_) external onlyOwner {\n _setConverterNetwork(converterNetwork_);\n }\n\n /// @notice Min amount to convert setter\n /// @param minAmountToConvert_ Min amount to convert\n /// @custom:access Only Governance\n function setMinAmountToConvert(uint256 minAmountToConvert_) external {\n _checkAccessAllowed(\"setMinAmountToConvert(uint256)\");\n _setMinAmountToConvert(minAmountToConvert_);\n }\n\n /// @notice Batch sets the conversion configurations\n /// @param tokenAddressIn Address of tokenIn\n /// @param tokenAddressesOut Array of addresses of tokenOut\n /// @param conversionConfigs Array of conversionConfig config details to update\n /// @custom:error InputLengthMisMatch is thrown when tokenAddressesOut and conversionConfigs array length mismatches\n function setConversionConfigs(\n address tokenAddressIn,\n address[] calldata tokenAddressesOut,\n ConversionConfig[] calldata conversionConfigs\n ) external {\n uint256 tokenOutArrayLength = tokenAddressesOut.length;\n if (tokenOutArrayLength != conversionConfigs.length) revert InputLengthMisMatch();\n\n for (uint256 i; i < tokenOutArrayLength; ) {\n setConversionConfig(tokenAddressIn, tokenAddressesOut[i], conversionConfigs[i]);\n unchecked {\n ++i;\n }\n }\n }\n\n /// @notice Converts exact amount of tokenAddressIn for tokenAddressOut if there is enough tokens held by the contract\n /// @dev Method does not support deflationary tokens transfer\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param amountOutMinMantissa Min amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount transferred to destination\n /// @return actualAmountOut Actual amount transferred to user\n /// @custom:event Emits ConvertedExactTokens event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when to address is zero\n /// @custom:error InvalidToAddress error is thrown when address(to) is same as tokenAddressIn or tokenAddressOut\n /// @custom:error AmountOutLowerThanMinRequired error is thrown when amount of output tokenAddressOut is less than amountOutMinMantissa\n /// @custom:error AmountInMismatched error is thrown when amount of output tokenAddressOut is less than amountOutMinMantissa\n function convertExactTokens(\n uint256 amountInMantissa,\n uint256 amountOutMinMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n )\n external\n validConversionParameters(to, tokenAddressIn, tokenAddressOut)\n nonReentrant\n returns (uint256 actualAmountIn, uint256 actualAmountOut)\n {\n (actualAmountIn, actualAmountOut) = _convertExactTokens(\n amountInMantissa,\n amountOutMinMantissa,\n tokenAddressIn,\n tokenAddressOut,\n to\n );\n\n if (actualAmountIn != amountInMantissa) {\n revert AmountInMismatched();\n }\n\n _postConversionHook(tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n emit ConvertedExactTokens(msg.sender, to, tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n }\n\n /// @notice Converts tokens for tokenAddressIn for exact amount of tokenAddressOut if there is enough tokens held by the contract,\n /// otherwise the amount is adjusted\n /// @dev Method does not support deflationary tokens transfer\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount transferred to destination\n /// @return actualAmountOut Actual amount transferred to user\n /// @custom:event Emits ConvertedForExactTokens event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when to address is zero\n /// @custom:error InvalidToAddress error is thrown when address(to) is same as tokenAddressIn or tokenAddressOut\n /// @custom:error AmountInHigherThanMax error is thrown when amount of tokenAddressIn is higher than amountInMaxMantissa\n /// @custom:error AmountOutMismatched error is thrown when actualAmountOut is does not match amountOutMantissa\n function convertForExactTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n )\n external\n validConversionParameters(to, tokenAddressIn, tokenAddressOut)\n nonReentrant\n returns (uint256 actualAmountIn, uint256 actualAmountOut)\n {\n (actualAmountIn, actualAmountOut) = _convertForExactTokens(\n amountInMaxMantissa,\n amountOutMantissa,\n tokenAddressIn,\n tokenAddressOut,\n to\n );\n\n if (actualAmountOut != amountOutMantissa) {\n revert AmountOutMismatched();\n }\n\n _postConversionHook(tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n emit ConvertedForExactTokens(msg.sender, to, tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n }\n\n /// @notice Converts exact amount of tokenAddressIn for tokenAddressOut if there is enough tokens held by the contract\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param amountOutMinMantissa Min amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount transferred to destination\n /// @return actualAmountOut Actual amount transferred to user\n /// @custom:event Emits ConvertedExactTokensSupportingFeeOnTransferTokens event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when to address is zero\n /// @custom:error InvalidToAddress error is thrown when address(to) is same as tokenAddressIn or tokenAddressOut\n /// @custom:error AmountOutLowerThanMinRequired error is thrown when amount of output tokenAddressOut is less than amountOutMinMantissa\n function convertExactTokensSupportingFeeOnTransferTokens(\n uint256 amountInMantissa,\n uint256 amountOutMinMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n )\n external\n validConversionParameters(to, tokenAddressIn, tokenAddressOut)\n nonReentrant\n returns (uint256 actualAmountIn, uint256 actualAmountOut)\n {\n (actualAmountIn, actualAmountOut) = _convertExactTokens(\n amountInMantissa,\n amountOutMinMantissa,\n tokenAddressIn,\n tokenAddressOut,\n to\n );\n\n _postConversionHook(tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n emit ConvertedExactTokensSupportingFeeOnTransferTokens(\n msg.sender,\n to,\n tokenAddressIn,\n tokenAddressOut,\n actualAmountIn,\n actualAmountOut\n );\n }\n\n /// @notice Converts tokens for tokenAddressIn for amount of tokenAddressOut calculated on the basis of amount of\n /// tokenAddressIn received by the contract, if there is enough tokens held by the contract, otherwise the amount is adjusted.\n /// The user will be responsible for bearing any fees associated with token transfers, whether pulling in or pushing out tokens\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount transferred to destination\n /// @return actualAmountOut Actual amount transferred to user\n /// @custom:event Emits ConvertedForExactTokensSupportingFeeOnTransferTokens event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when to address is zero\n /// @custom:error InvalidToAddress error is thrown when address(to) is same as tokenAddressIn or tokenAddressOut\n /// @custom:error AmountInHigherThanMax error is thrown when amount of tokenAddressIn is higher than amountInMaxMantissa\n function convertForExactTokensSupportingFeeOnTransferTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n )\n external\n validConversionParameters(to, tokenAddressIn, tokenAddressOut)\n nonReentrant\n returns (uint256 actualAmountIn, uint256 actualAmountOut)\n {\n (actualAmountIn, actualAmountOut) = _convertForExactTokensSupportingFeeOnTransferTokens(\n amountInMaxMantissa,\n amountOutMantissa,\n tokenAddressIn,\n tokenAddressOut,\n to\n );\n\n _postConversionHook(tokenAddressIn, tokenAddressOut, actualAmountIn, actualAmountOut);\n emit ConvertedForExactTokensSupportingFeeOnTransferTokens(\n msg.sender,\n to,\n tokenAddressIn,\n tokenAddressOut,\n actualAmountIn,\n actualAmountOut\n );\n }\n\n /// @notice To sweep ERC20 tokens and transfer them to user(to address)\n /// @param tokenAddress The address of the ERC-20 token to sweep\n /// @param to The address to which tokens will be transferred\n /// @param amount The amount to transfer\n /// @custom:event Emits SweepToken event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when tokenAddress/to address is zero\n /// @custom:access Only Governance\n function sweepToken(\n address tokenAddress,\n address to,\n uint256 amount\n ) external onlyOwner nonReentrant {\n ensureNonzeroAddress(tokenAddress);\n ensureNonzeroAddress(to);\n ensureNonzeroValue(amount);\n\n IERC20Upgradeable token = IERC20Upgradeable(tokenAddress);\n preSweepToken(tokenAddress, amount);\n token.safeTransfer(to, amount);\n\n emit SweepToken(tokenAddress, to, amount);\n }\n\n /// @notice To get the amount of tokenAddressOut tokens sender could receive on providing amountInMantissa tokens of tokenAddressIn.\n /// This function does not account for potential token transfer fees(in case of deflationary tokens)\n /// @notice The amountInMantissa might be adjusted if amountOutMantissa is greater than the balance of the contract for tokenAddressOut\n /// @dev This function retrieves values without altering token prices\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressIn should be transferred after conversion\n /// @return amountOutMantissa Amount of the tokenAddressOut sender should receive after conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n /// @custom:error ConversionEnabledOnlyForPrivateConversions is thrown when conversion is only enabled for private conversion\n function getAmountOut(\n uint256 amountInMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external view returns (uint256 amountConvertedMantissa, uint256 amountOutMantissa) {\n if (\n conversionConfigurations[tokenAddressIn][tokenAddressOut].conversionAccess ==\n ConversionAccessibility.ONLY_FOR_CONVERTERS\n ) {\n revert ConversionEnabledOnlyForPrivateConversions();\n }\n\n amountConvertedMantissa = amountInMantissa;\n uint256 tokenInToOutConversion;\n (amountOutMantissa, tokenInToOutConversion) = _getAmountOut(amountInMantissa, tokenAddressIn, tokenAddressOut);\n\n uint256 maxTokenOutReserve = balanceOf(tokenAddressOut);\n\n /// If contract has less liquidity for tokenAddressOut than amountOutMantissa\n if (maxTokenOutReserve < amountOutMantissa) {\n amountConvertedMantissa = _divRoundingUp(maxTokenOutReserve * EXP_SCALE, tokenInToOutConversion);\n amountOutMantissa = maxTokenOutReserve;\n }\n }\n\n /// @notice To get the amount of tokenAddressIn tokens sender would send on receiving amountOutMantissa tokens of tokenAddressOut.\n /// This function does not account for potential token transfer fees(in case of deflationary tokens)\n /// @dev This function retrieves values without altering token prices\n /// @param amountOutMantissa Amount of tokenAddressOut user wants to receive\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressOut should be transferred after conversion\n /// @return amountInMantissa Amount of the tokenAddressIn sender would send to contract before conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n /// @custom:error ConversionEnabledOnlyForPrivateConversions is thrown when conversion is only enabled for private conversion\n function getAmountIn(\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external view returns (uint256 amountConvertedMantissa, uint256 amountInMantissa) {\n if (\n conversionConfigurations[tokenAddressIn][tokenAddressOut].conversionAccess ==\n ConversionAccessibility.ONLY_FOR_CONVERTERS\n ) {\n revert ConversionEnabledOnlyForPrivateConversions();\n }\n\n uint256 maxTokenOutReserve = balanceOf(tokenAddressOut);\n\n /// If contract has less liquidity for tokenAddressOut than amountOutMantissa\n if (maxTokenOutReserve < amountOutMantissa) {\n amountOutMantissa = maxTokenOutReserve;\n }\n\n amountConvertedMantissa = amountOutMantissa;\n (amountInMantissa, ) = _getAmountIn(amountOutMantissa, tokenAddressIn, tokenAddressOut);\n }\n\n /// @notice To get the amount of tokenAddressOut tokens sender could receive on providing amountInMantissa tokens of tokenAddressIn\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressIn should be transferred after conversion\n /// @return amountOutMantissa Amount of the tokenAddressOut sender should receive after conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getUpdatedAmountOut(\n uint256 amountInMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) public returns (uint256 amountConvertedMantissa, uint256 amountOutMantissa) {\n priceOracle.updateAssetPrice(tokenAddressIn);\n priceOracle.updateAssetPrice(tokenAddressOut);\n\n (amountOutMantissa, ) = _getAmountOut(amountInMantissa, tokenAddressIn, tokenAddressOut);\n amountConvertedMantissa = amountInMantissa;\n }\n\n /// @notice To get the amount of tokenAddressIn tokens sender would send on receiving amountOutMantissa tokens of tokenAddressOut\n /// @param amountOutMantissa Amount of tokenAddressOut user wants to receive\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressOut should be transferred after conversion\n /// @return amountInMantissa Amount of the tokenAddressIn sender would send to contract before conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getUpdatedAmountIn(\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) public returns (uint256 amountConvertedMantissa, uint256 amountInMantissa) {\n priceOracle.updateAssetPrice(tokenAddressIn);\n priceOracle.updateAssetPrice(tokenAddressOut);\n\n (amountInMantissa, ) = _getAmountIn(amountOutMantissa, tokenAddressIn, tokenAddressOut);\n amountConvertedMantissa = amountOutMantissa;\n }\n\n /// @notice This method updated the states of this contract after getting funds from PSR\n /// after settling the amount(if any) through privateConversion between converters\n /// @dev This function is called by protocolShareReserve\n /// @dev call _updateAssetsState to update the states related to the comptroller and asset transfer to the specific converter then\n /// it calls the _privateConversion which will convert the asset into destination's base asset and transfer it to destination address\n /// @param comptroller Comptroller address (pool)\n /// @param asset Asset address\n function updateAssetsState(address comptroller, address asset) public nonReentrant {\n uint256 balanceDiff = _updateAssetsState(comptroller, asset);\n if (balanceDiff > 0) {\n _privateConversion(comptroller, asset, balanceDiff);\n }\n }\n\n /// @notice Set the configuration for new or existing conversion pair\n /// @param tokenAddressIn Address of tokenIn\n /// @param tokenAddressOut Address of tokenOut\n /// @param conversionConfig ConversionConfig config details to update\n /// @custom:event Emits ConversionConfigUpdated event on success\n /// @custom:error Unauthorized error is thrown when the call is not authorized by AccessControlManager\n /// @custom:error ZeroAddressNotAllowed is thrown when pool registry address is zero\n /// @custom:error NonZeroIncentiveForPrivateConversion is thrown when incentive is non zero for private conversion\n /// @custom:access Controlled by AccessControlManager\n function setConversionConfig(\n address tokenAddressIn,\n address tokenAddressOut,\n ConversionConfig calldata conversionConfig\n ) public {\n _checkAccessAllowed(\"setConversionConfig(address,address,ConversionConfig)\");\n ensureNonzeroAddress(tokenAddressIn);\n ensureNonzeroAddress(tokenAddressOut);\n\n if (conversionConfig.incentive > MAX_INCENTIVE) {\n revert IncentiveTooHigh(conversionConfig.incentive, MAX_INCENTIVE);\n }\n\n if (\n (tokenAddressIn == tokenAddressOut) ||\n (tokenAddressIn != _getDestinationBaseAsset()) ||\n conversionConfigurations[tokenAddressOut][tokenAddressIn].conversionAccess != ConversionAccessibility.NONE\n ) {\n revert InvalidTokenConfigAddresses();\n }\n\n if (\n (conversionConfig.conversionAccess == ConversionAccessibility.ONLY_FOR_CONVERTERS) &&\n conversionConfig.incentive != 0\n ) {\n revert NonZeroIncentiveForPrivateConversion();\n }\n\n if (\n ((conversionConfig.conversionAccess == ConversionAccessibility.ONLY_FOR_CONVERTERS) ||\n (conversionConfig.conversionAccess == ConversionAccessibility.ALL)) &&\n (address(converterNetwork) == address(0))\n ) {\n revert InvalidConverterNetwork();\n }\n\n ConversionConfig storage configuration = conversionConfigurations[tokenAddressIn][tokenAddressOut];\n\n emit ConversionConfigUpdated(\n tokenAddressIn,\n tokenAddressOut,\n configuration.incentive,\n conversionConfig.incentive,\n configuration.conversionAccess,\n conversionConfig.conversionAccess\n );\n\n if (conversionConfig.conversionAccess == ConversionAccessibility.NONE) {\n delete conversionConfigurations[tokenAddressIn][tokenAddressOut];\n } else {\n configuration.incentive = conversionConfig.incentive;\n configuration.conversionAccess = conversionConfig.conversionAccess;\n }\n }\n\n /// @notice Get the balance for specific token\n /// @param token Address of the token\n /// @return tokenBalance Balance of the token the contract has\n function balanceOf(address token) public view virtual returns (uint256 tokenBalance);\n\n /// @dev Operations to perform before sweeping tokens\n /// @param token Address of the token\n /// @param amount Amount transferred to address(to)\n function preSweepToken(address token, uint256 amount) internal virtual {}\n\n /// @dev Converts exact amount of tokenAddressIn for tokenAddressOut\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param amountOutMinMantissa Min amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount of tokenAddressIn transferred\n /// @return amountOutMantissa Actual amount of tokenAddressOut transferred\n /// @custom:error AmountOutLowerThanMinRequired error is thrown when amount of output tokenAddressOut is less than amountOutMinMantissa\n function _convertExactTokens(\n uint256 amountInMantissa,\n uint256 amountOutMinMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) internal returns (uint256 actualAmountIn, uint256 amountOutMantissa) {\n _checkPrivateConversion(tokenAddressIn, tokenAddressOut);\n actualAmountIn = _doTransferIn(tokenAddressIn, amountInMantissa);\n\n (, amountOutMantissa) = getUpdatedAmountOut(actualAmountIn, tokenAddressIn, tokenAddressOut);\n\n if (amountOutMantissa < amountOutMinMantissa) {\n revert AmountOutLowerThanMinRequired(amountOutMantissa, amountOutMinMantissa);\n }\n\n _doTransferOut(tokenAddressOut, to, amountOutMantissa);\n }\n\n /// @dev Converts tokens for tokenAddressIn for exact amount of tokenAddressOut used for non deflationry tokens\n /// it is called by convertForExactTokens function\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount of tokenAddressIn transferred\n /// @return actualAmountOut Actual amount of tokenAddressOut transferred\n /// @custom:error DeflationaryTokenNotSupported is thrown if tokenAddressIn is deflationary token\n /// @custom:error AmountInHigherThanMax error is thrown when amount of tokenAddressIn is higher than amountInMaxMantissa\n function _convertForExactTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) internal returns (uint256 actualAmountIn, uint256 actualAmountOut) {\n _checkPrivateConversion(tokenAddressIn, tokenAddressOut);\n (, uint256 amountInMantissa) = getUpdatedAmountIn(amountOutMantissa, tokenAddressIn, tokenAddressOut);\n\n actualAmountIn = _doTransferIn(tokenAddressIn, amountInMantissa);\n\n if (actualAmountIn != amountInMantissa) {\n revert DeflationaryTokenNotSupported();\n }\n\n if (actualAmountIn > amountInMaxMantissa) {\n revert AmountInHigherThanMax(amountInMantissa, amountInMaxMantissa);\n }\n\n _doTransferOut(tokenAddressOut, to, amountOutMantissa);\n actualAmountOut = amountOutMantissa;\n }\n\n /// @dev Converts tokens for tokenAddressIn for the amount of tokenAddressOut used for deflationary tokens\n /// it is called by convertForExactTokensSupportingFeeOnTransferTokens function\n /// @notice Advising users to input a smaller amountOutMantissa to avoid potential transaction revert\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @return actualAmountIn Actual amount of tokenAddressIn transferred\n /// @return actualAmountOut Actual amount of tokenAddressOut transferred\n /// @custom:error AmountInHigherThanMax error is thrown when amount of tokenAddressIn is higher than amountInMaxMantissa\n function _convertForExactTokensSupportingFeeOnTransferTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) internal returns (uint256 actualAmountIn, uint256 actualAmountOut) {\n _checkPrivateConversion(tokenAddressIn, tokenAddressOut);\n (, uint256 amountInMantissa) = getUpdatedAmountIn(amountOutMantissa, tokenAddressIn, tokenAddressOut);\n\n if (amountInMantissa > amountInMaxMantissa) {\n revert AmountInHigherThanMax(amountInMantissa, amountInMaxMantissa);\n }\n\n actualAmountIn = _doTransferIn(tokenAddressIn, amountInMantissa);\n\n (, actualAmountOut) = getUpdatedAmountOut(actualAmountIn, tokenAddressIn, tokenAddressOut);\n\n _doTransferOut(tokenAddressOut, to, actualAmountOut);\n }\n\n /// @dev return actualAmountOut from reserves for tokenAddressOut\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param to Address of the tokenAddressOut receiver\n /// @param amountConvertedMantissa Amount of tokenAddressOut supposed to get transferred\n /// @custom:error InsufficientPoolLiquidity If contract has less liquidity for tokenAddressOut than amountOutMantissa\n function _doTransferOut(\n address tokenAddressOut,\n address to,\n uint256 amountConvertedMantissa\n ) internal {\n uint256 maxTokenOutReserve = balanceOf(tokenAddressOut);\n\n /// If contract has less liquidity for tokenAddressOut than amountOutMantissa\n if (maxTokenOutReserve < amountConvertedMantissa) {\n revert InsufficientPoolLiquidity();\n }\n\n _preTransferHook(tokenAddressOut, amountConvertedMantissa);\n\n IERC20Upgradeable tokenOut = IERC20Upgradeable(tokenAddressOut);\n tokenOut.safeTransfer(to, amountConvertedMantissa);\n }\n\n /// @notice Transfer tokenAddressIn from user to destination\n /// @param tokenAddressIn Address of the token to convert\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @return actualAmountIn Actual amount transferred to destination\n function _doTransferIn(address tokenAddressIn, uint256 amountInMantissa) internal returns (uint256 actualAmountIn) {\n IERC20Upgradeable tokenIn = IERC20Upgradeable(tokenAddressIn);\n uint256 balanceBeforeDestination = tokenIn.balanceOf(destinationAddress);\n tokenIn.safeTransferFrom(msg.sender, destinationAddress, amountInMantissa);\n uint256 balanceAfterDestination = tokenIn.balanceOf(destinationAddress);\n actualAmountIn = balanceAfterDestination - balanceBeforeDestination;\n }\n\n /// @dev Sets a new price oracle\n /// @param priceOracle_ Address of the new price oracle to set\n /// @custom:event Emits PriceOracleUpdated event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when price oracle address is zero\n function _setPriceOracle(ResilientOracle priceOracle_) internal {\n ensureNonzeroAddress(address(priceOracle_));\n emit PriceOracleUpdated(priceOracle, priceOracle_);\n priceOracle = priceOracle_;\n }\n\n /// @dev Sets a new destination address\n /// @param destinationAddress_ The new destination address to be set\n /// @custom:event Emits DestinationAddressUpdated event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when destination address is zero\n function _setDestination(address destinationAddress_) internal {\n ensureNonzeroAddress(destinationAddress_);\n emit DestinationAddressUpdated(destinationAddress, destinationAddress_);\n destinationAddress = destinationAddress_;\n }\n\n /// @notice Sets a converter network contract address\n /// @param converterNetwork_ The converterNetwork address to be set\n /// @custom:event Emits ConverterNetworkAddressUpdated event on success\n /// @custom:error ZeroAddressNotAllowed is thrown when address is zero\n function _setConverterNetwork(IConverterNetwork converterNetwork_) internal {\n ensureNonzeroAddress(address(converterNetwork_));\n emit ConverterNetworkAddressUpdated(address(converterNetwork), address(converterNetwork_));\n converterNetwork = converterNetwork_;\n }\n\n /// @notice Min amount to convert setter\n /// @param minAmountToConvert_ Min amount to convert\n /// @custom:event MinAmountToConvertUpdated is emitted in success\n /// @custom:error ZeroValueNotAllowed is thrown if the provided value is 0\n function _setMinAmountToConvert(uint256 minAmountToConvert_) internal {\n ensureNonzeroValue(minAmountToConvert_);\n emit MinAmountToConvertUpdated(minAmountToConvert, minAmountToConvert_);\n minAmountToConvert = minAmountToConvert_;\n }\n\n /// @dev Hook to perform after converting tokens\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @param amountIn Amount of tokenIn converted\n /// @param amountOut Amount of tokenOut converted\n function _postConversionHook(\n address tokenAddressIn,\n address tokenAddressOut,\n uint256 amountIn,\n uint256 amountOut\n ) internal virtual {}\n\n /// @param accessControlManager_ Access control manager contract address\n /// @param priceOracle_ Resilient oracle address\n /// @param destinationAddress_ Address at all incoming tokens will transferred to\n /// @param minAmountToConvert_ minimum amount to convert\n function __AbstractTokenConverter_init(\n address accessControlManager_,\n ResilientOracle priceOracle_,\n address destinationAddress_,\n uint256 minAmountToConvert_\n ) internal onlyInitializing {\n __AccessControlled_init(accessControlManager_);\n __ReentrancyGuard_init();\n __AbstractTokenConverter_init_unchained(priceOracle_, destinationAddress_, minAmountToConvert_);\n }\n\n /// @param priceOracle_ Resilient oracle address\n /// @param destinationAddress_ Address at all incoming tokens will transferred to\n /// @param minAmountToConvert_ minimum amount to convert\n function __AbstractTokenConverter_init_unchained(\n ResilientOracle priceOracle_,\n address destinationAddress_,\n uint256 minAmountToConvert_\n ) internal onlyInitializing {\n _setPriceOracle(priceOracle_);\n _setDestination(destinationAddress_);\n _setMinAmountToConvert(minAmountToConvert_);\n conversionPaused = false;\n }\n\n /// @dev _updateAssetsState hook to update the states of reserves transferred for the specific comptroller\n /// @param comptroller Comptroller address (pool)\n /// @param asset Asset address\n /// @return Amount of asset, for _privateConversion\n function _updateAssetsState(address comptroller, address asset) internal virtual returns (uint256) {}\n\n /// @dev This method is used to convert asset into base asset by converting them with other converters which supports the pair and transfer the funds to\n /// destination contract as destination's base asset\n /// @param comptroller Comptroller address (pool)\n /// @param tokenAddressOut Address of the token transferred to converter, and through _privateConversion it will be converted into base asset\n /// @param amountToConvert Amount of the tokenAddressOut transferred to converter\n function _privateConversion(\n address comptroller,\n address tokenAddressOut,\n uint256 amountToConvert\n ) internal {\n address tokenAddressIn = _getDestinationBaseAsset();\n address _destinationAddress = destinationAddress;\n uint256 convertedTokenInBalance;\n if (address(converterNetwork) != address(0)) {\n (address[] memory converterAddresses, uint256[] memory converterBalances) = converterNetwork\n .findTokenConvertersForConverters(tokenAddressOut, tokenAddressIn);\n uint256 convertersLength = converterAddresses.length;\n for (uint256 i; i < convertersLength; ) {\n if (converterBalances[i] == 0) break;\n (, uint256 amountIn) = IAbstractTokenConverter(converterAddresses[i]).getUpdatedAmountIn(\n converterBalances[i],\n tokenAddressOut,\n tokenAddressIn\n );\n if (amountIn > amountToConvert) {\n amountIn = amountToConvert;\n }\n\n if (!_validateMinAmountToConvert(amountIn, tokenAddressOut)) {\n break;\n }\n\n uint256 balanceBefore = IERC20Upgradeable(tokenAddressIn).balanceOf(_destinationAddress);\n\n IERC20Upgradeable(tokenAddressOut).forceApprove(converterAddresses[i], amountIn);\n IAbstractTokenConverter(converterAddresses[i]).convertExactTokens(\n amountIn,\n 0,\n tokenAddressOut,\n tokenAddressIn,\n _destinationAddress\n );\n\n uint256 balanceAfter = IERC20Upgradeable(tokenAddressIn).balanceOf(_destinationAddress);\n amountToConvert -= amountIn;\n convertedTokenInBalance += (balanceAfter - balanceBefore);\n\n if (amountToConvert == 0) break;\n unchecked {\n ++i;\n }\n }\n }\n\n _postPrivateConversionHook(\n comptroller,\n tokenAddressIn,\n convertedTokenInBalance,\n tokenAddressOut,\n amountToConvert\n );\n }\n\n /// @dev This hook is used to update states for the converter after the privateConversion\n /// @param comptroller Comptroller address (pool)\n /// @param tokenAddressIn Address of the destination's base asset\n /// @param convertedTokenInBalance Amount of the base asset received after the conversion\n /// @param tokenAddressOut Address of the asset transferred to other converter in exchange of base asset\n /// @param convertedTokenOutBalance Amount of tokenAddressOut transferred from this converter\n function _postPrivateConversionHook(\n address comptroller,\n address tokenAddressIn,\n uint256 convertedTokenInBalance,\n address tokenAddressOut,\n uint256 convertedTokenOutBalance\n ) internal virtual {}\n\n /// @notice This hook is used to update the state for asset reserves before transferring tokenOut to user\n /// @param tokenOutAddress Address of the asset to be transferred to the user\n /// @param amountOut Amount of tokenAddressOut transferred from this converter\n function _preTransferHook(address tokenOutAddress, uint256 amountOut) internal virtual {}\n\n /// @dev Checks if amount to convert is greater than minimum amount to convert or not\n /// @param amountIn The amount to convert\n /// @param tokenAddress Address of the token\n /// @return isValid true if amount to convert is greater than minimum amount to convert\n function _validateMinAmountToConvert(uint256 amountIn, address tokenAddress) internal returns (bool isValid) {\n priceOracle.updateAssetPrice(tokenAddress);\n uint256 amountInInUsd = (priceOracle.getPrice(tokenAddress) * amountIn) / EXP_SCALE;\n\n if (amountInInUsd >= minAmountToConvert) {\n isValid = true;\n }\n }\n\n /// @notice To get the amount of tokenAddressOut tokens sender could receive on providing amountInMantissa tokens of tokenAddressIn\n /// @dev This function retrieves values without altering token prices.\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountOutMantissa Amount of the tokenAddressOut sender should receive after conversion\n /// @return tokenInToOutConversion Ratio of tokenIn price and incentive for conversion with tokenOut price\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function _getAmountOut(\n uint256 amountInMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) internal view returns (uint256 amountOutMantissa, uint256 tokenInToOutConversion) {\n if (amountInMantissa == 0) {\n revert InsufficientInputAmount();\n }\n\n ConversionConfig memory configuration = conversionConfigurations[tokenAddressIn][tokenAddressOut];\n\n if (configuration.conversionAccess == ConversionAccessibility.NONE) {\n revert ConversionConfigNotEnabled();\n }\n\n uint256 tokenInUnderlyingPrice = priceOracle.getPrice(tokenAddressIn);\n uint256 tokenOutUnderlyingPrice = priceOracle.getPrice(tokenAddressOut);\n\n uint256 incentive = configuration.incentive;\n if (address(converterNetwork) != address(0) && (converterNetwork.isTokenConverter(msg.sender))) {\n incentive = 0;\n }\n\n /// conversion rate after considering incentive(conversionWithIncentive)\n uint256 conversionWithIncentive = MANTISSA_ONE + incentive;\n\n tokenInToOutConversion = (tokenInUnderlyingPrice * conversionWithIncentive) / tokenOutUnderlyingPrice;\n /// amount of tokenAddressOut after including incentive as amountOutMantissa will be greater than actual as it gets\n /// multiplied by conversionWithIncentive which will be >= 1\n amountOutMantissa = (amountInMantissa * tokenInToOutConversion) / (EXP_SCALE);\n }\n\n /// @dev To get the amount of tokenAddressIn tokens sender would send on receiving amountOutMantissa tokens of tokenAddressOut\n /// @dev This function retrieves values without altering token prices.\n /// @dev For user conversions, the function returns an amountInMantissa that is rounded up, ensuring that the equivalent amountInMantissa\n /// is obtained from users for corresponding amountOutMantissa, preventing any losses to the protocol. However, no rounding up is required for private conversions\n /// @param amountOutMantissa Amount of tokenAddressOut user wants to receive\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountInMantissa Amount of the tokenAddressIn sender would send to contract before conversion\n /// @return tokenInToOutConversion Ratio of tokenIn price and incentive for conversion with tokenOut price\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function _getAmountIn(\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) internal view returns (uint256 amountInMantissa, uint256 tokenInToOutConversion) {\n if (amountOutMantissa == 0) {\n revert InsufficientOutputAmount();\n }\n\n ConversionConfig memory configuration = conversionConfigurations[tokenAddressIn][tokenAddressOut];\n\n if (configuration.conversionAccess == ConversionAccessibility.NONE) {\n revert ConversionConfigNotEnabled();\n }\n\n uint256 tokenInUnderlyingPrice = priceOracle.getPrice(tokenAddressIn);\n uint256 tokenOutUnderlyingPrice = priceOracle.getPrice(tokenAddressOut);\n\n uint256 incentive = configuration.incentive;\n\n bool isPrivateConversion = address(converterNetwork) != address(0) &&\n converterNetwork.isTokenConverter(msg.sender);\n if (isPrivateConversion) {\n incentive = 0;\n }\n\n /// conversion rate after considering incentive(conversionWithIncentive)\n uint256 conversionWithIncentive = MANTISSA_ONE + incentive;\n\n /// amount of tokenAddressIn after considering incentive(i.e. amountInMantissa will be less than actual amountInMantissa if incentive > 0)\n if (isPrivateConversion) {\n amountInMantissa =\n (amountOutMantissa * tokenOutUnderlyingPrice * EXP_SCALE) /\n (tokenInUnderlyingPrice * conversionWithIncentive);\n } else {\n amountInMantissa = _divRoundingUp(\n amountOutMantissa * tokenOutUnderlyingPrice * EXP_SCALE,\n tokenInUnderlyingPrice * conversionWithIncentive\n );\n }\n\n tokenInToOutConversion = (tokenInUnderlyingPrice * conversionWithIncentive) / tokenOutUnderlyingPrice;\n }\n\n /// @dev Check if msg.sender is allowed to convert as per onlyForPrivateConversions flag\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @custom:error ConversionEnabledOnlyForPrivateConversions is thrown when conversion is only enabled for private conversion\n function _checkPrivateConversion(address tokenAddressIn, address tokenAddressOut) internal view {\n bool isConverter = (address(converterNetwork) != address(0)) && converterNetwork.isTokenConverter(msg.sender);\n if (\n (!(isConverter) &&\n (conversionConfigurations[tokenAddressIn][tokenAddressOut].conversionAccess ==\n ConversionAccessibility.ONLY_FOR_CONVERTERS))\n ) {\n revert ConversionEnabledOnlyForPrivateConversions();\n }\n }\n\n /// @dev To check, is conversion paused\n /// @custom:error ConversionTokensPaused is thrown when token conversion is paused\n function _checkConversionPaused() internal view {\n if (conversionPaused) {\n revert ConversionTokensPaused();\n }\n }\n\n /// @dev Get base asset address of the destination contract\n /// @return Address of the base asset\n function _getDestinationBaseAsset() internal view virtual returns (address) {}\n\n /// @dev Performs division where the result is rounded up\n /// @param numerator The numerator of the division operation\n /// @param denominator The denominator of the division operation. Must be non-zero\n /// @return The result of the division, rounded up\n function _divRoundingUp(uint256 numerator, uint256 denominator) internal pure returns (uint256) {\n return (numerator + denominator - 1) / denominator;\n }\n}\n"
|
|
105
|
+
},
|
|
106
|
+
"contracts/TokenConverter/IAbstractTokenConverter.sol": {
|
|
107
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { ResilientOracle } from \"@venusprotocol/oracle/contracts/ResilientOracle.sol\";\nimport { IConverterNetwork } from \"../Interfaces/IConverterNetwork.sol\";\n\n/// @notice Interface for AbstractTokenConverter\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ninterface IAbstractTokenConverter {\n /// @notice This enum define the all possible ways of conversion can happen\n enum ConversionAccessibility {\n NONE, // Conversion is disable for the pair\n ALL, // Conversion is enable for private conversion and users\n ONLY_FOR_CONVERTERS, // Conversion is enable only for private conversion\n ONLY_FOR_USERS // Conversion is enable only for users\n }\n\n /// @notice This struct represents the configuration for a token conversion.\n struct ConversionConfig {\n /// incentive on conversion of tokens in mantissa i.e 10% incentive would be 0.1 * 1e18\n uint256 incentive;\n /// enable or disable conversion for users or converters or both or none\n ConversionAccessibility conversionAccess;\n }\n\n /// @notice Pause conversion of tokens\n function pauseConversion() external;\n\n /// @notice Resume conversion of tokens.\n function resumeConversion() external;\n\n /// @notice Sets a new price oracle\n /// @param priceOracle_ Address of the new price oracle to set\n function setPriceOracle(ResilientOracle priceOracle_) external;\n\n /// @notice Set the configuration for new or existing convert pair\n /// @param tokenAddressIn Address of tokenIn\n /// @param tokenAddressOut Address of tokenOut\n /// @param conversionConfig ConversionConfig config details to update\n function setConversionConfig(\n address tokenAddressIn,\n address tokenAddressOut,\n ConversionConfig calldata conversionConfig\n ) external;\n\n /// @notice Convert exact amount of tokenAddressIn for tokenAddressOut\n /// @dev Method does not support deflationary tokens transfer\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param amountOutMinMantissa Min amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after convert\n /// @param to Address of the tokenAddressOut receiver\n function convertExactTokens(\n uint256 amountInMantissa,\n uint256 amountOutMinMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) external returns (uint256 actualAmountIn, uint256 actualAmountOut);\n\n /// @notice Convert tokens for tokenAddressIn for exact amount of tokenAddressOut\n /// @dev Method does not support deflationary tokens transfer\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after convert\n /// @param to Address of the tokenAddressOut receiver\n function convertForExactTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) external returns (uint256 actualAmountIn, uint256 actualAmountOut);\n\n /// @notice Convert exact amount of tokenAddressIn for tokenAddressOut\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param amountOutMinMantissa Min amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after convert\n /// @param to Address of the tokenAddressOut receiver\n function convertExactTokensSupportingFeeOnTransferTokens(\n uint256 amountInMantissa,\n uint256 amountOutMinMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) external returns (uint256 actualAmountIn, uint256 actualAmountOut);\n\n /// @notice Convert tokens for tokenAddressIn for exact amount of tokenAddressOut\n /// @param amountInMaxMantissa Max amount of tokenAddressIn\n /// @param amountOutMantissa Amount of tokenAddressOut required as output\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after convert\n /// @param to Address of the tokenAddressOut receiver\n function convertForExactTokensSupportingFeeOnTransferTokens(\n uint256 amountInMaxMantissa,\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut,\n address to\n ) external returns (uint256 actualAmountIn, uint256 actualAmountOut);\n\n /// @notice Get the configuration for the pair of the tokens\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return incentives Percentage of incentives to be distributed for the pair of tokens\n /// @return conversionAccess Accessibility for the pair of tokens\n function conversionConfigurations(address tokenAddressIn, address tokenAddressOut)\n external\n returns (uint256 incentives, ConversionAccessibility conversionAccess);\n\n /// @notice Get the address of the converterNetwork\n function converterNetwork() external returns (IConverterNetwork converterNetwork);\n\n /// @notice To get the amount of tokenAddressOut tokens sender could receive on providing amountInMantissa tokens of tokenAddressIn\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressIn should be transferred after conversion\n /// @return amountOutMantissa Amount of the tokenAddressOut sender should receive after conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getUpdatedAmountOut(\n uint256 amountInMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external returns (uint256 amountConvertedMantissa, uint256 amountOutMantissa);\n\n /// @notice To get the amount of tokenAddressIn tokens sender would send on receiving amountOutMantissa tokens of tokenAddressOut\n /// @param amountOutMantissa Amount of tokenAddressOut user wants to receive\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressOut should be transferred after conversion\n /// @return amountInMantissa Amount of the tokenAddressIn sender would send to contract before conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getUpdatedAmountIn(\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external returns (uint256 amountConvertedMantissa, uint256 amountInMantissa);\n\n /// @notice To get the amount of tokenAddressIn tokens sender would send on receiving amountOutMantissa tokens of tokenAddressOut\n /// @dev This function retrieves values without altering token prices.\n /// @param amountOutMantissa Amount of tokenAddressOut user wants to receive\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressOut should be transferred after conversion\n /// @return amountInMantissa Amount of the tokenAddressIn sender would send to contract before conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getAmountIn(\n uint256 amountOutMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external view returns (uint256 amountConvertedMantissa, uint256 amountInMantissa);\n\n /// @notice To get the amount of tokenAddressOut tokens sender could receive on providing amountInMantissa tokens of tokenAddressIn\n /// @dev This function retrieves values without altering token prices.\n /// @param amountInMantissa Amount of tokenAddressIn\n /// @param tokenAddressIn Address of the token to convert\n /// @param tokenAddressOut Address of the token to get after conversion\n /// @return amountConvertedMantissa Amount of tokenAddressIn should be transferred after conversion\n /// @return amountOutMantissa Amount of the tokenAddressOut sender should receive after conversion\n /// @custom:error InsufficientInputAmount error is thrown when given input amount is zero\n /// @custom:error ConversionConfigNotEnabled is thrown when conversion is disabled or config does not exist for given pair\n function getAmountOut(\n uint256 amountInMantissa,\n address tokenAddressIn,\n address tokenAddressOut\n ) external view returns (uint256 amountConvertedMantissa, uint256 amountOutMantissa);\n\n /// @notice Get the balance for specific token\n /// @param token Address of the token\n /// @return tokenBalance Balance of the token the contract has\n function balanceOf(address token) external view returns (uint256 tokenBalance);\n}\n"
|
|
108
|
+
},
|
|
109
|
+
"contracts/TokenConverter/RiskFundConverter.sol": {
|
|
110
|
+
"content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracle } from \"@venusprotocol/oracle/contracts/ResilientOracle.sol\";\nimport { ensureNonzeroAddress, ensureNonzeroValue } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { AbstractTokenConverter } from \"./AbstractTokenConverter.sol\";\nimport { IPoolRegistry } from \"../Interfaces/IPoolRegistry.sol\";\nimport { IComptroller } from \"../Interfaces/IComptroller.sol\";\nimport { IRiskFundGetters } from \"../Interfaces/IRiskFund.sol\";\nimport { IVToken } from \"../Interfaces/IVToken.sol\";\n\n/// @dev Local interface retained so the deprecated RiskFundConverter still compiles\n/// after `updatePoolState` was removed from IRiskFund. New deployments do not\n/// call into this path; it only exists for historical contracts that remain in\n/// the repo for reference.\ninterface ILegacyRiskFundPoolState {\n function updatePoolState(\n address comptroller,\n address asset,\n uint256 amount\n ) external;\n}\n\n/// @title RiskFundConverter\n/// @author Venus\n/// @notice RiskFundConverter used for token conversions and sends received token to RiskFund\n/// @custom:security-contact https://github.com/VenusProtocol/protocol-reserve#discussion\ncontract RiskFundConverter is AbstractTokenConverter {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Address of the core pool comptroller\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable CORE_POOL_COMPTROLLER;\n\n ///@notice Address of the vBNB\n ///@dev This address is used to include the BNB market while in getPools method\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable VBNB;\n\n ///@notice Address of the native wrapped currency\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable NATIVE_WRAPPED;\n\n /// @notice Store the previous state for the asset transferred to ProtocolShareReserve combined(for all pools)\n mapping(address => uint256) internal assetsReserves;\n\n /// @notice Store the asset's reserve per pool in the ProtocolShareReserve\n /// @dev Comptroller(pool) -> Asset -> amount\n mapping(address => mapping(address => uint256)) internal poolsAssetsReserves;\n\n /// @notice Address of pool registry contract\n address public poolRegistry;\n\n /// @notice The mapping contains the assets for each pool which are sent to RiskFund directly\n /// @dev Comptroller(pool) -> Asset -> bool(should transfer directly on true)\n mapping(address => mapping(address => bool)) public poolsAssetsDirectTransfer;\n\n /// @notice Emitted when pool registry address is updated\n event PoolRegistryUpdated(address indexed oldPoolRegistry, address indexed newPoolRegistry);\n\n /// @notice Emitted after updating of the assets reserves\n /// amount -> reserve increased by amount\n event AssetsReservesUpdated(address indexed comptroller, address indexed asset, uint256 amount);\n\n /// @notice Emmitted after the funds transferred to the destination address\n event AssetTransferredToDestination(\n address indexed receiver,\n address indexed comptroller,\n address indexed asset,\n uint256 amount\n );\n\n /// @notice Emitted after the poolsAssetsDirectTransfer mapping is updated\n event PoolAssetsDirectTransferUpdated(address indexed comptroller, address indexed asset, bool value);\n\n // Error thrown when comptrollers array length is not equal to assets array length\n error InvalidArguments();\n\n /// @notice thrown when amount entered is greater than balance\n error InsufficientBalance();\n\n /// @notice thrown when asset does not exist in the pool\n error MarketNotExistInPool(address comptroller, address asset);\n\n /// @notice thrown to prevent reentrancy\n /// @dev This error is used to safeguard against reentrancy attacks, ensuring that a certain operation\n /// cannot be called recursively within the same transaction.\n error ReentrancyGuardError();\n\n /// @param corePoolComptroller_ Address of the Comptroller pool\n /// @param vBNB_ Address of the vBNB\n /// @param nativeWrapped_ Address of the wrapped native currency\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address corePoolComptroller_,\n address vBNB_,\n address nativeWrapped_\n ) {\n ensureNonzeroAddress(corePoolComptroller_);\n ensureNonzeroAddress(vBNB_);\n ensureNonzeroAddress(nativeWrapped_);\n\n CORE_POOL_COMPTROLLER = corePoolComptroller_;\n VBNB = vBNB_;\n NATIVE_WRAPPED = nativeWrapped_;\n\n // Note that the contract is upgradeable. Use initialize() or reinitializers\n // to set the state variables.\n _disableInitializers();\n }\n\n /// @param accessControlManager_ Access control manager contract address\n /// @param priceOracle_ Resilient oracle address\n /// @param destinationAddress_ Address at all incoming tokens will transferred to\n /// @param poolRegistry_ Address of the pool registry\n /// @param minAmountToConvert_ minimum amount to convert\n /// @param comptrollers Addresses of the pools\n /// @param assets Addresses of the assets need to be added for direct transfer\n /// @param values Boolean value to indicate whether direct transfer is allowed for each asset.\n /// @custom:event PoolAssetsDirectTransferUpdated emits on success\n function initialize(\n address accessControlManager_,\n ResilientOracle priceOracle_,\n address destinationAddress_,\n address poolRegistry_,\n uint256 minAmountToConvert_,\n address[] calldata comptrollers,\n address[][] calldata assets,\n bool[][] calldata values\n ) public initializer {\n // Initialize AbstractTokenConverter\n __AbstractTokenConverter_init(accessControlManager_, priceOracle_, destinationAddress_, minAmountToConvert_);\n ensureNonzeroAddress(poolRegistry_);\n poolRegistry = poolRegistry_;\n _setPoolsAssetsDirectTransfer(comptrollers, assets, values);\n }\n\n /// @dev Pool registry setter\n /// @param poolRegistry_ Address of the pool registry\n /// @custom:event PoolRegistryUpdated emits on success\n /// @custom:error ZeroAddressNotAllowed is thrown when pool registry address is zero\n /// @custom:access Only Governance\n function setPoolRegistry(address poolRegistry_) external onlyOwner {\n ensureNonzeroAddress(poolRegistry_);\n emit PoolRegistryUpdated(poolRegistry, poolRegistry_);\n poolRegistry = poolRegistry_;\n }\n\n /// @notice Update the poolsAssetsDirectTransfer mapping\n /// @param comptrollers Addresses of the pools\n /// @param assets Addresses of the assets need to be added for direct transfer\n /// @param values Boolean value to indicate whether direct transfer is allowed for each asset.\n /// @custom:event PoolAssetsDirectTransferUpdated emits on success\n /// @custom:access Restricted by ACM\n function setPoolsAssetsDirectTransfer(\n address[] calldata comptrollers,\n address[][] calldata assets,\n bool[][] calldata values\n ) external {\n _checkAccessAllowed(\"setPoolsAssetsDirectTransfer(address[],address[][],bool[][])\");\n _setPoolsAssetsDirectTransfer(comptrollers, assets, values);\n }\n\n /// @dev Get the Amount of the asset in the risk fund for the specific pool\n /// @param comptroller Comptroller address (pool)\n /// @param asset Asset address\n /// @return reserves Asset's reserve in risk fund\n /// @custom:error MarketNotExistInPool When asset does not exist in the pool(comptroller)\n /// @custom:error ReentrancyGuardError thrown to prevent reentrancy during the function execution\n function getPoolAssetReserve(address comptroller, address asset) external view returns (uint256 reserves) {\n if (_reentrancyGuardEntered()) revert ReentrancyGuardError();\n if (!ensureAssetListed(comptroller, asset)) revert MarketNotExistInPool(comptroller, asset);\n\n reserves = poolsAssetsReserves[comptroller][asset];\n }\n\n /// @notice Get the balance for specific token\n /// @param tokenAddress Address of the token\n /// @return tokenBalance Reserves of the token the contract has\n function balanceOf(address tokenAddress) public view override returns (uint256 tokenBalance) {\n tokenBalance = assetsReserves[tokenAddress];\n }\n\n /// @notice Get the array of all pools addresses\n /// @param tokenAddress Address of the token\n /// @return poolsWithCore Array of the pools addresses in which token is available\n function getPools(address tokenAddress) public view returns (address[] memory poolsWithCore) {\n poolsWithCore = IPoolRegistry(poolRegistry).getPoolsSupportedByAsset(tokenAddress);\n\n if (isAssetListedInCore(tokenAddress)) {\n uint256 poolsLength = poolsWithCore.length;\n address[] memory extendedPools = new address[](poolsLength + 1);\n\n for (uint256 i; i < poolsLength; ) {\n extendedPools[i] = poolsWithCore[i];\n unchecked {\n ++i;\n }\n }\n\n extendedPools[poolsLength] = CORE_POOL_COMPTROLLER;\n poolsWithCore = extendedPools;\n }\n }\n\n /// @dev This hook is used to update the state for asset reserves before transferring tokenOut to user\n /// @param tokenOutAddress Address of the asset to be transferred to the user\n /// @param amountOut Amount of tokenAddressOut transferred from this converter\n function _preTransferHook(address tokenOutAddress, uint256 amountOut) internal override {\n assetsReserves[tokenOutAddress] -= amountOut;\n }\n\n /// @notice Hook to perform after converting tokens\n /// @dev After transformation poolsAssetsReserves are settled by pool's reserves fraction\n /// @param tokenInAddress Address of the tokenIn\n /// @param tokenOutAddress Address of the tokenOut\n /// @param amountIn Amount of tokenIn transferred\n /// @param amountOut Amount of tokenOut transferred\n /// @custom:event AssetTransferredToDestination emits on success for each pool which has share\n function _postConversionHook(\n address tokenInAddress,\n address tokenOutAddress,\n uint256 amountIn,\n uint256 amountOut\n ) internal override {\n address[] memory pools = getPools(tokenOutAddress);\n uint256 assetReserve = assetsReserves[tokenOutAddress] + amountOut;\n ensureNonzeroValue(assetReserve);\n\n uint256 poolsLength = pools.length;\n uint256 distributedOutShare;\n uint256 poolAmountInShare;\n uint256 distributedInShare;\n\n for (uint256 i; i < poolsLength; ) {\n uint256 currentPoolsAssetsReserves = poolsAssetsReserves[pools[i]][tokenOutAddress];\n if (currentPoolsAssetsReserves != 0) {\n if (i < (poolsLength - 1)) {\n distributedOutShare += updatePoolAssetsReserve(pools[i], tokenOutAddress, amountOut, assetReserve);\n poolAmountInShare = (amountIn * currentPoolsAssetsReserves) / assetReserve;\n distributedInShare += poolAmountInShare;\n } else {\n uint256 distributedDiff = amountOut - distributedOutShare;\n poolsAssetsReserves[pools[i]][tokenOutAddress] -= distributedDiff;\n emit AssetsReservesUpdated(pools[i], tokenOutAddress, distributedDiff);\n poolAmountInShare = amountIn - distributedInShare;\n }\n emit AssetTransferredToDestination(destinationAddress, pools[i], tokenInAddress, poolAmountInShare);\n ILegacyRiskFundPoolState(destinationAddress).updatePoolState(\n pools[i],\n tokenInAddress,\n poolAmountInShare\n );\n }\n unchecked {\n ++i;\n }\n }\n }\n\n /// @dev Operations to perform before sweeping tokens\n /// @param tokenAddress Address of the token\n /// @param amount Amount transferred to address(to)\n /// @custom:error InsufficientBalance is thrown when amount entered is greater than balance of token\n function preSweepToken(address tokenAddress, uint256 amount) internal override {\n uint256 balance = IERC20Upgradeable(tokenAddress).balanceOf(address(this));\n if (amount > balance) revert InsufficientBalance();\n uint256 balanceDiff = balance - assetsReserves[tokenAddress];\n\n if (balanceDiff < amount) {\n uint256 amountDiff;\n unchecked {\n amountDiff = amount - balanceDiff;\n }\n\n address[] memory pools = getPools(tokenAddress);\n uint256 assetReserve = assetsReserves[tokenAddress];\n uint256 poolsLength = pools.length;\n uint256 distributedShare;\n\n for (uint256 i; i < poolsLength; ) {\n if (poolsAssetsReserves[pools[i]][tokenAddress] != 0) {\n if (i < (poolsLength - 1)) {\n distributedShare += updatePoolAssetsReserve(pools[i], tokenAddress, amountDiff, assetReserve);\n } else {\n uint256 distributedDiff = amountDiff - distributedShare;\n poolsAssetsReserves[pools[i]][tokenAddress] -= distributedDiff;\n emit AssetsReservesUpdated(pools[i], tokenAddress, distributedDiff);\n }\n }\n unchecked {\n ++i;\n }\n }\n assetsReserves[tokenAddress] -= amountDiff;\n }\n }\n\n /// @dev Update the poolAssetsReserves upon transferring the tokens\n /// @param pool Address of the pool\n /// @param tokenAddress Address of the token\n /// @param amount Amount transferred to address(to)\n /// @param assetReserve Asset's reserve for the pool\n /// @return poolAmountShare Share of the pool as per it's reserve in compare to total reserves for the asset\n /// @custom:event AssetsReservesUpdated emits on success\n function updatePoolAssetsReserve(\n address pool,\n address tokenAddress,\n uint256 amount,\n uint256 assetReserve\n ) internal returns (uint256 poolAmountShare) {\n poolAmountShare = (poolsAssetsReserves[pool][tokenAddress] * amount) / assetReserve;\n poolsAssetsReserves[pool][tokenAddress] -= poolAmountShare;\n emit AssetsReservesUpdated(pool, tokenAddress, poolAmountShare);\n }\n\n /// @dev Update the poolsAssetsDirectTransfer mapping\n /// @param comptrollers Addresses of the pools\n /// @param assets Addresses of the assets need to be added for direct transfer\n /// @param values Boolean value to indicate whether direct transfer is allowed for each asset.\n /// @custom:event PoolAssetsDirectTransferUpdated emits on success\n /// @custom:error InvalidArguments thrown when comptrollers array length is not equal to assets array length\n function _setPoolsAssetsDirectTransfer(\n address[] calldata comptrollers,\n address[][] calldata assets,\n bool[][] calldata values\n ) internal {\n uint256 comptrollersLength = comptrollers.length;\n\n if ((comptrollersLength != assets.length) || (comptrollersLength != values.length)) {\n revert InvalidArguments();\n }\n\n for (uint256 i; i < comptrollersLength; ) {\n address[] memory poolAssets = assets[i];\n bool[] memory assetsValues = values[i];\n uint256 poolAssetsLength = poolAssets.length;\n\n if (poolAssetsLength != assetsValues.length) {\n revert InvalidArguments();\n }\n\n for (uint256 j; j < poolAssetsLength; ) {\n poolsAssetsDirectTransfer[comptrollers[i]][poolAssets[j]] = assetsValues[j];\n emit PoolAssetsDirectTransferUpdated(comptrollers[i], poolAssets[j], assetsValues[j]);\n unchecked {\n ++j;\n }\n }\n\n unchecked {\n ++i;\n }\n }\n }\n\n /// @dev Update the reserve of the asset for the specific pool after transferring to risk fund\n /// and transferring funds to the protocol share reserve\n /// @param comptroller Comptroller address (pool)\n /// @param asset Asset address\n /// @return balanceDifference Amount of asset, for _privateConversion\n /// @custom:event AssetTransferredToDestination emits when poolsAssetsDirectTransfer is enabled for entered comptroller and asset\n /// @custom:error MarketNotExistInPool When asset does not exist in the pool(comptroller)\n function _updateAssetsState(address comptroller, address asset)\n internal\n override\n returns (uint256 balanceDifference)\n {\n if (!ensureAssetListed(comptroller, asset)) revert MarketNotExistInPool(comptroller, asset);\n\n IERC20Upgradeable token = IERC20Upgradeable(asset);\n uint256 currentBalance = token.balanceOf(address(this));\n uint256 assetReserve = assetsReserves[asset];\n if (currentBalance > assetReserve) {\n unchecked {\n balanceDifference = currentBalance - assetReserve;\n }\n if (poolsAssetsDirectTransfer[comptroller][asset]) {\n uint256 previousDestinationBalance = token.balanceOf(destinationAddress);\n token.safeTransfer(destinationAddress, balanceDifference);\n uint256 newDestinationBalance = token.balanceOf(destinationAddress);\n\n emit AssetTransferredToDestination(destinationAddress, comptroller, asset, balanceDifference);\n ILegacyRiskFundPoolState(destinationAddress).updatePoolState(\n comptroller,\n asset,\n newDestinationBalance - previousDestinationBalance\n );\n balanceDifference = 0;\n }\n }\n }\n\n /// @dev This hook is used to update states for the converter after the privateConversion\n /// @param comptroller Comptroller address (pool)\n /// @param tokenAddressIn Address of the destination's base asset\n /// @param convertedTokenInBalance Amount of the base asset received after the conversion\n /// @param tokenAddressOut Address of the asset transferred to other converter in exchange of base asset\n /// @param convertedTokenOutBalance Amount of tokenAddressOut transferred from this converter\n function _postPrivateConversionHook(\n address comptroller,\n address tokenAddressIn,\n uint256 convertedTokenInBalance,\n address tokenAddressOut,\n uint256 convertedTokenOutBalance\n ) internal override {\n if (convertedTokenInBalance > 0) {\n emit AssetTransferredToDestination(\n destinationAddress,\n comptroller,\n tokenAddressIn,\n convertedTokenInBalance\n );\n ILegacyRiskFundPoolState(destinationAddress).updatePoolState(\n comptroller,\n tokenAddressIn,\n convertedTokenInBalance\n );\n }\n if (convertedTokenOutBalance > 0) {\n assetsReserves[tokenAddressOut] += convertedTokenOutBalance;\n poolsAssetsReserves[comptroller][tokenAddressOut] += convertedTokenOutBalance;\n emit AssetsReservesUpdated(comptroller, tokenAddressOut, convertedTokenOutBalance);\n }\n }\n\n /// @dev This function checks for the given asset is listed in core pool or not\n /// @param tokenAddress Address of the asset\n /// @return isAssetListed true if the asset is listed\n function isAssetListedInCore(address tokenAddress) internal view returns (bool isAssetListed) {\n address[] memory coreMarkets = IComptroller(CORE_POOL_COMPTROLLER).getAllMarkets();\n\n uint256 coreMarketsLength = coreMarkets.length;\n for (uint256 i; i < coreMarketsLength; ) {\n isAssetListed = (VBNB == coreMarkets[i])\n ? (tokenAddress == NATIVE_WRAPPED)\n : (IVToken(coreMarkets[i]).underlying() == tokenAddress);\n\n if (isAssetListed) {\n break;\n }\n\n unchecked {\n ++i;\n }\n }\n }\n\n /// @dev This function checks for the given asset is listed or not\n /// @param comptroller Address of the comptroller\n /// @param asset Address of the asset\n /// @return isListed true if the asset is listed\n function ensureAssetListed(address comptroller, address asset) internal view returns (bool isListed) {\n if (comptroller == CORE_POOL_COMPTROLLER) {\n isListed = isAssetListedInCore(asset);\n } else {\n isListed = IPoolRegistry(poolRegistry).getVTokenForAsset(comptroller, asset) != address(0);\n }\n }\n\n /// @dev Get base asset address of the RiskFund\n /// @return destinationBaseAsset Address of the base asset(RiskFund)\n function _getDestinationBaseAsset() internal view override returns (address destinationBaseAsset) {\n destinationBaseAsset = IRiskFundGetters(destinationAddress).convertibleBaseAsset();\n }\n}\n"
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
"settings": {
|
|
114
|
+
"optimizer": {
|
|
115
|
+
"enabled": true,
|
|
116
|
+
"runs": 10000
|
|
117
|
+
},
|
|
118
|
+
"evmVersion": "paris",
|
|
119
|
+
"outputSelection": {
|
|
120
|
+
"*": {
|
|
121
|
+
"*": [
|
|
122
|
+
"storageLayout",
|
|
123
|
+
"abi",
|
|
124
|
+
"evm.bytecode",
|
|
125
|
+
"evm.deployedBytecode",
|
|
126
|
+
"evm.methodIdentifiers",
|
|
127
|
+
"metadata",
|
|
128
|
+
"devdoc",
|
|
129
|
+
"userdoc",
|
|
130
|
+
"evm.gasEstimates"
|
|
131
|
+
],
|
|
132
|
+
"": ["ast"]
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
"metadata": {
|
|
136
|
+
"useLiteralContent": true
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|