diff --git a/.env.example b/.env.example index cf9235853..6fa1c4a8e 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,8 @@ DEPLOYER_PRIVATE_KEY= #ARCHIVE_NODE_xlayermainnet=https://rpc.ankr.com/xlayer #ARCHIVE_NODE_zksyncsepolia=https://zksync-sepolia.g.alchemy.com/v2/ #ARCHIVE_NODE_zksyncmainnet=https://open-platform.nodereal.io//zksync +#ARCHIVE_NODE_opsepolia="https://sepolia.optimism.io" +#ARCHIVE_NODE_opmainnet="https://opt-mainnet.nodereal.io/v1/" ETHERSCAN_API_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e3db0aaf4..459de6d34 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,7 +139,7 @@ jobs: - name: Export deployments run: | - for NETWORK in bsctestnet bscmainnet ethereum sepolia opbnbtestnet opbnbmainnet arbitrumsepolia arbitrumone xlayertestnet xlayermainnet; do + for NETWORK in bsctestnet bscmainnet ethereum sepolia opbnbtestnet opbnbmainnet arbitrumsepolia arbitrumone xlayertestnet xlayermainnet opsepolia opmainnet; do EXPORT=true yarn hardhat export --network ${NETWORK} --export ./deployments/${NETWORK}.json jq -M '{name, chainId, addresses: .contracts | map_values(.address)}' ./deployments/${NETWORK}.json > ./deployments/${NETWORK}_addresses.json done diff --git a/deploy/005-deploy-VTreasuryV8.ts b/deploy/005-deploy-VTreasuryV8.ts index d5ee6786f..699fd4b82 100644 --- a/deploy/005-deploy-VTreasuryV8.ts +++ b/deploy/005-deploy-VTreasuryV8.ts @@ -34,6 +34,7 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { xlayertestnet: "0x5961449d63149035aCfC0714D5155f24C9819004", // XLAYER TESTNET MULTISIG zksyncsepolia: "0xa2f83de95E9F28eD443132C331B6a9C9B7a9F866", // ZKSYNC SEPOLIA MULTISIG zksyncmainnet: "0x751Aa759cfBB6CE71A43b48e40e1cCcFC66Ba4aa", // ZKSYNC MAINNET MULTISIG + opsepolia: "0xd57365EE4E850e881229e2F8Aa405822f289e78d", // OPSEPOLIA MULTISIG bscmainnet: await getTimelock(), bsctestnet: await getTimelock(), hardhat: deployer, diff --git a/deployments/opmainnet.json b/deployments/opmainnet.json new file mode 100644 index 000000000..58d00eb23 --- /dev/null +++ b/deployments/opmainnet.json @@ -0,0 +1,5 @@ +{ + "name": "opmainnet", + "chainId": "10", + "contracts": {} +} diff --git a/deployments/opmainnet_addresses.json b/deployments/opmainnet_addresses.json new file mode 100644 index 000000000..afe9164bb --- /dev/null +++ b/deployments/opmainnet_addresses.json @@ -0,0 +1,5 @@ +{ + "name": "opmainnet", + "chainId": "10", + "addresses": {} +} diff --git a/deployments/opsepolia.json b/deployments/opsepolia.json new file mode 100644 index 000000000..1eecf17a5 --- /dev/null +++ b/deployments/opsepolia.json @@ -0,0 +1,200 @@ +{ + "name": "opsepolia", + "chainId": "11155420", + "contracts": { + "VTreasuryV8": { + "address": "0x5A1a12F47FA7007C9e23cf5e025F3f5d3aC7d755", + "abi": [ + { + "inputs": [], + "name": "ZeroAddressNotAllowed", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferStarted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "WithdrawTreasuryNative", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "tokenAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "WithdrawTreasuryToken", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "acceptOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "internalType": "address payable", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "withdrawTreasuryNative", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "tokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "withdrawTreasuryToken", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ] + } + } +} diff --git a/deployments/opsepolia/.chainId b/deployments/opsepolia/.chainId new file mode 100644 index 000000000..03f37de82 --- /dev/null +++ b/deployments/opsepolia/.chainId @@ -0,0 +1 @@ +11155420 \ No newline at end of file diff --git a/deployments/opsepolia/VTreasuryV8.json b/deployments/opsepolia/VTreasuryV8.json new file mode 100644 index 000000000..441f341af --- /dev/null +++ b/deployments/opsepolia/VTreasuryV8.json @@ -0,0 +1,329 @@ +{ + "address": "0x5A1a12F47FA7007C9e23cf5e025F3f5d3aC7d755", + "abi": [ + { + "inputs": [], + "name": "ZeroAddressNotAllowed", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferStarted", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "WithdrawTreasuryNative", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "tokenAddress", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "indexed": true, + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "WithdrawTreasuryToken", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "acceptOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "internalType": "address payable", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "withdrawTreasuryNative", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "tokenAddress", + "type": "address" + }, + { + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + }, + { + "internalType": "address", + "name": "withdrawAddress", + "type": "address" + } + ], + "name": "withdrawTreasuryToken", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ], + "transactionHash": "0xf081de2e53287fbac77c3563ca8d4a805bc1fad02d4a50895511fce11cca5007", + "receipt": { + "to": null, + "from": "0x476c66CA1fE0E8AbB45c8566D635DcA9dC930F73", + "contractAddress": "0x5A1a12F47FA7007C9e23cf5e025F3f5d3aC7d755", + "transactionIndex": 3, + "gasUsed": "686933", + "logsBloom": "0x00020000000000000000000000000000000000000000000000800000200800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000020000000000000000000800000000000000000000000000000000440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000400000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0x4e5cb45d9ee5d1a5330c5ff7dd8f9f30ca8d7a0cf618370f4fd76a6ce4c0f27b", + "transactionHash": "0xf081de2e53287fbac77c3563ca8d4a805bc1fad02d4a50895511fce11cca5007", + "logs": [ + { + "transactionIndex": 3, + "blockNumber": 14147922, + "transactionHash": "0xf081de2e53287fbac77c3563ca8d4a805bc1fad02d4a50895511fce11cca5007", + "address": "0x5A1a12F47FA7007C9e23cf5e025F3f5d3aC7d755", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x000000000000000000000000476c66ca1fe0e8abb45c8566d635dca9dc930f73" + ], + "data": "0x", + "logIndex": 61, + "blockHash": "0x4e5cb45d9ee5d1a5330c5ff7dd8f9f30ca8d7a0cf618370f4fd76a6ce4c0f27b" + } + ], + "blockNumber": 14147922, + "cumulativeGasUsed": "3226869", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "e5e44f3906b0022bfdbc9e3b426f7ed1", + "metadata": "{\"compiler\":{\"version\":\"0.8.25+commit.b61c2a91\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[],\"name\":\"ZeroAddressNotAllowed\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferStarted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"withdrawAmount\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"withdrawAddress\",\"type\":\"address\"}],\"name\":\"WithdrawTreasuryNative\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"tokenAddress\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"withdrawAmount\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"withdrawAddress\",\"type\":\"address\"}],\"name\":\"WithdrawTreasuryToken\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"acceptOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"withdrawAmount\",\"type\":\"uint256\"},{\"internalType\":\"address payable\",\"name\":\"withdrawAddress\",\"type\":\"address\"}],\"name\":\"withdrawTreasuryNative\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"tokenAddress\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"withdrawAmount\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"withdrawAddress\",\"type\":\"address\"}],\"name\":\"withdrawTreasuryToken\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"author\":\"Venus\",\"kind\":\"dev\",\"methods\":{\"acceptOwnership()\":{\"details\":\"The new owner accepts the ownership transfer.\"},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"pendingOwner()\":{\"details\":\"Returns the address of the pending owner.\"},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner.\"},\"transferOwnership(address)\":{\"details\":\"Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner.\"},\"withdrawTreasuryNative(uint256,address)\":{\"custom:error\":\"ZeroAddressNotAllowed thrown when withdrawAddress is zero.\",\"params\":{\"withdrawAddress\":\"The withdraw address\",\"withdrawAmount\":\"The withdraw amount to owner\"}},\"withdrawTreasuryToken(address,uint256,address)\":{\"custom:error\":\"ZeroAddressNotAllowed thrown when token or withdrawAddress is zero.\",\"params\":{\"tokenAddress\":\"The address of treasury token\",\"withdrawAddress\":\"The withdraw address\",\"withdrawAmount\":\"The withdraw amount to owner\"}}},\"title\":\"VTreasuryV8\",\"version\":1},\"userdoc\":{\"errors\":{\"ZeroAddressNotAllowed()\":[{\"notice\":\"Thrown if the supplied address is a zero address where it is not allowed\"}]},\"kind\":\"user\",\"methods\":{\"withdrawTreasuryNative(uint256,address)\":{\"notice\":\"Withdraw Treasury Native, Only owner call it\"},\"withdrawTreasuryToken(address,uint256,address)\":{\"notice\":\"Withdraw Treasury Tokens, Only owner call it\"}},\"notice\":\"Protocol treasury that holds tokens owned by Venus\",\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/Governance/VTreasuryV8.sol\":\"VTreasuryV8\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin/contracts/access/Ownable.sol\":{\"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/Context.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 Ownable is Context {\\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 constructor() {\\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\",\"keccak256\":\"0xba43b97fba0d32eb4254f6a5a297b39a19a247082a02d6e69349e071e2946218\",\"license\":\"MIT\"},\"@openzeppelin/contracts/access/Ownable2Step.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./Ownable.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 Ownable2Step is Ownable {\\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\",\"keccak256\":\"0xde231558366826d7cb61725af8147965a61c53b77a352cc8c9af38fc5a92ac3c\",\"license\":\"MIT\"},\"@openzeppelin/contracts/security/ReentrancyGuard.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\\n\\npragma solidity ^0.8.0;\\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 ReentrancyGuard {\\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 constructor() {\\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\",\"keccak256\":\"0xa535a5df777d44e945dd24aa43a11e44b024140fc340ad0dfe42acf4002aade1\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/IERC20.sol\":{\"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\",\"keccak256\":\"0x287b55befed2961a7eabd7d7b1b2839cbca8a5b80ef8dcbb25ed3d4c2002c305\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\":{\"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 IERC20Permit {\\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\",\"keccak256\":\"0xec63854014a5b4f2b3290ab9103a21bdf902a508d0f41a8573fea49e98bf571a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\":{\"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 \\\"../IERC20.sol\\\";\\nimport \\\"../extensions/IERC20Permit.sol\\\";\\nimport \\\"../../../utils/Address.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 SafeERC20 {\\n using Address 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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 IERC20Permit 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(IERC20 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(IERC20 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))) && Address.isContract(address(token));\\n }\\n}\\n\",\"keccak256\":\"0xabefac93435967b4d36a4fabcbdbb918d1f0b7ae3c3d85bc30923b326c927ed1\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"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 Address {\\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\",\"keccak256\":\"0x006dd67219697fe68d7fbfdea512e7c4cb64a43565ed86171d67e844982da6fa\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n}\\n\",\"keccak256\":\"0xe2e337e6dde9ef6b680e07338c493ebea1b5fd09b43424112868e9cc1706bca7\",\"license\":\"MIT\"},\"contracts/Governance/VTreasuryV8.sol\":{\"content\":\"// SPDX-License-Identifier: BSD-3-Clause\\npragma solidity 0.8.25;\\n\\nimport { SafeERC20, IERC20 } from \\\"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\\\";\\nimport { Ownable2Step } from \\\"@openzeppelin/contracts/access/Ownable2Step.sol\\\";\\nimport { ReentrancyGuard } from \\\"@openzeppelin/contracts/security/ReentrancyGuard.sol\\\";\\n\\n/**\\n * @title VTreasuryV8\\n * @author Venus\\n * @notice Protocol treasury that holds tokens owned by Venus\\n */\\ncontract VTreasuryV8 is Ownable2Step, ReentrancyGuard {\\n using SafeERC20 for IERC20;\\n\\n // WithdrawTreasuryToken Event\\n event WithdrawTreasuryToken(address indexed tokenAddress, uint256 withdrawAmount, address indexed withdrawAddress);\\n\\n // WithdrawTreasuryNative Event\\n event WithdrawTreasuryNative(uint256 withdrawAmount, address indexed withdrawAddress);\\n\\n /// @notice Thrown if the supplied address is a zero address where it is not allowed\\n error ZeroAddressNotAllowed();\\n\\n /**\\n * @notice To receive Native when msg.data is not empty\\n */\\n fallback() external payable {}\\n\\n /**\\n * @notice To receive Native when msg.data is empty\\n */\\n receive() external payable {}\\n\\n /**\\n * @notice Withdraw Treasury Tokens, Only owner call it\\n * @param tokenAddress The address of treasury token\\n * @param withdrawAmount The withdraw amount to owner\\n * @param withdrawAddress The withdraw address\\n * @custom:error ZeroAddressNotAllowed thrown when token or withdrawAddress is zero.\\n */\\n function withdrawTreasuryToken(\\n address tokenAddress,\\n uint256 withdrawAmount,\\n address withdrawAddress\\n ) external onlyOwner nonReentrant {\\n ensureNonzeroAddress(tokenAddress);\\n ensureNonzeroAddress(withdrawAddress);\\n require(withdrawAmount > 0, \\\"withdrawAmount must not be zero\\\");\\n\\n uint256 actualWithdrawAmount = withdrawAmount;\\n // Get Treasury Token Balance\\n uint256 treasuryBalance = IERC20(tokenAddress).balanceOf(address(this));\\n\\n // Check Withdraw Amount\\n if (withdrawAmount > treasuryBalance) {\\n // Update actualWithdrawAmount\\n actualWithdrawAmount = treasuryBalance;\\n }\\n\\n // Transfer Token to withdrawAddress\\n IERC20(tokenAddress).safeTransfer(withdrawAddress, actualWithdrawAmount);\\n\\n emit WithdrawTreasuryToken(tokenAddress, actualWithdrawAmount, withdrawAddress);\\n }\\n\\n /**\\n * @notice Withdraw Treasury Native, Only owner call it\\n * @param withdrawAmount The withdraw amount to owner\\n * @param withdrawAddress The withdraw address\\n * @custom:error ZeroAddressNotAllowed thrown when withdrawAddress is zero.\\n */\\n function withdrawTreasuryNative(\\n uint256 withdrawAmount,\\n address payable withdrawAddress\\n ) external payable onlyOwner nonReentrant {\\n ensureNonzeroAddress(withdrawAddress);\\n require(withdrawAmount > 0, \\\"withdrawAmount must not be zero\\\");\\n uint256 actualWithdrawAmount = withdrawAmount;\\n // Get Treasury Native Balance\\n uint256 nativeBalance = address(this).balance;\\n\\n // Check Withdraw Amount\\n if (withdrawAmount > nativeBalance) {\\n // Update actualWithdrawAmount\\n actualWithdrawAmount = nativeBalance;\\n }\\n // Transfer the native token to withdrawAddress\\n (bool sent, ) = withdrawAddress.call{ value: actualWithdrawAmount }(\\\"\\\");\\n require(sent, \\\"Call failed\\\");\\n emit WithdrawTreasuryNative(actualWithdrawAmount, withdrawAddress);\\n }\\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\\n function ensureNonzeroAddress(address address_) internal pure {\\n if (address_ == address(0)) {\\n revert ZeroAddressNotAllowed();\\n }\\n }\\n}\\n\",\"keccak256\":\"0x254876cbfd6840dc6d610db8b4d930656f0eda51a00b3aeee6d91ed8c96dcfc1\",\"license\":\"BSD-3-Clause\"}},\"version\":1}", + "bytecode": "0x6080604052348015600f57600080fd5b506017336020565b6001600255608a565b600180546001600160a01b0319169055603781603a565b50565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b610a8e806100996000396000f3fe60806040526004361061006e5760003560e01c80638da5cb5b1161004b5780638da5cb5b146100c1578063e30c3978146100f7578063f2fde38b14610115578063fed7036e1461013557005b8063715018a61461007757806374c17a351461008c57806379ba5097146100ac57005b3661007557005b005b34801561008357600080fd5b50610075610148565b34801561009857600080fd5b506100756100a7366004610914565b61015c565b3480156100b857600080fd5b506100756102c0565b3480156100cd57600080fd5b506000546001600160a01b03165b6040516001600160a01b03909116815260200160405180910390f35b34801561010357600080fd5b506001546001600160a01b03166100db565b34801561012157600080fd5b50610075610130366004610956565b61033a565b61007561014336600461097a565b6103ab565b610150610507565b61015a6000610561565b565b610164610507565b61016c61057a565b610175836105d1565b61017e816105d1565b600082116101d35760405162461bcd60e51b815260206004820152601f60248201527f7769746864726177416d6f756e74206d757374206e6f74206265207a65726f0060448201526064015b60405180910390fd5b6040516370a0823160e01b815230600482015282906000906001600160a01b038616906370a0823190602401602060405180830381865afa15801561021c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061024091906109aa565b90508084111561024e578091505b6102626001600160a01b03861684846105f8565b826001600160a01b0316856001600160a01b03167f6d043f5c542a67e836c8f8bdf640d0de840c85d79c130dcbda8d42c9c056980c846040516102a791815260200190565b60405180910390a350506102bb6001600255565b505050565b60015433906001600160a01b0316811461032e5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f7420746865206044820152683732bb9037bbb732b960b91b60648201526084016101ca565b61033781610561565b50565b610342610507565b600180546001600160a01b0383166001600160a01b031990911681179091556103736000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6103b3610507565b6103bb61057a565b6103c4816105d1565b600082116104145760405162461bcd60e51b815260206004820152601f60248201527f7769746864726177416d6f756e74206d757374206e6f74206265207a65726f0060448201526064016101ca565b814780821115610422578091505b6000836001600160a01b03168360405160006040518083038185875af1925050503d806000811461046f576040519150601f19603f3d011682016040523d82523d6000602084013e610474565b606091505b50509050806104b35760405162461bcd60e51b815260206004820152600b60248201526a10d85b1b0819985a5b195960aa1b60448201526064016101ca565b836001600160a01b03167f41448dfa44379fc602c636f8939b0b1b598c481af871c76fbdd8bdfcdaf30dfa846040516104ee91815260200190565b60405180910390a25050506105036001600255565b5050565b6000546001600160a01b0316331461015a5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016101ca565b600180546001600160a01b03191690556103378161064a565b60028054036105cb5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101ca565b60028055565b6001600160a01b038116610337576040516342bcdf7f60e11b815260040160405180910390fd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526102bb90849061069a565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60006106ef826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661076f9092919063ffffffff16565b905080516000148061071057508080602001905181019061071091906109c3565b6102bb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016101ca565b606061077e8484600085610786565b949350505050565b6060824710156107e75760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016101ca565b600080866001600160a01b031685876040516108039190610a09565b60006040518083038185875af1925050503d8060008114610840576040519150601f19603f3d011682016040523d82523d6000602084013e610845565b606091505b509150915061085687838387610861565b979650505050505050565b606083156108d05782516000036108c9576001600160a01b0385163b6108c95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016101ca565b508161077e565b61077e83838151156108e55781518083602001fd5b8060405162461bcd60e51b81526004016101ca9190610a25565b6001600160a01b038116811461033757600080fd5b60008060006060848603121561092957600080fd5b8335610934816108ff565b925060208401359150604084013561094b816108ff565b809150509250925092565b60006020828403121561096857600080fd5b8135610973816108ff565b9392505050565b6000806040838503121561098d57600080fd5b82359150602083013561099f816108ff565b809150509250929050565b6000602082840312156109bc57600080fd5b5051919050565b6000602082840312156109d557600080fd5b8151801515811461097357600080fd5b60005b83811015610a005781810151838201526020016109e8565b50506000910152565b60008251610a1b8184602087016109e5565b9190910192915050565b6020815260008251806020840152610a448160408501602087016109e5565b601f01601f1916919091016040019291505056fea2646970667358221220487efce782941c68134d2ce3b82068b462757740ea04bee479d86bb1b1992e5d64736f6c63430008190033", + "deployedBytecode": "0x60806040526004361061006e5760003560e01c80638da5cb5b1161004b5780638da5cb5b146100c1578063e30c3978146100f7578063f2fde38b14610115578063fed7036e1461013557005b8063715018a61461007757806374c17a351461008c57806379ba5097146100ac57005b3661007557005b005b34801561008357600080fd5b50610075610148565b34801561009857600080fd5b506100756100a7366004610914565b61015c565b3480156100b857600080fd5b506100756102c0565b3480156100cd57600080fd5b506000546001600160a01b03165b6040516001600160a01b03909116815260200160405180910390f35b34801561010357600080fd5b506001546001600160a01b03166100db565b34801561012157600080fd5b50610075610130366004610956565b61033a565b61007561014336600461097a565b6103ab565b610150610507565b61015a6000610561565b565b610164610507565b61016c61057a565b610175836105d1565b61017e816105d1565b600082116101d35760405162461bcd60e51b815260206004820152601f60248201527f7769746864726177416d6f756e74206d757374206e6f74206265207a65726f0060448201526064015b60405180910390fd5b6040516370a0823160e01b815230600482015282906000906001600160a01b038616906370a0823190602401602060405180830381865afa15801561021c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061024091906109aa565b90508084111561024e578091505b6102626001600160a01b03861684846105f8565b826001600160a01b0316856001600160a01b03167f6d043f5c542a67e836c8f8bdf640d0de840c85d79c130dcbda8d42c9c056980c846040516102a791815260200190565b60405180910390a350506102bb6001600255565b505050565b60015433906001600160a01b0316811461032e5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f7420746865206044820152683732bb9037bbb732b960b91b60648201526084016101ca565b61033781610561565b50565b610342610507565b600180546001600160a01b0383166001600160a01b031990911681179091556103736000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b6103b3610507565b6103bb61057a565b6103c4816105d1565b600082116104145760405162461bcd60e51b815260206004820152601f60248201527f7769746864726177416d6f756e74206d757374206e6f74206265207a65726f0060448201526064016101ca565b814780821115610422578091505b6000836001600160a01b03168360405160006040518083038185875af1925050503d806000811461046f576040519150601f19603f3d011682016040523d82523d6000602084013e610474565b606091505b50509050806104b35760405162461bcd60e51b815260206004820152600b60248201526a10d85b1b0819985a5b195960aa1b60448201526064016101ca565b836001600160a01b03167f41448dfa44379fc602c636f8939b0b1b598c481af871c76fbdd8bdfcdaf30dfa846040516104ee91815260200190565b60405180910390a25050506105036001600255565b5050565b6000546001600160a01b0316331461015a5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016101ca565b600180546001600160a01b03191690556103378161064a565b60028054036105cb5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016101ca565b60028055565b6001600160a01b038116610337576040516342bcdf7f60e11b815260040160405180910390fd5b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526102bb90849061069a565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60006106ef826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661076f9092919063ffffffff16565b905080516000148061071057508080602001905181019061071091906109c3565b6102bb5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016101ca565b606061077e8484600085610786565b949350505050565b6060824710156107e75760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016101ca565b600080866001600160a01b031685876040516108039190610a09565b60006040518083038185875af1925050503d8060008114610840576040519150601f19603f3d011682016040523d82523d6000602084013e610845565b606091505b509150915061085687838387610861565b979650505050505050565b606083156108d05782516000036108c9576001600160a01b0385163b6108c95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016101ca565b508161077e565b61077e83838151156108e55781518083602001fd5b8060405162461bcd60e51b81526004016101ca9190610a25565b6001600160a01b038116811461033757600080fd5b60008060006060848603121561092957600080fd5b8335610934816108ff565b925060208401359150604084013561094b816108ff565b809150509250925092565b60006020828403121561096857600080fd5b8135610973816108ff565b9392505050565b6000806040838503121561098d57600080fd5b82359150602083013561099f816108ff565b809150509250929050565b6000602082840312156109bc57600080fd5b5051919050565b6000602082840312156109d557600080fd5b8151801515811461097357600080fd5b60005b83811015610a005781810151838201526020016109e8565b50506000910152565b60008251610a1b8184602087016109e5565b9190910192915050565b6020815260008251806020840152610a448160408501602087016109e5565b601f01601f1916919091016040019291505056fea2646970667358221220487efce782941c68134d2ce3b82068b462757740ea04bee479d86bb1b1992e5d64736f6c63430008190033", + "devdoc": { + "author": "Venus", + "kind": "dev", + "methods": { + "acceptOwnership()": { + "details": "The new owner accepts the ownership transfer." + }, + "owner()": { + "details": "Returns the address of the current owner." + }, + "pendingOwner()": { + "details": "Returns the address of the pending owner." + }, + "renounceOwnership()": { + "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby disabling any functionality that is only available to the owner." + }, + "transferOwnership(address)": { + "details": "Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. Can only be called by the current owner." + }, + "withdrawTreasuryNative(uint256,address)": { + "custom:error": "ZeroAddressNotAllowed thrown when withdrawAddress is zero.", + "params": { + "withdrawAddress": "The withdraw address", + "withdrawAmount": "The withdraw amount to owner" + } + }, + "withdrawTreasuryToken(address,uint256,address)": { + "custom:error": "ZeroAddressNotAllowed thrown when token or withdrawAddress is zero.", + "params": { + "tokenAddress": "The address of treasury token", + "withdrawAddress": "The withdraw address", + "withdrawAmount": "The withdraw amount to owner" + } + } + }, + "title": "VTreasuryV8", + "version": 1 + }, + "userdoc": { + "errors": { + "ZeroAddressNotAllowed()": [ + { + "notice": "Thrown if the supplied address is a zero address where it is not allowed" + } + ] + }, + "kind": "user", + "methods": { + "withdrawTreasuryNative(uint256,address)": { + "notice": "Withdraw Treasury Native, Only owner call it" + }, + "withdrawTreasuryToken(address,uint256,address)": { + "notice": "Withdraw Treasury Tokens, Only owner call it" + } + }, + "notice": "Protocol treasury that holds tokens owned by Venus", + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 3126, + "contract": "contracts/Governance/VTreasuryV8.sol:VTreasuryV8", + "label": "_owner", + "offset": 0, + "slot": "0", + "type": "t_address" + }, + { + "astId": 3239, + "contract": "contracts/Governance/VTreasuryV8.sol:VTreasuryV8", + "label": "_pendingOwner", + "offset": 0, + "slot": "1", + "type": "t_address" + }, + { + "astId": 4218, + "contract": "contracts/Governance/VTreasuryV8.sol:VTreasuryV8", + "label": "_status", + "offset": 0, + "slot": "2", + "type": "t_uint256" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + } + } + } +} diff --git a/deployments/opsepolia/solcInputs/e5e44f3906b0022bfdbc9e3b426f7ed1.json b/deployments/opsepolia/solcInputs/e5e44f3906b0022bfdbc9e3b426f7ed1.json new file mode 100644 index 000000000..82436be8b --- /dev/null +++ b/deployments/opsepolia/solcInputs/e5e44f3906b0022bfdbc9e3b426f7ed1.json @@ -0,0 +1,283 @@ +{ + "language": "Solidity", + "sources": { + "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\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" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20PermitUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": { + "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" + }, + "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\n downcasted = int128(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\n downcasted = int64(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\n downcasted = int32(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\n downcasted = int16(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\n downcasted = int8(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n" + }, + "@openzeppelin/contracts/access/IAccessControl.sol": { + "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" + }, + "@openzeppelin/contracts/access/Ownable.sol": { + "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/Context.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 Ownable is Context {\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 constructor() {\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" + }, + "@openzeppelin/contracts/access/Ownable2Step.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Ownable.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 Ownable2Step is Ownable {\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" + }, + "@openzeppelin/contracts/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/interfaces/IERC1967.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n *\n * _Available since v4.8.3._\n */\ninterface IERC1967 {\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Emitted when the beacon is changed.\n */\n event BeaconUpgraded(address indexed beacon);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Proxy.sol\";\nimport \"./ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n */\n constructor(address _logic, bytes memory _data) payable {\n _upgradeToAndCall(_logic, _data, false);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function _implementation() internal view virtual override returns (address impl) {\n return ERC1967Upgrade._getImplementation();\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/IERC1967.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n */\nabstract contract ERC1967Upgrade is IERC1967 {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.3) (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./TransparentUpgradeableProxy.sol\";\nimport \"../../access/Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev Returns the current implementation of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyImplementation(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"5c60da1b\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Returns the current admin of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyAdmin(ITransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"admin()\")) == 0xf851a440\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"f851a440\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Changes the admin of `proxy` to `newAdmin`.\n *\n * Requirements:\n *\n * - This contract must be the current admin of `proxy`.\n */\n function changeProxyAdmin(ITransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {\n proxy.changeAdmin(newAdmin);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgrade(ITransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {\n proxy.upgradeTo(implementation);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See\n * {TransparentUpgradeableProxy-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgradeAndCall(\n ITransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC1967/ERC1967Proxy.sol\";\n\n/**\n * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}\n * does not implement this interface directly, and some of its functions are implemented by an internal dispatch\n * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not\n * include them in the ABI so this interface must be used to interact with it.\n */\ninterface ITransparentUpgradeableProxy is IERC1967 {\n function admin() external view returns (address);\n\n function implementation() external view returns (address);\n\n function changeAdmin(address) external;\n\n function upgradeTo(address) external;\n\n function upgradeToAndCall(address, bytes memory) external payable;\n}\n\n/**\n * @dev This contract implements a proxy that is upgradeable by an admin.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches one of the admin functions exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\n * \"admin cannot fallback to proxy target\".\n *\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\n * to sudden errors when trying to call a function from the proxy implementation.\n *\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\n *\n * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not\n * inherit from that interface, and instead the admin functions are implicitly implemented using a custom dispatch\n * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to\n * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the\n * implementation.\n *\n * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the compiler\n * will not check that there are no selector conflicts, due to the note above. A selector clash between any new function\n * and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This could\n * render the admin operations inaccessible, which could prevent upgradeability. Transparency may also be compromised.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n /**\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\n */\n constructor(address _logic, address admin_, bytes memory _data) payable ERC1967Proxy(_logic, _data) {\n _changeAdmin(admin_);\n }\n\n /**\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\n *\n * CAUTION: This modifier is deprecated, as it could cause issues if the modified function has arguments, and the\n * implementation provides a function with the same selector.\n */\n modifier ifAdmin() {\n if (msg.sender == _getAdmin()) {\n _;\n } else {\n _fallback();\n }\n }\n\n /**\n * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior\n */\n function _fallback() internal virtual override {\n if (msg.sender == _getAdmin()) {\n bytes memory ret;\n bytes4 selector = msg.sig;\n if (selector == ITransparentUpgradeableProxy.upgradeTo.selector) {\n ret = _dispatchUpgradeTo();\n } else if (selector == ITransparentUpgradeableProxy.upgradeToAndCall.selector) {\n ret = _dispatchUpgradeToAndCall();\n } else if (selector == ITransparentUpgradeableProxy.changeAdmin.selector) {\n ret = _dispatchChangeAdmin();\n } else if (selector == ITransparentUpgradeableProxy.admin.selector) {\n ret = _dispatchAdmin();\n } else if (selector == ITransparentUpgradeableProxy.implementation.selector) {\n ret = _dispatchImplementation();\n } else {\n revert(\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\");\n }\n assembly {\n return(add(ret, 0x20), mload(ret))\n }\n } else {\n super._fallback();\n }\n }\n\n /**\n * @dev Returns the current admin.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function _dispatchAdmin() private returns (bytes memory) {\n _requireZeroValue();\n\n address admin = _getAdmin();\n return abi.encode(admin);\n }\n\n /**\n * @dev Returns the current implementation.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function _dispatchImplementation() private returns (bytes memory) {\n _requireZeroValue();\n\n address implementation = _implementation();\n return abi.encode(implementation);\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _dispatchChangeAdmin() private returns (bytes memory) {\n _requireZeroValue();\n\n address newAdmin = abi.decode(msg.data[4:], (address));\n _changeAdmin(newAdmin);\n\n return \"\";\n }\n\n /**\n * @dev Upgrade the implementation of the proxy.\n */\n function _dispatchUpgradeTo() private returns (bytes memory) {\n _requireZeroValue();\n\n address newImplementation = abi.decode(msg.data[4:], (address));\n _upgradeToAndCall(newImplementation, bytes(\"\"), false);\n\n return \"\";\n }\n\n /**\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\n * proxied contract.\n */\n function _dispatchUpgradeToAndCall() private returns (bytes memory) {\n (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));\n _upgradeToAndCall(newImplementation, data, true);\n\n return \"\";\n }\n\n /**\n * @dev Returns the current admin.\n *\n * CAUTION: This function is deprecated. Use {ERC1967Upgrade-_getAdmin} instead.\n */\n function _admin() internal view virtual returns (address) {\n return _getAdmin();\n }\n\n /**\n * @dev To keep this contract fully transparent, all `ifAdmin` functions must be payable. This helper is here to\n * emulate some proxy functions being non-payable while still allowing value to pass through.\n */\n function _requireZeroValue() private {\n require(msg.value == 0);\n }\n}\n" + }, + "@openzeppelin/contracts/security/ReentrancyGuard.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\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 ReentrancyGuard {\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 constructor() {\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" + }, + "@openzeppelin/contracts/token/ERC20/ERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n constructor(string memory name_, string memory symbol_) {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the default value returned by this function, unless\n * it's overridden.\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(address from, address to, uint256 amount) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(address owner, address spender, uint256 amount) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": { + "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" + }, + "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": { + "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 IERC20Permit {\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" + }, + "@openzeppelin/contracts/token/ERC20/IERC20.sol": { + "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" + }, + "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { + "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 \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.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 SafeERC20 {\n using Address 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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(IERC20 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 IERC20Permit 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(IERC20 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(IERC20 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))) && Address.isContract(address(token));\n }\n}\n" + }, + "@openzeppelin/contracts/utils/Address.sol": { + "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 Address {\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" + }, + "@openzeppelin/contracts/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._\n * _Available since v4.9 for `string`, `bytes`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n struct StringSlot {\n string value;\n }\n\n struct BytesSlot {\n bytes value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` with member `value` located at `slot`.\n */\n function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n */\n function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` with member `value` located at `slot`.\n */\n function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n */\n function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := store.slot\n }\n }\n}\n" + }, + "@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol": { + "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 private _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" + }, + "@venusprotocol/governance-contracts/contracts/Governance/IAccessControlManagerV8.sol": { + "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" + }, + "@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol": { + "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" + }, + "@venusprotocol/solidity-utilities/contracts/constants.sol": { + "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" + }, + "@venusprotocol/solidity-utilities/contracts/MaxLoopsLimitHelper.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n/**\n * @title MaxLoopsLimitHelper\n * @author Venus\n * @notice Abstract contract used to avoid collection with too many items that would generate gas errors and DoS.\n */\nabstract contract MaxLoopsLimitHelper {\n // Limit for the loops to avoid the DOS\n uint256 public maxLoopsLimit;\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 max loops limit is set\n event MaxLoopsLimitUpdated(uint256 oldMaxLoopsLimit, uint256 newmaxLoopsLimit);\n\n /// @notice Thrown an error on maxLoopsLimit exceeds for any loop\n error MaxLoopsLimitExceeded(uint256 loopsLimit, uint256 requiredLoops);\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param limit Limit for the max loops can execute at a time\n */\n function _setMaxLoopsLimit(uint256 limit) internal {\n require(limit > maxLoopsLimit, \"Comptroller: Invalid maxLoopsLimit\");\n\n uint256 oldMaxLoopsLimit = maxLoopsLimit;\n maxLoopsLimit = limit;\n\n emit MaxLoopsLimitUpdated(oldMaxLoopsLimit, limit);\n }\n\n /**\n * @notice Compare the maxLoopsLimit with number of the times loop iterate\n * @param len Length of the loops iterate\n * @custom:error MaxLoopsLimitExceeded error is thrown when loops length exceeds maxLoopsLimit\n */\n function _ensureMaxLoops(uint256 len) internal view {\n if (len > maxLoopsLimit) {\n revert MaxLoopsLimitExceeded(maxLoopsLimit, len);\n }\n }\n}\n" + }, + "@venusprotocol/solidity-utilities/contracts/TimeManagerV8.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SECONDS_PER_YEAR } from \"./constants.sol\";\n\nabstract contract TimeManagerV8 {\n /// @notice Stores blocksPerYear if isTimeBased is true else secondsPerYear is stored\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n uint256 public immutable blocksOrSecondsPerYear;\n\n /// @notice Acknowledges if a contract is time based or not\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n bool public immutable isTimeBased;\n\n /// @notice Stores the current block timestamp or block number depending on isTimeBased\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n function() view returns (uint256) private immutable _getCurrentSlot;\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[48] private __gap;\n\n /// @notice Thrown when blocks per year is invalid\n error InvalidBlocksPerYear();\n\n /// @notice Thrown when time based but blocks per year is provided\n error InvalidTimeBasedConfiguration();\n\n /**\n * @param timeBased_ A boolean indicating whether the contract is based on time or block\n * If timeBased is true than blocksPerYear_ param is ignored as blocksOrSecondsPerYear is set to SECONDS_PER_YEAR\n * @param blocksPerYear_ The number of blocks per year\n * @custom:error InvalidBlocksPerYear is thrown if blocksPerYear entered is zero and timeBased is false\n * @custom:error InvalidTimeBasedConfiguration is thrown if blocksPerYear entered is non zero and timeBased is true\n * @custom:oz-upgrades-unsafe-allow constructor\n */\n constructor(bool timeBased_, uint256 blocksPerYear_) {\n if (!timeBased_ && blocksPerYear_ == 0) {\n revert InvalidBlocksPerYear();\n }\n\n if (timeBased_ && blocksPerYear_ != 0) {\n revert InvalidTimeBasedConfiguration();\n }\n\n isTimeBased = timeBased_;\n blocksOrSecondsPerYear = timeBased_ ? SECONDS_PER_YEAR : blocksPerYear_;\n _getCurrentSlot = timeBased_ ? _getBlockTimestamp : _getBlockNumber;\n }\n\n /**\n * @dev Function to simply retrieve block number or block timestamp\n * @return Current block number or block timestamp\n */\n function getBlockNumberOrTimestamp() public view virtual returns (uint256) {\n return _getCurrentSlot();\n }\n\n /**\n * @dev Returns the current timestamp in seconds\n * @return The current timestamp\n */\n function _getBlockTimestamp() private view returns (uint256) {\n return block.timestamp;\n }\n\n /**\n * @dev Returns the current block number\n * @return The current block number\n */\n function _getBlockNumber() private view returns (uint256) {\n return block.number;\n }\n}\n" + }, + "@venusprotocol/solidity-utilities/contracts/validators.sol": { + "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" + }, + "contracts/Admin/VBNBAdmin.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IProtocolShareReserve, IWBNB, VBNBAdminStorage, VTokenInterface } from \"./VBNBAdminStorage.sol\";\n\n/**\n * @title VBNBAdmin\n * @author Venus\n * @notice This contract is the \"admin\" of the vBNB market, reducing the reserves of the market, sending them to the `ProtocolShareReserve` contract,\n * and allowing the executions of the rest of the privileged functions in the vBNB contract (after checking if the sender has the required permissions).\n */\ncontract VBNBAdmin is ReentrancyGuardUpgradeable, AccessControlledV8, VBNBAdminStorage {\n using SafeERC20Upgradeable for IWBNB;\n\n /// @notice address of vBNB\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n VTokenInterface public immutable vBNB;\n\n /// @notice address of WBNB contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IWBNB public immutable WBNB;\n\n /// @notice Emitted when PSR is updated\n event ProtocolShareReserveUpdated(\n IProtocolShareReserve indexed oldProtocolShareReserve,\n IProtocolShareReserve indexed newProtocolShareReserve\n );\n\n /// @notice Emitted reserves are reduced\n event ReservesReduced(uint256 reduceAmount);\n\n /// @param _vBNB Address of the vBNB contract\n /// @param _WBNB Address of the WBNB token\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(VTokenInterface _vBNB, IWBNB _WBNB) {\n require(address(_WBNB) != address(0), \"WBNB address invalid\");\n require(address(_vBNB) != address(0), \"vBNB address invalid\");\n\n vBNB = _vBNB;\n WBNB = _WBNB;\n\n // Note that the contract is upgradeable. Use initialize() or reinitializers\n // to set the state variables.\n _disableInitializers();\n }\n\n /// @notice Used to initialize non-immutable variables\n function initialize(\n IProtocolShareReserve _protocolShareReserve,\n address accessControlManager\n ) external initializer {\n require(address(_protocolShareReserve) != address(0), \"PSR address invalid\");\n protocolShareReserve = _protocolShareReserve;\n\n __ReentrancyGuard_init();\n __AccessControlled_init(accessControlManager);\n }\n\n /**\n * @notice PSR setter.\n * @param protocolShareReserve_ Address of the PSR contract\n * @custom:access Only owner (Governance)\n * @custom:event Emits ProtocolShareReserveUpdated event.\n */\n function setProtocolShareReserve(IProtocolShareReserve protocolShareReserve_) external onlyOwner {\n require(address(protocolShareReserve_) != address(0), \"PSR address invalid\");\n emit ProtocolShareReserveUpdated(protocolShareReserve, protocolShareReserve_);\n protocolShareReserve = protocolShareReserve_;\n }\n\n /**\n * @notice Reduce reserves of vBNB, wrap them and send them to the PSR contract\n * @param reduceAmount amount of reserves to reduce\n * @custom:event Emits ReservesReduced event.\n */\n function reduceReserves(uint reduceAmount) external nonReentrant {\n require(vBNB._reduceReserves(reduceAmount) == 0, \"reduceReserves failed\");\n _wrapBNB();\n\n uint256 balance = WBNB.balanceOf(address(this));\n WBNB.safeTransfer(address(protocolShareReserve), balance);\n protocolShareReserve.updateAssetsState(\n vBNB.comptroller(),\n address(WBNB),\n IProtocolShareReserve.IncomeType.SPREAD\n );\n\n emit ReservesReduced(reduceAmount);\n }\n\n /**\n * @notice Wraps BNB into WBNB\n */\n function _wrapBNB() internal {\n uint256 bnbBalance = address(this).balance;\n WBNB.deposit{ value: bnbBalance }();\n }\n\n /**\n * @notice Invoked when BNB is sent to this contract\n * @custom:access Only vBNB is considered a valid sender\n */\n receive() external payable {\n require(msg.sender == address(vBNB), \"only vBNB can send BNB to this contract\");\n }\n\n /**\n * @notice Invoked when called function does not exist in the contract. The function will be executed in the vBNB contract.\n * @custom:access Only owner (Governance)\n */\n fallback(bytes calldata data) external payable onlyOwner returns (bytes memory) {\n (bool ok, bytes memory res) = address(vBNB).call{ value: msg.value }(data);\n require(ok, \"call failed\");\n return res;\n }\n}\n" + }, + "contracts/Admin/VBNBAdminStorage.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\ninterface VTokenInterface {\n function _reduceReserves(uint reduceAmount) external returns (uint);\n\n function _acceptAdmin() external returns (uint);\n\n function comptroller() external returns (address);\n}\n\ninterface IWBNB is IERC20Upgradeable {\n function deposit() external payable;\n}\n\ninterface IProtocolShareReserve {\n enum IncomeType {\n SPREAD,\n LIQUIDATION\n }\n\n function updateAssetsState(address comptroller, address asset, IncomeType incomeType) external;\n}\n\ncontract VBNBAdminStorage {\n /// @notice address of protocol share reserve contract\n IProtocolShareReserve public protocolShareReserve;\n\n /// @dev gap to prevent collision in inheritence\n uint256[49] private __gap;\n}\n" + }, + "contracts/DelegateBorrowers/MoveDebtDelegate.sol": { + "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\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { approveOrRevert } from \"../lib/approveOrRevert.sol\";\nimport { IVBep20, IComptroller } from \"../InterfacesV8.sol\";\n\ncontract MoveDebtDelegate is Ownable2StepUpgradeable, ReentrancyGuardUpgradeable {\n /// @dev VToken return value signalling about successful execution\n uint256 internal constant NO_ERROR = 0;\n\n /// @notice A wildcard indicating that repayment is allowed for _any_ user in the market\n address public constant ANY_USER = address(1);\n\n /// @notice User to borrow on behalf of\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable newBorrower;\n\n /// @notice Whether to allow borrowing from the corresponding vToken\n mapping(address => bool) public borrowAllowed;\n\n /// @notice Whether to allow repaying to the corresponding vToken on behalf of\n /// a certain user. Use ANY_USER to check if repayment is allowed for any user.\n mapping(address => mapping(address => bool)) public repaymentAllowed;\n\n /// @notice Emitted when vToken is allowed or denied to be borrowed from\n event BorrowAllowedSet(address indexed vTokenToBorrow, bool allowed);\n\n /// @notice Emitted when vToken is allowed or denied to be borrowed from\n event RepaymentAllowedSet(address indexed vTokenToRepay, address indexed originalBorrower, bool allowed);\n\n /// @notice Emitted if debt is swapped successfully\n event DebtMoved(\n address indexed originalBorrower,\n address indexed vTokenRepaid,\n uint256 repaidAmount,\n address newBorrower,\n address indexed vTokenBorrowed,\n uint256 borrowedAmount\n );\n\n /// @notice Emitted when the owner transfers tokens, accidentially sent to this contract,\n /// to their account\n event SweptTokens(address indexed token, uint256 amount);\n\n /// @notice Thrown if VTokens' comptrollers are not equal\n error ComptrollerMismatch();\n\n /// @notice Thrown if repayment fails with an error code\n error RepaymentFailed(uint256 errorCode);\n\n /// @notice Thrown if borrow fails with an error code\n error BorrowFailed(uint256 errorCode);\n\n /// @notice Thrown if borrowing from the corresponding vToken is not allowed\n error BorrowNotAllowed(address vToken);\n\n /// @notice Thrown if repaying the debts of the borrower to the corresponding vToken is not allowed\n error RepaymentNotAllowed(address vToken, address borrower);\n\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param newBorrower_ User to borrow on behalf of\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address newBorrower_) {\n newBorrower = newBorrower_;\n _disableInitializers();\n }\n\n function initialize() external initializer {\n __Ownable2Step_init();\n __ReentrancyGuard_init();\n }\n\n /**\n * @notice Repays originalBorrower's borrow in vTokenToRepay.underlying() and borrows\n * vTokenToBorrow.underlying() on behalf of newBorrower.\n *\n * @param originalBorrower The address of the borrower, whose debt to repay\n * @param vTokenToRepay VToken to repay to on behalf of originalBorrower\n * @param repayAmount The amount to repay in terms of vTokenToRepay.underlying()\n * @param vTokenToBorrow VToken to borrow from\n */\n function moveDebt(\n IVBep20 vTokenToRepay,\n address originalBorrower,\n uint256 repayAmount,\n IVBep20 vTokenToBorrow\n ) external nonReentrant {\n if (!borrowAllowed[address(vTokenToBorrow)]) {\n revert BorrowNotAllowed(address(vTokenToBorrow));\n }\n\n mapping(address => bool) storage repaymentAllowedFor = repaymentAllowed[address(vTokenToRepay)];\n if (!repaymentAllowedFor[ANY_USER] && !repaymentAllowedFor[originalBorrower]) {\n revert RepaymentNotAllowed(address(vTokenToRepay), originalBorrower);\n }\n\n uint256 actualRepaymentAmount = _repay(vTokenToRepay, originalBorrower, repayAmount);\n uint256 amountToBorrow = _convert(vTokenToRepay, vTokenToBorrow, actualRepaymentAmount);\n _borrow(vTokenToBorrow, amountToBorrow);\n emit DebtMoved(\n originalBorrower,\n address(vTokenToRepay),\n actualRepaymentAmount,\n newBorrower,\n address(vTokenToBorrow),\n amountToBorrow\n );\n }\n\n /**\n * @notice Allows or denies borrowing from the corresponding vToken\n * @param vTokenToBorrow VToken to borrow from\n * @param allow Whether to allow borrowing from the corresponding vToken\n */\n function setBorrowAllowed(address vTokenToBorrow, bool allow) external onlyOwner {\n ensureNonzeroAddress(vTokenToBorrow);\n if (borrowAllowed[vTokenToBorrow] != allow) {\n borrowAllowed[vTokenToBorrow] = allow;\n emit BorrowAllowedSet(vTokenToBorrow, allow);\n }\n }\n\n /**\n * @notice Allows or denies repaying the debts of originalBorrower to the corresponding vToken\n * @param vTokenToRepay VToken to repay to\n * @param originalBorrower The address of the borrower, whose debt to repay (or ANY_USER to allow\n * repayments for all users in the market, e.g. if the market is going to be deprecated soon)\n * @param allow Whether to allow repaying to the corresponding vToken on behalf of originalBorrower\n */\n function setRepaymentAllowed(address vTokenToRepay, address originalBorrower, bool allow) external onlyOwner {\n ensureNonzeroAddress(vTokenToRepay);\n ensureNonzeroAddress(originalBorrower);\n if (repaymentAllowed[vTokenToRepay][originalBorrower] != allow) {\n repaymentAllowed[vTokenToRepay][originalBorrower] = allow;\n emit RepaymentAllowedSet(vTokenToRepay, originalBorrower, allow);\n }\n }\n\n /**\n * @notice Transfers tokens, accidentially sent to this contract, to the owner\n * @param token ERC-20 token to sweep\n */\n function sweepTokens(IERC20Upgradeable token) external onlyOwner {\n uint256 amount = token.balanceOf(address(this));\n token.safeTransfer(owner(), amount);\n emit SweptTokens(address(token), amount);\n }\n\n /**\n * @dev Transfers the funds from the sender and repays a borrow in vToken on behalf of the borrower\n * @param vTokenToRepay VToken to repay to\n * @param borrower The address of the borrower, whose debt to repay\n * @param repayAmount The amount to repay in terms of underlying\n */\n function _repay(\n IVBep20 vTokenToRepay,\n address borrower,\n uint256 repayAmount\n ) internal returns (uint256 actualRepaymentAmount) {\n IERC20Upgradeable underlying = IERC20Upgradeable(vTokenToRepay.underlying());\n uint256 balanceBefore = underlying.balanceOf(address(this));\n underlying.safeTransferFrom(msg.sender, address(this), repayAmount);\n uint256 balanceAfter = underlying.balanceOf(address(this));\n uint256 repayAmountMinusFee = balanceAfter - balanceBefore;\n\n uint256 borrowBalanceBefore = vTokenToRepay.borrowBalanceCurrent(borrower);\n approveOrRevert(underlying, address(vTokenToRepay), repayAmountMinusFee);\n uint256 err = vTokenToRepay.repayBorrowBehalf(borrower, repayAmountMinusFee);\n if (err != NO_ERROR) {\n revert RepaymentFailed(err);\n }\n approveOrRevert(underlying, address(vTokenToRepay), 0);\n uint256 borrowBalanceAfter = vTokenToRepay.borrowBalanceCurrent(borrower);\n return borrowBalanceBefore - borrowBalanceAfter;\n }\n\n /**\n * @dev Borrows in vToken on behalf of the borrower and transfers the funds to the sender\n * @param vTokenToBorrow VToken to borrow from\n * @param borrowAmount The amount to borrow in terms of underlying\n */\n function _borrow(IVBep20 vTokenToBorrow, uint256 borrowAmount) internal {\n IERC20Upgradeable underlying = IERC20Upgradeable(vTokenToBorrow.underlying());\n uint256 balanceBefore = underlying.balanceOf(address(this));\n uint256 err = vTokenToBorrow.borrowBehalf(newBorrower, borrowAmount);\n if (err != NO_ERROR) {\n revert BorrowFailed(err);\n }\n uint256 balanceAfter = underlying.balanceOf(address(this));\n uint256 actualBorrowedAmount = balanceAfter - balanceBefore;\n underlying.safeTransfer(msg.sender, actualBorrowedAmount);\n }\n\n /**\n * @dev Converts the value expressed in convertFrom.underlying() to a value\n * in convertTo.underlying(), using the oracle price\n * @param convertFrom VToken to convert from\n * @param convertTo VToken to convert to\n * @param amount The amount in convertFrom.underlying()\n */\n function _convert(IVBep20 convertFrom, IVBep20 convertTo, uint256 amount) internal view returns (uint256) {\n IComptroller comptroller = convertFrom.comptroller();\n if (comptroller != convertTo.comptroller()) {\n revert ComptrollerMismatch();\n }\n ResilientOracleInterface oracle = comptroller.oracle();\n\n // Decimals are accounted for in the oracle contract\n uint256 scaledUsdValue = oracle.getUnderlyingPrice(address(convertFrom)) * amount; // the USD value here has 36 decimals\n return scaledUsdValue / oracle.getUnderlyingPrice(address(convertTo));\n }\n}\n" + }, + "contracts/DelegateBorrowers/SwapDebtDelegate.sol": { + "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\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\n\nimport { approveOrRevert } from \"../lib/approveOrRevert.sol\";\nimport { IVBep20, IComptroller } from \"../InterfacesV8.sol\";\n\ncontract SwapDebtDelegate is Ownable2StepUpgradeable, ReentrancyGuardUpgradeable {\n /// @dev VToken return value signalling about successful execution\n uint256 internal constant NO_ERROR = 0;\n\n /// @notice Emitted if debt is swapped successfully\n event DebtSwapped(\n address indexed borrower,\n address indexed vTokenRepaid,\n uint256 repaidAmount,\n address indexed vTokenBorrowed,\n uint256 borrowedAmount\n );\n\n /// @notice Emitted when the owner transfers tokens, accidentially sent to this contract,\n /// to their account\n event SweptTokens(address indexed token, uint256 amount);\n\n /// @notice Thrown if VTokens' comptrollers are not equal\n error ComptrollerMismatch();\n\n /// @notice Thrown if repayment fails with an error code\n error RepaymentFailed(uint256 errorCode);\n\n /// @notice Thrown if borrow fails with an error code\n error BorrowFailed(uint256 errorCode);\n\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n function initialize() external initializer {\n __Ownable2Step_init();\n __ReentrancyGuard_init();\n }\n\n /**\n * @notice Repays a borrow in repayTo.underlying() and borrows borrowFrom.underlying()\n * @param borrower The address of the borrower, whose debt to swap\n * @param repayTo VToken to repay the debt to\n * @param borrowFrom VToken to borrow from\n * @param repayAmount The amount to repay in terms of repayTo.underlying()\n */\n function swapDebt(\n address borrower,\n IVBep20 repayTo,\n IVBep20 borrowFrom,\n uint256 repayAmount\n ) external onlyOwner nonReentrant {\n uint256 actualRepaymentAmount = _repay(repayTo, borrower, repayAmount);\n uint256 amountToBorrow = _convert(repayTo, borrowFrom, actualRepaymentAmount);\n _borrow(borrowFrom, borrower, amountToBorrow);\n emit DebtSwapped(borrower, address(repayTo), actualRepaymentAmount, address(borrowFrom), amountToBorrow);\n }\n\n /**\n * @notice Transfers tokens, accidentially sent to this contract, to the owner\n * @param token ERC-20 token to sweep\n */\n function sweepTokens(IERC20Upgradeable token) external onlyOwner {\n uint256 amount = token.balanceOf(address(this));\n token.safeTransfer(owner(), amount);\n emit SweptTokens(address(token), amount);\n }\n\n /**\n * @dev Transfers the funds from the sender and repays a borrow in vToken on behalf of the borrower\n * @param vToken VToken to repay the debt to\n * @param borrower The address of the borrower, whose debt to repay\n * @param repayAmount The amount to repay in terms of underlying\n */\n function _repay(\n IVBep20 vToken,\n address borrower,\n uint256 repayAmount\n ) internal returns (uint256 actualRepaymentAmount) {\n IERC20Upgradeable underlying = IERC20Upgradeable(vToken.underlying());\n uint256 balanceBefore = underlying.balanceOf(address(this));\n underlying.safeTransferFrom(msg.sender, address(this), repayAmount);\n uint256 balanceAfter = underlying.balanceOf(address(this));\n uint256 repayAmountMinusFee = balanceAfter - balanceBefore;\n\n underlying.safeApprove(address(vToken), 0);\n underlying.safeApprove(address(vToken), repayAmountMinusFee);\n uint256 borrowBalanceBefore = vToken.borrowBalanceCurrent(borrower);\n uint256 err = vToken.repayBorrowBehalf(borrower, repayAmountMinusFee);\n if (err != NO_ERROR) {\n revert RepaymentFailed(err);\n }\n uint256 borrowBalanceAfter = vToken.borrowBalanceCurrent(borrower);\n return borrowBalanceBefore - borrowBalanceAfter;\n }\n\n /**\n * @dev Borrows in vToken on behalf of the borrower and transfers the funds to the sender\n * @param vToken VToken to borrow from\n * @param borrower The address of the borrower, who will own the borrow\n * @param borrowAmount The amount to borrow in terms of underlying\n */\n function _borrow(IVBep20 vToken, address borrower, uint256 borrowAmount) internal {\n IERC20Upgradeable underlying = IERC20Upgradeable(vToken.underlying());\n uint256 balanceBefore = underlying.balanceOf(address(this));\n uint256 err = vToken.borrowBehalf(borrower, borrowAmount);\n if (err != NO_ERROR) {\n revert BorrowFailed(err);\n }\n uint256 balanceAfter = underlying.balanceOf(address(this));\n uint256 actualBorrowedAmount = balanceAfter - balanceBefore;\n underlying.safeTransfer(msg.sender, actualBorrowedAmount);\n }\n\n /**\n * @dev Converts the value expressed in convertFrom.underlying() to a value\n * in convertTo.underlying(), using the oracle price\n * @param convertFrom VToken to convert from\n * @param convertTo VToken to convert to\n * @param amount The amount in convertFrom.underlying()\n */\n function _convert(IVBep20 convertFrom, IVBep20 convertTo, uint256 amount) internal view returns (uint256) {\n IComptroller comptroller = convertFrom.comptroller();\n if (comptroller != convertTo.comptroller()) {\n revert ComptrollerMismatch();\n }\n ResilientOracleInterface oracle = comptroller.oracle();\n\n // Decimals are accounted for in the oracle contract\n uint256 scaledUsdValue = oracle.getUnderlyingPrice(address(convertFrom)) * amount; // the USD value here has 36 decimals\n return scaledUsdValue / oracle.getUnderlyingPrice(address(convertTo));\n }\n}\n" + }, + "contracts/Governance/TokenRedeemer.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport { Ownable2Step } from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { IVAIController, IVToken, IVBep20, IVBNB } from \"../InterfacesV8.sol\";\nimport { Currency, CurrencyLibrary } from \"../lib/Currency.sol\";\n\ncontract TokenRedeemer is ReentrancyGuard, Ownable2Step {\n using CurrencyLibrary for Currency;\n\n struct AccountBorrows {\n address borrower;\n uint256 amount;\n }\n\n struct Borrows {\n uint256 totalBorrows;\n AccountBorrows[] accountBorrows;\n }\n\n IVBNB public immutable VBNB;\n\n error AccrueInterestFailed(uint256 errCode);\n error RedeemFailed(uint256 errCode);\n error RepaymentFailed(uint256 errCode);\n error NativeTokenTransferFailed();\n\n constructor(address owner_, IVBNB vBNB) {\n ensureNonzeroAddress(owner_);\n VBNB = vBNB;\n _transferOwnership(owner_);\n }\n\n receive() external payable {}\n\n function redeemAndTransfer(IVToken vToken, address destination) external nonReentrant onlyOwner {\n Currency underlying = _underlying(vToken);\n uint256 err = vToken.redeem(vToken.balanceOf(address(this)));\n if (err != 0) {\n revert RedeemFailed(err);\n }\n underlying.transferAll(destination);\n }\n\n function redeemUnderlyingAndRepayBorrowBehalf(\n IVToken vToken,\n address borrower,\n uint256 amount,\n address receiver\n ) external nonReentrant onlyOwner {\n Currency underlying = _underlying(vToken);\n\n uint256 err = vToken.redeemUnderlying(amount);\n if (err != 0) {\n revert RedeemFailed(err);\n }\n\n underlying.approve(address(vToken), amount);\n\n _repay(vToken, borrower, amount);\n\n underlying.approve(address(vToken), 0);\n\n underlying.transferAll(receiver);\n Currency.wrap(address(vToken)).transferAll(receiver);\n }\n\n function redeemAndBatchRepay(\n IVToken vToken,\n address[] calldata borrowers,\n address receiver\n ) external nonReentrant onlyOwner {\n _accrueInterest(vToken);\n\n (uint256 totalBorrowedAmount, AccountBorrows[] memory borrows) = _getBorrows(vToken, borrowers);\n _redeemUpTo(vToken, totalBorrowedAmount);\n\n Currency underlying = _underlying(vToken);\n uint256 balance = underlying.balanceOfSelf();\n underlying.approve(address(vToken), totalBorrowedAmount);\n uint256 borrowsCount = borrows.length;\n // The code below assumes no fees on transfer\n if (balance >= totalBorrowedAmount) {\n // If we're doing a full repayment, we can optimize it by skipping the balance checks\n for (uint256 i = 0; i < borrowsCount; ++i) {\n AccountBorrows memory accountBorrows = borrows[i];\n _repay(vToken, accountBorrows.borrower, accountBorrows.amount);\n }\n } else {\n // Otherwise, we have to check and update the balance on every iteration\n for (uint256 i = 0; i < borrowsCount && balance != 0; ++i) {\n AccountBorrows memory accountBorrows = borrows[i];\n _repay(vToken, accountBorrows.borrower, _min(accountBorrows.amount, balance));\n balance = underlying.balanceOfSelf();\n }\n }\n underlying.approve(address(vToken), 0);\n\n underlying.transferAll(receiver);\n Currency.wrap(address(vToken)).transferAll(receiver);\n }\n\n function batchRepayVAI(\n IVAIController vaiController,\n address[] calldata borrowers,\n address receiver\n ) external nonReentrant onlyOwner {\n vaiController.accrueVAIInterest();\n Currency vai = Currency.wrap(vaiController.getVAIAddress());\n uint256 balance = vai.balanceOfSelf();\n vai.approve(address(vaiController), type(uint256).max);\n uint256 borrowersCount = borrowers.length;\n for (uint256 i = 0; i < borrowersCount && balance != 0; ++i) {\n address borrower = borrowers[i];\n uint256 debt = vaiController.getVAIRepayAmount(borrower);\n _repayVAI(vaiController, borrower, _min(debt, balance));\n balance = vai.balanceOfSelf();\n }\n vai.approve(address(vaiController), 0);\n vai.transferAll(receiver);\n }\n\n function sweepTokens(address token, address destination) external onlyOwner {\n Currency.wrap(token).transferAll(destination);\n }\n\n function _accrueInterest(IVToken vToken) internal {\n uint256 err = vToken.accrueInterest();\n if (err != 0) {\n revert AccrueInterestFailed(err);\n }\n }\n\n function _redeemUpTo(IVToken vToken, uint256 amount) internal {\n uint256 unredeemedUnderlying = vToken.balanceOfUnderlying(address(this));\n if (unredeemedUnderlying > 0) {\n uint256 err = vToken.redeemUnderlying(_min(amount, unredeemedUnderlying));\n if (err != 0) {\n revert RedeemFailed(err);\n }\n }\n }\n\n function _repay(IVToken vToken, address borrower, uint256 amount) internal {\n if (amount == 0) {\n return;\n }\n if (_isVBNB(vToken)) {\n IVBNB(address(vToken)).repayBorrowBehalf{ value: amount }(borrower);\n } else {\n uint256 err = IVBep20(address(vToken)).repayBorrowBehalf(borrower, amount);\n if (err != 0) {\n revert RepaymentFailed(err);\n }\n }\n }\n\n function _repayVAI(IVAIController vaiController, address borrower, uint256 amount) internal {\n if (amount == 0) {\n return;\n }\n (uint256 err, ) = vaiController.repayVAIBehalf(borrower, amount);\n if (err != 0) {\n revert RepaymentFailed(err);\n }\n }\n\n function _getBorrows(\n IVToken vToken,\n address[] calldata borrowers\n ) internal view returns (uint256, AccountBorrows[] memory) {\n uint256 borrowersCount = borrowers.length;\n AccountBorrows[] memory borrows = new AccountBorrows[](borrowersCount);\n uint256 totalBorrowedAmount = 0;\n for (uint256 i = 0; i < borrowers.length; ++i) {\n address borrower = borrowers[i];\n uint256 amount = vToken.borrowBalanceStored(borrower);\n totalBorrowedAmount += amount;\n borrows[i] = AccountBorrows({ borrower: borrower, amount: amount });\n }\n return (totalBorrowedAmount, borrows);\n }\n\n function _underlying(IVToken vToken) internal view returns (Currency) {\n if (_isVBNB(vToken)) {\n return CurrencyLibrary.NATIVE;\n }\n return Currency.wrap(IVBep20(address(vToken)).underlying());\n }\n\n function _isVBNB(IVToken vToken) internal view returns (bool) {\n return address(vToken) == address(VBNB);\n }\n\n function _min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n}\n" + }, + "contracts/Governance/VTreasuryV8.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20, IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { Ownable2Step } from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport { ReentrancyGuard } from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\n\n/**\n * @title VTreasuryV8\n * @author Venus\n * @notice Protocol treasury that holds tokens owned by Venus\n */\ncontract VTreasuryV8 is Ownable2Step, ReentrancyGuard {\n using SafeERC20 for IERC20;\n\n // WithdrawTreasuryToken Event\n event WithdrawTreasuryToken(address indexed tokenAddress, uint256 withdrawAmount, address indexed withdrawAddress);\n\n // WithdrawTreasuryNative Event\n event WithdrawTreasuryNative(uint256 withdrawAmount, address indexed withdrawAddress);\n\n /// @notice Thrown if the supplied address is a zero address where it is not allowed\n error ZeroAddressNotAllowed();\n\n /**\n * @notice To receive Native when msg.data is not empty\n */\n fallback() external payable {}\n\n /**\n * @notice To receive Native when msg.data is empty\n */\n receive() external payable {}\n\n /**\n * @notice Withdraw Treasury Tokens, Only owner call it\n * @param tokenAddress The address of treasury token\n * @param withdrawAmount The withdraw amount to owner\n * @param withdrawAddress The withdraw address\n * @custom:error ZeroAddressNotAllowed thrown when token or withdrawAddress is zero.\n */\n function withdrawTreasuryToken(\n address tokenAddress,\n uint256 withdrawAmount,\n address withdrawAddress\n ) external onlyOwner nonReentrant {\n ensureNonzeroAddress(tokenAddress);\n ensureNonzeroAddress(withdrawAddress);\n require(withdrawAmount > 0, \"withdrawAmount must not be zero\");\n\n uint256 actualWithdrawAmount = withdrawAmount;\n // Get Treasury Token Balance\n uint256 treasuryBalance = IERC20(tokenAddress).balanceOf(address(this));\n\n // Check Withdraw Amount\n if (withdrawAmount > treasuryBalance) {\n // Update actualWithdrawAmount\n actualWithdrawAmount = treasuryBalance;\n }\n\n // Transfer Token to withdrawAddress\n IERC20(tokenAddress).safeTransfer(withdrawAddress, actualWithdrawAmount);\n\n emit WithdrawTreasuryToken(tokenAddress, actualWithdrawAmount, withdrawAddress);\n }\n\n /**\n * @notice Withdraw Treasury Native, Only owner call it\n * @param withdrawAmount The withdraw amount to owner\n * @param withdrawAddress The withdraw address\n * @custom:error ZeroAddressNotAllowed thrown when withdrawAddress is zero.\n */\n function withdrawTreasuryNative(\n uint256 withdrawAmount,\n address payable withdrawAddress\n ) external payable onlyOwner nonReentrant {\n ensureNonzeroAddress(withdrawAddress);\n require(withdrawAmount > 0, \"withdrawAmount must not be zero\");\n uint256 actualWithdrawAmount = withdrawAmount;\n // Get Treasury Native Balance\n uint256 nativeBalance = address(this).balance;\n\n // Check Withdraw Amount\n if (withdrawAmount > nativeBalance) {\n // Update actualWithdrawAmount\n actualWithdrawAmount = nativeBalance;\n }\n // Transfer the native token to withdrawAddress\n (bool sent, ) = withdrawAddress.call{ value: actualWithdrawAmount }(\"\");\n require(sent, \"Call failed\");\n emit WithdrawTreasuryNative(actualWithdrawAmount, withdrawAddress);\n }\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\n function ensureNonzeroAddress(address address_) internal pure {\n if (address_ == address(0)) {\n revert ZeroAddressNotAllowed();\n }\n }\n}\n" + }, + "contracts/InterfacesV8.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\n\ninterface IVToken is IERC20Upgradeable {\n function accrueInterest() external returns (uint256);\n\n function redeem(uint256 redeemTokens) external returns (uint256);\n\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\n\n function borrowBalanceCurrent(address borrower) external returns (uint256);\n\n function balanceOfUnderlying(address owner) external returns (uint256);\n\n function comptroller() external view returns (IComptroller);\n\n function borrowBalanceStored(address account) external view returns (uint256);\n}\n\ninterface IVBep20 is IVToken {\n function borrowBehalf(address borrower, uint256 borrowAmount) external returns (uint256);\n\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\n\n function liquidateBorrow(\n address borrower,\n uint256 repayAmount,\n IVToken vTokenCollateral\n ) external returns (uint256);\n\n function underlying() external view returns (address);\n}\n\ninterface IVBNB is IVToken {\n function repayBorrowBehalf(address borrower) external payable;\n\n function liquidateBorrow(address borrower, IVToken vTokenCollateral) external payable;\n}\n\ninterface IVAIController {\n function accrueVAIInterest() external;\n\n function liquidateVAI(\n address borrower,\n uint256 repayAmount,\n IVToken vTokenCollateral\n ) external returns (uint256, uint256);\n\n function repayVAIBehalf(address borrower, uint256 amount) external returns (uint256, uint256);\n\n function getVAIAddress() external view returns (address);\n\n function getVAIRepayAmount(address borrower) external view returns (uint256);\n}\n\ninterface IComptroller {\n enum Action {\n MINT,\n REDEEM,\n BORROW,\n REPAY,\n SEIZE,\n LIQUIDATE,\n TRANSFER,\n ENTER_MARKET,\n EXIT_MARKET\n }\n\n function _setActionsPaused(address[] calldata markets_, Action[] calldata actions_, bool paused_) external;\n\n function liquidationIncentiveMantissa() external view returns (uint256);\n\n function vaiController() external view returns (IVAIController);\n\n function liquidatorContract() external view returns (address);\n\n function oracle() external view returns (ResilientOracleInterface);\n\n function actionPaused(address market, Action action) external view returns (bool);\n\n function markets(address) external view returns (bool, uint256, bool);\n\n function isForcedLiquidationEnabled(address) external view returns (bool);\n}\n\ninterface ILiquidator {\n function restrictLiquidation(address borrower) external;\n\n function unrestrictLiquidation(address borrower) external;\n\n function addToAllowlist(address borrower, address liquidator) external;\n\n function removeFromAllowlist(address borrower, address liquidator) external;\n\n function liquidateBorrow(\n address vToken,\n address borrower,\n uint256 repayAmount,\n IVToken vTokenCollateral\n ) external payable;\n\n function setTreasuryPercent(uint256 newTreasuryPercentMantissa) external;\n\n function treasuryPercentMantissa() external view returns (uint256);\n}\n\ninterface IProtocolShareReserve {\n enum IncomeType {\n SPREAD,\n LIQUIDATION\n }\n\n function updateAssetsState(address comptroller, address asset, IncomeType kind) external;\n}\n\ninterface IWBNB is IERC20Upgradeable {\n function deposit() external payable;\n}\n" + }, + "contracts/lib/approveOrRevert.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.25;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\n/// @notice Thrown if a contract is unable to approve a transfer\nerror ApproveFailed();\n\n/// @notice Approves a transfer, ensuring that it is successful. This function supports non-compliant\n/// tokens like the ones that don't return a boolean value on success. Thus, such approve call supports\n/// three different kinds of tokens:\n/// * Compliant tokens that revert on failure\n/// * Compliant tokens that return false on failure\n/// * Non-compliant tokens that don't return a value\n/// @param token The contract address of the token which will be transferred\n/// @param spender The spender contract address\n/// @param amount The value of the transfer\nfunction approveOrRevert(IERC20Upgradeable token, address spender, uint256 amount) {\n bytes memory callData = abi.encodeCall(token.approve, (spender, amount));\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory result) = address(token).call(callData);\n\n if (!success || (result.length != 0 && !abi.decode(result, (bool)))) {\n revert ApproveFailed();\n }\n}\n" + }, + "contracts/lib/Currency.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n// This library is heavily inspired by Uniswap v4 Currency lib\n// (https://github.com/Uniswap/v4-core/blob/b230769238879e1d4f58ffa57a4696b0c390d188/src/types/Currency.sol)\n// Contrary to the implementation above, this library does not\n// use assembly to save gas. It rather relies on OpenZeppelin's\n// SafeERC20 to simplify the review and audits. This might change\n// in future if it's more heavily used by Venus contracts.\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ntype Currency is address;\n\nlibrary CurrencyLibrary {\n using CurrencyLibrary for Currency;\n\n /// @notice Thrown when a native transfer fails\n error NativeTransferFailed();\n\n Currency public constant NATIVE = Currency.wrap(0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB);\n\n /**\n * @dev If currency is a token, invokes SafeERC20.forceApprove to allow spender\n * to spend the amount of tokens on behalf of the current contract. Otherwise,\n * does nothing.\n * @param currency Currency\n * @param spender The account approved to spend the tokens\n * @param amount The approved amount\n */\n function approve(Currency currency, address spender, uint256 amount) internal {\n if (!currency.isNative()) {\n // I'd rather use approveOrRevert instead of forceApprove\n // once we migrate to OZ v5: force-approve does approve(0)\n // before approving the amount, and it's not always\n // desirable. The users will need to pay gas unnecessarily,\n // and using just approve() is safe as long as we revert on\n // errors (approveOrRevert handles that) and reset the approvals\n // after transfers (which is a best practice recommended by\n // auditors anyway).\n SafeERC20.forceApprove(IERC20(Currency.unwrap(currency)), spender, amount);\n }\n }\n\n /**\n * @dev Transfers an amount of currency to the receiver. If currency is a token,\n * uses SafeERC20.safeTransfer, otherwise transfers the native currency using\n * the recommended approach (`receiver.call{value: amount}(\"\")`).\n * @param currency Currency\n * @param receiver The account that would receive the tokens\n * @param amount The amount to transfer\n */\n function transfer(Currency currency, address receiver, uint256 amount) internal {\n if (currency.isNative()) {\n (bool success, ) = receiver.call{ value: amount }(\"\");\n if (!success) {\n revert NativeTransferFailed();\n }\n } else {\n SafeERC20.safeTransfer(IERC20(Currency.unwrap(currency)), receiver, amount);\n }\n }\n\n function transferAll(Currency currency, address receiver) internal {\n uint256 balance = currency.balanceOfSelf();\n if (balance > 0) {\n currency.transfer(receiver, balance);\n }\n }\n\n function balanceOfSelf(Currency currency) internal view returns (uint256) {\n if (currency.isNative()) {\n return address(this).balance;\n }\n return IERC20(Currency.unwrap(currency)).balanceOf(address(this));\n }\n\n function isNative(Currency currency) internal pure returns (bool) {\n return Currency.unwrap(currency) == Currency.unwrap(NATIVE);\n }\n}\n" + }, + "contracts/Liquidator/BUSDLiquidator.sol": { + "content": "// SPDX-License-Identifier: MIT\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 { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { MANTISSA_ONE } from \"@venusprotocol/solidity-utilities/contracts/constants.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\n\nimport { approveOrRevert } from \"../lib/approveOrRevert.sol\";\nimport { ILiquidator, IComptroller, IVToken, IVBep20, IVBNB, IVAIController } from \"../InterfacesV8.sol\";\n\n/**\n * @title BUSDLiquidator\n * @author Venus\n * @notice A custom contract for force-liquidating BUSD debts\n */\ncontract BUSDLiquidator is Ownable2StepUpgradeable, ReentrancyGuardUpgradeable {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using SafeERC20Upgradeable for IVToken;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IVBep20 public immutable vBUSD;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IComptroller public immutable comptroller;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable treasury;\n\n /// @notice The liquidator's share, scaled by 1e18 (e.g. 1.02 * 1e18 for 102% of the debt covered)\n uint256 public liquidatorShareMantissa;\n\n /// @notice Thrown if trying to set liquidator's share lower than 100% of the debt covered\n error LiquidatorShareTooLow(uint256 liquidatorShareMantissa_);\n\n /// @notice Thrown if trying to set liquidator's share larger than this contract can receive from a liquidation\n error LiquidatorShareTooHigh(uint256 maxLiquidatorShareMantissa, uint256 liquidatorShareMantissa_);\n\n /// @notice Emitted when the liquidator's share is set\n event NewLiquidatorShare(uint256 oldLiquidatorShareMantissa, uint256 newLiquidatorShareMantissa);\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param comptroller_ The address of the Comptroller contract\n /// @param vBUSD_ The address of the VBNB\n /// @param treasury_ The address of Venus treasury\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address comptroller_, address vBUSD_, address treasury_) {\n ensureNonzeroAddress(vBUSD_);\n ensureNonzeroAddress(comptroller_);\n ensureNonzeroAddress(treasury_);\n vBUSD = IVBep20(vBUSD_);\n comptroller = IComptroller(comptroller_);\n treasury = treasury_;\n _disableInitializers();\n }\n\n /// @notice Initializer for the implementation contract.\n /// @param liquidatorShareMantissa_ Liquidator's share, scaled by 1e18 (e.g. 1.01 * 1e18 for 101%)\n /// @custom:error LiquidatorShareTooHigh is thrown if trying to set liquidator percent larger than the liquidation profit\n function initialize(uint256 liquidatorShareMantissa_) external virtual initializer {\n __Ownable2Step_init();\n __ReentrancyGuard_init();\n _validateLiquidatorShareMantissa(liquidatorShareMantissa_);\n liquidatorShareMantissa = liquidatorShareMantissa_;\n }\n\n /// @notice Liquidate the entire BUSD debt of a borrower, seizing vTokenCollateral\n /// @param borrower The borrower whose debt should be liquidated\n /// @param vTokenCollateral The collateral to seize from the borrower\n function liquidateEntireBorrow(address borrower, IVToken vTokenCollateral) external nonReentrant {\n uint256 repayAmount = vBUSD.borrowBalanceCurrent(borrower);\n _unpauseAndLiquidate(borrower, repayAmount, vTokenCollateral);\n }\n\n /// @notice Liquidate a BUSD borrow, repaying the repayAmount of BUSD\n /// @param borrower The borrower whose debt should be liquidated\n /// @param repayAmount The amount to repay\n /// @param vTokenCollateral The collateral to seize from the borrower\n function liquidateBorrow(address borrower, uint256 repayAmount, IVToken vTokenCollateral) external nonReentrant {\n _unpauseAndLiquidate(borrower, repayAmount, vTokenCollateral);\n }\n\n /// @notice Allows Governance to set the liquidator's share\n /// @param liquidatorShareMantissa_ Liquidator's share, scaled by 1e18 (e.g. 1.01 * 1e18 for 101%)\n /// @custom:access Only Governance\n function setLiquidatorShare(uint256 liquidatorShareMantissa_) external onlyOwner {\n _validateLiquidatorShareMantissa(liquidatorShareMantissa_);\n uint256 oldLiquidatorShareMantissa = liquidatorShareMantissa;\n liquidatorShareMantissa = liquidatorShareMantissa_;\n emit NewLiquidatorShare(oldLiquidatorShareMantissa, liquidatorShareMantissa_);\n }\n\n /// @notice Allows to recover token accidentally sent to this contract by sending the entire balance to Governance\n /// @param token The address of the token to recover\n /// @custom:access Only Governance\n function sweepToken(IERC20Upgradeable token) external onlyOwner {\n token.safeTransfer(msg.sender, token.balanceOf(address(this)));\n }\n\n /// @dev Unpauses the liquidation on the BUSD market, liquidates the borrower's debt,\n /// and pauses the liquidations back\n /// @param borrower The borrower whose debt should be liquidated\n /// @param repayAmount The amount to repay\n /// @param vTokenCollateral The collateral to seize from the borrower\n function _unpauseAndLiquidate(address borrower, uint256 repayAmount, IVToken vTokenCollateral) internal {\n address[] memory vTokens = new address[](1);\n vTokens[0] = address(vBUSD);\n IComptroller.Action[] memory actions = new IComptroller.Action[](1);\n actions[0] = IComptroller.Action.LIQUIDATE;\n\n comptroller._setActionsPaused(vTokens, actions, false);\n _liquidateBorrow(borrower, repayAmount, vTokenCollateral);\n comptroller._setActionsPaused(vTokens, actions, true);\n }\n\n /// @dev Performs the actual liquidation, transferring BUSD from the sender to this contract,\n /// repaying the debt, and transferring the seized collateral to the sender and the treasury\n /// @param borrower The borrower whose debt should be liquidated\n /// @param repayAmount The amount to repay\n /// @param vTokenCollateral The collateral to seize from the borrower\n function _liquidateBorrow(address borrower, uint256 repayAmount, IVToken vTokenCollateral) internal {\n ILiquidator liquidatorContract = ILiquidator(comptroller.liquidatorContract());\n IERC20Upgradeable busd = IERC20Upgradeable(vBUSD.underlying());\n\n uint256 actualRepayAmount = _transferIn(busd, msg.sender, repayAmount);\n approveOrRevert(busd, address(liquidatorContract), actualRepayAmount);\n uint256 balanceBefore = vTokenCollateral.balanceOf(address(this));\n liquidatorContract.liquidateBorrow(address(vBUSD), borrower, actualRepayAmount, vTokenCollateral);\n uint256 receivedAmount = vTokenCollateral.balanceOf(address(this)) - balanceBefore;\n approveOrRevert(busd, address(liquidatorContract), 0);\n\n (uint256 liquidatorAmount, uint256 treasuryAmount) = _computeShares(receivedAmount);\n vTokenCollateral.safeTransfer(msg.sender, liquidatorAmount);\n vTokenCollateral.safeTransfer(treasury, treasuryAmount);\n }\n\n /// @dev Transfers tokens to this contract and returns the actual transfer amount\n /// @param token The token to transfer\n /// @param from The account to transfer from\n /// @param amount The amount to transfer\n /// @return The actual amount transferred\n function _transferIn(IERC20Upgradeable token, address from, uint256 amount) internal returns (uint256) {\n uint256 prevBalance = token.balanceOf(address(this));\n token.safeTransferFrom(from, address(this), amount);\n return token.balanceOf(address(this)) - prevBalance;\n }\n\n /// @dev Computes the liquidator's and treasury's shares of the received amount\n /// @param receivedAmount The amount received from the liquidation\n /// @return liquidatorAmount The liquidator's share\n /// @return treasuryAmount The treasury's share\n function _computeShares(\n uint256 receivedAmount\n ) internal view returns (uint256 liquidatorAmount, uint256 treasuryAmount) {\n uint256 denominator = _getDenominator();\n liquidatorAmount = (receivedAmount * liquidatorShareMantissa) / denominator;\n treasuryAmount = receivedAmount - liquidatorAmount;\n }\n\n /// @dev Returns (liquidation incentive - treasury percent), the value used as the denominator\n /// when calculating the liquidator's share\n /// @return The denominator for the seized amount used when calculating the liquidator's share\n function _getDenominator() internal view returns (uint256) {\n uint256 totalPercentageToDistribute = comptroller.liquidationIncentiveMantissa();\n uint256 regularTreasuryPercent = ILiquidator(comptroller.liquidatorContract()).treasuryPercentMantissa();\n uint256 denominator = totalPercentageToDistribute - regularTreasuryPercent;\n return denominator;\n }\n\n /// @dev Checks if the liquidator's share is more than 100% of the debt covered and less\n /// than (liquidation incentive - treasury percent)\n /// @param liquidatorShareMantissa_ Liquidator's share, scaled by 1e18 (e.g. 1.01 * 1e18 for 101%)\n function _validateLiquidatorShareMantissa(uint256 liquidatorShareMantissa_) internal view {\n uint256 maxLiquidatorShareMantissa = _getDenominator();\n if (liquidatorShareMantissa_ < MANTISSA_ONE) {\n revert LiquidatorShareTooLow(liquidatorShareMantissa_);\n }\n\n if (liquidatorShareMantissa_ > maxLiquidatorShareMantissa) {\n revert LiquidatorShareTooHigh(maxLiquidatorShareMantissa, liquidatorShareMantissa_);\n }\n }\n}\n" + }, + "contracts/Liquidator/Liquidator.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { ensureNonzeroAddress } from \"@venusprotocol/solidity-utilities/contracts/validators.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport \"./LiquidatorStorage.sol\";\nimport { IComptroller, IVToken, IVBep20, IVBNB, IVAIController, IProtocolShareReserve, IWBNB } from \"../InterfacesV8.sol\";\n\ncontract Liquidator is Ownable2StepUpgradeable, ReentrancyGuardUpgradeable, LiquidatorStorage, AccessControlledV8 {\n /// @notice Address of vBNB contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IVBNB public immutable vBnb;\n\n /// @notice Address of Venus Unitroller contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IComptroller public immutable comptroller;\n\n /// @notice Address of VAIUnitroller contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IVAIController public immutable vaiController;\n\n /// @notice Address of wBNB contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable wBNB;\n\n /// @dev A unit (literal one) in EXP_SCALE, usually used in additions/subtractions\n uint256 internal constant MANTISSA_ONE = 1e18;\n\n /* Events */\n\n /// @notice Emitted when the percent of the seized amount that goes to treasury changes.\n event NewLiquidationTreasuryPercent(uint256 oldPercent, uint256 newPercent);\n\n /// @notice Emitted when a borrow is liquidated\n event LiquidateBorrowedTokens(\n address indexed liquidator,\n address indexed borrower,\n uint256 repayAmount,\n address vTokenBorrowed,\n address indexed vTokenCollateral,\n uint256 seizeTokensForTreasury,\n uint256 seizeTokensForLiquidator\n );\n\n /// @notice Emitted when the liquidation is restricted for a borrower\n event LiquidationRestricted(address indexed borrower);\n\n /// @notice Emitted when the liquidation restrictions are removed for a borrower\n event LiquidationRestrictionsDisabled(address indexed borrower);\n\n /// @notice Emitted when a liquidator is added to the allowedLiquidatorsByAccount mapping\n event AllowlistEntryAdded(address indexed borrower, address indexed liquidator);\n\n /// @notice Emitted when a liquidator is removed from the allowedLiquidatorsByAccount mapping\n event AllowlistEntryRemoved(address indexed borrower, address indexed liquidator);\n\n /// @notice Emitted when the amount of minLiquidatableVAI is updated\n event NewMinLiquidatableVAI(uint256 oldMinLiquidatableVAI, uint256 newMinLiquidatableVAI);\n\n /// @notice Emitted when the length of chunk gets updated\n event NewPendingRedeemChunkLength(uint256 oldPendingRedeemChunkLength, uint256 newPendingRedeemChunkLength);\n\n /// @notice Emitted when force liquidation is paused\n event ForceVAILiquidationPaused(address indexed sender);\n\n /// @notice Emitted when force liquidation is resumed\n event ForceVAILiquidationResumed(address indexed sender);\n\n /// @notice Emitted when new address of protocol share reserve is set\n event NewProtocolShareReserve(address indexed oldProtocolShareReserve, address indexed newProtocolShareReserves);\n\n /// @notice Emitted when reserves are reduced from liquidator contract to protocol share reserves\n event ProtocolLiquidationIncentiveTransferred(address indexed sender, address indexed token, uint256 reducedAmount);\n\n /* Errors */\n\n /// @notice Thrown if the liquidation is restricted and the liquidator is not in the allowedLiquidatorsByAccount mapping\n error LiquidationNotAllowed(address borrower, address liquidator);\n\n /// @notice Thrown if VToken transfer fails after the liquidation\n error VTokenTransferFailed(address from, address to, uint256 amount);\n\n /// @notice Thrown if the liquidation is not successful (the error code is from TokenErrorReporter)\n error LiquidationFailed(uint256 errorCode);\n\n /// @notice Thrown if trying to restrict liquidations for an already restricted borrower\n error AlreadyRestricted(address borrower);\n\n /// @notice Thrown if trying to unrestrict liquidations for a borrower that is not restricted\n error NoRestrictionsExist(address borrower);\n\n /// @notice Thrown if the liquidator is already in the allowedLiquidatorsByAccount mapping\n error AlreadyAllowed(address borrower, address liquidator);\n\n /// @notice Thrown if trying to remove a liquidator that is not in the allowedLiquidatorsByAccount mapping\n error AllowlistEntryNotFound(address borrower, address liquidator);\n\n /// @notice Thrown if BNB amount sent with the transaction doesn't correspond to the\n /// intended BNB repayment\n error WrongTransactionAmount(uint256 expected, uint256 actual);\n\n /// @notice Thrown if trying to set treasury percent larger than the liquidation profit\n error TreasuryPercentTooHigh(uint256 maxTreasuryPercentMantissa, uint256 treasuryPercentMantissa_);\n\n /// @notice Thrown if trying to liquidate any token when VAI debt is too high\n error VAIDebtTooHigh(uint256 vaiDebt, uint256 minLiquidatableVAI);\n\n /// @notice Thrown when vToken is not listed\n error MarketNotListed(address vToken);\n\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @param comptroller_ The address of the Comptroller contract\n /// @param vBnb_ The address of the VBNB\n /// @param wBNB_ The address of wBNB\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address comptroller_, address payable vBnb_, address wBNB_) {\n ensureNonzeroAddress(vBnb_);\n ensureNonzeroAddress(comptroller_);\n ensureNonzeroAddress(wBNB_);\n vBnb = IVBNB(vBnb_);\n wBNB = wBNB_;\n comptroller = IComptroller(comptroller_);\n vaiController = IVAIController(IComptroller(comptroller_).vaiController());\n _disableInitializers();\n }\n\n receive() external payable {}\n\n /// @notice Initializer for the implementation contract.\n /// @param treasuryPercentMantissa_ Treasury share, scaled by 1e18 (e.g. 0.2 * 1e18 for 20%)\n /// @param accessControlManager_ address of access control manager\n /// @param protocolShareReserve_ The address of the protocol share reserve contract\n function initialize(\n uint256 treasuryPercentMantissa_,\n address accessControlManager_,\n address protocolShareReserve_\n ) external virtual reinitializer(2) {\n __Liquidator_init(treasuryPercentMantissa_, accessControlManager_, protocolShareReserve_);\n }\n\n /// @dev Liquidator initializer for derived contracts.\n /// @param treasuryPercentMantissa_ Treasury share, scaled by 1e18 (e.g. 0.2 * 1e18 for 20%)\n /// @param accessControlManager_ address of access control manager\n /// @param protocolShareReserve_ The address of the protocol share reserve contract\n function __Liquidator_init(\n uint256 treasuryPercentMantissa_,\n address accessControlManager_,\n address protocolShareReserve_\n ) internal onlyInitializing {\n __Ownable2Step_init();\n __ReentrancyGuard_init();\n __Liquidator_init_unchained(treasuryPercentMantissa_, protocolShareReserve_);\n __AccessControlled_init_unchained(accessControlManager_);\n }\n\n /// @dev Liquidator initializer for derived contracts that doesn't call parent initializers.\n /// @param treasuryPercentMantissa_ Treasury share, scaled by 1e18 (e.g. 0.2 * 1e18 for 20%)\n /// @param protocolShareReserve_ The address of the protocol share reserve contract\n function __Liquidator_init_unchained(\n uint256 treasuryPercentMantissa_,\n address protocolShareReserve_\n ) internal onlyInitializing {\n validateTreasuryPercentMantissa(treasuryPercentMantissa_);\n treasuryPercentMantissa = treasuryPercentMantissa_;\n _setProtocolShareReserve(protocolShareReserve_);\n }\n\n /// @notice An admin function to restrict liquidations to allowed addresses only.\n /// @dev Use {addTo,removeFrom}AllowList to configure the allowed addresses.\n /// @param borrower The address of the borrower\n function restrictLiquidation(address borrower) external {\n _checkAccessAllowed(\"restrictLiquidation(address)\");\n if (liquidationRestricted[borrower]) {\n revert AlreadyRestricted(borrower);\n }\n liquidationRestricted[borrower] = true;\n emit LiquidationRestricted(borrower);\n }\n\n /// @notice An admin function to remove restrictions for liquidations.\n /// @dev Does not impact the allowedLiquidatorsByAccount mapping for the borrower, just turns off the check.\n /// @param borrower The address of the borrower\n function unrestrictLiquidation(address borrower) external {\n _checkAccessAllowed(\"unrestrictLiquidation(address)\");\n if (!liquidationRestricted[borrower]) {\n revert NoRestrictionsExist(borrower);\n }\n liquidationRestricted[borrower] = false;\n emit LiquidationRestrictionsDisabled(borrower);\n }\n\n /// @notice An admin function to add the liquidator to the allowedLiquidatorsByAccount mapping for a certain\n /// borrower. If the liquidations are restricted, only liquidators from the\n /// allowedLiquidatorsByAccount mapping can participate in liquidating the positions of this borrower.\n /// @param borrower The address of the borrower\n /// @param borrower The address of the liquidator\n function addToAllowlist(address borrower, address liquidator) external {\n _checkAccessAllowed(\"addToAllowlist(address,address)\");\n if (allowedLiquidatorsByAccount[borrower][liquidator]) {\n revert AlreadyAllowed(borrower, liquidator);\n }\n allowedLiquidatorsByAccount[borrower][liquidator] = true;\n emit AllowlistEntryAdded(borrower, liquidator);\n }\n\n /// @notice An admin function to remove the liquidator from the allowedLiquidatorsByAccount mapping of a certain\n /// borrower. If the liquidations are restricted, this liquidator will not be\n /// able to liquidate the positions of this borrower.\n /// @param borrower The address of the borrower\n /// @param borrower The address of the liquidator\n function removeFromAllowlist(address borrower, address liquidator) external {\n _checkAccessAllowed(\"removeFromAllowlist(address,address)\");\n if (!allowedLiquidatorsByAccount[borrower][liquidator]) {\n revert AllowlistEntryNotFound(borrower, liquidator);\n }\n allowedLiquidatorsByAccount[borrower][liquidator] = false;\n emit AllowlistEntryRemoved(borrower, liquidator);\n }\n\n /// @notice Liquidates a borrow and splits the seized amount between protocol share reserve and\n /// liquidator. The liquidators should use this interface instead of calling\n /// vToken.liquidateBorrow(...) directly.\n /// @notice Checks force VAI liquidation first; vToken should be address of vaiController if vaiDebt is greater than threshold\n /// @notice For BNB borrows msg.value should be equal to repayAmount; otherwise msg.value\n /// should be zero.\n /// @param vToken Borrowed vToken\n /// @param borrower The address of the borrower\n /// @param repayAmount The amount to repay on behalf of the borrower\n /// @param vTokenCollateral The collateral to seize\n function liquidateBorrow(\n address vToken,\n address borrower,\n uint256 repayAmount,\n IVToken vTokenCollateral\n ) external payable nonReentrant {\n ensureNonzeroAddress(borrower);\n checkRestrictions(borrower, msg.sender);\n (bool isListed, , ) = IComptroller(comptroller).markets(address(vTokenCollateral));\n if (!isListed) {\n revert MarketNotListed(address(vTokenCollateral));\n }\n\n _checkForceVAILiquidate(vToken, borrower);\n uint256 ourBalanceBefore = vTokenCollateral.balanceOf(address(this));\n if (vToken == address(vBnb)) {\n if (repayAmount != msg.value) {\n revert WrongTransactionAmount(repayAmount, msg.value);\n }\n vBnb.liquidateBorrow{ value: msg.value }(borrower, vTokenCollateral);\n } else {\n if (msg.value != 0) {\n revert WrongTransactionAmount(0, msg.value);\n }\n if (vToken == address(vaiController)) {\n _liquidateVAI(borrower, repayAmount, vTokenCollateral);\n } else {\n _liquidateBep20(IVBep20(vToken), borrower, repayAmount, vTokenCollateral);\n }\n }\n uint256 ourBalanceAfter = vTokenCollateral.balanceOf(address(this));\n uint256 seizedAmount = ourBalanceAfter - ourBalanceBefore;\n (uint256 ours, uint256 theirs) = _distributeLiquidationIncentive(vTokenCollateral, seizedAmount);\n _reduceReservesInternal();\n emit LiquidateBorrowedTokens(\n msg.sender,\n borrower,\n repayAmount,\n vToken,\n address(vTokenCollateral),\n ours,\n theirs\n );\n }\n\n /// @notice Sets the new percent of the seized amount that goes to treasury. Should\n /// be less than or equal to comptroller.liquidationIncentiveMantissa().sub(1e18).\n /// @param newTreasuryPercentMantissa New treasury percent (scaled by 10^18).\n function setTreasuryPercent(uint256 newTreasuryPercentMantissa) external {\n _checkAccessAllowed(\"setTreasuryPercent(uint256)\");\n validateTreasuryPercentMantissa(newTreasuryPercentMantissa);\n emit NewLiquidationTreasuryPercent(treasuryPercentMantissa, newTreasuryPercentMantissa);\n treasuryPercentMantissa = newTreasuryPercentMantissa;\n }\n\n /**\n * @notice Sets protocol share reserve contract address\n * @param protocolShareReserve_ The address of the protocol share reserve contract\n */\n function setProtocolShareReserve(address payable protocolShareReserve_) external onlyOwner {\n _setProtocolShareReserve(protocolShareReserve_);\n }\n\n /**\n * @notice Reduce the reserves of the pending accumulated reserves\n */\n function reduceReserves() external nonReentrant {\n _reduceReservesInternal();\n }\n\n function _reduceReservesInternal() internal {\n uint256 _pendingRedeemLength = pendingRedeem.length;\n uint256 range = _pendingRedeemLength >= pendingRedeemChunkLength\n ? pendingRedeemChunkLength\n : _pendingRedeemLength;\n for (uint256 index = range; index > 0; ) {\n address vToken = pendingRedeem[index - 1];\n uint256 vTokenBalance_ = IVToken(vToken).balanceOf(address(this));\n if (_redeemUnderlying(vToken, vTokenBalance_)) {\n if (vToken == address(vBnb)) {\n _reduceBnbReserves();\n } else {\n _reduceVTokenReserves(vToken);\n }\n pendingRedeem[index - 1] = pendingRedeem[pendingRedeem.length - 1];\n pendingRedeem.pop();\n }\n unchecked {\n index--;\n }\n }\n }\n\n /// @dev Transfers BEP20 tokens to self, then approves vToken to take these tokens.\n function _liquidateBep20(IVBep20 vToken, address borrower, uint256 repayAmount, IVToken vTokenCollateral) internal {\n (bool isListed, , ) = IComptroller(comptroller).markets(address(vToken));\n if (!isListed) {\n revert MarketNotListed(address(vToken));\n }\n\n IERC20Upgradeable borrowedToken = IERC20Upgradeable(vToken.underlying());\n uint256 actualRepayAmount = _transferBep20(borrowedToken, msg.sender, address(this), repayAmount);\n borrowedToken.safeApprove(address(vToken), 0);\n borrowedToken.safeApprove(address(vToken), actualRepayAmount);\n requireNoError(vToken.liquidateBorrow(borrower, actualRepayAmount, vTokenCollateral));\n }\n\n /// @dev Transfers BEP20 tokens to self, then approves VAI to take these tokens.\n function _liquidateVAI(address borrower, uint256 repayAmount, IVToken vTokenCollateral) internal {\n IERC20Upgradeable vai = IERC20Upgradeable(vaiController.getVAIAddress());\n vai.safeTransferFrom(msg.sender, address(this), repayAmount);\n vai.safeApprove(address(vaiController), 0);\n vai.safeApprove(address(vaiController), repayAmount);\n\n (uint256 err, ) = vaiController.liquidateVAI(borrower, repayAmount, vTokenCollateral);\n requireNoError(err);\n }\n\n /// @dev Distribute seized collateral between liquidator and protocol share reserve\n function _distributeLiquidationIncentive(\n IVToken vTokenCollateral,\n uint256 seizedAmount\n ) internal returns (uint256 ours, uint256 theirs) {\n (ours, theirs) = _splitLiquidationIncentive(seizedAmount);\n if (!vTokenCollateral.transfer(msg.sender, theirs)) {\n revert VTokenTransferFailed(address(this), msg.sender, theirs);\n }\n\n if (ours > 0 && !_redeemUnderlying(address(vTokenCollateral), ours)) {\n // Check if asset is already present in pendingRedeem array\n uint256 index;\n for (index; index < pendingRedeem.length; ) {\n if (pendingRedeem[index] == address(vTokenCollateral)) {\n break;\n }\n unchecked {\n index++;\n }\n }\n if (index == pendingRedeem.length) {\n pendingRedeem.push(address(vTokenCollateral));\n }\n } else {\n if (address(vTokenCollateral) == address(vBnb)) {\n _reduceBnbReserves();\n } else {\n _reduceVTokenReserves(address(vTokenCollateral));\n }\n }\n }\n\n /// @dev Wraps BNB to wBNB and sends to protocol share reserve\n function _reduceBnbReserves() private {\n uint256 bnbBalance = address(this).balance;\n IWBNB(wBNB).deposit{ value: bnbBalance }();\n IERC20Upgradeable(wBNB).safeTransfer(protocolShareReserve, bnbBalance);\n IProtocolShareReserve(protocolShareReserve).updateAssetsState(\n address(comptroller),\n wBNB,\n IProtocolShareReserve.IncomeType.LIQUIDATION\n );\n emit ProtocolLiquidationIncentiveTransferred(msg.sender, wBNB, bnbBalance);\n }\n\n /// @dev Redeem seized collateral to underlying assets\n function _redeemUnderlying(address vToken, uint256 amount) private returns (bool) {\n try IVToken(address(vToken)).redeem(amount) returns (uint256 response) {\n if (response == 0) {\n return true;\n } else {\n return false;\n }\n } catch {\n return false;\n }\n }\n\n /// @dev Transfers seized collateral other than BNB to protocol share reserve\n function _reduceVTokenReserves(address vToken) private {\n address underlying = IVBep20(vToken).underlying();\n uint256 underlyingBalance = IERC20Upgradeable(underlying).balanceOf(address(this));\n IERC20Upgradeable(underlying).safeTransfer(protocolShareReserve, underlyingBalance);\n IProtocolShareReserve(protocolShareReserve).updateAssetsState(\n address(comptroller),\n underlying,\n IProtocolShareReserve.IncomeType.LIQUIDATION\n );\n emit ProtocolLiquidationIncentiveTransferred(msg.sender, underlying, underlyingBalance);\n }\n\n /// @dev Transfers tokens and returns the actual transfer amount\n function _transferBep20(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 amount\n ) internal returns (uint256) {\n uint256 prevBalance = token.balanceOf(to);\n token.safeTransferFrom(from, to, amount);\n return token.balanceOf(to) - prevBalance;\n }\n\n /// @dev Computes the amounts that would go to treasury and to the liquidator.\n function _splitLiquidationIncentive(uint256 seizedAmount) internal view returns (uint256 ours, uint256 theirs) {\n uint256 totalIncentive = comptroller.liquidationIncentiveMantissa();\n ours = (seizedAmount * treasuryPercentMantissa) / totalIncentive;\n theirs = seizedAmount - ours;\n }\n\n function requireNoError(uint256 errCode) internal pure {\n if (errCode == uint256(0)) {\n return;\n }\n\n revert LiquidationFailed(errCode);\n }\n\n function checkRestrictions(address borrower, address liquidator) internal view {\n if (liquidationRestricted[borrower] && !allowedLiquidatorsByAccount[borrower][liquidator]) {\n revert LiquidationNotAllowed(borrower, liquidator);\n }\n }\n\n function validateTreasuryPercentMantissa(uint256 treasuryPercentMantissa_) internal view {\n uint256 maxTreasuryPercentMantissa = comptroller.liquidationIncentiveMantissa() - MANTISSA_ONE;\n if (treasuryPercentMantissa_ > maxTreasuryPercentMantissa) {\n revert TreasuryPercentTooHigh(maxTreasuryPercentMantissa, treasuryPercentMantissa_);\n }\n }\n\n /// @dev Checks liquidation action in comptroller and vaiDebt with minLiquidatableVAI threshold\n function _checkForceVAILiquidate(address vToken_, address borrower_) private view {\n uint256 _vaiDebt = vaiController.getVAIRepayAmount(borrower_);\n bool _isVAILiquidationPaused = comptroller.actionPaused(address(vaiController), IComptroller.Action.LIQUIDATE);\n bool _isForcedLiquidationEnabled = comptroller.isForcedLiquidationEnabled(vToken_);\n if (\n _isForcedLiquidationEnabled ||\n _isVAILiquidationPaused ||\n !forceVAILiquidate ||\n _vaiDebt < minLiquidatableVAI ||\n vToken_ == address(vaiController)\n ) return;\n revert VAIDebtTooHigh(_vaiDebt, minLiquidatableVAI);\n }\n\n function _setProtocolShareReserve(address protocolShareReserve_) internal {\n ensureNonzeroAddress(protocolShareReserve_);\n emit NewProtocolShareReserve(protocolShareReserve, protocolShareReserve_);\n protocolShareReserve = protocolShareReserve_;\n }\n\n /**\n * @notice Sets the threshold for minimum amount of vaiLiquidate\n * @param minLiquidatableVAI_ New address for the access control\n */\n function setMinLiquidatableVAI(uint256 minLiquidatableVAI_) external {\n _checkAccessAllowed(\"setMinLiquidatableVAI(uint256)\");\n emit NewMinLiquidatableVAI(minLiquidatableVAI, minLiquidatableVAI_);\n minLiquidatableVAI = minLiquidatableVAI_;\n }\n\n /**\n * @notice Length of the pendingRedeem array to be consider while redeeming in Liquidation transaction\n * @param newLength_ Length of the chunk\n */\n function setPendingRedeemChunkLength(uint256 newLength_) external {\n _checkAccessAllowed(\"setPendingRedeemChunkLength(uint256)\");\n require(newLength_ > 0, \"Invalid chunk size\");\n emit NewPendingRedeemChunkLength(pendingRedeemChunkLength, newLength_);\n pendingRedeemChunkLength = newLength_;\n }\n\n /**\n * @notice Pause Force Liquidation of VAI\n */\n function pauseForceVAILiquidate() external {\n _checkAccessAllowed(\"pauseForceVAILiquidate()\");\n require(forceVAILiquidate, \"Force Liquidation of VAI is already Paused\");\n forceVAILiquidate = false;\n emit ForceVAILiquidationPaused(msg.sender);\n }\n\n /**\n * @notice Resume Force Liquidation of VAI\n */\n function resumeForceVAILiquidate() external {\n _checkAccessAllowed(\"resumeForceVAILiquidate()\");\n require(!forceVAILiquidate, \"Force Liquidation of VAI is already resumed\");\n forceVAILiquidate = true;\n emit ForceVAILiquidationResumed(msg.sender);\n }\n\n function renounceOwnership() public override {}\n}\n" + }, + "contracts/Liquidator/LiquidatorStorage.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\ncontract LiquidatorStorage {\n /* State */\n\n /// @notice Percent of seized amount that goes to treasury.\n uint256 public treasuryPercentMantissa;\n\n /// @notice Mapping of addresses allowed to liquidate an account if liquidationRestricted[borrower] == true\n mapping(address => mapping(address => bool)) public allowedLiquidatorsByAccount;\n\n /// @notice Whether the liquidations are restricted to enabled allowedLiquidatorsByAccount addresses only\n mapping(address => bool) public liquidationRestricted;\n\n /// @notice minimum amount of VAI liquidation threshold\n uint256 public minLiquidatableVAI;\n\n /// @notice check for liquidation of VAI\n bool public forceVAILiquidate;\n\n /// @notice assests whose redeem is pending to reduce reserves\n address[] public pendingRedeem;\n\n /// @notice protocol share reserve contract address\n address public protocolShareReserve;\n\n /// @dev Size of chunk to consider when redeeming underlying at the time of liquidation\n uint256 internal pendingRedeemChunkLength;\n\n /// @notice gap to prevent collision in inheritance\n uint256[49] private __gap;\n}\n" + }, + "contracts/PegStability/IVAI.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IVAI {\n function balanceOf(address usr) external returns (uint256);\n\n function transferFrom(address src, address dst, uint amount) external returns (bool);\n\n function mint(address usr, uint wad) external;\n\n function burn(address usr, uint wad) external;\n}\n" + }, + "contracts/PegStability/PegStability.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\nimport { IVAI } from \"./IVAI.sol\";\n\n/**\n * @title Peg Stability Contract.\n * @notice Contract for swapping stable token for VAI token and vice versa to maintain the peg stability between them.\n * @author Venus Protocol\n */\ncontract PegStability is AccessControlledV8, ReentrancyGuardUpgradeable {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n // Helper enum for calculation of the fee.\n enum FeeDirection {\n IN,\n OUT\n }\n\n /// @notice The divisor used to convert fees to basis points.\n uint256 public constant BASIS_POINTS_DIVISOR = 10000;\n\n /// @notice The mantissa value representing 1 (used for calculations).\n uint256 public constant MANTISSA_ONE = 1e18;\n\n /// @notice The value representing one dollar in the stable token.\n /// @dev Our oracle is returning amount depending on the number of decimals of the stable token. (36 - asset_decimals) E.g. 8 decimal asset = 1e28.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n uint256 public immutable ONE_DOLLAR;\n\n /// @notice VAI token contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n IVAI public immutable VAI;\n\n /// @notice The address of the stable token contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable STABLE_TOKEN_ADDRESS;\n\n /// @notice The address of ResilientOracle contract wrapped in its interface.\n ResilientOracleInterface public oracle;\n\n /// @notice The address of the Venus Treasury contract.\n address public venusTreasury;\n\n /// @notice The incoming stableCoin fee. (Fee for swapStableForVAI).\n uint256 public feeIn;\n\n /// @notice The outgoing stableCoin fee. (Fee for swapVAIForStable).\n uint256 public feeOut;\n\n /// @notice The maximum amount of VAI that can be minted through this contract.\n uint256 public vaiMintCap;\n\n /// @notice The total amount of VAI minted through this contract.\n uint256 public vaiMinted;\n\n /// @notice A flag indicating whether the contract is currently paused or not.\n bool public isPaused;\n\n /// @notice Event emitted when contract is paused.\n event PSMPaused(address indexed admin);\n\n /// @notice Event emitted when the contract is resumed after pause.\n event PSMResumed(address indexed admin);\n\n /// @notice Event emitted when feeIn state var is modified.\n event FeeInChanged(uint256 oldFeeIn, uint256 newFeeIn);\n\n /// @notice Event emitted when feeOut state var is modified.\n event FeeOutChanged(uint256 oldFeeOut, uint256 newFeeOut);\n\n /// @notice Event emitted when vaiMintCap state var is modified.\n event VAIMintCapChanged(uint256 oldCap, uint256 newCap);\n\n /// @notice Event emitted when venusTreasury state var is modified.\n event VenusTreasuryChanged(address indexed oldTreasury, address indexed newTreasury);\n\n /// @notice Event emitted when oracle state var is modified.\n event OracleChanged(address indexed oldOracle, address indexed newOracle);\n\n /// @notice Event emitted when stable token is swapped for VAI.\n event StableForVAISwapped(uint256 stableIn, uint256 vaiOut, uint256 fee);\n\n /// @notice Event emitted when stable token is swapped for VAI.\n event VAIForStableSwapped(uint256 vaiBurnt, uint256 stableOut, uint256 vaiFee);\n\n /// @notice thrown when contract is in paused state\n error Paused();\n\n /// @notice thrown when attempted to pause an already paused contract\n error AlreadyPaused();\n\n /// @notice thrown when attempted to resume the contract if it is already resumed\n error NotPaused();\n\n /// @notice thrown when stable token has more than 18 decimals\n error TooManyDecimals();\n\n /// @notice thrown when fee is >= 100%\n error InvalidFee();\n\n /// @notice thrown when a zero address is passed as a function parameter\n error ZeroAddress();\n\n /// @notice thrown when a zero amount is passed as stable token amount parameter\n error ZeroAmount();\n\n /// @notice thrown when the user doesn't have enough VAI balance to provide for the amount of stable tokens he wishes to get\n error NotEnoughVAI();\n\n /// @notice thrown when the amount of VAI to be burnt exceeds the vaiMinted amount\n error VAIMintedUnderflow();\n\n /// @notice thrown when the VAI transfer to treasury fails\n error VAITransferFail();\n\n /// @notice thrown when VAI to be minted will go beyond the mintCap threshold\n error VAIMintCapReached();\n /// @notice thrown when fee calculation will result in rounding down to 0 due to stable token amount being a too small number\n error AmountTooSmall();\n\n /**\n * @dev Prevents functions to execute when contract is paused.\n */\n modifier isActive() {\n if (isPaused) revert Paused();\n _;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address stableTokenAddress_, address vaiAddress_) {\n _ensureNonzeroAddress(stableTokenAddress_);\n _ensureNonzeroAddress(vaiAddress_);\n\n uint256 decimals_ = IERC20MetadataUpgradeable(stableTokenAddress_).decimals();\n\n if (decimals_ > 18) {\n revert TooManyDecimals();\n }\n\n ONE_DOLLAR = 10 ** (36 - decimals_); // 1$ scaled to the decimals returned by our Oracle\n STABLE_TOKEN_ADDRESS = stableTokenAddress_;\n VAI = IVAI(vaiAddress_);\n _disableInitializers();\n }\n\n /**\n * @notice Initializes the contract via Proxy Contract with the required parameters.\n * @param accessControlManager_ The address of the AccessControlManager contract.\n * @param venusTreasury_ The address where fees will be sent.\n * @param oracleAddress_ The address of the ResilientOracle contract.\n * @param feeIn_ The percentage of fees to be applied to a stablecoin -> VAI swap.\n * @param feeOut_ The percentage of fees to be applied to a VAI -> stablecoin swap.\n * @param vaiMintCap_ The cap for the total amount of VAI that can be minted.\n */\n function initialize(\n address accessControlManager_,\n address venusTreasury_,\n address oracleAddress_,\n uint256 feeIn_,\n uint256 feeOut_,\n uint256 vaiMintCap_\n ) external initializer {\n _ensureNonzeroAddress(accessControlManager_);\n _ensureNonzeroAddress(venusTreasury_);\n _ensureNonzeroAddress(oracleAddress_);\n __AccessControlled_init(accessControlManager_);\n __ReentrancyGuard_init();\n\n if (feeIn_ >= BASIS_POINTS_DIVISOR || feeOut_ >= BASIS_POINTS_DIVISOR) {\n revert InvalidFee();\n }\n\n feeIn = feeIn_;\n feeOut = feeOut_;\n vaiMintCap = vaiMintCap_;\n venusTreasury = venusTreasury_;\n oracle = ResilientOracleInterface(oracleAddress_);\n }\n\n /*** Swap Functions ***/\n\n /**\n * @notice Swaps VAI for a stable token.\n * @param receiver The address where the stablecoin will be sent.\n * @param stableTknAmount The amount of stable tokens to receive.\n * @return The amount of VAI received and burnt from the sender.\n */\n // @custom:event Emits VAIForStableSwapped event.\n function swapVAIForStable(\n address receiver,\n uint256 stableTknAmount\n ) external isActive nonReentrant returns (uint256) {\n _ensureNonzeroAddress(receiver);\n _ensureNonzeroAmount(stableTknAmount);\n\n // update oracle price and calculate USD value of the stable token amount scaled in 18 decimals\n oracle.updateAssetPrice(STABLE_TOKEN_ADDRESS);\n uint256 stableTknAmountUSD = _previewTokenUSDAmount(stableTknAmount, FeeDirection.OUT);\n uint256 fee = _calculateFee(stableTknAmountUSD, FeeDirection.OUT);\n\n if (VAI.balanceOf(msg.sender) < stableTknAmountUSD + fee) {\n revert NotEnoughVAI();\n }\n if (vaiMinted < stableTknAmountUSD) {\n revert VAIMintedUnderflow();\n }\n\n unchecked {\n vaiMinted -= stableTknAmountUSD;\n }\n\n if (fee != 0) {\n bool success = VAI.transferFrom(msg.sender, venusTreasury, fee);\n if (!success) {\n revert VAITransferFail();\n }\n }\n\n VAI.burn(msg.sender, stableTknAmountUSD);\n IERC20Upgradeable(STABLE_TOKEN_ADDRESS).safeTransfer(receiver, stableTknAmount);\n emit VAIForStableSwapped(stableTknAmountUSD, stableTknAmount, fee);\n return stableTknAmountUSD;\n }\n\n /**\n * @notice Swaps stable tokens for VAI with fees.\n * @dev This function adds support to fee-on-transfer tokens. The actualTransferAmt is calculated, by recording token balance state before and after the transfer.\n * @param receiver The address that will receive the VAI tokens.\n * @param stableTknAmount The amount of stable tokens to be swapped.\n * @return Amount of VAI minted to the sender.\n */\n // @custom:event Emits StableForVAISwapped event.\n function swapStableForVAI(\n address receiver,\n uint256 stableTknAmount\n ) external isActive nonReentrant returns (uint256) {\n _ensureNonzeroAddress(receiver);\n _ensureNonzeroAmount(stableTknAmount);\n // transfer IN, supporting fee-on-transfer tokens\n uint256 balanceBefore = IERC20Upgradeable(STABLE_TOKEN_ADDRESS).balanceOf(address(this));\n IERC20Upgradeable(STABLE_TOKEN_ADDRESS).safeTransferFrom(msg.sender, address(this), stableTknAmount);\n uint256 balanceAfter = IERC20Upgradeable(STABLE_TOKEN_ADDRESS).balanceOf(address(this));\n\n //calculate actual transfered amount (in case of fee-on-transfer tokens)\n uint256 actualTransferAmt = balanceAfter - balanceBefore;\n\n // update oracle price and calculate USD value of the stable token amount scaled in 18 decimals\n oracle.updateAssetPrice(STABLE_TOKEN_ADDRESS);\n uint256 actualTransferAmtInUSD = _previewTokenUSDAmount(actualTransferAmt, FeeDirection.IN);\n\n //calculate feeIn\n uint256 fee = _calculateFee(actualTransferAmtInUSD, FeeDirection.IN);\n uint256 vaiToMint = actualTransferAmtInUSD - fee;\n\n if (vaiMinted + actualTransferAmtInUSD > vaiMintCap) {\n revert VAIMintCapReached();\n }\n unchecked {\n vaiMinted += actualTransferAmtInUSD;\n }\n\n // mint VAI to receiver\n VAI.mint(receiver, vaiToMint);\n\n // mint VAI fee to venus treasury\n if (fee != 0) {\n VAI.mint(venusTreasury, fee);\n }\n\n emit StableForVAISwapped(actualTransferAmt, vaiToMint, fee);\n return vaiToMint;\n }\n\n /*** Admin Functions ***/\n\n /**\n * @notice Pause the PSM contract.\n * @dev Reverts if the contract is already paused.\n */\n // @custom:event Emits PSMPaused event.\n function pause() external {\n _checkAccessAllowed(\"pause()\");\n if (isPaused) {\n revert AlreadyPaused();\n }\n isPaused = true;\n emit PSMPaused(msg.sender);\n }\n\n /**\n * @notice Resume the PSM contract.\n * @dev Reverts if the contract is not paused.\n */\n // @custom:event Emits PSMResumed event.\n function resume() external {\n _checkAccessAllowed(\"resume()\");\n if (!isPaused) {\n revert NotPaused();\n }\n isPaused = false;\n emit PSMResumed(msg.sender);\n }\n\n /**\n * @notice Set the fee percentage for incoming swaps.\n * @dev Reverts if the new fee percentage is invalid (greater than or equal to BASIS_POINTS_DIVISOR).\n * @param feeIn_ The new fee percentage for incoming swaps.\n */\n // @custom:event Emits FeeInChanged event.\n function setFeeIn(uint256 feeIn_) external {\n _checkAccessAllowed(\"setFeeIn(uint256)\");\n // feeIn = 10000 = 100%\n if (feeIn_ >= BASIS_POINTS_DIVISOR) {\n revert InvalidFee();\n }\n uint256 oldFeeIn = feeIn;\n feeIn = feeIn_;\n emit FeeInChanged(oldFeeIn, feeIn_);\n }\n\n /**\n * @notice Set the fee percentage for outgoing swaps.\n * @dev Reverts if the new fee percentage is invalid (greater than or equal to BASIS_POINTS_DIVISOR).\n * @param feeOut_ The new fee percentage for outgoing swaps.\n */\n // @custom:event Emits FeeOutChanged event.\n function setFeeOut(uint256 feeOut_) external {\n _checkAccessAllowed(\"setFeeOut(uint256)\");\n // feeOut = 10000 = 100%\n if (feeOut_ >= BASIS_POINTS_DIVISOR) {\n revert InvalidFee();\n }\n uint256 oldFeeOut = feeOut;\n feeOut = feeOut_;\n emit FeeOutChanged(oldFeeOut, feeOut_);\n }\n\n /**\n * @dev Set the maximum amount of VAI that can be minted through this contract.\n * @param vaiMintCap_ The new maximum amount of VAI that can be minted.\n */\n // @custom:event Emits VAIMintCapChanged event.\n function setVAIMintCap(uint256 vaiMintCap_) external {\n _checkAccessAllowed(\"setVAIMintCap(uint256)\");\n uint256 oldVAIMintCap = vaiMintCap;\n vaiMintCap = vaiMintCap_;\n emit VAIMintCapChanged(oldVAIMintCap, vaiMintCap_);\n }\n\n /**\n * @notice Set the address of the Venus Treasury contract.\n * @dev Reverts if the new address is zero.\n * @param venusTreasury_ The new address of the Venus Treasury contract.\n */\n // @custom:event Emits VenusTreasuryChanged event.\n function setVenusTreasury(address venusTreasury_) external {\n _checkAccessAllowed(\"setVenusTreasury(address)\");\n _ensureNonzeroAddress(venusTreasury_);\n address oldTreasuryAddress = venusTreasury;\n venusTreasury = venusTreasury_;\n emit VenusTreasuryChanged(oldTreasuryAddress, venusTreasury_);\n }\n\n /**\n * @notice Set the address of the ResilientOracle contract.\n * @dev Reverts if the new address is zero.\n * @param oracleAddress_ The new address of the ResilientOracle contract.\n */\n // @custom:event Emits OracleChanged event.\n function setOracle(address oracleAddress_) external {\n _checkAccessAllowed(\"setOracle(address)\");\n _ensureNonzeroAddress(oracleAddress_);\n address oldOracleAddress = address(oracle);\n oracle = ResilientOracleInterface(oracleAddress_);\n emit OracleChanged(oldOracleAddress, oracleAddress_);\n }\n\n /**\n * @dev Disabling renounceOwnership function.\n */\n function renounceOwnership() public override {}\n\n /*** Helper Functions ***/\n\n /**\n * @notice Calculates the amount of VAI that would be burnt from the user.\n * @dev This calculation might be off with a bit, if the price of the oracle for this asset is not updated in the block this function is invoked.\n * @param stableTknAmount The amount of stable tokens to be received after the swap.\n * @return The amount of VAI that would be taken from the user.\n */\n function previewSwapVAIForStable(uint256 stableTknAmount) external view returns (uint256) {\n _ensureNonzeroAmount(stableTknAmount);\n uint256 stableTknAmountUSD = _previewTokenUSDAmount(stableTknAmount, FeeDirection.OUT);\n uint256 fee = _calculateFee(stableTknAmountUSD, FeeDirection.OUT);\n\n if (vaiMinted < stableTknAmountUSD) {\n revert VAIMintedUnderflow();\n }\n\n return stableTknAmountUSD + fee;\n }\n\n /**\n * @notice Calculates the amount of VAI that would be sent to the receiver.\n * @dev This calculation might be off with a bit, if the price of the oracle for this asset is not updated in the block this function is invoked.\n * @param stableTknAmount The amount of stable tokens provided for the swap.\n * @return The amount of VAI that would be sent to the receiver.\n */\n function previewSwapStableForVAI(uint256 stableTknAmount) external view returns (uint256) {\n _ensureNonzeroAmount(stableTknAmount);\n uint256 stableTknAmountUSD = _previewTokenUSDAmount(stableTknAmount, FeeDirection.IN);\n\n //calculate feeIn\n uint256 fee = _calculateFee(stableTknAmountUSD, FeeDirection.IN);\n uint256 vaiToMint = stableTknAmountUSD - fee;\n\n if (vaiMinted + stableTknAmountUSD > vaiMintCap) {\n revert VAIMintCapReached();\n }\n\n return vaiToMint;\n }\n\n /**\n * @dev Calculates the USD value of the given amount of stable tokens depending on the swap direction.\n * @param amount The amount of stable tokens.\n * @param direction The direction of the swap.\n * @return The USD value of the given amount of stable tokens scaled by 1e18 taking into account the direction of the swap\n */\n function _previewTokenUSDAmount(uint256 amount, FeeDirection direction) internal view returns (uint256) {\n return (amount * _getPriceInUSD(direction)) / MANTISSA_ONE;\n }\n\n /**\n * @notice Get the price of stable token in USD.\n * @dev This function returns either min(1$,oraclePrice) or max(1$,oraclePrice) with a decimal scale (36 - asset_decimals). E.g. for 8 decimal token 1$ will be 1e28.\n * @param direction The direction of the swap: FeeDirection.IN or FeeDirection.OUT.\n * @return The price in USD, adjusted based on the selected direction.\n */\n function _getPriceInUSD(FeeDirection direction) internal view returns (uint256) {\n // get price with a scale = (36 - asset_decimals)\n uint256 price = oracle.getPrice(STABLE_TOKEN_ADDRESS);\n\n if (direction == FeeDirection.IN) {\n // MIN(1, price)\n return price < ONE_DOLLAR ? price : ONE_DOLLAR;\n } else {\n // MAX(1, price)\n return price > ONE_DOLLAR ? price : ONE_DOLLAR;\n }\n }\n\n /**\n * @notice Calculate the fee amount based on the input amount and fee percentage.\n * @dev Reverts if the fee percentage calculation results in rounding down to 0.\n * @param amount The input amount to calculate the fee from.\n * @param direction The direction of the fee: FeeDirection.IN or FeeDirection.OUT.\n * @return The fee amount.\n */\n function _calculateFee(uint256 amount, FeeDirection direction) internal view returns (uint256) {\n uint256 feePercent;\n if (direction == FeeDirection.IN) {\n feePercent = feeIn;\n } else {\n feePercent = feeOut;\n }\n if (feePercent == 0) {\n return 0;\n } else {\n // checking if the percent calculation will result in rounding down to 0\n if (amount * feePercent < BASIS_POINTS_DIVISOR) {\n revert AmountTooSmall();\n }\n return (amount * feePercent) / BASIS_POINTS_DIVISOR;\n }\n }\n\n /**\n * @notice Checks that the address is not the zero address.\n * @param someone The address to check.\n */\n function _ensureNonzeroAddress(address someone) private pure {\n if (someone == address(0)) revert ZeroAddress();\n }\n\n /**\n * @notice Checks that the amount passed as stable tokens is bigger than zero\n * @param amount The amount to validate\n */\n function _ensureNonzeroAmount(uint256 amount) private pure {\n if (amount == 0) revert ZeroAmount();\n }\n}\n" + }, + "contracts/Swap/interfaces/CustomErrors.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\n// **************\n// *** ERRORS ***\n// **************\n\n///@notice Error indicating that suplying to a given market failed.\nerror SupplyError(address supplier, address vToken, uint256 errorCode);\n\n///@notice Error indicating that repaying to given market failed.\nerror RepayError(address repayer, address vToken, uint256 errorCode);\n\n///@notice Error indicating wBNB address passed is not the expected one.\nerror WrongAddress(address expectedAdddress, address passedAddress);\n\n///@notice Error thrown when deadline for swap has expired\nerror SwapDeadlineExpire(uint256 deadline, uint256 timestemp);\n\n///@notice Error thrown where the input amount parameter for a token is 0\nerror InsufficientInputAmount();\n\n///@notice Error thrown when the amount out passed is 0\nerror InsufficientOutputAmount();\n\n///@notice Error thrown when the amount received from a trade is below the minimum\nerror OutputAmountBelowMinimum(uint256 amountOut, uint256 amountOutMin);\n\n///@notice Error thrown when the amount In is above the amount in maximum\nerror InputAmountAboveMaximum(uint256 amountIn, uint256 amountIntMax);\n\n///@notice Error thrown when amount is above the msg.value(amountMax)\nerror ExcessiveInputAmount(uint256 amount, uint256 amountMax);\n\n///@notice Error thrown when the given reserves are equal to 0\nerror InsufficientLiquidity();\n\n///@notice Error thrown if a zero address is passed\nerror ZeroAddress();\n\n///@notice Error thrown if two token addresses are identical\nerror IdenticalAddresses();\n\n///@notice Error thrown when the trade path[] parameter consists of only 1 token (i.e. path.length<2)\nerror InvalidPath();\n\n///@notice Error thrown when invalid vToken address is passed to swap router\nerror VTokenNotListed(address vToken);\n\n///@notice Error thrown when invalid underlying is passed as per given vToken\nerror VTokenUnderlyingInvalid(address underlying);\n\n///@notice Error thrown when swapamount is less than the amountOutmin\nerror SwapAmountLessThanAmountOutMin(uint256 swapAmount, uint256 amountOutMin);\n\n///@notice Error thrown when swapRouter's balance is less than sweep amount\nerror InsufficientBalance(uint256 sweepAmount, uint256 balance);\n\n///@notice Error thrown when safeApprove failed\nerror SafeApproveFailed();\n\n///@notice Error thrown when safeTransfer failed\nerror SafeTransferFailed();\n\n///@notice Error thrown when transferFrom failed\nerror SafeTransferFromFailed();\n\n///@notice Error thrown when safeTransferBNB failed\nerror SafeTransferBNBFailed();\n\n///@notice Error thrown when reentrant check fails\nerror ReentrantCheck();\n" + }, + "contracts/Swap/interfaces/InterfaceComptroller.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface InterfaceComptroller {\n function markets(address) external view returns (bool);\n}\n" + }, + "contracts/Swap/interfaces/IPancakePair.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IPancakePair {\n event Approval(address indexed owner, address indexed spender, uint value);\n event Transfer(address indexed from, address indexed to, uint value);\n\n function name() external pure returns (string memory);\n\n function symbol() external pure returns (string memory);\n\n function decimals() external pure returns (uint8);\n\n function totalSupply() external view returns (uint);\n\n function balanceOf(address owner) external view returns (uint);\n\n function allowance(address owner, address spender) external view returns (uint);\n\n function approve(address spender, uint value) external returns (bool);\n\n function transfer(address to, uint value) external returns (bool);\n\n function transferFrom(address from, address to, uint value) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n\n function nonces(address owner) external view returns (uint);\n\n function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;\n\n event Mint(address indexed sender, uint amount0, uint amount1);\n event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint amount0In,\n uint amount1In,\n uint amount0Out,\n uint amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint);\n\n function factory() external view returns (address);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\n\n function price0CumulativeLast() external view returns (uint);\n\n function price1CumulativeLast() external view returns (uint);\n\n function kLast() external view returns (uint);\n\n function mint(address to) external returns (uint liquidity);\n\n function burn(address to) external returns (uint amount0, uint amount1);\n\n function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;\n\n function skim(address to) external;\n\n function sync() external;\n\n function initialize(address, address) external;\n}\n" + }, + "contracts/Swap/interfaces/IPancakeSwapV2Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IPancakeSwapV2Factory {\n event PairCreated(address indexed token0, address indexed token1, address pair, uint);\n\n function feeTo() external view returns (address);\n\n function feeToSetter() external view returns (address);\n\n function getPair(address tokenA, address tokenB) external view returns (address pair);\n\n function allPairs(uint) external view returns (address pair);\n\n function allPairsLength() external view returns (uint);\n\n function createPair(address tokenA, address tokenB) external returns (address pair);\n\n function setFeeTo(address) external;\n\n function setFeeToSetter(address) external;\n}\n" + }, + "contracts/Swap/interfaces/IPancakeSwapV2Router.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IPancakeSwapV2Router {\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactTokensForTokensAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256 swapAmount);\n\n function swapExactBNBForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapExactBNBForTokensAtSupportingFee(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256 swapAmount);\n\n function swapExactTokensForBNB(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactTokensForBNBAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256 swapAmount);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapBNBForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactBNB(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactTokensForTokensAndSupply(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactTokensForTokensAndSupplyAtSupportingFee(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactBNBForTokensAndSupply(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapExactBNBForTokensAndSupplyAtSupportingFee(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapTokensForExactTokensAndSupply(\n address vTokenAddress,\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapBNBForExactTokensAndSupply(\n address vTokenAddress,\n uint256 amountOut,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapExactTokensForBNBAndSupply(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactTokensForBNBAndSupplyAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapTokensForExactBNBAndSupply(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapBNBForFullTokenDebtAndRepay(\n address vTokenAddress,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapExactTokensForTokensAndRepay(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactTokensForTokensAndRepayAtSupportingFee(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactBNBForTokensAndRepay(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapExactBNBForTokensAndRepayAtSupportingFee(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapTokensForExactTokensAndRepay(\n address vTokenAddress,\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapTokensForFullTokenDebtAndRepay(\n address vTokenAddress,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapBNBForExactTokensAndRepay(\n address vTokenAddress,\n uint256 amountOut,\n address[] calldata path,\n uint256 deadline\n ) external payable;\n\n function swapExactTokensForBNBAndRepay(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapExactTokensForBNBAndRepayAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapTokensForExactBNBAndRepay(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external;\n\n function swapTokensForFullBNBDebtAndRepay(uint256 amountInMax, address[] calldata path, uint256 deadline) external;\n}\n" + }, + "contracts/Swap/interfaces/IVBNB.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IVBNB {\n function repayBorrowBehalf(address borrower) external payable;\n\n function mint() external payable;\n\n function balanceOf(address owner) external view returns (uint256);\n}\n" + }, + "contracts/Swap/interfaces/IVtoken.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IVToken {\n function mintBehalf(address receiver, uint mintAmount) external returns (uint);\n\n function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);\n\n function borrowBalanceCurrent(address account) external returns (uint);\n\n function underlying() external returns (address);\n}\n" + }, + "contracts/Swap/interfaces/IWBNB.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IWBNB {\n function deposit() external payable;\n\n function transfer(address to, uint value) external returns (bool);\n\n function withdraw(uint) external;\n\n function balanceOf(address owner) external view returns (uint256 balance);\n}\n" + }, + "contracts/Swap/IRouterHelper.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface IRouterHelper {\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);\n}\n" + }, + "contracts/Swap/lib/PancakeLibrary.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.8.25;\n\nimport \"../interfaces/IPancakePair.sol\";\nimport \"../interfaces/CustomErrors.sol\";\n\nlibrary PancakeLibrary {\n /**\n * @notice Used to handle return values from pairs sorted in this order\n * @param tokenA The address of token A\n * @param tokenB The address of token B\n * @return token0 token1 Sorted token addresses\n **/\n function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n if (tokenA == tokenB) {\n revert IdenticalAddresses();\n }\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n if (token0 == address(0)) {\n revert ZeroAddress();\n }\n }\n\n /**\n * @notice Calculates the CREATE2 address for a pair without making any external calls\n * @param factory Address of the pancake swap factory\n * @param tokenA The address of token A\n * @param tokenB The address of token B\n * @return pair Address for a pair\n **/\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = sortTokens(tokenA, tokenB);\n pair = address(\n uint160(\n uint256(\n keccak256(\n abi.encodePacked(\n hex\"ff\",\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex\"00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5\" // init code hash\n )\n )\n )\n )\n );\n }\n\n /**\n * @notice Fetches and sorts the reserves for a pair\n * @param factory Address of the pancake swap factory\n * @param tokenA The address of token A\n * @param tokenB The address of token B\n * @return reserveA reserveB Reserves for the token A and token B\n **/\n function getReserves(\n address factory,\n address tokenA,\n address tokenB\n ) internal view returns (uint256 reserveA, uint256 reserveB) {\n (address token0, ) = sortTokens(tokenA, tokenB);\n address pairAddress = pairFor(factory, tokenA, tokenB);\n (uint256 reserve0, uint256 reserve1, ) = IPancakePair(pairAddress).getReserves();\n (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n }\n\n /**\n * @notice Given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n * @param amountA The amount of token A\n * @param reserveA The amount of reserves for token A before swap\n * @param reserveB The amount of reserves for token B before swap\n * @return amountB An equivalent amount of the token B\n **/\n function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) {\n if (amountA == 0) {\n revert InsufficientInputAmount();\n } else if (reserveA == 0 || reserveB == 0) {\n revert InsufficientLiquidity();\n }\n amountB = (amountA * reserveB) / reserveA;\n }\n\n /**\n * @notice Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n * @param amountIn The amount of token A need to swap\n * @param reserveIn The amount of reserves for token A before swap\n * @param reserveOut The amount of reserves for token B after swap\n * @return amountOut The maximum output amount of the token B\n **/\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) internal pure returns (uint256 amountOut) {\n if (amountIn == 0) {\n revert InsufficientInputAmount();\n } else if (reserveIn == 0 || reserveOut == 0) {\n revert InsufficientLiquidity();\n }\n uint256 amountInWithFee = amountIn * 9975;\n uint256 numerator = amountInWithFee * reserveOut;\n uint256 denominator = (reserveIn * 10000) + amountInWithFee;\n amountOut = numerator / denominator;\n }\n\n /**\n * @notice Given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n * @param amountOut The amount of token B after swap\n * @param reserveIn The amount of reserves for token A before swap\n * @param reserveOut The amount of reserves for token B after swap\n * @return amountIn Required input amount of the token A\n **/\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) internal pure returns (uint256 amountIn) {\n if (amountOut == 0) {\n revert InsufficientOutputAmount();\n } else if (reserveIn == 0 || reserveOut == 0) {\n revert InsufficientLiquidity();\n }\n uint256 numerator = reserveIn * amountOut * 10000;\n uint256 denominator = (reserveOut - amountOut) * 9975;\n amountIn = (numerator / denominator) + 1;\n }\n\n /**\n * @notice Performs chained getAmountOut calculations on any number of pairs\n * @param factory Address of the pancake swap factory\n * @param amountIn The amount of tokens to swap.\n * @param path Array with addresses of the underlying assets to be swapped\n * @return amounts Array of amounts after performing swap for respective pairs in path\n **/\n function getAmountsOut(\n address factory,\n uint256 amountIn,\n address[] memory path\n ) internal view returns (uint256[] memory amounts) {\n if (path.length <= 1) {\n revert InvalidPath();\n }\n amounts = new uint256[](path.length);\n amounts[0] = amountIn;\n for (uint256 i; i < path.length - 1; ) {\n (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);\n amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);\n unchecked {\n i += 1;\n }\n }\n }\n\n /**\n * @notice Performs chained getAmountIn calculations on any number of pairs\n * @param factory Address of the pancake swap factory\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped\n * @return amounts Array of amounts after performing swap for respective pairs in path\n **/\n function getAmountsIn(\n address factory,\n uint256 amountOut,\n address[] memory path\n ) internal view returns (uint256[] memory amounts) {\n if (path.length <= 1) {\n revert InvalidPath();\n }\n amounts = new uint256[](path.length);\n amounts[amounts.length - 1] = amountOut;\n for (uint256 i = path.length - 1; i > 0; ) {\n (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);\n amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);\n unchecked {\n i -= 1;\n }\n }\n }\n}\n" + }, + "contracts/Swap/lib/TransferHelper.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.8.25;\n\nimport \"../interfaces/CustomErrors.sol\";\n\n// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false\nlibrary TransferHelper {\n /**\n * @dev `value` as the allowance of `spender` over the caller's tokens.\n * @param token Address of the token\n * @param to Address of the spender\n * @param value Amount as allowance\n */\n function safeApprove(address token, address to, uint256 value) internal {\n // bytes4(keccak256(bytes('approve(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));\n if (!(success && (data.length == 0 || abi.decode(data, (bool))))) {\n revert SafeApproveFailed();\n }\n }\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 * @param token Address of the token\n * @param to Address of the receiver\n * @param value Amount need to transfer\n */\n function safeTransfer(address token, address to, uint256 value) internal {\n // bytes4(keccak256(bytes('transfer(address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));\n if (!(success && (data.length == 0 || abi.decode(data, (bool))))) {\n revert SafeTransferFailed();\n }\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 * @param token Address of the token\n * @param from Address of the asset'sowner\n * @param to Address of the receiver\n * @param value Amount need to transfer\n */\n function safeTransferFrom(address token, address from, address to, uint256 value) internal {\n // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));\n (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));\n if (!(success && (data.length == 0 || abi.decode(data, (bool))))) {\n revert SafeTransferFromFailed();\n }\n }\n\n /**\n * @dev Transfer `value` amount of `BNB` from the calling contract to `to`. If `token` returns no value,\n * non-reverting calls are assumed to be successful.\n * @param to Address of the receiver\n * @param value Amount need to transfer\n */\n function safeTransferBNB(address to, uint256 value) internal {\n (bool success, ) = to.call{ value: value }(new bytes(0));\n if (!success) {\n revert SafeTransferBNBFailed();\n }\n }\n}\n" + }, + "contracts/Swap/RouterHelper.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"./lib/PancakeLibrary.sol\";\nimport \"./interfaces/IWBNB.sol\";\nimport \"./lib/TransferHelper.sol\";\n\nimport \"./interfaces/CustomErrors.sol\";\nimport \"./IRouterHelper.sol\";\n\nabstract contract RouterHelper is IRouterHelper {\n /// @notice Select the type of Token for which either a supporting fee would be deducted or not at the time of transfer.\n enum TypesOfTokens {\n NON_SUPPORTING_FEE,\n SUPPORTING_FEE\n }\n\n /// @notice Address of WBNB contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WBNB;\n\n /// @notice Address of pancake swap factory contract.\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable factory;\n\n // **************\n // *** EVENTS ***\n // **************\n /// @notice This event is emitted whenever a successful swap (tokenA -> tokenB) occurs\n event SwapTokensForTokens(address indexed swapper, address[] indexed path, uint256[] indexed amounts);\n\n /// @notice This event is emitted whenever a successful swap (tokenA -> tokenB) occurs\n event SwapTokensForTokensAtSupportingFee(address indexed swapper, address[] indexed path);\n\n /// @notice This event is emitted whenever a successful swap (BNB -> token) occurs\n event SwapBnbForTokens(address indexed swapper, address[] indexed path, uint256[] indexed amounts);\n\n /// @notice This event is emitted whenever a successful swap (BNB -> token) occurs\n event SwapBnbForTokensAtSupportingFee(address indexed swapper, address[] indexed path);\n\n /// @notice This event is emitted whenever a successful swap (token -> BNB) occurs\n event SwapTokensForBnb(address indexed swapper, address[] indexed path, uint256[] indexed amounts);\n\n /// @notice This event is emitted whenever a successful swap (token -> BNB) occurs\n event SwapTokensForBnbAtSupportingFee(address indexed swapper, address[] indexed path);\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address WBNB_, address factory_) {\n if (WBNB_ == address(0) || factory_ == address(0)) {\n revert ZeroAddress();\n }\n WBNB = WBNB_;\n factory = factory_;\n }\n\n /**\n * @notice Perform swap on the path(pairs)\n * @param amounts Araay of amounts of tokens after performing the swap\n * @param path Array with addresses of the underlying assets to be swapped\n * @param _to Recipient of the output tokens.\n */\n function _swap(uint256[] memory amounts, address[] memory path, address _to) internal virtual {\n for (uint256 i; i < path.length - 1; ) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0, ) = PancakeLibrary.sortTokens(input, output);\n uint256 amountOut = amounts[i + 1];\n (uint256 amount0Out, uint256 amount1Out) = input == token0\n ? (uint256(0), amountOut)\n : (amountOut, uint256(0));\n address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to;\n IPancakePair(PancakeLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));\n unchecked {\n i += 1;\n }\n }\n }\n\n // **** SWAP (supporting fee-on-transfer tokens) ****\n\n /**\n * @notice Perform swap on the path(pairs) for supporting fee\n * @dev requires the initial amount to have already been sent to the first pair\n * @param path Array with addresses of the underlying assets to be swapped\n * @param _to Recipient of the output tokens.\n */\n function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {\n for (uint256 i; i < path.length - 1; ) {\n (address input, address output) = (path[i], path[i + 1]);\n (address token0, ) = PancakeLibrary.sortTokens(input, output);\n IPancakePair pair = IPancakePair(PancakeLibrary.pairFor(factory, input, output));\n uint256 amountInput;\n uint256 amountOutput;\n {\n // scope to avoid stack too deep errors\n (uint256 reserve0, uint256 reserve1, ) = pair.getReserves();\n (uint256 reserveInput, uint256 reserveOutput) = input == token0\n ? (reserve0, reserve1)\n : (reserve1, reserve0);\n\n uint256 balance = IERC20(input).balanceOf(address(pair));\n amountInput = balance - reserveInput;\n amountOutput = PancakeLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);\n }\n (uint256 amount0Out, uint256 amount1Out) = input == token0\n ? (uint256(0), amountOutput)\n : (amountOutput, uint256(0));\n address to = i < path.length - 2 ? PancakeLibrary.pairFor(factory, output, path[i + 2]) : _to;\n pair.swap(amount0Out, amount1Out, to, new bytes(0));\n unchecked {\n i += 1;\n }\n }\n }\n\n /**\n * @notice Swap token A for token B\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param swapFor TypesOfTokens, either supporing fee or non supporting fee\n * @return amounts Array of amounts after performing swap for respective pairs in path\n */\n function _swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n TypesOfTokens swapFor\n ) internal returns (uint256[] memory amounts) {\n address pairAddress = PancakeLibrary.pairFor(factory, path[0], path[1]);\n if (swapFor == TypesOfTokens.NON_SUPPORTING_FEE) {\n amounts = PancakeLibrary.getAmountsOut(factory, amountIn, path);\n if (amounts[amounts.length - 1] < amountOutMin) {\n revert OutputAmountBelowMinimum(amounts[amounts.length - 1], amountOutMin);\n }\n TransferHelper.safeTransferFrom(path[0], msg.sender, pairAddress, amounts[0]);\n _swap(amounts, path, to);\n emit SwapTokensForTokens(msg.sender, path, amounts);\n } else {\n TransferHelper.safeTransferFrom(path[0], msg.sender, pairAddress, amountIn);\n _swapSupportingFeeOnTransferTokens(path, to);\n emit SwapTokensForTokensAtSupportingFee(msg.sender, path);\n }\n }\n\n /**\n * @notice Swap exact BNB for token\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param swapFor TypesOfTokens, either supporing fee or non supporting fee\n * @return amounts Array of amounts after performing swap for respective pairs in path\n */\n function _swapExactBNBForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n TypesOfTokens swapFor\n ) internal returns (uint256[] memory amounts) {\n address wBNBAddress = WBNB;\n if (path[0] != wBNBAddress) {\n revert WrongAddress(wBNBAddress, path[0]);\n }\n IWBNB(wBNBAddress).deposit{ value: msg.value }();\n TransferHelper.safeTransfer(wBNBAddress, PancakeLibrary.pairFor(factory, path[0], path[1]), msg.value);\n if (swapFor == TypesOfTokens.NON_SUPPORTING_FEE) {\n amounts = PancakeLibrary.getAmountsOut(factory, msg.value, path);\n if (amounts[amounts.length - 1] < amountOutMin) {\n revert OutputAmountBelowMinimum(amounts[amounts.length - 1], amountOutMin);\n }\n _swap(amounts, path, to);\n emit SwapBnbForTokens(msg.sender, path, amounts);\n } else {\n _swapSupportingFeeOnTransferTokens(path, to);\n emit SwapBnbForTokensAtSupportingFee(msg.sender, path);\n }\n }\n\n /**\n * @notice Swap token A for BNB\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of BNB to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param swapFor TypesOfTokens, either supporing fee or non supporting fee\n * @return amounts Array of amounts after performing swap for respective pairs in path\n */\n function _swapExactTokensForBNB(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n TypesOfTokens swapFor\n ) internal returns (uint256[] memory amounts) {\n if (path[path.length - 1] != WBNB) {\n revert WrongAddress(WBNB, path[path.length - 1]);\n }\n uint256 WBNBAmount;\n if (swapFor == TypesOfTokens.NON_SUPPORTING_FEE) {\n amounts = PancakeLibrary.getAmountsOut(factory, amountIn, path);\n if (amounts[amounts.length - 1] < amountOutMin) {\n revert OutputAmountBelowMinimum(amounts[amounts.length - 1], amountOutMin);\n }\n TransferHelper.safeTransferFrom(\n path[0],\n msg.sender,\n PancakeLibrary.pairFor(factory, path[0], path[1]),\n amounts[0]\n );\n _swap(amounts, path, address(this));\n WBNBAmount = amounts[amounts.length - 1];\n } else {\n uint256 balanceBefore = IWBNB(WBNB).balanceOf(address(this));\n TransferHelper.safeTransferFrom(\n path[0],\n msg.sender,\n PancakeLibrary.pairFor(factory, path[0], path[1]),\n amountIn\n );\n _swapSupportingFeeOnTransferTokens(path, address(this));\n uint256 balanceAfter = IWBNB(WBNB).balanceOf(address(this));\n WBNBAmount = balanceAfter - balanceBefore;\n }\n IWBNB(WBNB).withdraw(WBNBAmount);\n if (to != address(this)) {\n TransferHelper.safeTransferBNB(to, WBNBAmount);\n }\n if (swapFor == TypesOfTokens.NON_SUPPORTING_FEE) {\n emit SwapTokensForBnb(msg.sender, path, amounts);\n } else {\n emit SwapTokensForBnbAtSupportingFee(msg.sender, path);\n }\n }\n\n /**\n * @notice Swap token A for exact amount of token B\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @return amounts Array of amounts after performing swap for respective pairs in path\n **/\n function _swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to\n ) internal returns (uint256[] memory amounts) {\n amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path);\n if (amounts[0] > amountInMax) {\n revert InputAmountAboveMaximum(amounts[0], amountInMax);\n }\n TransferHelper.safeTransferFrom(\n path[0],\n msg.sender,\n PancakeLibrary.pairFor(factory, path[0], path[1]),\n amounts[0]\n );\n _swap(amounts, path, to);\n emit SwapTokensForTokens(msg.sender, path, amounts);\n }\n\n /**\n * @notice Swap BNB for exact amount of token B\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @return amounts Array of amounts after performing swap for respective pairs in path\n **/\n function _swapBNBForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to\n ) internal returns (uint256[] memory amounts) {\n if (path[0] != WBNB) {\n revert WrongAddress(WBNB, path[0]);\n }\n amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path);\n if (amounts[0] > msg.value) {\n revert ExcessiveInputAmount(amounts[0], msg.value);\n }\n IWBNB(WBNB).deposit{ value: amounts[0] }();\n TransferHelper.safeTransfer(WBNB, PancakeLibrary.pairFor(factory, path[0], path[1]), amounts[0]);\n _swap(amounts, path, to);\n // refund dust BNB, if any\n if (msg.value > amounts[0]) TransferHelper.safeTransferBNB(msg.sender, msg.value - amounts[0]);\n emit SwapBnbForTokens(msg.sender, path, amounts);\n }\n\n /**\n * @notice Swap token A for exact BNB\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @return amounts Array of amounts after performing swap for respective pairs in path\n **/\n function _swapTokensForExactBNB(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to\n ) internal returns (uint256[] memory amounts) {\n if (path[path.length - 1] != WBNB) {\n revert WrongAddress(WBNB, path[path.length - 1]);\n }\n amounts = PancakeLibrary.getAmountsIn(factory, amountOut, path);\n if (amounts[0] > amountInMax) {\n revert InputAmountAboveMaximum(amounts[amounts.length - 1], amountInMax);\n }\n TransferHelper.safeTransferFrom(\n path[0],\n msg.sender,\n PancakeLibrary.pairFor(factory, path[0], path[1]),\n amounts[0]\n );\n _swap(amounts, path, address(this));\n IWBNB(WBNB).withdraw(amounts[amounts.length - 1]);\n if (to != address(this)) {\n TransferHelper.safeTransferBNB(to, amounts[amounts.length - 1]);\n }\n emit SwapTokensForBnb(msg.sender, path, amounts);\n }\n\n // **** LIBRARY FUNCTIONS ****\n\n /**\n * @notice Given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n * @param amountA The amount of token A\n * @param reserveA The amount of reserves for token A before swap\n * @param reserveB The amount of reserves for token B before swap\n * @return amountB An equivalent amount of the token B\n **/\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) external pure virtual override returns (uint256 amountB) {\n return PancakeLibrary.quote(amountA, reserveA, reserveB);\n }\n\n /**\n * @notice Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n * @param amountIn The amount of token A need to swap\n * @param reserveIn The amount of reserves for token A before swap\n * @param reserveOut The amount of reserves for token B after swap\n * @return amountOut The maximum output amount of the token B\n **/\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure virtual override returns (uint256 amountOut) {\n return PancakeLibrary.getAmountOut(amountIn, reserveIn, reserveOut);\n }\n\n /**\n * @notice Given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n * @param amountOut The amount of token B after swap\n * @param reserveIn The amount of reserves for token A before swap\n * @param reserveOut The amount of reserves for token B after swap\n * @return amountIn Required input amount of the token A\n **/\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure virtual override returns (uint256 amountIn) {\n return PancakeLibrary.getAmountIn(amountOut, reserveIn, reserveOut);\n }\n\n /**\n * @notice performs chained getAmountOut calculations on any number of pairs.\n * @param amountIn The amount of tokens to swap.\n * @param path Array with addresses of the underlying assets to be swapped.\n */\n function getAmountsOut(\n uint256 amountIn,\n address[] memory path\n ) external view virtual override returns (uint256[] memory amounts) {\n return PancakeLibrary.getAmountsOut(factory, amountIn, path);\n }\n\n /**\n * @notice performs chained getAmountIn calculations on any number of pairs.\n * @param amountOut amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped.\n */\n function getAmountsIn(\n uint256 amountOut,\n address[] memory path\n ) external view virtual override returns (uint256[] memory amounts) {\n return PancakeLibrary.getAmountsIn(factory, amountOut, path);\n }\n}\n" + }, + "contracts/Swap/SwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport \"./interfaces/IPancakeSwapV2Router.sol\";\nimport \"./interfaces/IVtoken.sol\";\nimport \"./RouterHelper.sol\";\nimport \"./interfaces/IVBNB.sol\";\nimport \"./interfaces/IVtoken.sol\";\nimport \"./interfaces/InterfaceComptroller.sol\";\n\n/**\n * @title Venus's Pancake Swap Integration Contract\n * @notice This contracts allows users to swap a token for another one and supply/repay with the latter.\n * @dev For all functions that do not swap native BNB, user must approve this contract with the amount, prior the calling the swap function.\n * @author 0xlucian\n */\n\ncontract SwapRouter is Ownable2Step, RouterHelper, IPancakeSwapV2Router {\n using SafeERC20 for IERC20;\n\n address public immutable comptrollerAddress;\n\n uint256 private constant _NOT_ENTERED = 1;\n\n uint256 private constant _ENTERED = 2;\n\n address public vBNBAddress;\n\n /**\n * @dev Guard variable for re-entrancy checks\n */\n uint256 internal _status;\n\n // ***************\n // ** MODIFIERS **\n // ***************\n modifier ensure(uint256 deadline) {\n if (deadline < block.timestamp) {\n revert SwapDeadlineExpire(deadline, block.timestamp);\n }\n _;\n }\n\n modifier ensurePath(address[] calldata path) {\n if (path.length < 2) {\n revert InvalidPath();\n }\n _;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n */\n modifier nonReentrant() {\n if (_status == _ENTERED) {\n revert ReentrantCheck();\n }\n _status = _ENTERED;\n _;\n _status = _NOT_ENTERED;\n }\n\n /// @notice event emitted on sweep token success\n event SweepToken(address indexed token, address indexed to, uint256 sweepAmount);\n\n /// @notice event emitted on vBNBAddress update\n event VBNBAddressUpdated(address indexed oldAddress, address indexed newAddress);\n\n // *********************\n // **** CONSTRUCTOR ****\n // *********************\n\n /// @notice Constructor for the implementation contract. Sets immutable variables.\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address WBNB_,\n address factory_,\n address _comptrollerAddress,\n address _vBNBAddress\n ) RouterHelper(WBNB_, factory_) {\n if (_comptrollerAddress == address(0) || _vBNBAddress == address(0)) {\n revert ZeroAddress();\n }\n comptrollerAddress = _comptrollerAddress;\n _status = _NOT_ENTERED;\n vBNBAddress = _vBNBAddress;\n }\n\n receive() external payable {\n assert(msg.sender == WBNB); // only accept BNB via fallback from the WBNB contract\n }\n\n // ****************************\n // **** EXTERNAL FUNCTIONS ****\n // ****************************\n\n /**\n * @notice Setter for the vBNB address.\n * @param _vBNBAddress Address of the BNB vToken to update.\n */\n function setVBNBAddress(address _vBNBAddress) external onlyOwner {\n if (_vBNBAddress == address(0)) {\n revert ZeroAddress();\n }\n\n _isVTokenListed(_vBNBAddress);\n\n address oldAddress = vBNBAddress;\n vBNBAddress = _vBNBAddress;\n\n emit VBNBAddressUpdated(oldAddress, vBNBAddress);\n }\n\n /**\n * @notice Swap token A for token B and supply to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n */\n function swapExactTokensForTokensAndSupply(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap deflationary (a small amount of fee is deducted at the time of transfer of token) token A for token B and supply to a Venus market.\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n */\n function swapExactTokensForTokensAndSupplyAtSupportingFee(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, address(this));\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for another token and supply to a Venus market\n * @dev The amount to be swapped is obtained from the msg.value, since we are swapping BNB\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactBNBForTokensAndSupply(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactBNBForTokens(amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for another deflationary token (a small amount of fee is deducted at the time of transfer of token) and supply to a Venus market\n * @dev The amount to be swapped is obtained from the msg.value, since we are swapping BNB\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactBNBForTokensAndSupplyAtSupportingFee(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactBNBForTokens(amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, address(this));\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap tokens for Exact tokens and supply to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForExactTokensAndSupply(\n address vTokenAddress,\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapTokensForExactTokens(amountOut, amountInMax, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for Exact tokens and supply to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapBNBForExactTokensAndSupply(\n address vTokenAddress,\n uint256 amountOut,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapBNBForExactTokens(amountOut, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _supply(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap Exact tokens for BNB and supply to a Venus market\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactTokensForBNBAndSupply(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapExactTokensForBNB(amountIn, amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n _mintVBNBandTransfer(swapAmount);\n }\n\n /**\n * @notice Swap Exact deflationary tokens (a small amount of fee is deducted at the time of transfer of tokens) for BNB and supply to a Venus market\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactTokensForBNBAndSupplyAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapExactTokensForBNB(amountIn, amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n if (swapAmount < amountOutMin) {\n revert SwapAmountLessThanAmountOutMin(swapAmount, amountOutMin);\n }\n _mintVBNBandTransfer(swapAmount);\n }\n\n /**\n * @notice Swap tokens for Exact BNB and supply to a Venus market\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForExactBNBAndSupply(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapTokensForExactBNB(amountOut, amountInMax, path, address(this));\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n _mintVBNBandTransfer(swapAmount);\n }\n\n /**\n * @notice Swap token A for token B and repay a borrow from a Venus market\n * @param vTokenAddress The address of the vToken contract to repay.\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive (and repay)\n */\n function swapExactTokensForTokensAndRepay(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap deflationary token (a small amount of fee is deducted at the time of transfer of token) token A for token B and repay a borrow from a Venus market\n * @param vTokenAddress The address of the vToken contract to repay.\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive (and repay)\n */\n function swapExactTokensForTokensAndRepayAtSupportingFee(\n address vTokenAddress,\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, address(this));\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for another token and repay a borrow from a Venus market\n * @dev The amount to be swapped is obtained from the msg.value, since we are swapping BNB\n * @param vTokenAddress The address of the vToken contract to repay.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered so the swap path tokens are listed first and last asset is the token we receive\n */\n function swapExactBNBForTokensAndRepay(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactBNBForTokens(amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for another deflationary token (a small amount of fee is deducted at the time of transfer of token) and repay a borrow from a Venus market\n * @dev The amount to be swapped is obtained from the msg.value, since we are swapping BNB\n * @param vTokenAddress The address of the vToken contract to repay.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered so the swap path tokens are listed first and last asset is the token we receive\n */\n function swapExactBNBForTokensAndRepayAtSupportingFee(\n address vTokenAddress,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapExactBNBForTokens(amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, address(this));\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap tokens for Exact tokens and repay to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForExactTokensAndRepay(\n address vTokenAddress,\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapTokensForExactTokens(amountOut, amountInMax, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap tokens for full tokens debt and repay to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForFullTokenDebtAndRepay(\n address vTokenAddress,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n uint256 amountOut = IVToken(vTokenAddress).borrowBalanceCurrent(msg.sender);\n _swapTokensForExactTokens(amountOut, amountInMax, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for Exact tokens and repay to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapBNBForExactTokensAndRepay(\n address vTokenAddress,\n uint256 amountOut,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n _swapBNBForExactTokens(amountOut, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap BNB for Exact tokens and repay to a Venus market\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapBNBForFullTokenDebtAndRepay(\n address vTokenAddress,\n address[] calldata path,\n uint256 deadline\n ) external payable override nonReentrant ensure(deadline) ensurePath(path) {\n _ensureVTokenChecks(vTokenAddress, path[path.length - 1]);\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(address(this));\n uint256 amountOut = IVToken(vTokenAddress).borrowBalanceCurrent(msg.sender);\n _swapBNBForExactTokens(amountOut, path, address(this));\n uint256 swapAmount = _getSwapAmount(lastAsset, balanceBefore);\n _repay(lastAsset, vTokenAddress, swapAmount);\n }\n\n /**\n * @notice Swap Exact tokens for BNB and repay to a Venus market\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactTokensForBNBAndRepay(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapExactTokensForBNB(amountIn, amountOutMin, path, address(this), TypesOfTokens.NON_SUPPORTING_FEE);\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n IVBNB(vBNBAddress).repayBorrowBehalf{ value: swapAmount }(msg.sender);\n }\n\n /**\n * @notice Swap Exact deflationary tokens (a small amount of fee is deducted at the time of transfer of tokens) for BNB and repay to a Venus market\n * @param amountIn The amount of tokens to swap.\n * @param amountOutMin Minimum amount of tokens to receive.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapExactTokensForBNBAndRepayAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapExactTokensForBNB(amountIn, amountOutMin, path, address(this), TypesOfTokens.SUPPORTING_FEE);\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n if (swapAmount < amountOutMin) {\n revert SwapAmountLessThanAmountOutMin(swapAmount, amountOutMin);\n }\n IVBNB(vBNBAddress).repayBorrowBehalf{ value: swapAmount }(msg.sender);\n }\n\n /**\n * @notice Swap tokens for Exact BNB and repay to a Venus market\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForExactBNBAndRepay(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n _swapTokensForExactBNB(amountOut, amountInMax, path, address(this));\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n IVBNB(vBNBAddress).repayBorrowBehalf{ value: swapAmount }(msg.sender);\n }\n\n /**\n * @notice Swap tokens for Exact BNB and repay to a Venus market\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param deadline Unix timestamp after which the transaction will revert.\n * @dev Addresses of underlying assets should be ordered that first asset is the token we are swapping and second asset is the token we receive\n * @dev In case of swapping native BNB the first asset in path array should be the wBNB address\n */\n function swapTokensForFullBNBDebtAndRepay(\n uint256 amountInMax,\n address[] calldata path,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) {\n uint256 balanceBefore = address(this).balance;\n uint256 amountOut = IVToken(vBNBAddress).borrowBalanceCurrent(msg.sender);\n _swapTokensForExactBNB(amountOut, amountInMax, path, address(this));\n uint256 balanceAfter = address(this).balance;\n uint256 swapAmount = balanceAfter - balanceBefore;\n IVBNB(vBNBAddress).repayBorrowBehalf{ value: swapAmount }(msg.sender);\n }\n\n /**\n * @notice Swaps an exact amount of input tokens for as many output tokens as possible,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output token, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountIn The address of the vToken contract to repay.\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external virtual override nonReentrant ensure(deadline) ensurePath(path) returns (uint256[] memory amounts) {\n amounts = _swapExactTokensForTokens(amountIn, amountOutMin, path, to, TypesOfTokens.NON_SUPPORTING_FEE);\n }\n\n /**\n * @notice Swaps an exact amount of input tokens for as many output tokens as possible,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output token, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * This method to swap deflationary tokens which would require supporting fee.\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountIn The address of the vToken contract to repay.\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactTokensForTokensAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external virtual override nonReentrant ensure(deadline) ensurePath(path) returns (uint256 swapAmount) {\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(to);\n _swapExactTokensForTokens(amountIn, amountOutMin, path, to, TypesOfTokens.SUPPORTING_FEE);\n swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, to);\n }\n\n /**\n * @notice Swaps an exact amount of BNB for as many output tokens as possible,\n * along the route determined by the path. The first element of path must be WBNB,\n * the last is the output token, and any intermediate elements represent\n * intermediate pairs to trade through (if, for example, a direct pair does not exist).\n * @dev amountIn is passed through the msg.value of the transaction\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactBNBForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n )\n external\n payable\n virtual\n override\n nonReentrant\n ensure(deadline)\n ensurePath(path)\n returns (uint256[] memory amounts)\n {\n amounts = _swapExactBNBForTokens(amountOutMin, path, to, TypesOfTokens.NON_SUPPORTING_FEE);\n }\n\n /**\n * @notice Swaps an exact amount of ETH for as many output tokens as possible,\n * along the route determined by the path. The first element of path must be WBNB,\n * the last is the output token, and any intermediate elements represent\n * intermediate pairs to trade through (if, for example, a direct pair does not exist).\n * This method to swap deflationary tokens which would require supporting fee.\n * @dev amountIn is passed through the msg.value of the transaction\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactBNBForTokensAtSupportingFee(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable virtual override nonReentrant ensure(deadline) ensurePath(path) returns (uint256 swapAmount) {\n address lastAsset = path[path.length - 1];\n uint256 balanceBefore = IERC20(lastAsset).balanceOf(to);\n _swapExactBNBForTokens(amountOutMin, path, to, TypesOfTokens.SUPPORTING_FEE);\n swapAmount = _checkForAmountOut(lastAsset, balanceBefore, amountOutMin, to);\n }\n\n /**\n * @notice Swaps an exact amount of input tokens for as many output ETH as possible,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output ETH, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountIn The address of the vToken contract to repay.\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactTokensForBNB(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) returns (uint256[] memory amounts) {\n amounts = _swapExactTokensForBNB(amountIn, amountOutMin, path, to, TypesOfTokens.NON_SUPPORTING_FEE);\n }\n\n /**\n * @notice Swaps an exact amount of input tokens for as many output ETH as possible,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output ETH, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * This method to swap deflationary tokens which would require supporting fee.\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountIn The address of the vToken contract to repay.\n * @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n */\n function swapExactTokensForBNBAtSupportingFee(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external override nonReentrant ensure(deadline) ensurePath(path) returns (uint256 swapAmount) {\n uint256 balanceBefore = to.balance;\n _swapExactTokensForBNB(amountIn, amountOutMin, path, to, TypesOfTokens.SUPPORTING_FEE);\n uint256 balanceAfter = to.balance;\n swapAmount = balanceAfter - balanceBefore;\n if (swapAmount < amountOutMin) {\n revert SwapAmountLessThanAmountOutMin(swapAmount, amountOutMin);\n }\n }\n\n /**\n * @notice Swaps an as many amount of input tokens for as exact amount of tokens as output,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output token, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n **/\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external virtual override nonReentrant ensure(deadline) ensurePath(path) returns (uint256[] memory amounts) {\n amounts = _swapTokensForExactTokens(amountOut, amountInMax, path, to);\n }\n\n /**\n * @notice Swaps an as ETH as input tokens for as exact amount of tokens as output,\n * along the route determined by the path. The first element of path is the input WBNB,\n * the last is the output as token, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n **/\n function swapBNBForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n )\n external\n payable\n virtual\n override\n nonReentrant\n ensure(deadline)\n ensurePath(path)\n returns (uint256[] memory amounts)\n {\n amounts = _swapBNBForExactTokens(amountOut, path, to);\n }\n\n /**\n * @notice Swaps an as many amount of input tokens for as exact amount of ETH as output,\n * along the route determined by the path. The first element of path is the input token,\n * the last is the output as ETH, and any intermediate elements represent intermediate\n * pairs to trade through (if, for example, a direct pair does not exist).\n * @dev msg.sender should have already given the router an allowance of at least amountIn on the input token.\n * @param amountOut The amount of the tokens needs to be as output token.\n * @param amountInMax The maximum amount of input tokens that can be taken for the transaction not to revert.\n * @param path Array with addresses of the underlying assets to be swapped\n * @param to Recipient of the output tokens.\n * @param deadline Unix timestamp after which the transaction will revert.\n **/\n function swapTokensForExactBNB(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external virtual override nonReentrant ensure(deadline) ensurePath(path) returns (uint256[] memory amounts) {\n amounts = _swapTokensForExactBNB(amountOut, amountInMax, path, to);\n }\n\n /**\n * @notice A public function to sweep accidental BEP-20 transfers to this contract. Tokens are sent to the address `to`, provided in input\n * @param token The address of the ERC-20 token to sweep\n * @param to Recipient of the output tokens.\n * @param sweepAmount The ampunt of the tokens to sweep\n * @custom:access Only Governance\n */\n function sweepToken(IERC20 token, address to, uint256 sweepAmount) external onlyOwner nonReentrant {\n if (to == address(0)) {\n revert ZeroAddress();\n }\n uint256 balance = token.balanceOf(address(this));\n if (sweepAmount > balance) {\n revert InsufficientBalance(sweepAmount, balance);\n }\n token.safeTransfer(to, sweepAmount);\n\n emit SweepToken(address(token), to, sweepAmount);\n }\n\n /**\n * @notice Supply token to a Venus market\n * @param path The addresses of the underlying token\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param swapAmount The amount of tokens supply to Venus Market.\n */\n function _supply(address path, address vTokenAddress, uint256 swapAmount) internal {\n TransferHelper.safeApprove(path, vTokenAddress, 0);\n TransferHelper.safeApprove(path, vTokenAddress, swapAmount);\n uint256 response = IVToken(vTokenAddress).mintBehalf(msg.sender, swapAmount);\n if (response != 0) {\n revert SupplyError(msg.sender, vTokenAddress, response);\n }\n }\n\n /**\n * @notice Repay a borrow from Venus market\n * @param path The addresses of the underlying token\n * @param vTokenAddress The address of the vToken contract for supplying assets.\n * @param swapAmount The amount of tokens repay to Venus Market.\n */\n function _repay(address path, address vTokenAddress, uint256 swapAmount) internal {\n TransferHelper.safeApprove(path, vTokenAddress, 0);\n TransferHelper.safeApprove(path, vTokenAddress, swapAmount);\n uint256 response = IVToken(vTokenAddress).repayBorrowBehalf(msg.sender, swapAmount);\n if (response != 0) {\n revert RepayError(msg.sender, vTokenAddress, response);\n }\n }\n\n /**\n * @notice Check if the balance of to minus the balanceBefore is greater or equal to the amountOutMin.\n * @param asset The address of the underlying token\n * @param balanceBefore Balance before the swap.\n * @param amountOutMin Min amount out threshold.\n * @param to Recipient of the output tokens.\n */\n function _checkForAmountOut(\n address asset,\n uint256 balanceBefore,\n uint256 amountOutMin,\n address to\n ) internal view returns (uint256 swapAmount) {\n uint256 balanceAfter = IERC20(asset).balanceOf(to);\n swapAmount = balanceAfter - balanceBefore;\n if (swapAmount < amountOutMin) {\n revert SwapAmountLessThanAmountOutMin(swapAmount, amountOutMin);\n }\n }\n\n /**\n * @notice Returns the difference between the balance of this and the balanceBefore\n * @param asset The address of the underlying token\n * @param balanceBefore Balance before the swap.\n */\n function _getSwapAmount(address asset, uint256 balanceBefore) internal view returns (uint256 swapAmount) {\n uint256 balanceAfter = IERC20(asset).balanceOf(address(this));\n swapAmount = balanceAfter - balanceBefore;\n }\n\n /**\n * @notice Check isVTokenListed and last address in the path should be vToken underlying.\n * @param vTokenAddress Address of the vToken.\n * @param underlying Address of the underlying asset.\n */\n function _ensureVTokenChecks(address vTokenAddress, address underlying) internal {\n _isVTokenListed(vTokenAddress);\n if (IVToken(vTokenAddress).underlying() != underlying) {\n revert VTokenUnderlyingInvalid(underlying);\n }\n }\n\n /**\n * @notice Check is vToken listed in the pool.\n * @param vToken Address of the vToken.\n */\n function _isVTokenListed(address vToken) internal view {\n bool isListed = InterfaceComptroller(comptrollerAddress).markets(vToken);\n if (!isListed) {\n revert VTokenNotListed(vToken);\n }\n }\n\n /**\n * @notice Mint vBNB tokens to the market then transfer them to user\n * @param swapAmount Swapped BNB amount\n */\n function _mintVBNBandTransfer(uint256 swapAmount) internal {\n uint256 vBNBBalanceBefore = IVBNB(vBNBAddress).balanceOf(address(this));\n IVBNB(vBNBAddress).mint{ value: swapAmount }();\n uint256 vBNBBalanceAfter = IVBNB(vBNBAddress).balanceOf(address(this));\n IERC20(vBNBAddress).safeTransfer(msg.sender, (vBNBBalanceAfter - vBNBBalanceBefore));\n }\n}\n" + }, + "contracts/test/AccessControlManagerMock.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\ncontract AccessControlManagerMock {\n address public owner;\n\n constructor(address _owner) {\n owner = _owner;\n }\n\n function isAllowedToCall(address account, string calldata functionSig) public view returns (bool) {\n if (account == owner) {\n return true;\n }\n\n functionSig;\n\n return false;\n }\n}\n" + }, + "contracts/test/LiquidatorHarness.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"../Liquidator/Liquidator.sol\";\nimport \"@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol\";\n\ncontract LiquidatorHarness is Liquidator {\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address comptroller_, address payable vBnb_, address wBnb_) Liquidator(comptroller_, vBnb_, wBnb_) {}\n\n function initialize(\n uint256 liquidationIncentiveMantissa_,\n address accessControlManager_,\n address protocolShareReserve_\n ) external override initializer {\n __Liquidator_init(liquidationIncentiveMantissa_, accessControlManager_, protocolShareReserve_);\n }\n\n event DistributeLiquidationIncentive(uint256 seizeTokensForTreasury, uint256 seizeTokensForLiquidator);\n\n /// @dev Splits the received vTokens between the liquidator and treasury.\n function distributeLiquidationIncentive(\n IVToken vTokenCollateral,\n uint256 siezedAmount\n ) public returns (uint256 ours, uint256 theirs) {\n (ours, theirs) = super._distributeLiquidationIncentive(vTokenCollateral, siezedAmount);\n emit DistributeLiquidationIncentive(ours, theirs);\n return (ours, theirs);\n }\n\n /// @dev Computes the amounts that would go to treasury and to the liquidator.\n function splitLiquidationIncentive(uint256 seizedAmount) public view returns (uint256 ours, uint256 theirs) {\n return super._splitLiquidationIncentive(seizedAmount);\n }\n}\n" + }, + "contracts/test/MockProtocolShareReserve.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20Upgradeable, IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol\";\n\ninterface IIncomeDestination {\n function updateAssetsState(address comptroller, address asset) external;\n}\n\ninterface IVToken {\n function underlying() external view returns (address);\n}\n\ninterface IPrime is IIncomeDestination {\n function accrueInterest(address vToken) external;\n\n function vTokenForAsset(address asset) external view returns (address);\n\n function getAllMarkets() external view returns (address[] memory);\n}\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\ninterface IMockProtocolShareReserve {\n /// @notice it represents the type of vToken income\n enum IncomeType {\n SPREAD,\n LIQUIDATION\n }\n\n function updateAssetsState(address comptroller, address asset, IncomeType incomeType) external;\n}\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\nerror InvalidAddress();\nerror UnsupportedAsset();\nerror InvalidTotalPercentage();\nerror InvalidMaxLoopsLimit();\n\n/**\n * @title MaxLoopsLimitHelper\n * @author Venus\n * @notice Abstract contract used to avoid collection with too many items that would generate gas errors and DoS.\n */\nabstract contract MaxLoopsLimitHelper {\n // Limit for the loops to avoid the DOS\n uint256 public maxLoopsLimit;\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 max loops limit is set\n event MaxLoopsLimitUpdated(uint256 oldMaxLoopsLimit, uint256 newmaxLoopsLimit);\n\n /// @notice Thrown an error on maxLoopsLimit exceeds for any loop\n error MaxLoopsLimitExceeded(uint256 loopsLimit, uint256 requiredLoops);\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param limit Limit for the max loops can execute at a time\n */\n function _setMaxLoopsLimit(uint256 limit) internal {\n require(limit > maxLoopsLimit, \"Comptroller: Invalid maxLoopsLimit\");\n\n uint256 oldMaxLoopsLimit = maxLoopsLimit;\n maxLoopsLimit = limit;\n\n emit MaxLoopsLimitUpdated(oldMaxLoopsLimit, limit);\n }\n\n /**\n * @notice Compare the maxLoopsLimit with number of the times loop iterate\n * @param len Length of the loops iterate\n * @custom:error MaxLoopsLimitExceeded error is thrown when loops length exceeds maxLoopsLimit\n */\n function _ensureMaxLoops(uint256 len) internal view {\n if (len > maxLoopsLimit) {\n revert MaxLoopsLimitExceeded(maxLoopsLimit, len);\n }\n }\n}\n\ncontract MockProtocolShareReserve is\n AccessControlledV8,\n ReentrancyGuardUpgradeable,\n MaxLoopsLimitHelper,\n IMockProtocolShareReserve\n{\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice protocol income is categorized into two schemas.\n /// The first schema is the default one\n /// The second schema is for spread income from prime markets in core protocol\n enum Schema {\n DEFAULT,\n SPREAD_PRIME_CORE\n }\n\n struct DistributionConfig {\n Schema schema;\n /// @dev percenatge is represented without any scale\n uint256 percentage;\n address destination;\n }\n\n /// @notice address of core pool comptroller contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable CORE_POOL_COMPTROLLER;\n\n /// @notice address of WBNB contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WBNB;\n\n /// @notice address of vBNB contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable vBNB;\n\n /// @notice address of Prime contract\n address public prime;\n\n /// @notice address of pool registry contract\n address public poolRegistry;\n\n uint256 private constant MAX_PERCENT = 100;\n\n /// @notice comptroller => asset => schema => balance\n mapping(address => mapping(address => mapping(Schema => uint256))) public assetsReserves;\n\n /// @notice asset => balance\n mapping(address => uint256) public totalAssetReserve;\n\n /// @notice configuration for different income distribution targets\n DistributionConfig[] public distributionTargets;\n\n /// @notice Emitted when pool registry address is updated\n event PoolRegistryUpdated(address indexed oldPoolRegistry, address indexed newPoolRegistry);\n\n /// @notice Emitted when prime address is updated\n event PrimeUpdated(address indexed oldPrime, address indexed newPrime);\n\n /// @notice Event emitted after the updation of the assets reserves.\n event AssetsReservesUpdated(\n address indexed comptroller,\n address indexed asset,\n uint256 amount,\n IncomeType incomeType,\n Schema schema\n );\n\n /// @notice Event emitted when an asset is released to a target\n event AssetReleased(\n address indexed destination,\n address indexed asset,\n Schema schema,\n uint256 percent,\n uint256 amount\n );\n\n /// @notice Event emitted when asset reserves state is updated\n event ReservesUpdated(\n address indexed comptroller,\n address indexed asset,\n Schema schema,\n uint256 oldBalance,\n uint256 newBalance\n );\n\n /// @notice Event emitted when distribution configuration is updated\n event DistributionConfigUpdated(\n address indexed destination,\n uint256 oldPercentage,\n uint256 newPercentage,\n Schema schema\n );\n\n /// @notice Event emitted when distribution configuration is added\n event DistributionConfigAdded(address indexed destination, uint256 percentage, Schema schema);\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(address _corePoolComptroller, address _wbnb, address _vbnb) {\n if (_corePoolComptroller == address(0)) revert InvalidAddress();\n if (_wbnb == address(0)) revert InvalidAddress();\n if (_vbnb == address(0)) revert InvalidAddress();\n\n CORE_POOL_COMPTROLLER = _corePoolComptroller;\n WBNB = _wbnb;\n vBNB = _vbnb;\n\n // Note that the contract is upgradeable. Use initialize() or reinitializers\n // to set the state variables.\n _disableInitializers();\n }\n\n /**\n * @dev Initializes the deployer to owner.\n * @param _accessControlManager The address of ACM contract\n * @param _loopsLimit Limit for the loops in the contract to avoid DOS\n */\n function initialize(address _accessControlManager, uint256 _loopsLimit) external initializer {\n __AccessControlled_init(_accessControlManager);\n __ReentrancyGuard_init();\n _setMaxLoopsLimit(_loopsLimit);\n }\n\n /**\n * @dev Pool registry setter.\n * @param _poolRegistry Address of the pool registry\n * @custom:error ZeroAddressNotAllowed is thrown when pool registry address is zero\n */\n function setPoolRegistry(address _poolRegistry) external onlyOwner {\n if (_poolRegistry == address(0)) revert InvalidAddress();\n emit PoolRegistryUpdated(poolRegistry, _poolRegistry);\n poolRegistry = _poolRegistry;\n }\n\n /**\n * @dev Prime contract address setter.\n * @param _prime Address of the prime contract\n */\n function setPrime(address _prime) external onlyOwner {\n if (_prime == address(0)) revert InvalidAddress();\n emit PrimeUpdated(prime, _prime);\n prime = _prime;\n }\n\n /**\n * @dev Add or update destination targets based on destination address\n * @param configs configurations of the destinations.\n */\n function addOrUpdateDistributionConfigs(DistributionConfig[] memory configs) external nonReentrant {\n _checkAccessAllowed(\"addOrUpdateDistributionConfigs(DistributionConfig[])\");\n\n //we need to accrue and release funds to prime before updating the distribution configuration\n //because prime relies on getUnreleasedFunds and its return value may change after config update\n _accrueAndReleaseFundsToPrime();\n for (uint256 i = 0; i < configs.length; ) {\n DistributionConfig memory _config = configs[i];\n require(_config.destination != address(0), \"ProtocolShareReserve: Destination address invalid\");\n\n bool updated = false;\n for (uint256 j = 0; j < distributionTargets.length; ) {\n DistributionConfig storage config = distributionTargets[j];\n\n if (_config.schema == config.schema && config.destination == _config.destination) {\n emit DistributionConfigUpdated(\n _config.destination,\n config.percentage,\n _config.percentage,\n _config.schema\n );\n config.percentage = _config.percentage;\n updated = true;\n break;\n }\n\n unchecked {\n ++j;\n }\n }\n\n if (!updated) {\n distributionTargets.push(_config);\n emit DistributionConfigAdded(_config.destination, _config.percentage, _config.schema);\n }\n\n unchecked {\n ++i;\n }\n }\n\n _ensurePercentages();\n _ensureMaxLoops(distributionTargets.length);\n }\n\n /**\n * @dev Release funds\n * @param comptroller the comptroller address of the pool\n * @param assets assets to be released to distribution targets\n */\n function releaseFunds(address comptroller, address[] memory assets) external nonReentrant {\n _accruePrimeInterest();\n\n for (uint256 i = 0; i < assets.length; ) {\n _releaseFund(comptroller, assets[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Used to find out the amount of funds that's going to be released when release funds is called.\n * @param comptroller the comptroller address of the pool\n * @param schema the schema of the distribution target\n * @param destination the destination address of the distribution target\n * @param asset the asset address which will be released\n */\n function getUnreleasedFunds(\n address comptroller,\n Schema schema,\n address destination,\n address asset\n ) external view returns (uint256) {\n for (uint256 i = 0; i < distributionTargets.length; ) {\n DistributionConfig storage _config = distributionTargets[i];\n if (_config.schema == schema && _config.destination == destination) {\n uint256 total = assetsReserves[comptroller][asset][schema];\n return (total * _config.percentage) / MAX_PERCENT;\n }\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Returns the total number of distribution targets\n */\n function totalDistributions() external view returns (uint256) {\n return distributionTargets.length;\n }\n\n /**\n * @dev Update the reserve of the asset for the specific pool after transferring to the protocol share reserve.\n * @param comptroller Comptroller address (pool)\n * @param asset Asset address.\n * @param incomeType type of income\n */\n function updateAssetsState(\n address comptroller,\n address asset,\n IncomeType incomeType\n ) public override(IMockProtocolShareReserve) nonReentrant {\n if (!IComptroller(comptroller).isComptroller()) revert InvalidAddress();\n if (asset == address(0)) revert InvalidAddress();\n if (\n comptroller != CORE_POOL_COMPTROLLER &&\n IPoolRegistry(poolRegistry).getVTokenForAsset(comptroller, asset) == address(0)\n ) revert InvalidAddress();\n\n Schema schema = getSchema(comptroller, asset, incomeType);\n uint256 currentBalance = IERC20Upgradeable(asset).balanceOf(address(this));\n uint256 assetReserve = totalAssetReserve[asset];\n\n if (currentBalance > assetReserve) {\n uint256 balanceDifference;\n unchecked {\n balanceDifference = currentBalance - assetReserve;\n }\n\n assetsReserves[comptroller][asset][schema] += balanceDifference;\n totalAssetReserve[asset] += balanceDifference;\n emit AssetsReservesUpdated(comptroller, asset, balanceDifference, incomeType, schema);\n }\n }\n\n /**\n * @dev Fetches the list of prime markets and then accrues interest and\n * releases the funds to prime for each market\n */\n function _accrueAndReleaseFundsToPrime() internal {\n address[] memory markets = IPrime(prime).getAllMarkets();\n for (uint256 i = 0; i < markets.length; ) {\n address market = markets[i];\n IPrime(prime).accrueInterest(market);\n _releaseFund(CORE_POOL_COMPTROLLER, _getUnderlying(market));\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev Fetches the list of prime markets and then accrues interest\n * to prime for each market\n */\n function _accruePrimeInterest() internal {\n // address[] memory markets = IPrime(prime).getAllMarkets();\n address[] memory markets = IPrime(prime).getAllMarkets();\n\n for (uint256 i = 0; i < markets.length; ) {\n address market = markets[i];\n IPrime(prime).accrueInterest(market);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @dev asset from a particular pool to be release to distribution targets\n * @param comptroller Comptroller address(pool)\n * @param asset Asset address.\n */\n function _releaseFund(address comptroller, address asset) internal {\n uint256 totalSchemas = uint256(type(Schema).max) + 1;\n uint256[] memory schemaBalances = new uint256[](totalSchemas);\n uint256 totalBalance;\n for (uint256 schemaValue; schemaValue < totalSchemas; ) {\n schemaBalances[schemaValue] = assetsReserves[comptroller][asset][Schema(schemaValue)];\n totalBalance += schemaBalances[schemaValue];\n\n unchecked {\n ++schemaValue;\n }\n }\n\n if (totalBalance == 0) {\n return;\n }\n\n uint256[] memory totalTransferAmounts = new uint256[](totalSchemas);\n for (uint256 i = 0; i < distributionTargets.length; ) {\n DistributionConfig memory _config = distributionTargets[i];\n\n uint256 transferAmount = (schemaBalances[uint256(_config.schema)] * _config.percentage) / MAX_PERCENT;\n totalTransferAmounts[uint256(_config.schema)] += transferAmount;\n\n IERC20Upgradeable(asset).safeTransfer(_config.destination, transferAmount);\n IIncomeDestination(_config.destination).updateAssetsState(comptroller, asset);\n\n emit AssetReleased(_config.destination, asset, _config.schema, _config.percentage, transferAmount);\n\n unchecked {\n ++i;\n }\n }\n\n uint256[] memory newSchemaBalances = new uint256[](totalSchemas);\n for (uint256 schemaValue = 0; schemaValue < totalSchemas; ) {\n newSchemaBalances[schemaValue] = schemaBalances[schemaValue] - totalTransferAmounts[schemaValue];\n assetsReserves[comptroller][asset][Schema(schemaValue)] = newSchemaBalances[schemaValue];\n totalAssetReserve[asset] = totalAssetReserve[asset] - totalTransferAmounts[schemaValue];\n\n emit ReservesUpdated(\n comptroller,\n asset,\n Schema(schemaValue),\n schemaBalances[schemaValue],\n newSchemaBalances[schemaValue]\n );\n\n unchecked {\n ++schemaValue;\n }\n }\n }\n\n /**\n * @dev Returns the schema based on comptroller, asset and income type\n * @param comptroller Comptroller address(pool)\n * @param asset Asset address.\n * @param incomeType type of income\n * @return schema schema for distribution\n */\n function getSchema(\n address comptroller,\n address asset,\n IncomeType incomeType\n ) internal view returns (Schema schema) {\n schema = Schema.DEFAULT;\n address vToken = IPrime(prime).vTokenForAsset(asset);\n if (vToken != address(0) && comptroller == CORE_POOL_COMPTROLLER && incomeType == IncomeType.SPREAD) {\n schema = Schema.SPREAD_PRIME_CORE;\n }\n }\n\n function _ensurePercentages() internal view {\n uint256 totalSchemas = uint256(type(Schema).max) + 1;\n uint256[] memory totalPercentages = new uint256[](totalSchemas);\n\n for (uint256 i = 0; i < distributionTargets.length; ) {\n DistributionConfig memory config = distributionTargets[i];\n totalPercentages[uint256(config.schema)] += config.percentage;\n\n unchecked {\n ++i;\n }\n }\n for (uint256 schemaValue = 0; schemaValue < totalSchemas; ) {\n if (totalPercentages[schemaValue] != MAX_PERCENT && totalPercentages[schemaValue] != 0)\n revert InvalidTotalPercentage();\n\n unchecked {\n ++schemaValue;\n }\n }\n }\n\n /**\n * @dev Returns the underlying asset address for the vToken\n * @param vToken vToken address\n * @return asset address of asset\n */\n function _getUnderlying(address vToken) internal view returns (address) {\n if (vToken == vBNB) {\n return WBNB;\n } else {\n return IVToken(vToken).underlying();\n }\n }\n}\n" + }, + "contracts/test/MockToken.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport { ERC20 } from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract MockToken is ERC20 {\n uint8 private immutable _decimals;\n\n constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {\n _decimals = decimals_;\n }\n\n function faucet(uint256 amount) external {\n _mint(msg.sender, amount);\n }\n\n function decimals() public view virtual override returns (uint8) {\n return _decimals;\n }\n}\n" + }, + "contracts/test/PrimeScenario.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport \"../Tokens/Prime/Prime.sol\";\n\ncontract PrimeScenario is Prime {\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _wbnb,\n address _vbnb,\n uint256 _blocksPerYear,\n uint256 _stakingPeriod,\n uint256 _minimumStakedXVS,\n uint256 _maximumXVSCap,\n bool _timeBased\n ) Prime(_wbnb, _vbnb, _blocksPerYear, _stakingPeriod, _minimumStakedXVS, _maximumXVSCap, _timeBased) {}\n\n function calculateScore(uint256 xvs, uint256 capital) external view returns (uint256) {\n return Scores._calculateScore(xvs, capital, alphaNumerator, alphaDenominator);\n }\n\n function setPLP(address plp) external {\n primeLiquidityProvider = plp;\n }\n\n function mintForUser(address user) external {\n tokens[user] = Token(true, true);\n }\n\n function burnForUser(address user) external {\n tokens[user] = Token(false, false);\n }\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/InterfaceComptroller.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.25;\n\ninterface InterfaceComptroller {\n function markets(address) external view returns (bool);\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/IPoolRegistry.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\n/**\n * @title PoolRegistryInterface\n * @author Venus\n * @notice Interface implemented by `PoolRegistry`.\n */\ninterface PoolRegistryInterface {\n /**\n * @notice Struct for a Venus interest rate pool.\n */\n struct VenusPool {\n string name;\n address creator;\n address comptroller;\n uint256 blockPosted;\n uint256 timestampPosted;\n }\n\n /// @notice Get a pool by comptroller address\n function getPoolByComptroller(address comptroller) external view returns (VenusPool memory);\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/IPrime.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { PrimeStorageV1 } from \"../PrimeStorage.sol\";\n\n/**\n * @title IPrime\n * @author Venus\n * @notice Interface for Prime Token\n */\ninterface IPrime {\n struct APRInfo {\n // supply APR of the user in BPS\n uint256 supplyAPR;\n // borrow APR of the user in BPS\n uint256 borrowAPR;\n // total score of the market\n uint256 totalScore;\n // score of the user\n uint256 userScore;\n // capped XVS balance of the user\n uint256 xvsBalanceForScore;\n // capital of the user\n uint256 capital;\n // capped supply of the user\n uint256 cappedSupply;\n // capped borrow of the user\n uint256 cappedBorrow;\n // capped supply of user in USD\n uint256 supplyCapUSD;\n // capped borrow of user in USD\n uint256 borrowCapUSD;\n }\n\n struct Capital {\n // capital of the user\n uint256 capital;\n // capped supply of the user\n uint256 cappedSupply;\n // capped borrow of the user\n uint256 cappedBorrow;\n // capped supply of user in USD\n uint256 supplyCapUSD;\n // capped borrow of user in USD\n uint256 borrowCapUSD;\n }\n\n /**\n * @notice Returns boosted pending interest accrued for a user for all markets\n * @param user the account for which to get the accrued interests\n * @return pendingRewards the number of underlying tokens accrued by the user for all markets\n */\n function getPendingRewards(address user) external returns (PrimeStorageV1.PendingReward[] memory pendingRewards);\n\n /**\n * @notice Update total score of multiple users and market\n * @param users accounts for which we need to update score\n */\n function updateScores(address[] memory users) external;\n\n /**\n * @notice Update value of alpha\n * @param _alphaNumerator numerator of alpha. If alpha is 0.5 then numerator is 1\n * @param _alphaDenominator denominator of alpha. If alpha is 0.5 then denominator is 2\n */\n function updateAlpha(uint128 _alphaNumerator, uint128 _alphaDenominator) external;\n\n /**\n * @notice Update multipliers for a market\n * @param market address of the market vToken\n * @param supplyMultiplier new supply multiplier for the market, scaled by 1e18\n * @param borrowMultiplier new borrow multiplier for the market, scaled by 1e18\n */\n function updateMultipliers(address market, uint256 supplyMultiplier, uint256 borrowMultiplier) external;\n\n /**\n * @notice Add a market to prime program\n * @param comptroller address of the comptroller\n * @param market address of the market vToken\n * @param supplyMultiplier the multiplier for supply cap. It should be converted to 1e18\n * @param borrowMultiplier the multiplier for borrow cap. It should be converted to 1e18\n */\n function addMarket(\n address comptroller,\n address market,\n uint256 supplyMultiplier,\n uint256 borrowMultiplier\n ) external;\n\n /**\n * @notice Set limits for total tokens that can be minted\n * @param _irrevocableLimit total number of irrevocable tokens that can be minted\n * @param _revocableLimit total number of revocable tokens that can be minted\n */\n function setLimit(uint256 _irrevocableLimit, uint256 _revocableLimit) external;\n\n /**\n * @notice Directly issue prime tokens to users\n * @param isIrrevocable are the tokens being issued\n * @param users list of address to issue tokens to\n */\n function issue(bool isIrrevocable, address[] calldata users) external;\n\n /**\n * @notice Executed by XVSVault whenever user's XVSVault balance changes\n * @param user the account address whose balance was updated\n */\n function xvsUpdated(address user) external;\n\n /**\n * @notice accrues interest and updates score for an user for a specific market\n * @param user the account address for which to accrue interest and update score\n * @param market the market for which to accrue interest and update score\n */\n function accrueInterestAndUpdateScore(address user, address market) external;\n\n /**\n * @notice For claiming prime token when staking period is completed\n */\n function claim() external;\n\n /**\n * @notice For burning any prime token\n * @param user the account address for which the prime token will be burned\n */\n function burn(address user) external;\n\n /**\n * @notice To pause or unpause claiming of interest\n */\n function togglePause() external;\n\n /**\n * @notice For user to claim boosted yield\n * @param vToken the market for which claim the accrued interest\n * @return amount the amount of tokens transferred to the user\n */\n function claimInterest(address vToken) external returns (uint256);\n\n /**\n * @notice For user to claim boosted yield\n * @param vToken the market for which claim the accrued interest\n * @param user the user for which to claim the accrued interest\n * @return amount the amount of tokens transferred to the user\n */\n function claimInterest(address vToken, address user) external returns (uint256);\n\n /**\n * @notice Distributes income from market since last distribution\n * @param vToken the market for which to distribute the income\n */\n function accrueInterest(address vToken) external;\n\n /**\n * @notice Returns boosted interest accrued for a user\n * @param vToken the market for which to fetch the accrued interest\n * @param user the account for which to get the accrued interest\n * @return interestAccrued the number of underlying tokens accrued by the user since the last accrual\n */\n function getInterestAccrued(address vToken, address user) external returns (uint256);\n\n /**\n * @notice Retrieves an array of all available markets\n * @return an array of addresses representing all available markets\n */\n function getAllMarkets() external view returns (address[] memory);\n\n /**\n * @notice fetch the numbers of seconds remaining for staking period to complete\n * @param user the account address for which we are checking the remaining time\n * @return timeRemaining the number of seconds the user needs to wait to claim prime token\n */\n function claimTimeRemaining(address user) external view returns (uint256);\n\n /**\n * @notice Returns supply and borrow APR for user for a given market\n * @param market the market for which to fetch the APR\n * @param user the account for which to get the APR\n * @return aprInfo APR information for the user for the given market\n */\n function calculateAPR(address market, address user) external view returns (APRInfo memory aprInfo);\n\n /**\n * @notice Returns supply and borrow APR for estimated supply, borrow and XVS staked\n * @param market the market for which to fetch the APR\n * @param user the account for which to get the APR\n * @param borrow hypothetical borrow amount\n * @param supply hypothetical supply amount\n * @param xvsStaked hypothetical staked XVS amount\n * @return aprInfo APR information for the user for the given market\n */\n function estimateAPR(\n address market,\n address user,\n uint256 borrow,\n uint256 supply,\n uint256 xvsStaked\n ) external view returns (APRInfo memory aprInfo);\n\n /**\n * @notice the total income that's going to be distributed in a year to prime token holders\n * @param vToken the market for which to fetch the total income that's going to distributed in a year\n * @return amount the total income\n */\n function incomeDistributionYearly(address vToken) external view returns (uint256 amount);\n\n /**\n * @notice Returns if user is a prime holder\n * @return isPrimeHolder true if user is a prime holder\n */\n function isUserPrimeHolder(address user) external view returns (bool);\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param loopsLimit Number of loops limit\n */\n function setMaxLoopsLimit(uint256 loopsLimit) external;\n\n /**\n * @notice Update staked at timestamp for multiple users\n * @param users accounts for which we need to update staked at timestamp\n * @param timestamps new staked at timestamp for the users\n */\n function setStakedAt(address[] calldata users, uint256[] calldata timestamps) external;\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/IPrimeLiquidityProvider.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\nimport { IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\n/**\n * @title IPrimeLiquidityProvider\n * @author Venus\n * @notice Interface for PrimeLiquidityProvider\n */\ninterface IPrimeLiquidityProvider {\n /**\n * @notice Initialize the distribution of the token\n * @param tokens_ Array of addresses of the tokens to be intialized\n */\n function initializeTokens(address[] calldata tokens_) external;\n\n /**\n * @notice Pause fund transfer of tokens to Prime contract\n */\n function pauseFundsTransfer() external;\n\n /**\n * @notice Resume fund transfer of tokens to Prime contract\n */\n function resumeFundsTransfer() external;\n\n /**\n * @notice Set distribution speed (amount of token distribute per block or second)\n * @param tokens_ Array of addresses of the tokens\n * @param distributionSpeeds_ New distribution speeds for tokens\n */\n function setTokensDistributionSpeed(address[] calldata tokens_, uint256[] calldata distributionSpeeds_) external;\n\n /**\n * @notice Set max distribution speed for token (amount of maximum token distribute per block or second)\n * @param tokens_ Array of addresses of the tokens\n * @param maxDistributionSpeeds_ New distribution speeds for tokens\n */\n function setMaxTokensDistributionSpeed(\n address[] calldata tokens_,\n uint256[] calldata maxDistributionSpeeds_\n ) external;\n\n /**\n * @notice Set the prime token contract address\n * @param prime_ The new address of the prime token contract\n */\n function setPrimeToken(address prime_) external;\n\n /**\n * @notice Claim all the token accrued till last block or second\n * @param token_ The token to release to the Prime contract\n */\n function releaseFunds(address token_) external;\n\n /**\n * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to user\n * @param token_ The address of the ERC-20 token to sweep\n * @param to_ The address of the recipient\n * @param amount_ The amount of tokens needs to transfer\n */\n function sweepToken(IERC20Upgradeable token_, address to_, uint256 amount_) external;\n\n /**\n * @notice Accrue token by updating the distribution state\n * @param token_ Address of the token\n */\n function accrueTokens(address token_) external;\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param loopsLimit Limit for the max loops can execute at a time\n */\n function setMaxLoopsLimit(uint256 loopsLimit) external;\n\n /**\n * @notice Get rewards per block or second for token\n * @param token_ Address of the token\n * @return speed returns the per block or second reward\n */\n function getEffectiveDistributionSpeed(address token_) external view returns (uint256);\n\n /**\n * @notice Get the amount of tokens accrued\n * @param token_ Address of the token\n * @return Amount of tokens that are accrued\n */\n function tokenAmountAccrued(address token_) external view returns (uint256);\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/IVToken.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IVToken {\n function borrowBalanceStored(address account) external view returns (uint256);\n\n function exchangeRateStored() external view returns (uint256);\n\n function balanceOf(address account) external view returns (uint256);\n\n function underlying() external view returns (address);\n\n function totalBorrows() external view returns (uint256);\n\n function borrowRatePerBlock() external view returns (uint256);\n\n function reserveFactorMantissa() external view returns (uint256);\n\n function decimals() external view returns (uint8);\n}\n" + }, + "contracts/Tokens/Prime/Interfaces/IXVSVault.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.25;\n\ninterface IXVSVault {\n function getUserInfo(\n address _rewardToken,\n uint256 _pid,\n address _user\n ) external view returns (uint256 amount, uint256 rewardDebt, uint256 pendingWithdrawals);\n\n function xvsAddress() external view returns (address);\n}\n" + }, + "contracts/Tokens/Prime/libs/FixedMath.sol": { + "content": "// SPDX-License-Identifier: MIT\n// solhint-disable var-name-mixedcase\n\npragma solidity 0.8.25;\n\nimport { SafeCastUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol\";\nimport { FixedMath0x } from \"./FixedMath0x.sol\";\n\nusing SafeCastUpgradeable for uint256;\n\nerror InvalidFixedPoint();\n\n/**\n * @title FixedMath\n * @author Venus\n * @notice FixedMath library is used for complex mathematical operations\n */\nlibrary FixedMath {\n error InvalidFraction(uint256 n, uint256 d);\n\n /**\n * @notice Convert some uint256 fraction `n` numerator / `d` denominator to a fixed-point number `f`.\n * @param n numerator\n * @param d denominator\n * @return fixed-point number\n */\n function _toFixed(uint256 n, uint256 d) internal pure returns (int256) {\n if (d.toInt256() < n.toInt256()) revert InvalidFraction(n, d);\n\n return (n.toInt256() * FixedMath0x.FIXED_1) / int256(d.toInt256());\n }\n\n /**\n * @notice Divide some unsigned int `u` by a fixed point number `f`\n * @param u unsigned dividend\n * @param f fixed point divisor, in FIXED_1 units\n * @return unsigned int quotient\n */\n function _uintDiv(uint256 u, int256 f) internal pure returns (uint256) {\n if (f < 0) revert InvalidFixedPoint();\n // multiply `u` by FIXED_1 to cancel out the built-in FIXED_1 in f\n return uint256((u.toInt256() * FixedMath0x.FIXED_1) / f);\n }\n\n /**\n * @notice Multiply some unsigned int `u` by a fixed point number `f`\n * @param u unsigned multiplicand\n * @param f fixed point multiplier, in FIXED_1 units\n * @return unsigned int product\n */\n function _uintMul(uint256 u, int256 f) internal pure returns (uint256) {\n if (f < 0) revert InvalidFixedPoint();\n // divide the product by FIXED_1 to cancel out the built-in FIXED_1 in f\n return uint256((u.toInt256() * f) / FixedMath0x.FIXED_1);\n }\n\n /// @notice see FixedMath0x\n function _ln(int256 x) internal pure returns (int256) {\n return FixedMath0x._ln(x);\n }\n\n /// @notice see FixedMath0x\n function _exp(int256 x) internal pure returns (int256) {\n return FixedMath0x._exp(x);\n }\n}\n" + }, + "contracts/Tokens/Prime/libs/FixedMath0x.sol": { + "content": "// SPDX-License-Identifier: MIT\n// solhint-disable max-line-length\n\npragma solidity 0.8.25;\n\n// Below is code from 0x's LibFixedMath.sol. Changes:\n// - addition of 0.8-style errors\n// - removal of unused functions\n// - added comments for clarity\n// https://github.com/0xProject/exchange-v3/blob/aae46bef841bfd1cc31028f41793db4fe7197084/contracts/staking/contracts/src/libs/LibFixedMath.sol\n\n/*\n\n Copyright 2017 Bprotocol Foundation, 2019 ZeroEx Intl.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*/\n/// Thrown when the natural log function is given too large of an argument\nerror LnTooLarge(int256 x);\n/// Thrown when the natural log would have returned a number outside of ℝ\nerror LnNonRealResult(int256 x);\n/// Thrown when exp is given too large of an argument\nerror ExpTooLarge(int256 x);\n/// Thrown when an unsigned value is too large to be converted to a signed value\nerror UnsignedValueTooLarge(uint256 x);\n\n/**\n * @title FixedMath0x\n * @notice Signed, fixed-point, 127-bit precision math library\n */\nlibrary FixedMath0x {\n // Base for the fixed point numbers (this is our 1)\n int256 internal constant FIXED_1 = int256(0x0000000000000000000000000000000080000000000000000000000000000000);\n // Maximum ln argument (1)\n int256 private constant LN_MAX_VAL = FIXED_1;\n // Minimum ln argument. Notice this is related to EXP_MIN_VAL (e ^ -63.875)\n int256 private constant LN_MIN_VAL = int256(0x0000000000000000000000000000000000000000000000000000000733048c5a);\n // Maximum exp argument (0)\n int256 private constant EXP_MAX_VAL = 0;\n // Minimum exp argument. Notice this is related to LN_MIN_VAL (-63.875)\n int256 private constant EXP_MIN_VAL = -int256(0x0000000000000000000000000000001ff0000000000000000000000000000000);\n\n /// @dev Get the natural logarithm of a fixed-point number 0 < `x` <= LN_MAX_VAL\n function _ln(int256 x) internal pure returns (int256 r) {\n if (x > LN_MAX_VAL) {\n revert LnTooLarge(x);\n }\n if (x <= 0) {\n revert LnNonRealResult(x);\n }\n if (x == FIXED_1) {\n return 0;\n }\n if (x <= LN_MIN_VAL) {\n return EXP_MIN_VAL;\n }\n\n int256 y;\n int256 z;\n int256 w;\n\n // Rewrite the input as a quotient of negative natural exponents and a single residual q, such that 1 < q < 2\n // For example: log(0.3) = log(e^-1 * e^-0.25 * 1.0471028872385522)\n // = 1 - 0.25 - log(1 + 0.0471028872385522)\n // e ^ -32\n if (x <= int256(0x00000000000000000000000000000000000000000001c8464f76164760000000)) {\n r -= int256(0x0000000000000000000000000000001000000000000000000000000000000000); // - 32\n x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000000001c8464f76164760000000); // / e ^ -32\n }\n // e ^ -16\n if (x <= int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000)) {\n r -= int256(0x0000000000000000000000000000000800000000000000000000000000000000); // - 16\n x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000000f1aaddd7742e90000000000000); // / e ^ -16\n }\n // e ^ -8\n if (x <= int256(0x00000000000000000000000000000000000afe10820813d78000000000000000)) {\n r -= int256(0x0000000000000000000000000000000400000000000000000000000000000000); // - 8\n x = (x * FIXED_1) / int256(0x00000000000000000000000000000000000afe10820813d78000000000000000); // / e ^ -8\n }\n // e ^ -4\n if (x <= int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000)) {\n r -= int256(0x0000000000000000000000000000000200000000000000000000000000000000); // - 4\n x = (x * FIXED_1) / int256(0x0000000000000000000000000000000002582ab704279ec00000000000000000); // / e ^ -4\n }\n // e ^ -2\n if (x <= int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000)) {\n r -= int256(0x0000000000000000000000000000000100000000000000000000000000000000); // - 2\n x = (x * FIXED_1) / int256(0x000000000000000000000000000000001152aaa3bf81cc000000000000000000); // / e ^ -2\n }\n // e ^ -1\n if (x <= int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000)) {\n r -= int256(0x0000000000000000000000000000000080000000000000000000000000000000); // - 1\n x = (x * FIXED_1) / int256(0x000000000000000000000000000000002f16ac6c59de70000000000000000000); // / e ^ -1\n }\n // e ^ -0.5\n if (x <= int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000)) {\n r -= int256(0x0000000000000000000000000000000040000000000000000000000000000000); // - 0.5\n x = (x * FIXED_1) / int256(0x000000000000000000000000000000004da2cbf1be5828000000000000000000); // / e ^ -0.5\n }\n // e ^ -0.25\n if (x <= int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000)) {\n r -= int256(0x0000000000000000000000000000000020000000000000000000000000000000); // - 0.25\n x = (x * FIXED_1) / int256(0x0000000000000000000000000000000063afbe7ab2082c000000000000000000); // / e ^ -0.25\n }\n // e ^ -0.125\n if (x <= int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) {\n r -= int256(0x0000000000000000000000000000000010000000000000000000000000000000); // - 0.125\n x = (x * FIXED_1) / int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d); // / e ^ -0.125\n }\n // `x` is now our residual in the range of 1 <= x <= 2 (or close enough).\n\n // Add the taylor series for log(1 + z), where z = x - 1\n z = y = x - FIXED_1;\n w = (y * y) / FIXED_1;\n r += (z * (0x100000000000000000000000000000000 - y)) / 0x100000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^01 / 01 - y^02 / 02\n r += (z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y)) / 0x200000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^03 / 03 - y^04 / 04\n r += (z * (0x099999999999999999999999999999999 - y)) / 0x300000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^05 / 05 - y^06 / 06\n r += (z * (0x092492492492492492492492492492492 - y)) / 0x400000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^07 / 07 - y^08 / 08\n r += (z * (0x08e38e38e38e38e38e38e38e38e38e38e - y)) / 0x500000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^09 / 09 - y^10 / 10\n r += (z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y)) / 0x600000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^11 / 11 - y^12 / 12\n r += (z * (0x089d89d89d89d89d89d89d89d89d89d89 - y)) / 0x700000000000000000000000000000000;\n z = (z * w) / FIXED_1; // add y^13 / 13 - y^14 / 14\n r += (z * (0x088888888888888888888888888888888 - y)) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16\n }\n\n /// @dev Compute the natural exponent for a fixed-point number EXP_MIN_VAL <= `x` <= 1\n function _exp(int256 x) internal pure returns (int256 r) {\n if (x < EXP_MIN_VAL) {\n // Saturate to zero below EXP_MIN_VAL.\n return 0;\n }\n if (x == 0) {\n return FIXED_1;\n }\n if (x > EXP_MAX_VAL) {\n revert ExpTooLarge(x);\n }\n\n // Rewrite the input as a product of natural exponents and a\n // single residual q, where q is a number of small magnitude.\n // For example: e^-34.419 = e^(-32 - 2 - 0.25 - 0.125 - 0.044)\n // = e^-32 * e^-2 * e^-0.25 * e^-0.125 * e^-0.044\n // -> q = -0.044\n\n // Multiply with the taylor series for e^q\n int256 y;\n int256 z;\n // q = x % 0.125 (the residual)\n z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000;\n z = (z * y) / FIXED_1;\n r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)\n z = (z * y) / FIXED_1;\n r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)\n z = (z * y) / FIXED_1;\n r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)\n z = (z * y) / FIXED_1;\n r += z * 0x004807432bc18000; // add y^05 * (20! / 05!)\n z = (z * y) / FIXED_1;\n r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)\n z = (z * y) / FIXED_1;\n r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)\n z = (z * y) / FIXED_1;\n r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)\n z = (z * y) / FIXED_1;\n r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)\n z = (z * y) / FIXED_1;\n r += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000017499f00; // add y^13 * (20! / 13!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)\n z = (z * y) / FIXED_1;\n r += z * 0x00000000001c6380; // add y^15 * (20! / 15!)\n z = (z * y) / FIXED_1;\n r += z * 0x000000000001c638; // add y^16 * (20! / 16!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)\n z = (z * y) / FIXED_1;\n r += z * 0x000000000000017c; // add y^18 * (20! / 18!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000000000014; // add y^19 * (20! / 19!)\n z = (z * y) / FIXED_1;\n r += z * 0x0000000000000001; // add y^20 * (20! / 20!)\n r = r / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0!\n\n // Multiply with the non-residual terms.\n x = -x;\n // e ^ -32\n if ((x & int256(0x0000000000000000000000000000001000000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x00000000000000000000000000000000000000f1aaddd7742e56d32fb9f99744)) /\n int256(0x0000000000000000000000000043cbaf42a000812488fc5c220ad7b97bf6e99e); // * e ^ -32\n }\n // e ^ -16\n if ((x & int256(0x0000000000000000000000000000000800000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x00000000000000000000000000000000000afe10820813d65dfe6a33c07f738f)) /\n int256(0x000000000000000000000000000005d27a9f51c31b7c2f8038212a0574779991); // * e ^ -16\n }\n // e ^ -8\n if ((x & int256(0x0000000000000000000000000000000400000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x0000000000000000000000000000000002582ab704279e8efd15e0265855c47a)) /\n int256(0x0000000000000000000000000000001b4c902e273a58678d6d3bfdb93db96d02); // * e ^ -8\n }\n // e ^ -4\n if ((x & int256(0x0000000000000000000000000000000200000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x000000000000000000000000000000001152aaa3bf81cb9fdb76eae12d029571)) /\n int256(0x00000000000000000000000000000003b1cc971a9bb5b9867477440d6d157750); // * e ^ -4\n }\n // e ^ -2\n if ((x & int256(0x0000000000000000000000000000000100000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x000000000000000000000000000000002f16ac6c59de6f8d5d6f63c1482a7c86)) /\n int256(0x000000000000000000000000000000015bf0a8b1457695355fb8ac404e7a79e3); // * e ^ -2\n }\n // e ^ -1\n if ((x & int256(0x0000000000000000000000000000000080000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x000000000000000000000000000000004da2cbf1be5827f9eb3ad1aa9866ebb3)) /\n int256(0x00000000000000000000000000000000d3094c70f034de4b96ff7d5b6f99fcd8); // * e ^ -1\n }\n // e ^ -0.5\n if ((x & int256(0x0000000000000000000000000000000040000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x0000000000000000000000000000000063afbe7ab2082ba1a0ae5e4eb1b479dc)) /\n int256(0x00000000000000000000000000000000a45af1e1f40c333b3de1db4dd55f29a7); // * e ^ -0.5\n }\n // e ^ -0.25\n if ((x & int256(0x0000000000000000000000000000000020000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x0000000000000000000000000000000070f5a893b608861e1f58934f97aea57d)) /\n int256(0x00000000000000000000000000000000910b022db7ae67ce76b441c27035c6a1); // * e ^ -0.25\n }\n // e ^ -0.125\n if ((x & int256(0x0000000000000000000000000000000010000000000000000000000000000000)) != 0) {\n r =\n (r * int256(0x00000000000000000000000000000000783eafef1c0a8f3978c7f81824d62ebf)) /\n int256(0x0000000000000000000000000000000088415abbe9a76bead8d00cf112e4d4a8); // * e ^ -0.125\n }\n }\n}\n" + }, + "contracts/Tokens/Prime/libs/Scores.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.25;\n\nimport { SafeCastUpgradeable } from \"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol\";\nimport { FixedMath } from \"./FixedMath.sol\";\n\nusing SafeCastUpgradeable for uint256;\n\n/**\n * @title Scores\n * @author Venus\n * @notice Scores library is used to calculate score of users\n */\nlibrary Scores {\n /**\n * @notice Calculate a membership score given some amount of `xvs` and `capital`, along\n * with some 𝝰 = `alphaNumerator` / `alphaDenominator`.\n * @param xvs amount of xvs (xvs, 1e18 decimal places)\n * @param capital amount of capital (1e18 decimal places)\n * @param alphaNumerator alpha param numerator\n * @param alphaDenominator alpha param denominator\n * @return membership score with 1e18 decimal places\n *\n * @dev 𝝰 must be in the range [0, 1]\n */\n function _calculateScore(\n uint256 xvs,\n uint256 capital,\n uint256 alphaNumerator,\n uint256 alphaDenominator\n ) internal pure returns (uint256) {\n // Score function is:\n // xvs^𝝰 * capital^(1-𝝰)\n // = capital * capital^(-𝝰) * xvs^𝝰\n // = capital * (xvs / capital)^𝝰\n // = capital * (e ^ (ln(xvs / capital))) ^ 𝝰\n // = capital * e ^ (𝝰 * ln(xvs / capital)) (1)\n // or\n // = capital / ( 1 / e ^ (𝝰 * ln(xvs / capital)))\n // = capital / (e ^ (𝝰 * ln(xvs / capital)) ^ -1)\n // = capital / e ^ (𝝰 * -1 * ln(xvs / capital))\n // = capital / e ^ (𝝰 * ln(capital / xvs)) (2)\n //\n // To avoid overflows, use (1) when xvs < capital and\n // use (2) when capital < xvs\n\n // If any side is 0, exit early\n if (xvs == 0 || capital == 0) return 0;\n\n // If both sides are equal, we have:\n // xvs^𝝰 * capital^(1-𝝰)\n // = xvs^𝝰 * xvs^(1-𝝰)\n // = xvs^(𝝰 + 1 - 𝝰) = xvs\n if (xvs == capital) return xvs;\n\n bool lessxvsThanCapital = xvs < capital;\n\n // (xvs / capital) or (capital / xvs), always in range (0, 1)\n int256 ratio = lessxvsThanCapital ? FixedMath._toFixed(xvs, capital) : FixedMath._toFixed(capital, xvs);\n\n // e ^ ( ln(ratio) * 𝝰 )\n int256 exponentiation = FixedMath._exp(\n (FixedMath._ln(ratio) * alphaNumerator.toInt256()) / alphaDenominator.toInt256()\n );\n\n if (lessxvsThanCapital) {\n // capital * e ^ (𝝰 * ln(xvs / capital))\n return FixedMath._uintMul(capital, exponentiation);\n }\n\n // capital / e ^ (𝝰 * ln(capital / xvs))\n return FixedMath._uintDiv(capital, exponentiation);\n }\n}\n" + }, + "contracts/Tokens/Prime/Prime.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { SafeERC20Upgradeable, IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\nimport { PausableUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport { MaxLoopsLimitHelper } from \"@venusprotocol/solidity-utilities/contracts/MaxLoopsLimitHelper.sol\";\nimport { TimeManagerV8 } from \"@venusprotocol/solidity-utilities/contracts/TimeManagerV8.sol\";\n\nimport { IERC20MetadataUpgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\nimport { PrimeStorageV1 } from \"./PrimeStorage.sol\";\nimport { Scores } from \"./libs/Scores.sol\";\n\nimport { IPrimeLiquidityProvider } from \"./Interfaces/IPrimeLiquidityProvider.sol\";\nimport { IPrime } from \"./Interfaces/IPrime.sol\";\nimport { IXVSVault } from \"./Interfaces/IXVSVault.sol\";\nimport { IVToken } from \"./Interfaces/IVToken.sol\";\nimport { InterfaceComptroller } from \"./Interfaces/InterfaceComptroller.sol\";\nimport { PoolRegistryInterface } from \"./Interfaces/IPoolRegistry.sol\";\n\n/**\n * @title Prime\n * @author Venus\n * @notice Prime Token is used to provide extra rewards to the users who have staked a minimum of `MINIMUM_STAKED_XVS` XVS in the XVSVault for `STAKING_PERIOD` days\n * @custom:security-contact https://github.com/VenusProtocol/venus-protocol\n */\ncontract Prime is IPrime, AccessControlledV8, PausableUpgradeable, MaxLoopsLimitHelper, PrimeStorageV1, TimeManagerV8 {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice address of wrapped native token contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable WRAPPED_NATIVE_TOKEN;\n\n /// @notice address of native market contract\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n address public immutable NATIVE_MARKET;\n\n /// @notice minimum amount of XVS user needs to stake to become a prime member\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n uint256 public immutable MINIMUM_STAKED_XVS;\n\n /// @notice maximum XVS taken in account when calculating user score\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n uint256 public immutable MAXIMUM_XVS_CAP;\n\n /// @notice number of days user need to stake to claim prime token\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n uint256 public immutable STAKING_PERIOD;\n\n /// @notice Emitted when prime token is minted\n event Mint(address indexed user, bool isIrrevocable);\n\n /// @notice Emitted when prime token is burned\n event Burn(address indexed user);\n\n /// @notice Emitted when a market is added to prime program\n event MarketAdded(\n address indexed comptroller,\n address indexed market,\n uint256 supplyMultiplier,\n uint256 borrowMultiplier\n );\n\n /// @notice Emitted when mint limits are updated\n event MintLimitsUpdated(\n uint256 indexed oldIrrevocableLimit,\n uint256 indexed oldRevocableLimit,\n uint256 indexed newIrrevocableLimit,\n uint256 newRevocableLimit\n );\n\n /// @notice Emitted when user score is updated\n event UserScoreUpdated(address indexed user);\n\n /// @notice Emitted when alpha is updated\n event AlphaUpdated(\n uint128 indexed oldNumerator,\n uint128 indexed oldDenominator,\n uint128 indexed newNumerator,\n uint128 newDenominator\n );\n\n /// @notice Emitted when multiplier is updated\n event MultiplierUpdated(\n address indexed market,\n uint256 indexed oldSupplyMultiplier,\n uint256 indexed oldBorrowMultiplier,\n uint256 newSupplyMultiplier,\n uint256 newBorrowMultiplier\n );\n\n /// @notice Emitted when interest is claimed\n event InterestClaimed(address indexed user, address indexed market, uint256 amount);\n\n /// @notice Emitted when revocable token is upgraded to irrevocable token\n event TokenUpgraded(address indexed user);\n\n /// @notice Emitted when stakedAt is updated\n event StakedAtUpdated(address indexed user, uint256 timestamp);\n\n /// @notice Error thrown when market is not supported\n error MarketNotSupported();\n\n /// @notice Error thrown when mint limit is reached\n error InvalidLimit();\n\n /// @notice Error thrown when user is not eligible to claim prime token\n error IneligibleToClaim();\n\n /// @notice Error thrown when user needs to wait more time to claim prime token\n error WaitMoreTime();\n\n /// @notice Error thrown when user has no prime token\n error UserHasNoPrimeToken();\n\n /// @notice Error thrown when no score updates are required\n error NoScoreUpdatesRequired();\n\n /// @notice Error thrown when market already exists\n error MarketAlreadyExists();\n\n /// @notice Error thrown when asset already exists\n error AssetAlreadyExists();\n\n /// @notice Error thrown when invalid address is passed\n error InvalidAddress();\n\n /// @notice Error thrown when invalid alpha arguments are passed\n error InvalidAlphaArguments();\n\n /// @notice Error thrown when invalid vToken is passed\n error InvalidVToken();\n\n /// @notice Error thrown when invalid length is passed\n error InvalidLength();\n\n /// @notice Error thrown when timestamp is invalid\n error InvalidTimestamp();\n\n /// @notice Error thrown when invalid comptroller is passed\n error InvalidComptroller();\n\n /**\n * @notice Prime constructor\n * @param _wrappedNativeToken Address of wrapped native token\n * @param _nativeMarket Address of native market\n * @param _blocksPerYear total blocks per year\n * @param _stakingPeriod total number of seconds for which user needs to stake to claim prime token\n * @param _minimumStakedXVS minimum amount of XVS user needs to stake to become a prime member (scaled by 1e18)\n * @param _maximumXVSCap maximum XVS taken in account when calculating user score (scaled by 1e18)\n * @param _timeBased A boolean indicating whether the contract is based on time or block.\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(\n address _wrappedNativeToken,\n address _nativeMarket,\n uint256 _blocksPerYear,\n uint256 _stakingPeriod,\n uint256 _minimumStakedXVS,\n uint256 _maximumXVSCap,\n bool _timeBased\n ) TimeManagerV8(_timeBased, _blocksPerYear) {\n WRAPPED_NATIVE_TOKEN = _wrappedNativeToken;\n NATIVE_MARKET = _nativeMarket;\n STAKING_PERIOD = _stakingPeriod;\n MINIMUM_STAKED_XVS = _minimumStakedXVS;\n MAXIMUM_XVS_CAP = _maximumXVSCap;\n\n // Note that the contract is upgradeable. Use initialize() or reinitializers\n // to set the state variables.\n _disableInitializers();\n }\n\n /**\n * @notice Prime initializer\n * @param xvsVault_ Address of XVSVault\n * @param xvsVaultRewardToken_ Address of XVSVault reward token\n * @param xvsVaultPoolId_ Pool id of XVSVault\n * @param alphaNumerator_ numerator of alpha. If alpha is 0.5 then numerator is 1.\n alphaDenominator_ must be greater than alphaNumerator_, alphaDenominator_ cannot be zero and alphaNumerator_ cannot be zero\n * @param alphaDenominator_ denominator of alpha. If alpha is 0.5 then denominator is 2.\n alpha is alphaNumerator_/alphaDenominator_. So, 0 < alpha < 1\n * @param accessControlManager_ Address of AccessControlManager\n * @param primeLiquidityProvider_ Address of PrimeLiquidityProvider\n * @param comptroller_ Address of core pool comptroller\n * @param oracle_ Address of Oracle\n * @param loopsLimit_ Maximum number of loops allowed in a single transaction\n * @custom:error Throw InvalidAddress if any of the address is invalid\n */\n function initialize(\n address xvsVault_,\n address xvsVaultRewardToken_,\n uint256 xvsVaultPoolId_,\n uint128 alphaNumerator_,\n uint128 alphaDenominator_,\n address accessControlManager_,\n address primeLiquidityProvider_,\n address comptroller_,\n address oracle_,\n uint256 loopsLimit_\n ) external initializer {\n if (xvsVault_ == address(0)) revert InvalidAddress();\n if (xvsVaultRewardToken_ == address(0)) revert InvalidAddress();\n if (oracle_ == address(0)) revert InvalidAddress();\n if (primeLiquidityProvider_ == address(0)) revert InvalidAddress();\n\n _checkAlphaArguments(alphaNumerator_, alphaDenominator_);\n\n alphaNumerator = alphaNumerator_;\n alphaDenominator = alphaDenominator_;\n xvsVaultRewardToken = xvsVaultRewardToken_;\n xvsVaultPoolId = xvsVaultPoolId_;\n xvsVault = xvsVault_;\n nextScoreUpdateRoundId = 0;\n primeLiquidityProvider = primeLiquidityProvider_;\n corePoolComptroller = comptroller_;\n oracle = ResilientOracleInterface(oracle_);\n\n __AccessControlled_init(accessControlManager_);\n __Pausable_init();\n _setMaxLoopsLimit(loopsLimit_);\n\n _pause();\n }\n\n /**\n * @notice Prime initializer V2 for initializing pool registry\n * @param poolRegistry_ Address of IL pool registry\n */\n function initializeV2(address poolRegistry_) external reinitializer(2) {\n poolRegistry = poolRegistry_;\n }\n\n /**\n * @notice Returns boosted pending interest accrued for a user for all markets\n * @param user the account for which to get the accrued interests\n * @return pendingRewards the number of underlying tokens accrued by the user for all markets\n */\n function getPendingRewards(address user) external returns (PendingReward[] memory pendingRewards) {\n address[] storage allMarkets = _allMarkets;\n uint256 marketsLength = allMarkets.length;\n\n pendingRewards = new PendingReward[](marketsLength);\n for (uint256 i; i < marketsLength; ) {\n address market = allMarkets[i];\n uint256 interestAccrued = getInterestAccrued(market, user);\n uint256 accrued = interests[market][user].accrued;\n\n pendingRewards[i] = PendingReward({\n vToken: market,\n rewardToken: _getUnderlying(market),\n amount: interestAccrued + accrued\n });\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Update total score of multiple users and market\n * @param users accounts for which we need to update score\n * @custom:error Throw NoScoreUpdatesRequired if no score updates are required\n * @custom:error Throw UserHasNoPrimeToken if user has no prime token\n * @custom:event Emits UserScoreUpdated event\n */\n function updateScores(address[] calldata users) external {\n if (pendingScoreUpdates == 0) revert NoScoreUpdatesRequired();\n if (nextScoreUpdateRoundId == 0) revert NoScoreUpdatesRequired();\n\n for (uint256 i; i < users.length; ) {\n address user = users[i];\n\n if (!tokens[user].exists) revert UserHasNoPrimeToken();\n if (isScoreUpdated[nextScoreUpdateRoundId][user]) {\n unchecked {\n ++i;\n }\n continue;\n }\n\n address[] storage allMarkets = _allMarkets;\n uint256 marketsLength = allMarkets.length;\n\n for (uint256 j; j < marketsLength; ) {\n address market = allMarkets[j];\n _executeBoost(user, market);\n _updateScore(user, market);\n\n unchecked {\n ++j;\n }\n }\n\n --pendingScoreUpdates;\n isScoreUpdated[nextScoreUpdateRoundId][user] = true;\n\n unchecked {\n ++i;\n }\n\n emit UserScoreUpdated(user);\n }\n }\n\n /**\n * @notice Update value of alpha\n * @param _alphaNumerator numerator of alpha. If alpha is 0.5 then numerator is 1\n * @param _alphaDenominator denominator of alpha. If alpha is 0.5 then denominator is 2\n * @custom:event Emits AlphaUpdated event\n * @custom:access Controlled by ACM\n */\n function updateAlpha(uint128 _alphaNumerator, uint128 _alphaDenominator) external {\n _checkAccessAllowed(\"updateAlpha(uint128,uint128)\");\n _checkAlphaArguments(_alphaNumerator, _alphaDenominator);\n\n emit AlphaUpdated(alphaNumerator, alphaDenominator, _alphaNumerator, _alphaDenominator);\n\n alphaNumerator = _alphaNumerator;\n alphaDenominator = _alphaDenominator;\n\n uint256 marketslength = _allMarkets.length;\n\n for (uint256 i; i < marketslength; ) {\n accrueInterest(_allMarkets[i]);\n\n unchecked {\n ++i;\n }\n }\n\n _startScoreUpdateRound();\n }\n\n /**\n * @notice Update multipliers for a market\n * @param market address of the market vToken\n * @param supplyMultiplier new supply multiplier for the market, scaled by 1e18\n * @param borrowMultiplier new borrow multiplier for the market, scaled by 1e18\n * @custom:error Throw MarketNotSupported if market is not supported\n * @custom:event Emits MultiplierUpdated event\n * @custom:access Controlled by ACM\n */\n function updateMultipliers(address market, uint256 supplyMultiplier, uint256 borrowMultiplier) external {\n _checkAccessAllowed(\"updateMultipliers(address,uint256,uint256)\");\n\n Market storage _market = markets[market];\n if (!_market.exists) revert MarketNotSupported();\n\n accrueInterest(market);\n\n emit MultiplierUpdated(\n market,\n _market.supplyMultiplier,\n _market.borrowMultiplier,\n supplyMultiplier,\n borrowMultiplier\n );\n _market.supplyMultiplier = supplyMultiplier;\n _market.borrowMultiplier = borrowMultiplier;\n\n _startScoreUpdateRound();\n }\n\n /**\n * @notice Update staked at timestamp for multiple users\n * @param users accounts for which we need to update staked at timestamp\n * @param timestamps new staked at timestamp for the users\n * @custom:error Throw InvalidLength if users and timestamps length are not equal\n * @custom:event Emits StakedAtUpdated event for each user\n * @custom:access Controlled by ACM\n */\n function setStakedAt(address[] calldata users, uint256[] calldata timestamps) external {\n _checkAccessAllowed(\"setStakedAt(address[],uint256[])\");\n if (users.length != timestamps.length) revert InvalidLength();\n\n for (uint256 i; i < users.length; ) {\n if (timestamps[i] > block.timestamp) revert InvalidTimestamp();\n\n stakedAt[users[i]] = timestamps[i];\n emit StakedAtUpdated(users[i], timestamps[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Add a market to prime program\n * @param comptroller address of the comptroller\n * @param market address of the market vToken\n * @param supplyMultiplier the multiplier for supply cap. It should be converted to 1e18\n * @param borrowMultiplier the multiplier for borrow cap. It should be converted to 1e18\n * @custom:error Throw MarketAlreadyExists if market already exists\n * @custom:error Throw InvalidVToken if market is not valid\n * @custom:event Emits MarketAdded event\n * @custom:access Controlled by ACM\n */\n function addMarket(\n address comptroller,\n address market,\n uint256 supplyMultiplier,\n uint256 borrowMultiplier\n ) external {\n _checkAccessAllowed(\"addMarket(address,address,uint256,uint256)\");\n\n if (comptroller == address(0)) revert InvalidComptroller();\n\n if (\n comptroller != corePoolComptroller &&\n PoolRegistryInterface(poolRegistry).getPoolByComptroller(comptroller).comptroller != comptroller\n ) revert InvalidComptroller();\n\n Market storage _market = markets[market];\n if (_market.exists) revert MarketAlreadyExists();\n\n bool isMarketExist = InterfaceComptroller(comptroller).markets(market);\n if (!isMarketExist) revert InvalidVToken();\n\n delete _market.rewardIndex;\n _market.supplyMultiplier = supplyMultiplier;\n _market.borrowMultiplier = borrowMultiplier;\n delete _market.sumOfMembersScore;\n _market.exists = true;\n\n address underlying = _getUnderlying(market);\n\n if (vTokenForAsset[underlying] != address(0)) revert AssetAlreadyExists();\n vTokenForAsset[underlying] = market;\n\n _allMarkets.push(market);\n _startScoreUpdateRound();\n\n _ensureMaxLoops(_allMarkets.length);\n\n emit MarketAdded(comptroller, market, supplyMultiplier, borrowMultiplier);\n }\n\n /**\n * @notice Set limits for total tokens that can be minted\n * @param _irrevocableLimit total number of irrevocable tokens that can be minted\n * @param _revocableLimit total number of revocable tokens that can be minted\n * @custom:error Throw InvalidLimit if any of the limit is less than total tokens minted\n * @custom:event Emits MintLimitsUpdated event\n * @custom:access Controlled by ACM\n */\n function setLimit(uint256 _irrevocableLimit, uint256 _revocableLimit) external {\n _checkAccessAllowed(\"setLimit(uint256,uint256)\");\n if (_irrevocableLimit < totalIrrevocable || _revocableLimit < totalRevocable) revert InvalidLimit();\n\n emit MintLimitsUpdated(irrevocableLimit, revocableLimit, _irrevocableLimit, _revocableLimit);\n\n revocableLimit = _revocableLimit;\n irrevocableLimit = _irrevocableLimit;\n }\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param loopsLimit Number of loops limit\n * @custom:event Emits MaxLoopsLimitUpdated event on success\n * @custom:access Controlled by ACM\n */\n function setMaxLoopsLimit(uint256 loopsLimit) external {\n _checkAccessAllowed(\"setMaxLoopsLimit(uint256)\");\n _setMaxLoopsLimit(loopsLimit);\n }\n\n /**\n * @notice Directly issue prime tokens to users\n * @param isIrrevocable are the tokens being issued\n * @param users list of address to issue tokens to\n * @custom:access Controlled by ACM\n */\n function issue(bool isIrrevocable, address[] calldata users) external {\n _checkAccessAllowed(\"issue(bool,address[])\");\n\n if (isIrrevocable) {\n for (uint256 i; i < users.length; ) {\n Token storage userToken = tokens[users[i]];\n if (userToken.exists && !userToken.isIrrevocable) {\n _upgrade(users[i]);\n } else {\n _mint(true, users[i]);\n _initializeMarkets(users[i]);\n }\n\n unchecked {\n ++i;\n }\n }\n } else {\n for (uint256 i; i < users.length; ) {\n _mint(false, users[i]);\n _initializeMarkets(users[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n }\n\n /**\n * @notice Executed by XVSVault whenever user's XVSVault balance changes\n * @param user the account address whose balance was updated\n */\n function xvsUpdated(address user) external {\n uint256 totalStaked = _xvsBalanceOfUser(user);\n bool isAccountEligible = _isEligible(totalStaked);\n\n uint256 userStakedAt = stakedAt[user];\n Token memory token = tokens[user];\n\n if (token.exists && !isAccountEligible) {\n delete stakedAt[user];\n emit StakedAtUpdated(user, 0);\n\n if (token.isIrrevocable) {\n _accrueInterestAndUpdateScore(user);\n } else {\n _burn(user);\n }\n } else if (!isAccountEligible && !token.exists && userStakedAt != 0) {\n delete stakedAt[user];\n emit StakedAtUpdated(user, 0);\n } else if (userStakedAt == 0 && isAccountEligible && !token.exists) {\n stakedAt[user] = block.timestamp;\n emit StakedAtUpdated(user, block.timestamp);\n } else if (token.exists && isAccountEligible) {\n _accrueInterestAndUpdateScore(user);\n\n if (stakedAt[user] == 0) {\n stakedAt[user] = block.timestamp;\n emit StakedAtUpdated(user, block.timestamp);\n }\n }\n }\n\n /**\n * @notice accrues interes and updates score for an user for a specific market\n * @param user the account address for which to accrue interest and update score\n * @param market the market for which to accrue interest and update score\n */\n function accrueInterestAndUpdateScore(address user, address market) external {\n _executeBoost(user, market);\n _updateScore(user, market);\n }\n\n /**\n * @notice For claiming prime token when staking period is completed\n */\n function claim() external {\n uint256 userStakedAt = stakedAt[msg.sender];\n if (userStakedAt == 0) revert IneligibleToClaim();\n if (block.timestamp - userStakedAt < STAKING_PERIOD) revert WaitMoreTime();\n\n _mint(false, msg.sender);\n _initializeMarkets(msg.sender);\n }\n\n /**\n * @notice For burning any prime token\n * @param user the account address for which the prime token will be burned\n * @custom:access Controlled by ACM\n */\n function burn(address user) external {\n _checkAccessAllowed(\"burn(address)\");\n _burn(user);\n }\n\n /**\n * @notice To pause or unpause claiming of interest\n * @custom:access Controlled by ACM\n */\n function togglePause() external {\n _checkAccessAllowed(\"togglePause()\");\n if (paused()) {\n _unpause();\n } else {\n _pause();\n }\n }\n\n /**\n * @notice For user to claim boosted yield\n * @param vToken the market for which claim the accrued interest\n * @return amount the amount of tokens transferred to the msg.sender\n */\n function claimInterest(address vToken) external whenNotPaused returns (uint256) {\n return _claimInterest(vToken, msg.sender);\n }\n\n /**\n * @notice For user to claim boosted yield\n * @param vToken the market for which claim the accrued interest\n * @param user the user for which to claim the accrued interest\n * @return amount the amount of tokens transferred to the user\n */\n function claimInterest(address vToken, address user) external whenNotPaused returns (uint256) {\n return _claimInterest(vToken, user);\n }\n\n /**\n * @notice Retrieves an array of all available markets\n * @return an array of addresses representing all available markets\n */\n function getAllMarkets() external view returns (address[] memory) {\n return _allMarkets;\n }\n\n /**\n * @notice Retrieves the core pool comptroller address\n * @return the core pool comptroller address\n */\n function comptroller() external view returns (address) {\n return corePoolComptroller;\n }\n\n /**\n * @notice fetch the numbers of seconds remaining for staking period to complete\n * @param user the account address for which we are checking the remaining time\n * @return timeRemaining the number of seconds the user needs to wait to claim prime token\n */\n function claimTimeRemaining(address user) external view returns (uint256) {\n uint256 userStakedAt = stakedAt[user];\n if (userStakedAt == 0) return STAKING_PERIOD;\n\n uint256 totalTimeStaked;\n unchecked {\n totalTimeStaked = block.timestamp - userStakedAt;\n }\n\n if (totalTimeStaked < STAKING_PERIOD) {\n unchecked {\n return STAKING_PERIOD - totalTimeStaked;\n }\n }\n return 0;\n }\n\n /**\n * @notice Returns if user is a prime holder\n * @return isPrimeHolder true if user is a prime holder\n */\n function isUserPrimeHolder(address user) external view returns (bool) {\n return tokens[user].exists;\n }\n\n /**\n * @notice Returns supply and borrow APR for user for a given market\n * @param market the market for which to fetch the APR\n * @param user the account for which to get the APR\n * @return aprInfo APR information for the user for the given market\n */\n function calculateAPR(address market, address user) external view returns (APRInfo memory aprInfo) {\n IVToken vToken = IVToken(market);\n uint256 borrow = vToken.borrowBalanceStored(user);\n uint256 exchangeRate = vToken.exchangeRateStored();\n uint256 balanceOfAccount = vToken.balanceOf(user);\n uint256 supply = (exchangeRate * balanceOfAccount) / EXP_SCALE;\n\n aprInfo.userScore = interests[market][user].score;\n aprInfo.totalScore = markets[market].sumOfMembersScore;\n\n aprInfo.xvsBalanceForScore = _xvsBalanceForScore(_xvsBalanceOfUser(user));\n Capital memory capital = _capitalForScore(aprInfo.xvsBalanceForScore, borrow, supply, address(vToken));\n\n aprInfo.capital = capital.capital;\n aprInfo.cappedSupply = capital.cappedSupply;\n aprInfo.cappedBorrow = capital.cappedBorrow;\n aprInfo.supplyCapUSD = capital.supplyCapUSD;\n aprInfo.borrowCapUSD = capital.borrowCapUSD;\n\n (aprInfo.supplyAPR, aprInfo.borrowAPR) = _calculateUserAPR(\n market,\n supply,\n borrow,\n aprInfo.cappedSupply,\n aprInfo.cappedBorrow,\n aprInfo.userScore,\n aprInfo.totalScore\n );\n }\n\n /**\n * @notice Returns supply and borrow APR for estimated supply, borrow and XVS staked\n * @param market the market for which to fetch the APR\n * @param user the account for which to get the APR\n * @return aprInfo APR information for the user for the given market\n */\n function estimateAPR(\n address market,\n address user,\n uint256 borrow,\n uint256 supply,\n uint256 xvsStaked\n ) external view returns (APRInfo memory aprInfo) {\n aprInfo.totalScore = markets[market].sumOfMembersScore - interests[market][user].score;\n\n aprInfo.xvsBalanceForScore = _xvsBalanceForScore(xvsStaked);\n Capital memory capital = _capitalForScore(aprInfo.xvsBalanceForScore, borrow, supply, market);\n\n aprInfo.capital = capital.capital;\n aprInfo.cappedSupply = capital.cappedSupply;\n aprInfo.cappedBorrow = capital.cappedBorrow;\n aprInfo.supplyCapUSD = capital.supplyCapUSD;\n aprInfo.borrowCapUSD = capital.borrowCapUSD;\n\n uint256 decimals = IERC20MetadataUpgradeable(_getUnderlying(market)).decimals();\n aprInfo.capital = aprInfo.capital * (10 ** (18 - decimals));\n\n aprInfo.userScore = Scores._calculateScore(\n aprInfo.xvsBalanceForScore,\n aprInfo.capital,\n alphaNumerator,\n alphaDenominator\n );\n\n aprInfo.totalScore = aprInfo.totalScore + aprInfo.userScore;\n\n (aprInfo.supplyAPR, aprInfo.borrowAPR) = _calculateUserAPR(\n market,\n supply,\n borrow,\n aprInfo.cappedSupply,\n aprInfo.cappedBorrow,\n aprInfo.userScore,\n aprInfo.totalScore\n );\n }\n\n /**\n * @notice Distributes income from market since last distribution\n * @param vToken the market for which to distribute the income\n * @custom:error Throw MarketNotSupported if market is not supported\n */\n function accrueInterest(address vToken) public {\n Market storage market = markets[vToken];\n\n if (!market.exists) revert MarketNotSupported();\n\n address underlying = _getUnderlying(vToken);\n\n IPrimeLiquidityProvider _primeLiquidityProvider = IPrimeLiquidityProvider(primeLiquidityProvider);\n _primeLiquidityProvider.accrueTokens(underlying);\n uint256 totalAccruedInPLP = _primeLiquidityProvider.tokenAmountAccrued(underlying);\n uint256 unreleasedPLPAccruedInterest = totalAccruedInPLP - unreleasedPLPIncome[underlying];\n uint256 distributionIncome = unreleasedPLPAccruedInterest;\n\n if (distributionIncome == 0) {\n return;\n }\n\n unreleasedPLPIncome[underlying] = totalAccruedInPLP;\n\n uint256 delta;\n if (market.sumOfMembersScore != 0) {\n delta = ((distributionIncome * EXP_SCALE) / market.sumOfMembersScore);\n }\n\n market.rewardIndex += delta;\n }\n\n /**\n * @notice Returns boosted interest accrued for a user\n * @param vToken the market for which to fetch the accrued interest\n * @param user the account for which to get the accrued interest\n * @return interestAccrued the number of underlying tokens accrued by the user since the last accrual\n */\n function getInterestAccrued(address vToken, address user) public returns (uint256) {\n accrueInterest(vToken);\n\n return _interestAccrued(vToken, user);\n }\n\n /**\n * @notice accrues interest and updates score of all markets for an user\n * @param user the account address for which to accrue interest and update score\n */\n function _accrueInterestAndUpdateScore(address user) internal {\n address[] storage allMarkets = _allMarkets;\n uint256 marketsLength = allMarkets.length;\n\n for (uint256 i; i < marketsLength; ) {\n address market = allMarkets[i];\n _executeBoost(user, market);\n _updateScore(user, market);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Initializes all the markets for the user when a prime token is minted\n * @param account the account address for which markets needs to be initialized\n */\n function _initializeMarkets(address account) internal {\n address[] storage allMarkets = _allMarkets;\n uint256 marketsLength = allMarkets.length;\n\n for (uint256 i; i < marketsLength; ) {\n address market = allMarkets[i];\n accrueInterest(market);\n\n interests[market][account].rewardIndex = markets[market].rewardIndex;\n\n uint256 score = _calculateScore(market, account);\n interests[market][account].score = score;\n markets[market].sumOfMembersScore = markets[market].sumOfMembersScore + score;\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice calculate the current score of user\n * @param market the market for which to calculate the score\n * @param user the account for which to calculate the score\n * @return score the score of the user\n */\n function _calculateScore(address market, address user) internal returns (uint256) {\n uint256 xvsBalanceForScore = _xvsBalanceForScore(_xvsBalanceOfUser(user));\n\n IVToken vToken = IVToken(market);\n uint256 borrow = vToken.borrowBalanceStored(user);\n uint256 exchangeRate = vToken.exchangeRateStored();\n uint256 balanceOfAccount = vToken.balanceOf(user);\n uint256 supply = (exchangeRate * balanceOfAccount) / EXP_SCALE;\n\n address xvsToken = IXVSVault(xvsVault).xvsAddress();\n oracle.updateAssetPrice(xvsToken);\n oracle.updatePrice(market);\n\n Capital memory capital = _capitalForScore(xvsBalanceForScore, borrow, supply, market);\n\n uint256 decimals = IERC20MetadataUpgradeable(_getUnderlying(market)).decimals();\n\n capital.capital = capital.capital * (10 ** (18 - decimals));\n\n return Scores._calculateScore(xvsBalanceForScore, capital.capital, alphaNumerator, alphaDenominator);\n }\n\n /**\n * @notice To transfer the accrued interest to user\n * @param vToken the market for which to claim\n * @param user the account for which to get the accrued interest\n * @return amount the amount of tokens transferred to the user\n * @custom:event Emits InterestClaimed event\n */\n function _claimInterest(address vToken, address user) internal returns (uint256) {\n uint256 amount = getInterestAccrued(vToken, user);\n amount += interests[vToken][user].accrued;\n\n interests[vToken][user].rewardIndex = markets[vToken].rewardIndex;\n delete interests[vToken][user].accrued;\n\n address underlying = _getUnderlying(vToken);\n IERC20Upgradeable asset = IERC20Upgradeable(underlying);\n\n if (amount > asset.balanceOf(address(this))) {\n delete unreleasedPLPIncome[underlying];\n IPrimeLiquidityProvider(primeLiquidityProvider).releaseFunds(address(asset));\n }\n\n asset.safeTransfer(user, amount);\n\n emit InterestClaimed(user, vToken, amount);\n\n return amount;\n }\n\n /**\n * @notice Used to mint a new prime token\n * @param isIrrevocable is the tokens being issued is irrevocable\n * @param user token owner\n * @custom:error Throw IneligibleToClaim if user is not eligible to claim prime token\n * @custom:event Emits Mint event\n */\n function _mint(bool isIrrevocable, address user) internal {\n Token storage token = tokens[user];\n if (token.exists) revert IneligibleToClaim();\n\n token.exists = true;\n token.isIrrevocable = isIrrevocable;\n\n if (isIrrevocable) {\n ++totalIrrevocable;\n } else {\n ++totalRevocable;\n }\n\n if (totalIrrevocable > irrevocableLimit || totalRevocable > revocableLimit) revert InvalidLimit();\n _updateRoundAfterTokenMinted(user);\n\n emit Mint(user, isIrrevocable);\n }\n\n /**\n * @notice Used to burn a new prime token\n * @param user owner whose prime token to burn\n * @custom:error Throw UserHasNoPrimeToken if user has no prime token\n * @custom:event Emits Burn event\n */\n function _burn(address user) internal {\n Token memory token = tokens[user];\n if (!token.exists) revert UserHasNoPrimeToken();\n\n address[] storage allMarkets = _allMarkets;\n uint256 marketsLength = allMarkets.length;\n\n for (uint256 i; i < marketsLength; ) {\n address market = allMarkets[i];\n _executeBoost(user, market);\n markets[market].sumOfMembersScore = markets[market].sumOfMembersScore - interests[market][user].score;\n\n delete interests[market][user].score;\n delete interests[market][user].rewardIndex;\n\n unchecked {\n ++i;\n }\n }\n\n if (token.isIrrevocable) {\n --totalIrrevocable;\n } else {\n --totalRevocable;\n }\n\n delete tokens[user].exists;\n delete tokens[user].isIrrevocable;\n\n _updateRoundAfterTokenBurned(user);\n\n emit Burn(user);\n }\n\n /**\n * @notice Used to upgrade an token\n * @param user owner whose prime token to upgrade\n * @custom:error Throw InvalidLimit if total irrevocable tokens exceeds the limit\n * @custom:event Emits TokenUpgraded event\n */\n function _upgrade(address user) internal {\n Token storage userToken = tokens[user];\n\n userToken.isIrrevocable = true;\n ++totalIrrevocable;\n --totalRevocable;\n\n if (totalIrrevocable > irrevocableLimit) revert InvalidLimit();\n\n emit TokenUpgraded(user);\n }\n\n /**\n * @notice Accrue rewards for the user. Must be called before updating score\n * @param user account for which we need to accrue rewards\n * @param vToken the market for which we need to accrue rewards\n */\n function _executeBoost(address user, address vToken) internal {\n if (!markets[vToken].exists || !tokens[user].exists) {\n return;\n }\n\n accrueInterest(vToken);\n interests[vToken][user].accrued += _interestAccrued(vToken, user);\n interests[vToken][user].rewardIndex = markets[vToken].rewardIndex;\n }\n\n /**\n * @notice Update total score of user and market. Must be called after changing account's borrow or supply balance.\n * @param user account for which we need to update score\n * @param market the market for which we need to score\n */\n function _updateScore(address user, address market) internal {\n Market storage _market = markets[market];\n if (!_market.exists || !tokens[user].exists) {\n return;\n }\n\n uint256 score = _calculateScore(market, user);\n _market.sumOfMembersScore = _market.sumOfMembersScore - interests[market][user].score + score;\n\n interests[market][user].score = score;\n }\n\n /**\n * @notice Verify new alpha arguments\n * @param _alphaNumerator numerator of alpha. If alpha is 0.5 then numerator is 1\n * @param _alphaDenominator denominator of alpha. If alpha is 0.5 then denominator is 2\n * @custom:error Throw InvalidAlphaArguments if alpha is invalid\n */\n function _checkAlphaArguments(uint128 _alphaNumerator, uint128 _alphaDenominator) internal pure {\n if (_alphaNumerator >= _alphaDenominator || _alphaNumerator == 0) {\n revert InvalidAlphaArguments();\n }\n }\n\n /**\n * @notice starts round to update scores of a particular or all markets\n */\n function _startScoreUpdateRound() internal {\n nextScoreUpdateRoundId++;\n totalScoreUpdatesRequired = totalIrrevocable + totalRevocable;\n pendingScoreUpdates = totalScoreUpdatesRequired;\n }\n\n /**\n * @notice update the required score updates when token is burned before round is completed\n */\n function _updateRoundAfterTokenBurned(address user) internal {\n if (totalScoreUpdatesRequired != 0) --totalScoreUpdatesRequired;\n\n if (pendingScoreUpdates != 0 && !isScoreUpdated[nextScoreUpdateRoundId][user]) {\n --pendingScoreUpdates;\n }\n }\n\n /**\n * @notice update the required score updates when token is minted before round is completed\n */\n function _updateRoundAfterTokenMinted(address user) internal {\n if (totalScoreUpdatesRequired != 0) isScoreUpdated[nextScoreUpdateRoundId][user] = true;\n }\n\n /**\n * @notice fetch the current XVS balance of user in the XVSVault\n * @param user the account address\n * @return xvsBalance the XVS balance of user\n */\n function _xvsBalanceOfUser(address user) internal view returns (uint256) {\n (uint256 xvs, , uint256 pendingWithdrawals) = IXVSVault(xvsVault).getUserInfo(\n xvsVaultRewardToken,\n xvsVaultPoolId,\n user\n );\n return (xvs - pendingWithdrawals);\n }\n\n /**\n * @notice calculate the current XVS balance that will be used in calculation of score\n * @param xvs the actual XVS balance of user\n * @return xvsBalanceForScore the XVS balance to use in score\n */\n function _xvsBalanceForScore(uint256 xvs) internal view returns (uint256) {\n if (xvs > MAXIMUM_XVS_CAP) {\n return MAXIMUM_XVS_CAP;\n }\n return xvs;\n }\n\n /**\n * @notice calculate the capital for calculation of score\n * @param xvs the actual XVS balance of user\n * @param borrow the borrow balance of user\n * @param supply the supply balance of user\n * @param market the market vToken address\n * @return capital the capital to use in calculation of score\n */\n function _capitalForScore(\n uint256 xvs,\n uint256 borrow,\n uint256 supply,\n address market\n ) internal view returns (Capital memory capital) {\n address xvsToken = IXVSVault(xvsVault).xvsAddress();\n\n uint256 xvsPrice = oracle.getPrice(xvsToken);\n capital.borrowCapUSD = (xvsPrice * ((xvs * markets[market].borrowMultiplier) / EXP_SCALE)) / EXP_SCALE;\n capital.supplyCapUSD = (xvsPrice * ((xvs * markets[market].supplyMultiplier) / EXP_SCALE)) / EXP_SCALE;\n\n uint256 tokenPrice = oracle.getUnderlyingPrice(market);\n uint256 supplyUSD = (tokenPrice * supply) / EXP_SCALE;\n uint256 borrowUSD = (tokenPrice * borrow) / EXP_SCALE;\n\n if (supplyUSD >= capital.supplyCapUSD) {\n supply = supplyUSD != 0 ? (supply * capital.supplyCapUSD) / supplyUSD : 0;\n }\n\n if (borrowUSD >= capital.borrowCapUSD) {\n borrow = borrowUSD != 0 ? (borrow * capital.borrowCapUSD) / borrowUSD : 0;\n }\n\n capital.capital = supply + borrow;\n capital.cappedSupply = supply;\n capital.cappedBorrow = borrow;\n }\n\n /**\n * @notice Used to get if the XVS balance is eligible for prime token\n * @param amount amount of XVS\n * @return isEligible true if the staked XVS amount is enough to consider the associated user eligible for a Prime token, false otherwise\n */\n function _isEligible(uint256 amount) internal view returns (bool) {\n if (amount >= MINIMUM_STAKED_XVS) {\n return true;\n }\n\n return false;\n }\n\n /**\n * @notice Calculate the interests accrued by the user in the market, since the last accrual\n * @param vToken the market for which to calculate the accrued interest\n * @param user the user for which to calculate the accrued interest\n * @return interestAccrued the number of underlying tokens accrued by the user since the last accrual\n */\n function _interestAccrued(address vToken, address user) internal view returns (uint256) {\n Interest memory interest = interests[vToken][user];\n uint256 index = markets[vToken].rewardIndex - interest.rewardIndex;\n\n uint256 score = interest.score;\n\n return (index * score) / EXP_SCALE;\n }\n\n /**\n * @notice Returns the underlying token associated with the VToken, or wrapped native token if the market is native market\n * @param vToken the market whose underlying token will be returned\n * @return underlying The address of the underlying token associated with the VToken, or the address of the WRAPPED_NATIVE_TOKEN token if the market is NATIVE_MARKET\n */\n function _getUnderlying(address vToken) internal view returns (address) {\n if (vToken == NATIVE_MARKET) {\n return WRAPPED_NATIVE_TOKEN;\n }\n return IVToken(vToken).underlying();\n }\n\n //////////////////////////////////////////////////\n //////////////// APR Calculation ////////////////\n ////////////////////////////////////////////////\n\n /**\n * @notice the total income that's going to be distributed in a year to prime token holders\n * @param vToken the market for which to fetch the total income that's going to distributed in a year\n * @return amount the total income\n */\n function incomeDistributionYearly(address vToken) public view returns (uint256 amount) {\n uint256 totalIncomePerBlockOrSecondFromPLP = IPrimeLiquidityProvider(primeLiquidityProvider)\n .getEffectiveDistributionSpeed(_getUnderlying(vToken));\n amount = blocksOrSecondsPerYear * totalIncomePerBlockOrSecondFromPLP;\n }\n\n /**\n * @notice used to calculate the supply and borrow APR of the user\n * @param vToken the market for which to fetch the APR\n * @param totalSupply the total token supply of the user\n * @param totalBorrow the total tokens borrowed by the user\n * @param totalCappedSupply the total token capped supply of the user\n * @param totalCappedBorrow the total capped tokens borrowed by the user\n * @param userScore the score of the user\n * @param totalScore the total market score\n * @return supplyAPR the supply APR of the user\n * @return borrowAPR the borrow APR of the user\n */\n function _calculateUserAPR(\n address vToken,\n uint256 totalSupply,\n uint256 totalBorrow,\n uint256 totalCappedSupply,\n uint256 totalCappedBorrow,\n uint256 userScore,\n uint256 totalScore\n ) internal view returns (uint256 supplyAPR, uint256 borrowAPR) {\n if (totalScore == 0) return (0, 0);\n\n uint256 userYearlyIncome = (userScore * incomeDistributionYearly(vToken)) / totalScore;\n\n uint256 totalCappedValue = totalCappedSupply + totalCappedBorrow;\n\n if (totalCappedValue == 0) return (0, 0);\n\n uint256 maximumBps = MAXIMUM_BPS;\n uint256 userSupplyIncomeYearly;\n uint256 userBorrowIncomeYearly;\n userSupplyIncomeYearly = (userYearlyIncome * totalCappedSupply) / totalCappedValue;\n userBorrowIncomeYearly = (userYearlyIncome * totalCappedBorrow) / totalCappedValue;\n supplyAPR = totalSupply == 0 ? 0 : ((userSupplyIncomeYearly * maximumBps) / totalSupply);\n borrowAPR = totalBorrow == 0 ? 0 : ((userBorrowIncomeYearly * maximumBps) / totalBorrow);\n }\n}\n" + }, + "contracts/Tokens/Prime/PrimeLiquidityProvider.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { PrimeLiquidityProviderStorageV1 } from \"./PrimeLiquidityProviderStorage.sol\";\nimport { SafeERC20Upgradeable, IERC20Upgradeable } from \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { AccessControlledV8 } from \"@venusprotocol/governance-contracts/contracts/Governance/AccessControlledV8.sol\";\nimport { PausableUpgradeable } from \"@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol\";\nimport { IPrimeLiquidityProvider } from \"./Interfaces/IPrimeLiquidityProvider.sol\";\nimport { MaxLoopsLimitHelper } from \"@venusprotocol/solidity-utilities/contracts/MaxLoopsLimitHelper.sol\";\nimport { TimeManagerV8 } from \"@venusprotocol/solidity-utilities/contracts/TimeManagerV8.sol\";\n\n/**\n * @title PrimeLiquidityProvider\n * @author Venus\n * @notice PrimeLiquidityProvider is used to fund Prime\n */\ncontract PrimeLiquidityProvider is\n IPrimeLiquidityProvider,\n AccessControlledV8,\n PausableUpgradeable,\n MaxLoopsLimitHelper,\n PrimeLiquidityProviderStorageV1,\n TimeManagerV8\n{\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /// @notice The default max token distribution speed\n uint256 public constant DEFAULT_MAX_DISTRIBUTION_SPEED = 1e18;\n\n /// @notice Emitted when a token distribution is initialized\n event TokenDistributionInitialized(address indexed token);\n\n /// @notice Emitted when a new token distribution speed is set\n event TokenDistributionSpeedUpdated(address indexed token, uint256 oldSpeed, uint256 newSpeed);\n\n /// @notice Emitted when a new max distribution speed for token is set\n event MaxTokenDistributionSpeedUpdated(address indexed token, uint256 oldSpeed, uint256 newSpeed);\n\n /// @notice Emitted when prime token contract address is changed\n event PrimeTokenUpdated(address indexed oldPrimeToken, address indexed newPrimeToken);\n\n /// @notice Emitted when distribution state(Index and block or second) is updated\n event TokensAccrued(address indexed token, uint256 amount);\n\n /// @notice Emitted when token is transferred to the prime contract\n event TokenTransferredToPrime(address indexed token, uint256 amount);\n\n /// @notice Emitted on sweep token success\n event SweepToken(address indexed token, address indexed to, uint256 sweepAmount);\n\n /// @notice Thrown when arguments are passed are invalid\n error InvalidArguments();\n\n /// @notice Thrown when distribution speed is greater than maxTokenDistributionSpeeds[tokenAddress]\n error InvalidDistributionSpeed(uint256 speed, uint256 maxSpeed);\n\n /// @notice Thrown when caller is not the desired caller\n error InvalidCaller();\n\n /// @notice Thrown when token is initialized\n error TokenAlreadyInitialized(address token);\n\n ///@notice Error thrown when PrimeLiquidityProvider's balance is less than sweep amount\n error InsufficientBalance(uint256 sweepAmount, uint256 balance);\n\n /// @notice Error thrown when funds transfer is paused\n error FundsTransferIsPaused();\n\n /// @notice Error thrown when accrueTokens is called for an uninitialized token\n error TokenNotInitialized(address token_);\n\n /// @notice Error thrown when argument value in setter is same as previous value\n error AddressesMustDiffer();\n\n /**\n * @notice Compares two addresses to ensure they are different\n * @param oldAddress The original address to compare\n * @param newAddress The new address to compare\n */\n modifier compareAddress(address oldAddress, address newAddress) {\n if (newAddress == oldAddress) {\n revert AddressesMustDiffer();\n }\n _;\n }\n\n /**\n * @notice Prime Liquidity Provider constructor\n * @param _timeBased A boolean indicating whether the contract is based on time or block.\n * @param _blocksPerYear total blocks per year\n */\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor(bool _timeBased, uint256 _blocksPerYear) TimeManagerV8(_timeBased, _blocksPerYear) {\n _disableInitializers();\n }\n\n /**\n * @notice PrimeLiquidityProvider initializer\n * @dev Initializes the deployer to owner\n * @param accessControlManager_ AccessControlManager contract address\n * @param tokens_ Array of addresses of the tokens\n * @param distributionSpeeds_ New distribution speeds for tokens\n * @param loopsLimit_ Maximum number of loops allowed in a single transaction\n * @custom:error Throw InvalidArguments on different length of tokens and speeds array\n */\n function initialize(\n address accessControlManager_,\n address[] calldata tokens_,\n uint256[] calldata distributionSpeeds_,\n uint256[] calldata maxDistributionSpeeds_,\n uint256 loopsLimit_\n ) external initializer {\n _ensureZeroAddress(accessControlManager_);\n\n __AccessControlled_init(accessControlManager_);\n __Pausable_init();\n _setMaxLoopsLimit(loopsLimit_);\n\n uint256 numTokens = tokens_.length;\n _ensureMaxLoops(numTokens);\n\n if ((numTokens != distributionSpeeds_.length) || (numTokens != maxDistributionSpeeds_.length)) {\n revert InvalidArguments();\n }\n\n for (uint256 i; i < numTokens; ) {\n _initializeToken(tokens_[i]);\n _setMaxTokenDistributionSpeed(tokens_[i], maxDistributionSpeeds_[i]);\n _setTokenDistributionSpeed(tokens_[i], distributionSpeeds_[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Initialize the distribution of the token\n * @param tokens_ Array of addresses of the tokens to be intialized\n * @custom:access Only Governance\n */\n function initializeTokens(address[] calldata tokens_) external onlyOwner {\n uint256 tokensLength = tokens_.length;\n _ensureMaxLoops(tokensLength);\n\n for (uint256 i; i < tokensLength; ) {\n _initializeToken(tokens_[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Pause fund transfer of tokens to Prime contract\n * @custom:access Controlled by ACM\n */\n function pauseFundsTransfer() external {\n _checkAccessAllowed(\"pauseFundsTransfer()\");\n _pause();\n }\n\n /**\n * @notice Resume fund transfer of tokens to Prime contract\n * @custom:access Controlled by ACM\n */\n function resumeFundsTransfer() external {\n _checkAccessAllowed(\"resumeFundsTransfer()\");\n _unpause();\n }\n\n /**\n * @notice Set distribution speed (amount of token distribute per block or second)\n * @param tokens_ Array of addresses of the tokens\n * @param distributionSpeeds_ New distribution speeds for tokens\n * @custom:access Controlled by ACM\n * @custom:error Throw InvalidArguments on different length of tokens and speeds array\n */\n function setTokensDistributionSpeed(address[] calldata tokens_, uint256[] calldata distributionSpeeds_) external {\n _checkAccessAllowed(\"setTokensDistributionSpeed(address[],uint256[])\");\n uint256 numTokens = tokens_.length;\n _ensureMaxLoops(numTokens);\n\n if (numTokens != distributionSpeeds_.length) {\n revert InvalidArguments();\n }\n\n for (uint256 i; i < numTokens; ) {\n _ensureTokenInitialized(tokens_[i]);\n _setTokenDistributionSpeed(tokens_[i], distributionSpeeds_[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Set max distribution speed for token (amount of maximum token distribute per block or second)\n * @param tokens_ Array of addresses of the tokens\n * @param maxDistributionSpeeds_ New distribution speeds for tokens\n * @custom:access Controlled by ACM\n * @custom:error Throw InvalidArguments on different length of tokens and speeds array\n */\n function setMaxTokensDistributionSpeed(\n address[] calldata tokens_,\n uint256[] calldata maxDistributionSpeeds_\n ) external {\n _checkAccessAllowed(\"setMaxTokensDistributionSpeed(address[],uint256[])\");\n uint256 numTokens = tokens_.length;\n _ensureMaxLoops(numTokens);\n\n if (numTokens != maxDistributionSpeeds_.length) {\n revert InvalidArguments();\n }\n\n for (uint256 i; i < numTokens; ) {\n _setMaxTokenDistributionSpeed(tokens_[i], maxDistributionSpeeds_[i]);\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Set the prime token contract address\n * @param prime_ The new address of the prime token contract\n * @custom:event Emits PrimeTokenUpdated event\n * @custom:access Only owner\n */\n function setPrimeToken(address prime_) external onlyOwner compareAddress(prime, prime_) {\n _ensureZeroAddress(prime_);\n\n emit PrimeTokenUpdated(prime, prime_);\n prime = prime_;\n }\n\n /**\n * @notice Set the limit for the loops can iterate to avoid the DOS\n * @param loopsLimit Limit for the max loops can execute at a time\n * @custom:event Emits MaxLoopsLimitUpdated event on success\n * @custom:access Controlled by ACM\n */\n function setMaxLoopsLimit(uint256 loopsLimit) external {\n _checkAccessAllowed(\"setMaxLoopsLimit(uint256)\");\n _setMaxLoopsLimit(loopsLimit);\n }\n\n /**\n * @notice Claim all the token accrued till last block or second\n * @param token_ The token to release to the Prime contract\n * @custom:event Emits TokenTransferredToPrime event\n * @custom:error Throw InvalidArguments on Zero address(token)\n * @custom:error Throw FundsTransferIsPaused is paused\n * @custom:error Throw InvalidCaller if the sender is not the Prime contract\n */\n function releaseFunds(address token_) external {\n address _prime = prime;\n if (msg.sender != _prime) revert InvalidCaller();\n if (paused()) {\n revert FundsTransferIsPaused();\n }\n\n accrueTokens(token_);\n uint256 accruedAmount = _tokenAmountAccrued[token_];\n delete _tokenAmountAccrued[token_];\n\n emit TokenTransferredToPrime(token_, accruedAmount);\n\n IERC20Upgradeable(token_).safeTransfer(_prime, accruedAmount);\n }\n\n /**\n * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to user\n * @param token_ The address of the ERC-20 token to sweep\n * @param to_ The address of the recipient\n * @param amount_ The amount of tokens needs to transfer\n * @custom:event Emits SweepToken event\n * @custom:error Throw InsufficientBalance if amount_ is greater than the available balance of the token in the contract\n * @custom:access Only Governance\n */\n function sweepToken(IERC20Upgradeable token_, address to_, uint256 amount_) external onlyOwner {\n uint256 balance = token_.balanceOf(address(this));\n if (amount_ > balance) {\n revert InsufficientBalance(amount_, balance);\n }\n\n emit SweepToken(address(token_), to_, amount_);\n\n token_.safeTransfer(to_, amount_);\n }\n\n /**\n * @notice Get rewards per block or second for token\n * @param token_ Address of the token\n * @return speed returns the per block or second reward\n */\n function getEffectiveDistributionSpeed(address token_) external view returns (uint256) {\n uint256 distributionSpeed = tokenDistributionSpeeds[token_];\n uint256 balance = IERC20Upgradeable(token_).balanceOf(address(this));\n uint256 accrued = _tokenAmountAccrued[token_];\n\n if (balance > accrued) {\n return distributionSpeed;\n }\n\n return 0;\n }\n\n /**\n * @notice Accrue token by updating the distribution state\n * @param token_ Address of the token\n * @custom:event Emits TokensAccrued event\n */\n function accrueTokens(address token_) public {\n _ensureZeroAddress(token_);\n\n _ensureTokenInitialized(token_);\n\n uint256 blockNumberOrSecond = getBlockNumberOrTimestamp();\n uint256 deltaBlocksOrSeconds;\n unchecked {\n deltaBlocksOrSeconds = blockNumberOrSecond - lastAccruedBlockOrSecond[token_];\n }\n\n if (deltaBlocksOrSeconds != 0) {\n uint256 distributionSpeed = tokenDistributionSpeeds[token_];\n uint256 balance = IERC20Upgradeable(token_).balanceOf(address(this));\n\n uint256 balanceDiff = balance - _tokenAmountAccrued[token_];\n if (distributionSpeed != 0 && balanceDiff != 0) {\n uint256 accruedSinceUpdate = deltaBlocksOrSeconds * distributionSpeed;\n uint256 tokenAccrued = (balanceDiff <= accruedSinceUpdate ? balanceDiff : accruedSinceUpdate);\n\n _tokenAmountAccrued[token_] += tokenAccrued;\n emit TokensAccrued(token_, tokenAccrued);\n }\n\n lastAccruedBlockOrSecond[token_] = blockNumberOrSecond;\n }\n }\n\n /**\n * @notice Get the last accrued block or second for token\n * @param token_ Address of the token\n * @return blockNumberOrSecond returns the last accrued block or second\n */\n function lastAccruedBlock(address token_) external view returns (uint256) {\n return lastAccruedBlockOrSecond[token_];\n }\n\n /**\n * @notice Get the tokens accrued\n * @param token_ Address of the token\n * @return returns the amount of accrued tokens for the token provided\n */\n function tokenAmountAccrued(address token_) external view returns (uint256) {\n return _tokenAmountAccrued[token_];\n }\n\n /**\n * @notice Initialize the distribution of the token\n * @param token_ Address of the token to be intialized\n * @custom:event Emits TokenDistributionInitialized event\n * @custom:error Throw TokenAlreadyInitialized if token is already initialized\n */\n function _initializeToken(address token_) internal {\n _ensureZeroAddress(token_);\n uint256 blockNumberOrSecond = getBlockNumberOrTimestamp();\n uint256 initializedBlockOrSecond = lastAccruedBlockOrSecond[token_];\n\n if (initializedBlockOrSecond != 0) {\n revert TokenAlreadyInitialized(token_);\n }\n\n /*\n * Update token state block number or second\n */\n lastAccruedBlockOrSecond[token_] = blockNumberOrSecond;\n\n emit TokenDistributionInitialized(token_);\n }\n\n /**\n * @notice Set distribution speed (amount of token distribute per block or second)\n * @param token_ Address of the token\n * @param distributionSpeed_ New distribution speed for token\n * @custom:event Emits TokenDistributionSpeedUpdated event\n * @custom:error Throw InvalidDistributionSpeed if speed is greater than max speed\n */\n function _setTokenDistributionSpeed(address token_, uint256 distributionSpeed_) internal {\n uint256 maxDistributionSpeed = maxTokenDistributionSpeeds[token_];\n if (maxDistributionSpeed == 0) {\n maxTokenDistributionSpeeds[token_] = maxDistributionSpeed = DEFAULT_MAX_DISTRIBUTION_SPEED;\n }\n\n if (distributionSpeed_ > maxDistributionSpeed) {\n revert InvalidDistributionSpeed(distributionSpeed_, maxDistributionSpeed);\n }\n\n uint256 oldDistributionSpeed = tokenDistributionSpeeds[token_];\n if (oldDistributionSpeed != distributionSpeed_) {\n // Distribution speed updated so let's update distribution state to ensure that\n // 1. Token accrued properly for the old speed, and\n // 2. Token accrued at the new speed starts after this block or second.\n accrueTokens(token_);\n\n // Update speed\n tokenDistributionSpeeds[token_] = distributionSpeed_;\n\n emit TokenDistributionSpeedUpdated(token_, oldDistributionSpeed, distributionSpeed_);\n }\n }\n\n /**\n * @notice Set max distribution speed (amount of maximum token distribute per block or second)\n * @param token_ Address of the token\n * @param maxDistributionSpeed_ New max distribution speed for token\n * @custom:event Emits MaxTokenDistributionSpeedUpdated event\n */\n function _setMaxTokenDistributionSpeed(address token_, uint256 maxDistributionSpeed_) internal {\n emit MaxTokenDistributionSpeedUpdated(token_, tokenDistributionSpeeds[token_], maxDistributionSpeed_);\n maxTokenDistributionSpeeds[token_] = maxDistributionSpeed_;\n }\n\n /**\n * @notice Revert on non initialized token\n * @param token_ Token Address to be verified for\n */\n function _ensureTokenInitialized(address token_) internal view {\n uint256 lastBlockOrSecondAccrued = lastAccruedBlockOrSecond[token_];\n\n if (lastBlockOrSecondAccrued == 0) {\n revert TokenNotInitialized(token_);\n }\n }\n\n /**\n * @notice Revert on zero address\n * @param address_ Address to be verified\n */\n function _ensureZeroAddress(address address_) internal pure {\n if (address_ == address(0)) {\n revert InvalidArguments();\n }\n }\n}\n" + }, + "contracts/Tokens/Prime/PrimeLiquidityProviderStorage.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\n/**\n * @title PrimeLiquidityProviderStorageV1\n * @author Venus\n * @notice Storage for Prime Liquidity Provider\n */\ncontract PrimeLiquidityProviderStorageV1 {\n /// @notice Address of the Prime contract\n address public prime;\n\n /// @notice The rate at which token is distributed (per block or second)\n mapping(address => uint256) public tokenDistributionSpeeds;\n\n /// @notice The max token distribution speed for token\n mapping(address => uint256) public maxTokenDistributionSpeeds;\n\n /// @notice The block or second till which rewards are distributed for an asset\n mapping(address => uint256) public lastAccruedBlockOrSecond;\n\n /// @notice The token accrued but not yet transferred to prime contract\n mapping(address => uint256) internal _tokenAmountAccrued;\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[45] private __gap;\n}\n" + }, + "contracts/Tokens/Prime/PrimeStorage.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.25;\n\nimport { ResilientOracleInterface } from \"@venusprotocol/oracle/contracts/interfaces/OracleInterface.sol\";\n\n/**\n * @title PrimeStorageV1\n * @author Venus\n * @notice Storage for Prime Token\n */\ncontract PrimeStorageV1 {\n struct Token {\n bool exists;\n bool isIrrevocable;\n }\n\n struct Market {\n uint256 supplyMultiplier;\n uint256 borrowMultiplier;\n uint256 rewardIndex;\n uint256 sumOfMembersScore;\n bool exists;\n }\n\n struct Interest {\n uint256 accrued;\n uint256 score;\n uint256 rewardIndex;\n }\n\n struct PendingReward {\n address vToken;\n address rewardToken;\n uint256 amount;\n }\n\n /// @notice Base unit for computations, usually used in scaling (multiplications, divisions)\n uint256 internal constant EXP_SCALE = 1e18;\n\n /// @notice maximum BPS = 100%\n uint256 internal constant MAXIMUM_BPS = 1e4;\n\n /// @notice Mapping to get prime token's metadata\n mapping(address => Token) public tokens;\n\n /// @notice Tracks total irrevocable tokens minted\n uint256 public totalIrrevocable;\n\n /// @notice Tracks total revocable tokens minted\n uint256 public totalRevocable;\n\n /// @notice Indicates maximum revocable tokens that can be minted\n uint256 public revocableLimit;\n\n /// @notice Indicates maximum irrevocable tokens that can be minted\n uint256 public irrevocableLimit;\n\n /// @notice Tracks when prime token eligible users started staking for claiming prime token\n mapping(address => uint256) public stakedAt;\n\n /// @notice vToken to market configuration\n mapping(address => Market) public markets;\n\n /// @notice vToken to user to user index\n mapping(address => mapping(address => Interest)) public interests;\n\n /// @notice A list of boosted markets\n address[] internal _allMarkets;\n\n /// @notice numerator of alpha. Ex: if alpha is 0.5 then this will be 1\n uint128 public alphaNumerator;\n\n /// @notice denominator of alpha. Ex: if alpha is 0.5 then this will be 2\n uint128 public alphaDenominator;\n\n /// @notice address of XVS vault\n address public xvsVault;\n\n /// @notice address of XVS vault reward token\n address public xvsVaultRewardToken;\n\n /// @notice address of XVS vault pool id\n uint256 public xvsVaultPoolId;\n\n /// @notice mapping to check if a account's score was updated in the round\n mapping(uint256 => mapping(address => bool)) public isScoreUpdated;\n\n /// @notice unique id for next round\n uint256 public nextScoreUpdateRoundId;\n\n /// @notice total number of accounts whose score needs to be updated\n uint256 public totalScoreUpdatesRequired;\n\n /// @notice total number of accounts whose score is yet to be updated\n uint256 public pendingScoreUpdates;\n\n /// @notice mapping used to find if an asset is part of prime markets\n mapping(address => address) public vTokenForAsset;\n\n /// @notice Address of core pool comptroller contract\n address internal corePoolComptroller;\n\n /// @notice unreleased income from PLP that's already distributed to prime holders\n /// @dev mapping of asset address => amount\n mapping(address => uint256) public unreleasedPLPIncome;\n\n /// @notice The address of PLP contract\n address public primeLiquidityProvider;\n\n /// @notice The address of ResilientOracle contract\n ResilientOracleInterface public oracle;\n\n /// @notice The address of PoolRegistry contract\n address public poolRegistry;\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[26] private __gap;\n}\n" + } + }, + "settings": { + "optimizer": { + "enabled": true, + "runs": 200 + }, + "evmVersion": "paris", + "outputSelection": { + "*": { + "*": [ + "storageLayout", + "abi", + "evm.bytecode", + "evm.deployedBytecode", + "evm.methodIdentifiers", + "metadata", + "devdoc", + "userdoc", + "evm.gasEstimates" + ], + "": ["ast"] + } + }, + "metadata": { + "useLiteralContent": true + } + } +} diff --git a/deployments/opsepolia_addresses.json b/deployments/opsepolia_addresses.json new file mode 100644 index 000000000..7f2635eba --- /dev/null +++ b/deployments/opsepolia_addresses.json @@ -0,0 +1,7 @@ +{ + "name": "opsepolia", + "chainId": "11155420", + "addresses": { + "VTreasuryV8": "0x5A1a12F47FA7007C9e23cf5e025F3f5d3aC7d755" + } +} diff --git a/hardhat.config.ts b/hardhat.config.ts index 6c0ccc0e8..a0d6ff6ed 100644 --- a/hardhat.config.ts +++ b/hardhat.config.ts @@ -202,6 +202,18 @@ const config: HardhatUserConfig = { live: true, accounts: DEPLOYER_PRIVATE_KEY ? [`0x${DEPLOYER_PRIVATE_KEY}`] : [], }, + opsepolia: { + url: process.env.ARCHIVE_NODE_opsepolia || "https://sepolia.optimism.io", + chainId: 11155420, + live: true, + accounts: DEPLOYER_PRIVATE_KEY ? [`0x${DEPLOYER_PRIVATE_KEY}`] : [], + }, + opmainnet: { + url: process.env.ARCHIVE_NODE_opmainnet || "https://mainnet.optimism.io", + chainId: 10, + live: true, + accounts: DEPLOYER_PRIVATE_KEY ? [`0x${DEPLOYER_PRIVATE_KEY}`] : [], + }, }, etherscan: { apiKey: { @@ -215,6 +227,8 @@ const config: HardhatUserConfig = { arbitrumone: process.env.ETHERSCAN_API_KEY || "ETHERSCAN_API_KEY", xlayertestnet: process.env.ETHERSCAN_API_KEY || "ETHERSCAN_API_KEY", xlayermainnet: process.env.ETHERSCAN_API_KEY || "ETHERSCAN_API_KEY", + opsepolia: process.env.ETHERSCAN_API_KEY || "ETHERSCAN_API_KEY", + opmainnet: process.env.ETHERSCAN_API_KEY || "ETHERSCAN_API_KEY", }, customChains: [ { @@ -297,6 +311,22 @@ const config: HardhatUserConfig = { browserURL: "https://www.oklink.com/xlayer", }, }, + { + network: "opsepolia", + chainId: 11155420, + urls: { + apiURL: "https://api-sepolia-optimistic.etherscan.io/api/", + browserURL: "https://sepolia-optimistic.etherscan.io/", + }, + }, + { + network: "opmainnet", + chainId: 10, + urls: { + apiURL: "https://api-optimistic.etherscan.io/api", + browserURL: "https://optimistic.etherscan.io/", + }, + }, ], }, paths: {