{ "language": "Solidity", "sources": { "contracts/RewardsHubV1.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/AccessControl.sol\";\nimport \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport \"./interfaces/IBDSystem.sol\";\nimport \"./interfaces/IEmissionBooster.sol\";\nimport \"./interfaces/IMnt.sol\";\nimport \"./interfaces/IMToken.sol\";\nimport \"./libraries/ErrorCodes.sol\";\nimport \"./libraries/PauseControl.sol\";\nimport \"./InterconnectorLeaf.sol\";\n\ncontract RewardsHubV1 is Initializable, ReentrancyGuard, AccessControl, PauseControl, InterconnectorLeaf {\n using SafeCast for uint256;\n using SafeERC20Upgradeable for IMnt;\n\n event DistributedSupplierMnt(\n IMToken indexed mToken,\n address indexed supplier,\n uint256 mntDelta,\n uint256 mntSupplyIndex\n );\n event DistributedBorrowerMnt(\n IMToken indexed mToken,\n address indexed borrower,\n uint256 mntDelta,\n uint256 mntBorrowIndex\n );\n event EmissionRewardAccrued(address indexed account, uint256 amount);\n event RepresentativeRewardAccrued(address indexed account, address provider, uint256 amount);\n event BuybackRewardAccrued(address indexed account, uint256 amount);\n event Withdraw(address indexed account, uint256 amount);\n event MntGranted(address recipient, uint256 amount);\n event MntSupplyEmissionRateUpdated(IMToken indexed mToken, uint256 newSupplyEmissionRate);\n event MntBorrowEmissionRateUpdated(IMToken indexed mToken, uint256 newBorrowEmissionRate);\n\n struct IndexState {\n uint224 index;\n uint32 block; // block number of the last index update\n }\n\n /// @dev The right part is the keccak-256 hash of \"GATEKEEPER\"\n bytes32 public constant GATEKEEPER = bytes32(0x20162831d2f54c3e11eebafebfeda495d4c52c67b1708251179ec91fb76dd3b2);\n /// @dev Value is the Keccak-256 hash of \"TIMELOCK\"\n bytes32 public constant TIMELOCK = bytes32(0xaefebe170cbaff0af052a32795af0e1b8afff9850f946ad2869be14f35534371);\n\n uint256 internal constant EXP_SCALE = 1e18;\n uint256 internal constant DOUBLE_SCALE = 1e36;\n\n /// @notice The initial MNT index for a market\n uint224 internal constant MNT_INITIAL_INDEX = 1e36;\n\n IMnt public mnt;\n IEmissionBooster public emissionBooster;\n IBDSystem public bdSystem;\n\n /// @dev Contains amounts of regular rewards for individual accounts.\n mapping(address => uint256) public balances;\n\n // // // // // // MNT emissions\n\n /// @dev The rate at which MNT is distributed to the corresponding supply market (per block)\n mapping(IMToken => uint256) public mntSupplyEmissionRate;\n /// @dev The rate at which MNT is distributed to the corresponding borrow market (per block)\n mapping(IMToken => uint256) public mntBorrowEmissionRate;\n /// @dev The MNT market supply state for each market\n mapping(IMToken => IndexState) public mntSupplyState;\n /// @dev The MNT market borrow state for each market\n mapping(IMToken => IndexState) public mntBorrowState;\n /// @dev The MNT supply index and block number for each market\n /// for each supplier as of the last time they accrued MNT\n mapping(IMToken => mapping(address => IndexState)) public mntSupplierState;\n /// @dev The MNT borrow index and block number for each market\n /// for each supplier as of the last time they accrued MNT\n mapping(IMToken => mapping(address => IndexState)) public mntBorrowerState;\n\n /**\n * @notice Initialise RewardsHub contract\n * @param admin_ admin address\n * @param mnt_ Mnt contract address\n * @param emissionBooster_ EmissionBooster contract address\n * @param bdSystem_ BDSystem contract address\n */\n function initialize(\n address admin_,\n IMnt mnt_,\n IEmissionBooster emissionBooster_,\n IBDSystem bdSystem_\n ) public initializer {\n _grantRole(DEFAULT_ADMIN_ROLE, admin_);\n _grantRole(GATEKEEPER, admin_);\n _grantRole(TIMELOCK, admin_);\n\n mnt = mnt_;\n emissionBooster = emissionBooster_;\n bdSystem = bdSystem_;\n }\n\n // // // // Getters\n\n /**\n * @notice Gets summary amount of available and delayed balances of an account.\n */\n function totalBalanceOf(address account) external view returns (uint256) {\n return balances[account];\n }\n\n /**\n * @notice Gets amount of MNT that can be withdrawn from an account at this block.\n */\n function availableBalanceOf(address account) external view returns (uint256) {\n return balances[account];\n }\n\n // // // // MNT emissions\n\n /**\n * @notice Initializes market in RewardsHub. Should be called once from Supervisor.supportMarket\n * @dev RESTRICTION: Supervisor only\n */\n function initMarket(IMToken mToken) external {\n require(msg.sender == address(supervisor()), ErrorCodes.UNAUTHORIZED);\n require(\n mntSupplyState[mToken].index == 0 && mntBorrowState[mToken].index == 0,\n ErrorCodes.MARKET_ALREADY_LISTED\n );\n\n // Initialize MNT emission indexes of the market\n uint32 currentBlock = getBlockNumber();\n mntSupplyState[mToken] = IndexState({index: MNT_INITIAL_INDEX, block: currentBlock});\n mntBorrowState[mToken] = IndexState({index: MNT_INITIAL_INDEX, block: currentBlock});\n }\n\n /**\n * @dev Calculates the new state of the market.\n * @param state The block number the index was last updated at and the market's last updated mntBorrowIndex\n * or mntSupplyIndex in this block\n * @param emissionRate MNT rate that each market currently receives (supply or borrow)\n * @param totalBalance Total market balance (totalSupply or totalBorrow)\n * Note: this method doesn't return anything, it only mutates memory variable `state`.\n */\n function calculateUpdatedMarketState(\n IndexState memory state,\n uint256 emissionRate,\n uint256 totalBalance\n ) internal view {\n uint256 blockNumber = getBlockNumber();\n\n if (emissionRate > 0) {\n uint256 deltaBlocks = blockNumber - state.block;\n uint256 mntAccrued_ = deltaBlocks * emissionRate;\n uint256 ratio = totalBalance > 0 ? (mntAccrued_ * DOUBLE_SCALE) / totalBalance : 0;\n // index = lastUpdatedIndex + deltaBlocks * emissionRate / amount\n state.index += ratio.toUint224();\n }\n\n state.block = uint32(blockNumber);\n }\n\n /**\n * @dev Gets current market state (the block number and MNT supply index)\n * @param mToken The market whose MNT supply index to get\n */\n function getUpdatedMntSupplyIndex(IMToken mToken) internal view returns (IndexState memory supplyState) {\n supplyState = mntSupplyState[mToken];\n require(supplyState.index >= MNT_INITIAL_INDEX, ErrorCodes.MARKET_NOT_LISTED);\n calculateUpdatedMarketState(supplyState, mntSupplyEmissionRate[mToken], mToken.totalSupply());\n return supplyState;\n }\n\n /**\n * @dev Gets current market state (the block number and MNT supply index)\n * @param mToken The market whose MNT supply index to get\n */\n function getUpdatedMntBorrowIndex(IMToken mToken, uint224 marketBorrowIndex)\n internal\n view\n returns (IndexState memory borrowState)\n {\n borrowState = mntBorrowState[mToken];\n require(borrowState.index >= MNT_INITIAL_INDEX, ErrorCodes.MARKET_NOT_LISTED);\n uint256 borrowAmount = (mToken.totalBorrows() * EXP_SCALE) / marketBorrowIndex;\n calculateUpdatedMarketState(borrowState, mntBorrowEmissionRate[mToken], borrowAmount);\n return borrowState;\n }\n\n /**\n * @dev Accrue MNT to the market by updating the MNT supply index.\n * Index is a cumulative sum of the MNT per mToken accrued.\n * @param mToken The market whose MNT supply index to update\n */\n function updateMntSupplyIndex(IMToken mToken) internal {\n uint32 lastUpdatedBlock = mntSupplyState[mToken].block;\n if (lastUpdatedBlock == getBlockNumber()) return;\n\n if (emissionBooster.isEmissionBoostingEnabled()) {\n uint224 lastUpdatedIndex = mntSupplyState[mToken].index;\n IndexState memory currentState = getUpdatedMntSupplyIndex(mToken);\n mntSupplyState[mToken] = currentState;\n // slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events\n emissionBooster.updateSupplyIndexesHistory(mToken, lastUpdatedBlock, lastUpdatedIndex, currentState.index);\n } else {\n mntSupplyState[mToken] = getUpdatedMntSupplyIndex(mToken);\n }\n }\n\n /**\n * @dev Accrue MNT to the market by updating the MNT borrow index.\n * Index is a cumulative sum of the MNT per mToken accrued.\n * @param mToken The market whose MNT borrow index to update\n * @param marketBorrowIndex The market's last updated BorrowIndex\n */\n function updateMntBorrowIndex(IMToken mToken, uint224 marketBorrowIndex) internal {\n uint32 lastUpdatedBlock = mntBorrowState[mToken].block;\n if (lastUpdatedBlock == getBlockNumber()) return;\n\n if (emissionBooster.isEmissionBoostingEnabled()) {\n uint224 lastUpdatedIndex = mntBorrowState[mToken].index;\n IndexState memory currentState = getUpdatedMntBorrowIndex(mToken, marketBorrowIndex);\n mntBorrowState[mToken] = currentState;\n // slither-disable-next-line reentrancy-no-eth,reentrancy-benign,reentrancy-events\n emissionBooster.updateBorrowIndexesHistory(mToken, lastUpdatedBlock, lastUpdatedIndex, currentState.index);\n } else {\n mntBorrowState[mToken] = getUpdatedMntBorrowIndex(mToken, marketBorrowIndex);\n }\n }\n\n /**\n * @notice Accrues MNT to the market by updating the borrow and supply indexes\n * @dev This method doesn't update MNT index history in Minterest NFT.\n * @param market The market whose supply and borrow index to update\n * @return (MNT supply index, MNT borrow index)\n */\n function updateAndGetMntIndexes(IMToken market) external returns (uint224, uint224) {\n IndexState memory supplyState = getUpdatedMntSupplyIndex(market);\n mntSupplyState[market] = supplyState;\n\n uint224 borrowIndex = market.borrowIndex().toUint224();\n IndexState memory borrowState = getUpdatedMntBorrowIndex(market, borrowIndex);\n mntBorrowState[market] = borrowState;\n\n return (supplyState.index, borrowState.index);\n }\n\n struct EmissionsDistributionVars {\n address account;\n address representative;\n uint256 representativeBonus;\n uint256 liquidityProviderBoost;\n uint256 accruedMnt;\n }\n\n /// @dev Basically EmissionsDistributionVars constructor\n function createDistributionState(address account)\n internal\n view\n checkPaused(DISTRIBUTION_OP)\n returns (EmissionsDistributionVars memory vars)\n {\n vars.account = account;\n\n (\n vars.liquidityProviderBoost,\n vars.representativeBonus,\n ,\n // ^^^ skips endBlock\n vars.representative\n ) = bdSystem.providerToAgreement(account);\n }\n\n /// @dev Accrues MNT emissions of account per market and saves result to EmissionsDistributionVars\n function updateDistributionState(\n EmissionsDistributionVars memory vars,\n IMToken mToken,\n uint256 accountBalance,\n uint224 currentMntIndex,\n IndexState storage accountIndex,\n bool isSupply\n ) internal {\n uint32 currentBlock = getBlockNumber();\n uint224 lastAccountIndex = accountIndex.index;\n uint32 lastUpdateBlock = accountIndex.block;\n\n if (lastAccountIndex == 0 && currentMntIndex >= MNT_INITIAL_INDEX) {\n // Covers the case where users interacted with market before its state index was set.\n // Rewards the user with MNT accrued from the start of when account rewards were first\n // set for the market.\n lastAccountIndex = MNT_INITIAL_INDEX;\n lastUpdateBlock = currentBlock;\n }\n\n // Update supplier's index and block to the current index and block since we are distributing accrued MNT\n accountIndex.index = currentMntIndex;\n accountIndex.block = currentBlock;\n\n if (currentMntIndex == lastAccountIndex) return;\n\n uint256 deltaIndex = currentMntIndex - lastAccountIndex;\n\n if (vars.representative != address(0)) {\n // Calc change in the cumulative sum of the MNT per mToken accrued (with considering BD system boosts)\n deltaIndex += (deltaIndex * vars.liquidityProviderBoost) / EXP_SCALE;\n } else {\n // Calc change in the cumulative sum of the MNT per mToken accrued (with considering NFT emission boost).\n // NFT emission boost doesn't work with liquidity provider emission boost at the same time.\n deltaIndex += emissionBooster.calculateEmissionBoost(\n mToken,\n vars.account,\n lastAccountIndex,\n lastUpdateBlock,\n currentMntIndex,\n isSupply\n );\n }\n\n uint256 accruedMnt = (accountBalance * deltaIndex) / DOUBLE_SCALE;\n vars.accruedMnt += accruedMnt;\n\n if (isSupply) emit DistributedSupplierMnt(mToken, vars.account, accruedMnt, currentMntIndex);\n else emit DistributedBorrowerMnt(mToken, vars.account, accruedMnt, currentMntIndex);\n }\n\n /// @dev Accumulate accrued MNT to user balance and its BDR representative if they have any.\n /// Also updates buyback and voting weights for user\n function payoutDistributionState(EmissionsDistributionVars memory vars) internal {\n if (vars.accruedMnt == 0) return;\n\n balances[vars.account] += vars.accruedMnt;\n emit EmissionRewardAccrued(vars.account, vars.accruedMnt);\n\n if (vars.representative != address(0)) {\n uint256 repReward = (vars.accruedMnt * vars.representativeBonus) / EXP_SCALE;\n balances[vars.representative] += repReward;\n emit RepresentativeRewardAccrued(vars.representative, vars.account, repReward);\n }\n\n // Use relaxed update so it could skip if buyback update is paused\n buyback().updateBuybackAndVotingWeightsRelaxed(vars.account);\n }\n\n /**\n * @notice Shorthand function to distribute MNT emissions from supplies of one market.\n */\n function distributeSupplierMnt(IMToken mToken, address account) external {\n updateMntSupplyIndex(mToken);\n\n EmissionsDistributionVars memory vars = createDistributionState(account);\n uint256 supplyAmount = mToken.balanceOf(account);\n updateDistributionState(\n vars,\n mToken,\n supplyAmount,\n mntSupplyState[mToken].index,\n mntSupplierState[mToken][account],\n true\n );\n payoutDistributionState(vars);\n }\n\n /**\n * @notice Shorthand function to distribute MNT emissions from borrows of one market.\n */\n function distributeBorrowerMnt(IMToken mToken, address account) external {\n uint224 borrowIndex = mToken.borrowIndex().toUint224();\n updateMntBorrowIndex(mToken, borrowIndex);\n\n EmissionsDistributionVars memory vars = createDistributionState(account);\n uint256 borrowAmount = (mToken.borrowBalanceStored(account) * EXP_SCALE) / borrowIndex;\n updateDistributionState(\n vars,\n mToken,\n borrowAmount,\n mntBorrowState[mToken].index,\n mntBorrowerState[mToken][account],\n false\n );\n payoutDistributionState(vars);\n }\n\n /**\n * @notice Updates market indices and distributes tokens (if any) for holder\n * @dev Updates indices and distributes only for those markets where the holder have a\n * non-zero supply or borrow balance.\n * @param account The address to distribute MNT for\n */\n function distributeAllMnt(address account) external nonReentrant {\n return distributeAccountMnt(account, supervisor().getAllMarkets(), true, true);\n }\n\n /**\n * @notice Distribute all MNT accrued by the accounts\n * @param accounts The addresses to distribute MNT for\n * @param mTokens The list of markets to distribute MNT in\n * @param borrowers Whether or not to distribute MNT earned by borrowing\n * @param suppliers Whether or not to distribute MNT earned by supplying\n */\n function distributeMnt(\n address[] calldata accounts,\n IMToken[] calldata mTokens,\n bool borrowers,\n bool suppliers\n ) external nonReentrant {\n ISupervisor cachedSupervisor = supervisor();\n for (uint256 i = 0; i < mTokens.length; i++) {\n require(cachedSupervisor.isMarketListed(mTokens[i]), ErrorCodes.MARKET_NOT_LISTED);\n }\n for (uint256 i = 0; i < accounts.length; i++) {\n distributeAccountMnt(accounts[i], mTokens, borrowers, suppliers);\n }\n }\n\n function distributeAccountMnt(\n address account,\n IMToken[] memory mTokens,\n bool borrowers,\n bool suppliers\n ) internal {\n EmissionsDistributionVars memory vars = createDistributionState(account);\n\n for (uint256 i = 0; i < mTokens.length; i++) {\n IMToken mToken = mTokens[i];\n if (borrowers) {\n uint256 accountBorrowUnderlying = mToken.borrowBalanceStored(account);\n if (accountBorrowUnderlying > 0) {\n uint224 borrowIndex = mToken.borrowIndex().toUint224();\n updateMntBorrowIndex(mToken, borrowIndex);\n updateDistributionState(\n vars,\n mToken,\n (accountBorrowUnderlying * EXP_SCALE) / borrowIndex,\n mntBorrowState[mToken].index,\n mntBorrowerState[mToken][account],\n false\n );\n }\n }\n if (suppliers) {\n uint256 accountSupplyWrap = mToken.balanceOf(account);\n if (accountSupplyWrap > 0) {\n updateMntSupplyIndex(mToken);\n updateDistributionState(\n vars,\n mToken,\n accountSupplyWrap,\n mntSupplyState[mToken].index,\n mntSupplierState[mToken][account],\n true\n );\n }\n }\n }\n\n payoutDistributionState(vars);\n }\n\n // // // // Rewards accrual\n\n /**\n * @notice Accrues buyback reward\n * @dev RESTRICTION: Buyback only\n */\n function accrueBuybackReward(address account, uint256 amount) external {\n require(msg.sender == address(buyback()), ErrorCodes.UNAUTHORIZED);\n accrueReward(account, amount);\n emit BuybackRewardAccrued(account, amount);\n }\n\n function accrueReward(address account, uint256 amount) internal {\n revert(\"unimplemented\"); // TODO: Implement delay buckets\n\n balances[account] += amount;\n }\n\n // // // // Withdrawal\n\n /**\n * @notice Transfers available part of MNT rewards to the sender.\n * This will decrease accounts buyback and voting weights.\n */\n function withdraw(uint256 amount) external checkPaused(WITHDRAW_OP) {\n revert(\"unimplemented\"); // TODO: Claim rewards unlocked from delay here\n\n uint256 balance = balances[msg.sender];\n if (amount == type(uint256).max) amount = balance;\n\n require(amount <= balance, ErrorCodes.INCORRECT_AMOUNT);\n balances[msg.sender] = balance - amount;\n\n emit Withdraw(msg.sender, amount);\n\n buyback().updateBuybackAndVotingWeights(msg.sender);\n mnt.safeTransfer(msg.sender, amount);\n }\n\n /**\n * @notice Transfers\n * @dev RESTRICTION: Admin only\n */\n function grant(address recipient, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {\n require(amount > 0, ErrorCodes.INCORRECT_AMOUNT);\n\n uint256 balance = mnt.balanceOf(address(this));\n require(balance >= amount, ErrorCodes.INSUFFICIENT_MNT_FOR_GRANT);\n\n emit MntGranted(recipient, amount);\n\n mnt.safeTransfer(recipient, amount);\n }\n\n // // // // Admin zone\n\n /**\n * @notice Set MNT borrow and supply emission rates for a single market\n * @param mToken The market whose MNT emission rate to update\n * @param newMntSupplyEmissionRate New supply MNT emission rate for market\n * @param newMntBorrowEmissionRate New borrow MNT emission rate for market\n * @dev RESTRICTION Timelock only\n */\n function setMntEmissionRates(\n IMToken mToken,\n uint256 newMntSupplyEmissionRate,\n uint256 newMntBorrowEmissionRate\n ) external onlyRole(TIMELOCK) {\n require(supervisor().isMarketListed(mToken), ErrorCodes.MARKET_NOT_LISTED);\n\n if (mntSupplyEmissionRate[mToken] != newMntSupplyEmissionRate) {\n // Supply emission rate updated so let's update supply state to ensure that\n // 1. MNT accrued properly for the old emission rate.\n // 2. MNT accrued at the new speed starts after this block.\n updateMntSupplyIndex(mToken);\n\n // Update emission rate and emit event\n mntSupplyEmissionRate[mToken] = newMntSupplyEmissionRate;\n emit MntSupplyEmissionRateUpdated(mToken, newMntSupplyEmissionRate);\n }\n\n if (mntBorrowEmissionRate[mToken] != newMntBorrowEmissionRate) {\n // Borrow emission rate updated so let's update borrow state to ensure that\n // 1. MNT accrued properly for the old emission rate.\n // 2. MNT accrued at the new speed starts after this block.\n uint224 borrowIndex = mToken.borrowIndex().toUint224();\n updateMntBorrowIndex(mToken, borrowIndex);\n\n // Update emission rate and emit event\n mntBorrowEmissionRate[mToken] = newMntBorrowEmissionRate;\n emit MntBorrowEmissionRateUpdated(mToken, newMntBorrowEmissionRate);\n }\n }\n\n // // // // Pause control\n\n bytes32 internal constant DISTRIBUTION_OP = \"MntDistribution\";\n bytes32 internal constant WITHDRAW_OP = \"Withdraw\";\n\n function validatePause(address) internal view override {\n require(hasRole(GATEKEEPER, msg.sender), ErrorCodes.UNAUTHORIZED);\n }\n\n function validateUnpause(address) internal view override {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), ErrorCodes.UNAUTHORIZED);\n }\n\n // // // // Utils\n\n function getTimestamp() internal view virtual returns (uint32) {\n return block.timestamp.toUint32();\n }\n\n function getBlockNumber() internal view virtual returns (uint32) {\n return uint32(block.number);\n }\n\n function supervisor() internal view returns (ISupervisor) {\n return getInterconnector().supervisor();\n }\n\n function buyback() internal view returns (IBuyback) {\n return getInterconnector().buyback();\n }\n}\n" }, "contracts/InterconnectorLeaf.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./libraries/ProtocolLinkage.sol\";\nimport \"./interfaces/IInterconnectorLeaf.sol\";\n\nabstract contract InterconnectorLeaf is IInterconnectorLeaf, LinkageLeaf {\n function getInterconnector() public view returns (IInterconnector) {\n return IInterconnector(getLinkageRootAddress());\n }\n}\n" }, "contracts/interfaces/IBDSystem.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IBDSystem is IAccessControl, ILinkageLeaf {\n event AgreementAdded(\n address indexed liquidityProvider,\n address indexed representative,\n uint256 representativeBonus,\n uint256 liquidityProviderBoost,\n uint32 startBlock,\n uint32 endBlock\n );\n event AgreementEnded(\n address indexed liquidityProvider,\n address indexed representative,\n uint256 representativeBonus,\n uint256 liquidityProviderBoost,\n uint32 endBlock\n );\n\n /**\n * @notice getter function to get liquidity provider agreement\n */\n function providerToAgreement(address)\n external\n view\n returns (\n uint256 liquidityProviderBoost,\n uint256 representativeBonus,\n uint32 endBlock,\n address representative\n );\n\n /**\n * @notice getter function to get counts\n * of liquidity providers of the representative\n */\n function representativesProviderCounter(address) external view returns (uint256);\n\n /**\n * @notice Creates a new agreement between liquidity provider and representative\n * @dev Admin function to create a new agreement\n * @param liquidityProvider_ address of the liquidity provider\n * @param representative_ address of the liquidity provider representative.\n * @param representativeBonus_ percentage of the emission boost for representative\n * @param liquidityProviderBoost_ percentage of the boost for liquidity provider\n * @param endBlock_ The number of the first block when agreement will not be in effect\n * @dev RESTRICTION: Admin only\n */\n function createAgreement(\n address liquidityProvider_,\n address representative_,\n uint256 representativeBonus_,\n uint256 liquidityProviderBoost_,\n uint32 endBlock_\n ) external;\n\n /**\n * @notice Removes a agreement between liquidity provider and representative\n * @dev Admin function to remove a agreement\n * @param liquidityProvider_ address of the liquidity provider\n * @param representative_ address of the representative.\n * @dev RESTRICTION: Admin only\n */\n function removeAgreement(address liquidityProvider_, address representative_) external;\n\n /**\n * @notice checks if `account_` is liquidity provider.\n * @dev account_ is liquidity provider if he has agreement.\n * @param account_ address to check\n * @return `true` if `account_` is liquidity provider, otherwise returns false\n */\n function isAccountLiquidityProvider(address account_) external view returns (bool);\n\n /**\n * @notice checks if `account_` is business development representative.\n * @dev account_ is business development representative if he has liquidity providers.\n * @param account_ address to check\n * @return `true` if `account_` is business development representative, otherwise returns false\n */\n function isAccountRepresentative(address account_) external view returns (bool);\n\n /**\n * @notice checks if agreement is expired\n * @dev reverts if the `account_` is not a valid liquidity provider\n * @param account_ address of the liquidity provider\n * @return `true` if agreement is expired, otherwise returns false\n */\n function isAgreementExpired(address account_) external view returns (bool);\n}\n" }, "contracts/libraries/PauseControl.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./ErrorCodes.sol\";\n\nabstract contract PauseControl {\n event OperationPaused(bytes32 op, address subject);\n event OperationUnpaused(bytes32 op, address subject);\n\n mapping(address => mapping(bytes32 => bool)) internal pausedOps;\n\n function validatePause(address subject) internal view virtual;\n\n function validateUnpause(address subject) internal view virtual;\n\n function isOperationPaused(bytes32 op, address subject) public view returns (bool) {\n return pausedOps[subject][op];\n }\n\n function pauseOperation(bytes32 op, address subject) external virtual {\n validatePause(subject);\n require(!isOperationPaused(op, subject));\n pausedOps[subject][op] = true;\n emit OperationPaused(op, subject);\n }\n\n function unpauseOperation(bytes32 op, address subject) external virtual {\n validateUnpause(subject);\n require(isOperationPaused(op, subject));\n pausedOps[subject][op] = false;\n emit OperationUnpaused(op, subject);\n }\n\n modifier checkPausedSubject(bytes32 op, address subject) {\n require(!isOperationPaused(op, subject), ErrorCodes.OPERATION_PAUSED);\n _;\n }\n\n modifier checkPaused(bytes32 op) {\n require(!isOperationPaused(op, address(0)), ErrorCodes.OPERATION_PAUSED);\n _;\n }\n}\n" }, "contracts/libraries/ErrorCodes.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nlibrary ErrorCodes {\n // Common\n string internal constant ADMIN_ONLY = \"E101\";\n string internal constant UNAUTHORIZED = \"E102\";\n string internal constant OPERATION_PAUSED = \"E103\";\n string internal constant WHITELISTED_ONLY = \"E104\";\n string internal constant ADDRESS_IS_NOT_IN_AML_SYSTEM = \"E105\";\n string internal constant ADDRESS_IS_BLACKLISTED = \"E106\";\n\n // Invalid input\n string internal constant ADMIN_ADDRESS_CANNOT_BE_ZERO = \"E201\";\n string internal constant INVALID_REDEEM = \"E202\";\n string internal constant REDEEM_TOO_MUCH = \"E203\";\n string internal constant MARKET_NOT_LISTED = \"E204\";\n string internal constant INSUFFICIENT_LIQUIDITY = \"E205\";\n string internal constant INVALID_SENDER = \"E206\";\n string internal constant BORROW_CAP_REACHED = \"E207\";\n string internal constant BALANCE_OWED = \"E208\";\n string internal constant UNRELIABLE_LIQUIDATOR = \"E209\";\n string internal constant INVALID_DESTINATION = \"E210\";\n string internal constant INSUFFICIENT_STAKE = \"E211\";\n string internal constant INVALID_DURATION = \"E212\";\n string internal constant INVALID_PERIOD_RATE = \"E213\";\n string internal constant EB_TIER_LIMIT_REACHED = \"E214\";\n string internal constant INVALID_DEBT_REDEMPTION_RATE = \"E215\";\n string internal constant LQ_INVALID_SEIZE_DISTRIBUTION = \"E216\";\n string internal constant EB_TIER_DOES_NOT_EXIST = \"E217\";\n string internal constant EB_ZERO_TIER_CANNOT_BE_ENABLED = \"E218\";\n string internal constant EB_ALREADY_ACTIVATED_TIER = \"E219\";\n string internal constant EB_END_BLOCK_MUST_BE_LARGER_THAN_CURRENT = \"E220\";\n string internal constant EB_CANNOT_MINT_TOKEN_FOR_ACTIVATED_TIER = \"E221\";\n string internal constant EB_EMISSION_BOOST_IS_NOT_IN_RANGE = \"E222\";\n string internal constant TARGET_ADDRESS_CANNOT_BE_ZERO = \"E223\";\n string internal constant INSUFFICIENT_TOKEN_IN_VESTING_CONTRACT = \"E224\";\n string internal constant VESTING_SCHEDULE_ALREADY_EXISTS = \"E225\";\n string internal constant INSUFFICIENT_TOKENS_TO_CREATE_SCHEDULE = \"E226\";\n string internal constant NO_VESTING_SCHEDULE = \"E227\";\n string internal constant SCHEDULE_IS_IRREVOCABLE = \"E228\";\n string internal constant MNT_AMOUNT_IS_ZERO = \"E230\";\n string internal constant INCORRECT_AMOUNT = \"E231\";\n string internal constant MEMBERSHIP_LIMIT = \"E232\";\n string internal constant MEMBER_NOT_EXIST = \"E233\";\n string internal constant MEMBER_ALREADY_ADDED = \"E234\";\n string internal constant MEMBERSHIP_LIMIT_REACHED = \"E235\";\n string internal constant REPORTED_PRICE_SHOULD_BE_GREATER_THAN_ZERO = \"E236\";\n string internal constant MTOKEN_ADDRESS_CANNOT_BE_ZERO = \"E237\";\n string internal constant TOKEN_ADDRESS_CANNOT_BE_ZERO = \"E238\";\n string internal constant REDEEM_TOKENS_OR_REDEEM_AMOUNT_MUST_BE_ZERO = \"E239\";\n string internal constant FL_TOKEN_IS_NOT_UNDERLYING = \"E240\";\n string internal constant FL_AMOUNT_IS_TOO_LARGE = \"E241\";\n string internal constant FL_CALLBACK_FAILED = \"E242\";\n string internal constant DD_UNSUPPORTED_TOKEN = \"E243\";\n string internal constant DD_MARKET_ADDRESS_IS_ZERO = \"E244\";\n string internal constant DD_ROUTER_ADDRESS_IS_ZERO = \"E245\";\n string internal constant DD_RECEIVER_ADDRESS_IS_ZERO = \"E246\";\n string internal constant DD_BOT_ADDRESS_IS_ZERO = \"E247\";\n string internal constant DD_MARKET_NOT_FOUND = \"E248\";\n string internal constant DD_RECEIVER_NOT_FOUND = \"E249\";\n string internal constant DD_BOT_NOT_FOUND = \"E250\";\n string internal constant DD_ROUTER_ALREADY_SET = \"E251\";\n string internal constant DD_RECEIVER_ALREADY_SET = \"E252\";\n string internal constant DD_BOT_ALREADY_SET = \"E253\";\n string internal constant EB_MARKET_INDEX_IS_LESS_THAN_USER_INDEX = \"E254\";\n string internal constant LQ_INVALID_DRR_ARRAY = \"E255\";\n string internal constant LQ_INVALID_SEIZE_ARRAY = \"E256\";\n string internal constant LQ_INVALID_DEBT_REDEMPTION_RATE = \"E257\";\n string internal constant LQ_INVALID_SEIZE_INDEX = \"E258\";\n string internal constant LQ_DUPLICATE_SEIZE_INDEX = \"E259\";\n string internal constant DD_INVALID_TOKEN_IN_ADDRESS = \"E260\";\n string internal constant DD_INVALID_TOKEN_OUT_ADDRESS = \"E261\";\n string internal constant DD_INVALID_TOKEN_IN_AMOUNT = \"E262\";\n\n // Protocol errors\n string internal constant INVALID_PRICE = \"E301\";\n string internal constant MARKET_NOT_FRESH = \"E302\";\n string internal constant BORROW_RATE_TOO_HIGH = \"E303\";\n string internal constant INSUFFICIENT_TOKEN_CASH = \"E304\";\n string internal constant INSUFFICIENT_TOKENS_FOR_RELEASE = \"E305\";\n string internal constant INSUFFICIENT_MNT_FOR_GRANT = \"E306\";\n string internal constant TOKEN_TRANSFER_IN_UNDERFLOW = \"E307\";\n string internal constant NOT_PARTICIPATING_IN_BUYBACK = \"E308\";\n string internal constant NOT_ENOUGH_PARTICIPATING_ACCOUNTS = \"E309\";\n string internal constant NOTHING_TO_DISTRIBUTE = \"E310\";\n string internal constant ALREADY_PARTICIPATING_IN_BUYBACK = \"E311\";\n string internal constant MNT_APPROVE_FAILS = \"E312\";\n string internal constant TOO_EARLY_TO_DRIP = \"E313\";\n string internal constant BB_UNSTAKE_TOO_EARLY = \"E314\";\n string internal constant INSUFFICIENT_SHORTFALL = \"E315\";\n string internal constant HEALTHY_FACTOR_NOT_IN_RANGE = \"E316\";\n string internal constant BUYBACK_DRIPS_ALREADY_HAPPENED = \"E317\";\n string internal constant EB_INDEX_SHOULD_BE_GREATER_THAN_INITIAL = \"E318\";\n string internal constant NO_VESTING_SCHEDULES = \"E319\";\n string internal constant INSUFFICIENT_UNRELEASED_TOKENS = \"E320\";\n string internal constant ORACLE_PRICE_EXPIRED = \"E321\";\n string internal constant TOKEN_NOT_FOUND = \"E322\";\n string internal constant RECEIVED_PRICE_HAS_INVALID_ROUND = \"E323\";\n string internal constant FL_PULL_AMOUNT_IS_TOO_LOW = \"E324\";\n string internal constant INSUFFICIENT_TOTAL_PROTOCOL_INTEREST = \"E325\";\n string internal constant BB_ACCOUNT_RECENTLY_VOTED = \"E326\";\n string internal constant DD_SWAP_ROUTER_IS_ZERO = \"E327\";\n string internal constant DD_SWAP_CALL_FAILS = \"E328\";\n string internal constant LL_NEW_ROOT_CANNOT_BE_ZERO = \"E329\";\n\n // Invalid input - Admin functions\n string internal constant ZERO_EXCHANGE_RATE = \"E401\";\n string internal constant SECOND_INITIALIZATION = \"E402\";\n string internal constant MARKET_ALREADY_LISTED = \"E403\";\n string internal constant IDENTICAL_VALUE = \"E404\";\n string internal constant ZERO_ADDRESS = \"E405\";\n string internal constant EC_INVALID_PROVIDER_REPRESENTATIVE = \"E406\";\n string internal constant EC_PROVIDER_CANT_BE_REPRESENTATIVE = \"E407\";\n string internal constant OR_ORACLE_ADDRESS_CANNOT_BE_ZERO = \"E408\";\n string internal constant OR_UNDERLYING_TOKENS_DECIMALS_SHOULD_BE_GREATER_THAN_ZERO = \"E409\";\n string internal constant OR_REPORTER_MULTIPLIER_SHOULD_BE_GREATER_THAN_ZERO = \"E410\";\n string internal constant INVALID_TOKEN = \"E411\";\n string internal constant INVALID_PROTOCOL_INTEREST_FACTOR_MANTISSA = \"E412\";\n string internal constant INVALID_REDUCE_AMOUNT = \"E413\";\n string internal constant LIQUIDATION_FEE_MANTISSA_SHOULD_BE_GREATER_THAN_ZERO = \"E414\";\n string internal constant INVALID_UTILISATION_FACTOR_MANTISSA = \"E415\";\n string internal constant INVALID_MTOKENS_OR_BORROW_CAPS = \"E416\";\n string internal constant FL_PARAM_IS_TOO_LARGE = \"E417\";\n string internal constant MNT_INVALID_NONVOTING_PERIOD = \"E418\";\n string internal constant INPUT_ARRAY_LENGTHS_ARE_NOT_EQUAL = \"E419\";\n string internal constant EC_INVALID_BOOSTS = \"E420\";\n string internal constant EC_ACCOUNT_IS_ALREADY_LIQUIDITY_PROVIDER = \"E421\";\n string internal constant EC_ACCOUNT_HAS_NO_AGREEMENT = \"E422\";\n string internal constant OR_TIMESTAMP_THRESHOLD_SHOULD_BE_GREATER_THAN_ZERO = \"E423\";\n string internal constant OR_UNDERLYING_TOKENS_DECIMALS_TOO_BIG = \"E424\";\n string internal constant OR_REPORTER_MULTIPLIER_TOO_BIG = \"E425\";\n string internal constant SHOULD_HAVE_REVOCABLE_SCHEDULE = \"E426\";\n string internal constant MEMBER_NOT_IN_DELAY_LIST = \"E427\";\n string internal constant DELAY_LIST_LIMIT = \"E428\";\n}\n" }, "contracts/interfaces/IMnt.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IMnt is IERC20Upgradeable, IERC165, IAccessControlUpgradeable, ILinkageLeaf {\n event MaxNonVotingPeriodChanged(uint256 oldPeriod, uint256 newPeriod);\n event NewGovernor(address governor);\n event VotesUpdated(address account, uint256 oldVotingWeight, uint256 newVotingWeight);\n event TotalVotesUpdated(uint256 oldTotalVotes, uint256 newTotalVotes);\n\n /**\n * @notice get governor\n */\n function governor() external view returns (address);\n\n /**\n * @notice returns votingWeight for user\n */\n function votingWeight(address) external view returns (uint256);\n\n /**\n * @notice get total voting weight\n */\n function totalVotingWeight() external view returns (uint256);\n\n /**\n * @notice Updates voting power of the account\n */\n function updateVotingWeight(address account) external;\n\n /**\n * @notice Creates new total voting weight checkpoint\n * @dev RESTRICTION: Governor only.\n */\n function updateTotalWeightCheckpoint() external;\n\n /**\n * @notice Checks user activity for the last `maxNonVotingPeriod` blocks\n * @param account_ The address of the account\n * @return returns true if the user voted or his delegatee voted for the last maxNonVotingPeriod blocks,\n * otherwise returns false\n */\n function isParticipantActive(address account_) external view returns (bool);\n\n /**\n * @notice Updates last voting timestamp of the account\n * @dev RESTRICTION: Governor only.\n */\n function updateVoteTimestamp(address account) external;\n\n /**\n * @notice Gets the latest voting timestamp for account.\n * @dev If the user delegated his votes, then it also checks the timestamp of the last vote of the delegatee\n * @param account The address of the account\n * @return latest voting timestamp for account\n */\n function lastActivityTimestamp(address account) external view returns (uint256);\n\n /**\n * @notice set new governor\n * @dev RESTRICTION: Admin only.\n */\n function setGovernor(address newGovernor) external;\n\n /**\n * @notice Sets the maxNonVotingPeriod\n * @dev Admin function to set maxNonVotingPeriod\n * @param newPeriod_ The new maxNonVotingPeriod (in sec). Must be greater than 90 days and lower than 2 years.\n * @dev RESTRICTION: Admin only.\n */\n function setMaxNonVotingPeriod(uint256 newPeriod_) external;\n}\n" }, "contracts/interfaces/IMToken.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"./IInterestRateModel.sol\";\n\ninterface IMToken is IAccessControl, IERC20, IERC3156FlashLender, IERC165 {\n /**\n * @notice Event emitted when interest is accrued\n */\n event AccrueInterest(\n uint256 cashPrior,\n uint256 interestAccumulated,\n uint256 borrowIndex,\n uint256 totalBorrows,\n uint256 totalProtocolInterest\n );\n\n /**\n * @notice Event emitted when tokens are lended\n */\n event Lend(address lender, uint256 lendAmount, uint256 lendTokens, uint256 newTotalTokenSupply);\n\n /**\n * @notice Event emitted when tokens are redeemed\n */\n event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens, uint256 newTotalTokenSupply);\n\n /**\n * @notice Event emitted when underlying is borrowed\n */\n event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);\n\n /**\n * @notice Event emitted when tokens are seized\n */\n event Seize(\n address borrower,\n address receiver,\n uint256 seizeTokens,\n uint256 accountsTokens,\n uint256 totalSupply,\n uint256 seizeUnderlyingAmount\n );\n\n /**\n * @notice Event emitted when a borrow is repaid\n */\n event RepayBorrow(\n address payer,\n address borrower,\n uint256 repayAmount,\n uint256 accountBorrows,\n uint256 totalBorrows\n );\n\n /**\n * @notice Event emitted when a borrow is repaid during autoliquidation\n */\n event AutoLiquidationRepayBorrow(\n address borrower,\n uint256 repayAmount,\n uint256 accountBorrowsNew,\n uint256 totalBorrowsNew,\n uint256 TotalProtocolInterestNew\n );\n\n /**\n * @notice Event emitted when flash loan is executed\n */\n event FlashLoanExecuted(address receiver, uint256 amount, uint256 fee);\n\n /**\n * @notice Event emitted when interestRateModel is changed\n */\n event NewMarketInterestRateModel(IInterestRateModel oldInterestRateModel, IInterestRateModel newInterestRateModel);\n\n /**\n * @notice Event emitted when the protocol interest factor is changed\n */\n event NewProtocolInterestFactor(\n uint256 oldProtocolInterestFactorMantissa,\n uint256 newProtocolInterestFactorMantissa\n );\n\n /**\n * @notice Event emitted when the flash loan max share is changed\n */\n event NewFlashLoanMaxShare(uint256 oldMaxShare, uint256 newMaxShare);\n\n /**\n * @notice Event emitted when the flash loan fee is changed\n */\n event NewFlashLoanFee(uint256 oldFee, uint256 newFee);\n\n /**\n * @notice Event emitted when the protocol interest are added\n */\n event ProtocolInterestAdded(address benefactor, uint256 addAmount, uint256 newTotalProtocolInterest);\n\n /**\n * @notice Event emitted when the protocol interest reduced\n */\n event ProtocolInterestReduced(address admin, uint256 reduceAmount, uint256 newTotalProtocolInterest);\n\n /**\n * @notice Value is the Keccak-256 hash of \"TIMELOCK\"\n */\n function TIMELOCK() external view returns (bytes32);\n\n /**\n * @notice Underlying asset for this MToken\n */\n function underlying() external view returns (IERC20);\n\n /**\n * @notice EIP-20 token name for this token\n */\n function name() external view returns (string memory);\n\n /**\n * @notice EIP-20 token symbol for this token\n */\n function symbol() external view returns (string memory);\n\n /**\n * @notice EIP-20 token decimals for this token\n */\n function decimals() external view returns (uint8);\n\n /**\n * @notice Model which tells what the current interest rate should be\n */\n function interestRateModel() external view returns (IInterestRateModel);\n\n /**\n * @notice Initial exchange rate used when lending the first MTokens (used when totalTokenSupply = 0)\n */\n function initialExchangeRateMantissa() external view returns (uint256);\n\n /**\n * @notice Fraction of interest currently set aside for protocol interest\n */\n function protocolInterestFactorMantissa() external view returns (uint256);\n\n /**\n * @notice Block number that interest was last accrued at\n */\n function accrualBlockNumber() external view returns (uint256);\n\n /**\n * @notice Accumulator of the total earned interest rate since the opening of the market\n */\n function borrowIndex() external view returns (uint256);\n\n /**\n * @notice Total amount of outstanding borrows of the underlying in this market\n */\n function totalBorrows() external view returns (uint256);\n\n /**\n * @notice Total amount of protocol interest of the underlying held in this market\n */\n function totalProtocolInterest() external view returns (uint256);\n\n /**\n * @notice Share of market's current underlying token balance that can be used as flash loan (scaled by 1e18).\n */\n function maxFlashLoanShare() external view returns (uint256);\n\n /**\n * @notice Share of flash loan amount that would be taken as fee (scaled by 1e18).\n */\n function flashLoanFeeShare() external view returns (uint256);\n\n /**\n * @notice Returns total token supply\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transfer(address dst, uint256 amount) external returns (bool);\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @dev This will overwrite the approval amount for `spender`\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved (-1 means infinite)\n * @return Whether or not the approval succeeded\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param owner The address of the account which owns the tokens to be spent\n * @param spender The address of the account which may transfer tokens\n * @return The number of tokens allowed to be spent (-1 means infinite)\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @notice Get the token balance of the `owner`\n * @param owner The address of the account to query\n * @return The number of tokens owned by `owner`\n */\n function balanceOf(address owner) external view returns (uint256);\n\n /**\n * @notice Get the underlying balance of the `owner`\n * @dev This also accrues interest in a transaction\n * @param owner The address of the account to query\n * @return The amount of underlying owned by `owner`\n */\n function balanceOfUnderlying(address owner) external returns (uint256);\n\n /**\n * @notice Get a snapshot of the account's balances, and the cached exchange rate\n * @dev This is used by supervisor to more efficiently perform liquidity checks.\n * @param account Address of the account to snapshot\n * @return (token balance, borrow balance, exchange rate mantissa)\n */\n function getAccountSnapshot(address account)\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n /**\n * @notice Returns the current per-block borrow interest rate for this mToken\n * @return The borrow interest rate per block, scaled by 1e18\n */\n function borrowRatePerBlock() external view returns (uint256);\n\n /**\n * @notice Returns the current per-block supply interest rate for this mToken\n * @return The supply interest rate per block, scaled by 1e18\n */\n function supplyRatePerBlock() external view returns (uint256);\n\n /**\n * @notice Returns the current total borrows plus accrued interest\n * @return The total borrows with interest\n */\n function totalBorrowsCurrent() external returns (uint256);\n\n /**\n * @notice Accrue interest to updated borrowIndex and then calculate account's\n * borrow balance using the updated borrowIndex\n * @param account The address whose balance should be calculated after updating borrowIndex\n * @return The calculated balance\n */\n function borrowBalanceCurrent(address account) external returns (uint256);\n\n /**\n * @notice Return the borrow balance of account based on stored data\n * @param account The address whose balance should be calculated\n * @return The calculated balance\n */\n function borrowBalanceStored(address account) external view returns (uint256);\n\n /**\n * @notice Accrue interest then return the up-to-date exchange rate\n * @return Calculated exchange rate scaled by 1e18\n */\n function exchangeRateCurrent() external returns (uint256);\n\n /**\n * @notice Calculates the exchange rate from the underlying to the MToken\n * @dev This function does not accrue interest before calculating the exchange rate\n * @return Calculated exchange rate scaled by 1e18\n */\n function exchangeRateStored() external view returns (uint256);\n\n /**\n * @notice Get cash balance of this mToken in the underlying asset\n * @return The quantity of underlying asset owned by this contract\n */\n function getCash() external view returns (uint256);\n\n /**\n * @notice Applies accrued interest to total borrows and protocol interest\n * @dev This calculates interest accrued from the last checkpointed block\n * up to the current block and writes new checkpoint to storage.\n */\n function accrueInterest() external;\n\n /**\n * @notice Sender supplies assets into the market and receives mTokens in exchange\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param lendAmount The amount of the underlying asset to supply\n */\n function lend(uint256 lendAmount) external;\n\n /**\n * @notice Sender redeems mTokens in exchange for the underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemTokens The number of mTokens to redeem into underlying\n */\n function redeem(uint256 redeemTokens) external;\n\n /**\n * @notice Redeems all mTokens for account in exchange for the underlying asset.\n * Can only be called within the AML system!\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param account An account that is potentially sanctioned by the AML system\n */\n function redeemByAmlDecision(address account) external;\n\n /**\n * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemAmount The amount of underlying to receive from redeeming mTokens\n */\n function redeemUnderlying(uint256 redeemAmount) external;\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n */\n function borrow(uint256 borrowAmount) external;\n\n /**\n * @notice Sender repays their own borrow\n * @param repayAmount The amount to repay\n */\n function repayBorrow(uint256 repayAmount) external;\n\n /**\n * @notice Sender repays a borrow belonging to borrower\n * @param borrower the account with the debt being payed off\n * @param repayAmount The amount to repay\n */\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external;\n\n /**\n * @notice Liquidator repays a borrow belonging to borrower\n * @param borrower_ the account with the debt being payed off\n * @param repayAmount_ the amount of underlying tokens being returned\n */\n function autoLiquidationRepayBorrow(address borrower_, uint256 repayAmount_) external;\n\n /**\n * @notice A public function to sweep accidental ERC-20 transfers to this contract.\n * Tokens are sent to admin (timelock)\n * @param token The address of the ERC-20 token to sweep\n * @dev RESTRICTION: Admin only.\n */\n function sweepToken(IERC20 token, address admin_) external;\n\n /**\n * @notice Burns collateral tokens at the borrower's address, transfer underlying assets\n to the DeadDrop or Liquidator address.\n * @dev Called only during an auto liquidation process, msg.sender must be the Liquidation contract.\n * @param borrower_ The account having collateral seized\n * @param seizeUnderlyingAmount_ The number of underlying assets to seize. The caller must ensure\n that the parameter is greater than zero.\n * @param isLoanInsignificant_ Marker for insignificant loan whose collateral must be credited to the\n protocolInterest\n * @param receiver_ Address that receives accounts collateral\n */\n function autoLiquidationSeize(\n address borrower_,\n uint256 seizeUnderlyingAmount_,\n bool isLoanInsignificant_,\n address receiver_\n ) external;\n\n /**\n * @notice The amount of currency available to be lent.\n * @param token The loan currency.\n * @return The amount of `token` that can be borrowed.\n */\n function maxFlashLoan(address token) external view returns (uint256);\n\n /**\n * @notice The fee to be charged for a given loan.\n * @param token The loan currency.\n * @param amount The amount of tokens lent.\n * @return The amount of `token` to be charged for the loan, on top of the returned principal.\n */\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n /**\n * @notice Initiate a flash loan.\n * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.\n * @param token The loan currency.\n * @param amount The amount of tokens lent.\n * @param data Arbitrary data structure, intended to contain user-defined parameters.\n */\n function flashLoan(\n IERC3156FlashBorrower receiver,\n address token,\n uint256 amount,\n bytes calldata data\n ) external returns (bool);\n\n /**\n * @notice accrues interest and sets a new protocol interest factor for the protocol\n * @dev Admin function to accrue interest and set a new protocol interest factor\n * @dev RESTRICTION: Timelock only.\n */\n function setProtocolInterestFactor(uint256 newProtocolInterestFactorMantissa) external;\n\n /**\n * @notice Accrues interest and increase protocol interest by transferring from msg.sender\n * @param addAmount_ Amount of addition to protocol interest\n */\n function addProtocolInterest(uint256 addAmount_) external;\n\n /**\n * @notice Can only be called by liquidation contract. Increase protocol interest by transferring from payer.\n * @dev Calling code should make sure that accrueInterest() was called before.\n * @param payer_ The address from which the protocol interest will be transferred\n * @param addAmount_ Amount of addition to protocol interest\n */\n function addProtocolInterestBehalf(address payer_, uint256 addAmount_) external;\n\n /**\n * @notice Accrues interest and reduces protocol interest by transferring to admin\n * @param reduceAmount Amount of reduction to protocol interest\n * @dev RESTRICTION: Admin only.\n */\n function reduceProtocolInterest(uint256 reduceAmount, address admin_) external;\n\n /**\n * @notice accrues interest and updates the interest rate model using setInterestRateModelFresh\n * @dev Admin function to accrue interest and update the interest rate model\n * @param newInterestRateModel the new interest rate model to use\n * @dev RESTRICTION: Admin only.\n */\n function setInterestRateModel(IInterestRateModel newInterestRateModel) external;\n\n /**\n * @notice Updates share of markets cash that can be used as maximum amount of flash loan.\n * @param newMax New max amount share\n * @dev RESTRICTION: Admin only.\n */\n function setFlashLoanMaxShare(uint256 newMax) external;\n\n /**\n * @notice Updates fee of flash loan.\n * @param newFee New fee share of flash loan\n * @dev RESTRICTION: Timelock only.\n */\n function setFlashLoanFeeShare(uint256 newFee) external;\n}\n" }, "contracts/interfaces/IEmissionBooster.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\n\nimport \"./ISupervisor.sol\";\nimport \"./IRewardsHub.sol\";\nimport \"./IMToken.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IEmissionBooster is IAccessControl, ILinkageLeaf {\n /**\n * @notice Emitted when new Tier was created\n */\n event NewTierCreated(uint256 createdTier, uint32 endBoostBlock, uint256 emissionBoost);\n\n /**\n * @notice Emitted when Tier was enabled\n */\n event TierEnabled(\n IMToken market,\n uint256 enabledTier,\n uint32 startBoostBlock,\n uint224 mntSupplyIndex,\n uint224 mntBorrowIndex\n );\n\n /**\n * @notice Emitted when emission boost mode was enabled\n */\n event EmissionBoostEnabled(address caller);\n\n /**\n * @notice Emitted when MNT supply index of the tier ending on the market was saved to storage\n */\n event SupplyIndexUpdated(address market, uint256 nextTier, uint224 newIndex, uint32 endBlock);\n\n /**\n * @notice Emitted when MNT borrow index of the tier ending on the market was saved to storage\n */\n event BorrowIndexUpdated(address market, uint256 nextTier, uint224 newIndex, uint32 endBlock);\n\n /**\n * @notice get the Tier for each MinterestNFT token\n */\n function tokenTier(uint256) external view returns (uint256);\n\n /**\n * @notice get a list of all created Tiers\n */\n function tiers(uint256)\n external\n view\n returns (\n uint32,\n uint32,\n uint256\n );\n\n /**\n * @notice get status of emission boost mode.\n */\n function isEmissionBoostingEnabled() external view returns (bool);\n\n /**\n * @notice get Stored markets indexes per block.\n */\n function marketSupplyIndexes(IMToken, uint256) external view returns (uint256);\n\n /**\n * @notice get Stored markets indexes per block.\n */\n function marketBorrowIndexes(IMToken, uint256) external view returns (uint256);\n\n /**\n * @notice Mint token hook which is called from MinterestNFT.mint() and sets specific\n * settings for this NFT\n * @param to_ NFT ovner\n * @param ids_ NFTs IDs\n * @param amounts_ Amounts of minted NFTs per tier\n * @param tiers_ NFT tiers\n * @dev RESTRICTION: MinterestNFT only\n */\n function onMintToken(\n address to_,\n uint256[] memory ids_,\n uint256[] memory amounts_,\n uint256[] memory tiers_\n ) external;\n\n /**\n * @notice Transfer token hook which is called from MinterestNFT.transfer() and sets specific\n * settings for this NFT\n * @param from_ Address of the tokens previous owner. Should not be zero (minter).\n * @param to_ Address of the tokens new owner.\n * @param ids_ NFTs IDs\n * @param amounts_ Amounts of minted NFTs per tier\n * @dev RESTRICTION: MinterestNFT only\n */\n function onTransferToken(\n address from_,\n address to_,\n uint256[] memory ids_,\n uint256[] memory amounts_\n ) external;\n\n /**\n * @notice Enables emission boost mode.\n * @dev Admin function for enabling emission boosts.\n * @dev RESTRICTION: Whitelist only\n */\n function enableEmissionBoosting() external;\n\n /**\n * @notice Creates new Tiers for MinterestNFT tokens\n * @dev Admin function for creating Tiers\n * @param endBoostBlocks Emission boost end blocks for created Tiers\n * @param emissionBoosts Emission boosts for created Tiers, scaled by 1e18\n * Note: The arrays passed to the function must be of the same length and the order of the elements must match\n * each other\n * @dev RESTRICTION: Admin only\n */\n function createTiers(uint32[] memory endBoostBlocks, uint256[] memory emissionBoosts) external;\n\n /**\n * @notice Enables emission boost in specified Tiers\n * @param tiersForEnabling Tier for enabling emission boost\n * @dev RESTRICTION: Admin only\n */\n function enableTiers(uint256[] memory tiersForEnabling) external;\n\n /**\n * @notice Return the number of created Tiers\n * @return The number of created Tiers\n */\n function getNumberOfTiers() external view returns (uint256);\n\n /**\n * @notice Checks if the specified Tier is active\n * @param tier_ The Tier that is being checked\n */\n function isTierActive(uint256 tier_) external view returns (bool);\n\n /**\n * @notice Checks if the specified Tier exists\n * @param tier_ The Tier that is being checked\n */\n function tierExists(uint256 tier_) external view returns (bool);\n\n /**\n * @param account_ The address of the account\n * @return Bitmap of all accounts tiers\n */\n function getAccountTiersBitmap(address account_) external view returns (uint256);\n\n /**\n * @param account_ The address of the account to check if they have any tokens with tier\n */\n function isAccountHaveTiers(address account_) external view returns (bool);\n\n /**\n * @param account_ Address of the account\n * @return tier Highest tier number\n * @return boost Highest boost amount\n */\n function getCurrentAccountBoost(address account_) external view returns (uint256 tier, uint256 boost);\n\n /**\n * @notice Calculates emission boost for the account.\n * @param market_ Market for which we are calculating emission boost\n * @param account_ The address of the account for which we are calculating emission boost\n * @param userLastIndex_ The account's last updated mntBorrowIndex or mntSupplyIndex\n * @param userLastBlock_ The block number in which the index for the account was last updated\n * @param marketIndex_ The market's current mntBorrowIndex or mntSupplyIndex\n * @param isSupply_ boolean value, if true, then return calculate emission boost for suppliers\n * @return boostedIndex Boost part of delta index\n */\n function calculateEmissionBoost(\n IMToken market_,\n address account_,\n uint256 userLastIndex_,\n uint256 userLastBlock_,\n uint256 marketIndex_,\n bool isSupply_\n ) external view returns (uint256 boostedIndex);\n\n /**\n * @notice Update MNT supply index for market for NFT tiers that are expired but not yet updated.\n * @dev This function checks if there are tiers to update and process them one by one:\n * calculates the MNT supply index depending on the delta index and delta blocks between\n * last MNT supply index update and the current state,\n * emits SupplyIndexUpdated event and recalculates next tier to update.\n * @param market Address of the market to update\n * @param lastUpdatedBlock Last updated block number\n * @param lastUpdatedIndex Last updated index value\n * @param currentSupplyIndex Current MNT supply index value\n * @dev RESTRICTION: RewardsHub only\n */\n function updateSupplyIndexesHistory(\n IMToken market,\n uint256 lastUpdatedBlock,\n uint256 lastUpdatedIndex,\n uint256 currentSupplyIndex\n ) external;\n\n /**\n * @notice Update MNT borrow index for market for NFT tiers that are expired but not yet updated.\n * @dev This function checks if there are tiers to update and process them one by one:\n * calculates the MNT borrow index depending on the delta index and delta blocks between\n * last MNT borrow index update and the current state,\n * emits BorrowIndexUpdated event and recalculates next tier to update.\n * @param market Address of the market to update\n * @param lastUpdatedBlock Last updated block number\n * @param lastUpdatedIndex Last updated index value\n * @param currentBorrowIndex Current MNT borrow index value\n * @dev RESTRICTION: RewardsHub only\n */\n function updateBorrowIndexesHistory(\n IMToken market,\n uint256 lastUpdatedBlock,\n uint256 lastUpdatedIndex,\n uint256 currentBorrowIndex\n ) external;\n\n /**\n * @notice Get Id of NFT tier to update next on provided market MNT index, supply or borrow\n * @param market Market for which should the next Tier to update be updated\n * @param isSupply_ Flag that indicates whether MNT supply or borrow market should be updated\n * @return Id of tier to update\n */\n function getNextTierToBeUpdatedIndex(IMToken market, bool isSupply_) external view returns (uint256);\n}\n" }, "@openzeppelin/contracts/access/AccessControl.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControl.sol\";\nimport \"../utils/Context.sol\";\nimport \"../utils/Strings.sol\";\nimport \"../utils/introspection/ERC165.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context, IAccessControl, ERC165 {\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n Strings.toHexString(uint160(account), 20),\n \" is missing role \",\n Strings.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\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 {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\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 * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\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 * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\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 revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n" }, "@openzeppelin/contracts/security/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (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 // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\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" }, "@openzeppelin/contracts/proxy/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/math/SafeCast.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248) {\n require(value >= type(int248).min && value <= type(int248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return int248(value);\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240) {\n require(value >= type(int240).min && value <= type(int240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return int240(value);\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232) {\n require(value >= type(int232).min && value <= type(int232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return int232(value);\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224) {\n require(value >= type(int224).min && value <= type(int224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return int224(value);\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216) {\n require(value >= type(int216).min && value <= type(int216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return int216(value);\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208) {\n require(value >= type(int208).min && value <= type(int208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return int208(value);\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200) {\n require(value >= type(int200).min && value <= type(int200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return int200(value);\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192) {\n require(value >= type(int192).min && value <= type(int192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return int192(value);\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184) {\n require(value >= type(int184).min && value <= type(int184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return int184(value);\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176) {\n require(value >= type(int176).min && value <= type(int176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return int176(value);\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168) {\n require(value >= type(int168).min && value <= type(int168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return int168(value);\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160) {\n require(value >= type(int160).min && value <= type(int160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return int160(value);\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152) {\n require(value >= type(int152).min && value <= type(int152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return int152(value);\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144) {\n require(value >= type(int144).min && value <= type(int144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return int144(value);\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136) {\n require(value >= type(int136).min && value <= type(int136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return int136(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120) {\n require(value >= type(int120).min && value <= type(int120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return int120(value);\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112) {\n require(value >= type(int112).min && value <= type(int112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return int112(value);\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104) {\n require(value >= type(int104).min && value <= type(int104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return int104(value);\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96) {\n require(value >= type(int96).min && value <= type(int96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return int96(value);\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88) {\n require(value >= type(int88).min && value <= type(int88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return int88(value);\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80) {\n require(value >= type(int80).min && value <= type(int80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return int80(value);\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72) {\n require(value >= type(int72).min && value <= type(int72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return int72(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56) {\n require(value >= type(int56).min && value <= type(int56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return int56(value);\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48) {\n require(value >= type(int48).min && value <= type(int48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return int48(value);\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40) {\n require(value >= type(int40).min && value <= type(int40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return int40(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24) {\n require(value >= type(int24).min && value <= type(int24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return int24(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n" }, "@openzeppelin/contracts/utils/math/Math.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`.\n // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.\n // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.\n // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a\n // good first aproximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1;\n uint256 x = a;\n if (x >> 128 > 0) {\n x >>= 128;\n result <<= 64;\n }\n if (x >> 64 > 0) {\n x >>= 64;\n result <<= 32;\n }\n if (x >> 32 > 0) {\n x >>= 32;\n result <<= 16;\n }\n if (x >> 16 > 0) {\n x >>= 16;\n result <<= 8;\n }\n if (x >> 8 > 0) {\n x >>= 8;\n result <<= 4;\n }\n if (x >> 4 > 0) {\n x >>= 4;\n result <<= 2;\n }\n if (x >> 2 > 0) {\n result <<= 1;\n }\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n uint256 result = sqrt(a);\n if (rounding == Rounding.Up && result * result < a) {\n result += 1;\n }\n return result;\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-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 function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) 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(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) 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 function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\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 if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "contracts/interfaces/IInterconnectorLeaf.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./IInterconnector.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IInterconnectorLeaf is ILinkageLeaf {\n function getInterconnector() external view returns (IInterconnector);\n}\n" }, "contracts/libraries/ProtocolLinkage.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@openzeppelin/contracts/utils/StorageSlot.sol\";\nimport \"../interfaces/ILinkageLeaf.sol\";\nimport \"../interfaces/ILinkageRoot.sol\";\nimport \"./ErrorCodes.sol\";\n\nabstract contract LinkageRoot is ILinkageRoot {\n /// @notice Store self address to prevent context changing while delegateCall\n ILinkageRoot internal immutable _self = this;\n /// @notice Owner address\n address public immutable _linkage_owner;\n\n constructor(address owner_) {\n require(owner_ != address(0), ErrorCodes.ADMIN_ADDRESS_CANNOT_BE_ZERO);\n _linkage_owner = owner_;\n }\n\n /// @inheritdoc ILinkageRoot\n function switchLinkageRoot(ILinkageRoot newRoot) external {\n require(msg.sender == _linkage_owner, ErrorCodes.UNAUTHORIZED);\n\n emit LinkageRootSwitch(newRoot);\n\n Address.functionDelegateCall(\n address(newRoot),\n abi.encodePacked(LinkageRoot.interconnect.selector),\n \"LinkageRoot: low-level delegate call failed\"\n );\n }\n\n /// @inheritdoc ILinkageRoot\n function interconnect() external {\n emit LinkageRootInterconnected();\n interconnectInternal();\n }\n\n function interconnectInternal() internal virtual;\n}\n\nabstract contract LinkageLeaf is ILinkageLeaf {\n /// @inheritdoc ILinkageLeaf\n function switchLinkageRoot(ILinkageRoot newRoot) public {\n require(address(newRoot) != address(0), ErrorCodes.LL_NEW_ROOT_CANNOT_BE_ZERO);\n\n StorageSlot.AddressSlot storage slot = getRootSlot();\n address oldRoot = slot.value;\n if (oldRoot == address(newRoot)) return;\n\n require(oldRoot == address(0) || oldRoot == msg.sender, ErrorCodes.UNAUTHORIZED);\n slot.value = address(newRoot);\n\n emit LinkageRootSwitched(newRoot, LinkageRoot(oldRoot));\n }\n\n /**\n * @dev Gets current root contract address\n */\n function getLinkageRootAddress() internal view returns (address) {\n return getRootSlot().value;\n }\n\n /**\n * @dev Gets current root contract storage slot\n */\n function getRootSlot() private pure returns (StorageSlot.AddressSlot storage) {\n // keccak256(\"minterest.slot.linkageRoot\")\n return StorageSlot.getAddressSlot(0xc34f336ef21a27e6cdbefdb1e201a57e5e6cb9d267e34fc3134d22f9decc8bbf);\n }\n}\n" }, "contracts/interfaces/IInterconnector.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./ISupervisor.sol\";\nimport \"./IRewardsHub.sol\";\nimport \"./IMnt.sol\";\nimport \"./IBuyback.sol\";\nimport \"./IVesting.sol\";\nimport \"./IMinterestNFT.sol\";\nimport \"./IPriceOracle.sol\";\nimport \"./ILiquidation.sol\";\nimport \"./IBDSystem.sol\";\nimport \"./IWeightAggregator.sol\";\nimport \"./IEmissionBooster.sol\";\n\ninterface IInterconnector {\n function supervisor() external view returns (ISupervisor);\n\n function buyback() external view returns (IBuyback);\n\n function emissionBooster() external view returns (IEmissionBooster);\n\n function bdSystem() external view returns (IBDSystem);\n\n function rewardsHub() external view returns (IRewardsHub);\n\n function mnt() external view returns (IMnt);\n\n function minterestNFT() external view returns (IMinterestNFT);\n\n function liquidation() external view returns (ILiquidation);\n\n function oracle() external view returns (IPriceOracle);\n\n function vesting() external view returns (IVesting);\n\n function whitelist() external view returns (IWhitelist);\n\n function weightAggregator() external view returns (IWeightAggregator);\n}\n" }, "contracts/interfaces/ILinkageLeaf.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./ILinkageRoot.sol\";\n\ninterface ILinkageLeaf {\n /**\n * @notice Emitted when root contract address is changed\n */\n event LinkageRootSwitched(ILinkageRoot newRoot, ILinkageRoot oldRoot);\n\n /**\n * @notice Connects new root contract address\n * @param newRoot New root contract address\n */\n function switchLinkageRoot(ILinkageRoot newRoot) external;\n}\n" }, "contracts/interfaces/ISupervisor.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"./IMToken.sol\";\nimport \"./IBuyback.sol\";\nimport \"./IRewardsHub.sol\";\nimport \"./ILinkageLeaf.sol\";\nimport \"./IWhitelist.sol\";\n\n/**\n * @title Minterest Supervisor Contract\n * @author Minterest\n */\ninterface ISupervisor is IAccessControl, ILinkageLeaf {\n /**\n * @notice Emitted when an admin supports a market\n */\n event MarketListed(IMToken mToken);\n\n /**\n * @notice Emitted when an account enable a market\n */\n event MarketEnabledAsCollateral(IMToken mToken, address account);\n\n /**\n * @notice Emitted when an account disable a market\n */\n event MarketDisabledAsCollateral(IMToken mToken, address account);\n\n /**\n * @notice Emitted when a utilisation factor is changed by admin\n */\n event NewUtilisationFactor(\n IMToken mToken,\n uint256 oldUtilisationFactorMantissa,\n uint256 newUtilisationFactorMantissa\n );\n\n /**\n * @notice Emitted when liquidation fee is changed by admin\n */\n event NewLiquidationFee(IMToken marketAddress, uint256 oldLiquidationFee, uint256 newLiquidationFee);\n\n /**\n * @notice Emitted when borrow cap for a mToken is changed\n */\n event NewBorrowCap(IMToken indexed mToken, uint256 newBorrowCap);\n\n /**\n * @notice Per-account mapping of \"assets you are in\"\n */\n function accountAssets(address, uint256) external view returns (IMToken);\n\n /**\n * @notice Collection of states of supported markets\n * @dev Types containing (nested) mappings could not be parameters or return of external methods\n */\n function markets(IMToken)\n external\n view\n returns (\n bool isListed,\n uint256 utilisationFactorMantissa,\n uint256 liquidationFeeMantissa\n );\n\n /**\n * @notice get A list of all markets\n */\n function allMarkets(uint256) external view returns (IMToken);\n\n /**\n * @notice get Borrow caps enforced by beforeBorrow for each mToken address.\n */\n function borrowCaps(IMToken) external view returns (uint256);\n\n /**\n * @notice get keccak-256 hash of gatekeeper role\n */\n function GATEKEEPER() external view returns (bytes32);\n\n /**\n * @notice get keccak-256 hash of timelock\n */\n function TIMELOCK() external view returns (bytes32);\n\n /**\n * @notice Returns the assets an account has enabled as collateral\n * @param account The address of the account to pull assets for\n * @return A dynamic list with the assets the account has enabled as collateral\n */\n function getAccountAssets(address account) external view returns (IMToken[] memory);\n\n /**\n * @notice Returns whether the given account is enabled as collateral in the given asset\n * @param account The address of the account to check\n * @param mToken The mToken to check\n * @return True if the account is in the asset, otherwise false.\n */\n function checkMembership(address account, IMToken mToken) external view returns (bool);\n\n /**\n * @notice Add assets to be included in account liquidity calculation\n * @param mTokens The list of addresses of the mToken markets to be enabled as collateral\n */\n function enableAsCollateral(IMToken[] memory mTokens) external;\n\n /**\n * @notice Removes asset from sender's account liquidity calculation\n * @dev Sender must not have an outstanding borrow balance in the asset,\n * or be providing necessary collateral for an outstanding borrow.\n * @param mTokenAddress The address of the asset to be removed\n */\n function disableAsCollateral(IMToken mTokenAddress) external;\n\n /**\n * @notice Makes checks if the account should be allowed to lend tokens in the given market\n * @param mToken The market to verify the lend against\n * @param lender The account which would get the lent tokens\n */\n function beforeLend(IMToken mToken, address lender) external;\n\n /**\n * @notice Checks if the account should be allowed to redeem tokens in the given market and triggers emission system\n * @param mToken The market to verify the redeem against\n * @param redeemer The account which would redeem the tokens\n * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market\n * @param isAmlProcess Do we need to check the AML system or not\n */\n function beforeRedeem(\n IMToken mToken,\n address redeemer,\n uint256 redeemTokens,\n bool isAmlProcess\n ) external;\n\n /**\n * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\n * @param mToken The market to verify the borrow against\n * @param borrower The account which would borrow the asset\n * @param borrowAmount The amount of underlying the account would borrow\n */\n function beforeBorrow(\n IMToken mToken,\n address borrower,\n uint256 borrowAmount\n ) external;\n\n /**\n * @notice Checks if the account should be allowed to repay a borrow in the given market\n * @param mToken The market to verify the repay against\n * @param borrower The account which would borrowed the asset\n */\n function beforeRepayBorrow(IMToken mToken, address borrower) external;\n\n /**\n * @notice Checks if the seizing of assets should be allowed to occur (auto liquidation process)\n * @param mToken Asset which was used as collateral and will be seized\n * @param liquidator_ The address of liquidator contract\n * @param borrower The address of the borrower\n */\n function beforeAutoLiquidationSeize(\n IMToken mToken,\n address liquidator_,\n address borrower\n ) external;\n\n /**\n * @notice Checks if the sender should be allowed to repay borrow in the given market (auto liquidation process)\n * @param liquidator_ The address of liquidator contract\n * @param borrower_ The account which borrowed the asset\n * @param mToken_ The market to verify the repay against\n */\n function beforeAutoLiquidationRepay(\n address liquidator_,\n address borrower_,\n IMToken mToken_\n ) external;\n\n /**\n * @notice Checks if the address is the Liquidation contract\n * @dev Used in liquidation process\n * @param liquidator_ Prospective address of the Liquidation contract\n */\n function isLiquidator(address liquidator_) external view;\n\n /**\n * @notice Checks if the account should be allowed to transfer tokens in the given market\n * @param mToken The market to verify the transfer against\n * @param src The account which sources the tokens\n * @param dst The account which receives the tokens\n * @param transferTokens The number of mTokens to transfer\n */\n function beforeTransfer(\n IMToken mToken,\n address src,\n address dst,\n uint256 transferTokens\n ) external;\n\n /**\n * @notice Makes checks before flash loan in MToken\n * @param mToken The address of the token\n * receiver - The address of the loan receiver\n * amount - How much tokens to flash loan\n * fee - Flash loan fee\n */\n function beforeFlashLoan(\n IMToken mToken,\n address, /* receiver */\n uint256, /* amount */\n uint256 /* fee */\n ) external view;\n\n /**\n * @notice Calculate account liquidity in USD related to utilisation factors of underlying assets\n * @return (USD value above total utilisation requirements of all assets,\n * USD value below total utilisation requirements of all assets)\n */\n function getAccountLiquidity(address account) external view returns (uint256, uint256);\n\n /**\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\n * @param mTokenModify The market to hypothetically redeem/borrow in\n * @param account The account to determine liquidity for\n * @param redeemTokens The number of tokens to hypothetically redeem\n * @param borrowAmount The amount of underlying to hypothetically borrow\n * @return (hypothetical account liquidity in excess of collateral requirements,\n * hypothetical account shortfall below collateral requirements)\n */\n function getHypotheticalAccountLiquidity(\n address account,\n IMToken mTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount\n ) external returns (uint256, uint256);\n\n /**\n * @notice Get liquidationFeeMantissa and utilisationFactorMantissa for market\n * @param market Market for which values are obtained\n * @return (liquidationFeeMantissa, utilisationFactorMantissa)\n */\n function getMarketData(IMToken market) external view returns (uint256, uint256);\n\n /**\n * @notice Validates redeem and reverts on rejection. May emit logs.\n * @param redeemAmount The amount of the underlying asset being redeemed\n * @param redeemTokens The number of tokens being redeemed\n */\n function redeemVerify(uint256 redeemAmount, uint256 redeemTokens) external view;\n\n /**\n * @notice Sets the utilisationFactor for a market\n * @dev Governance function to set per-market utilisationFactor\n * @param mToken The market to set the factor on\n * @param newUtilisationFactorMantissa The new utilisation factor, scaled by 1e18\n * @dev RESTRICTION: Timelock only.\n */\n function setUtilisationFactor(IMToken mToken, uint256 newUtilisationFactorMantissa) external;\n\n /**\n * @notice Sets the liquidationFee for a market\n * @dev Governance function to set per-market liquidationFee\n * @param mToken The market to set the fee on\n * @param newLiquidationFeeMantissa The new liquidation fee, scaled by 1e18\n * @dev RESTRICTION: Timelock only.\n */\n function setLiquidationFee(IMToken mToken, uint256 newLiquidationFeeMantissa) external;\n\n /**\n * @notice Add the market to the markets mapping and set it as listed, also initialize MNT market state.\n * @dev Admin function to set isListed and add support for the market\n * @param mToken The address of the market (token) to list\n * @dev RESTRICTION: Admin only.\n */\n function supportMarket(IMToken mToken) external;\n\n /**\n * @notice Set the given borrow caps for the given mToken markets.\n * Borrowing that brings total borrows to or above borrow cap will revert.\n * @dev Admin or gateKeeper function to set the borrow caps.\n * A borrow cap of 0 corresponds to unlimited borrowing.\n * @param mTokens The addresses of the markets (tokens) to change the borrow caps for\n * @param newBorrowCaps The new borrow cap values in underlying to be set.\n * A value of 0 corresponds to unlimited borrowing.\n * @dev RESTRICTION: Gatekeeper only.\n */\n function setMarketBorrowCaps(IMToken[] calldata mTokens, uint256[] calldata newBorrowCaps) external;\n\n /**\n * @notice Return all of the markets\n * @dev The automatic getter may be used to access an individual market.\n * @return The list of market addresses\n */\n function getAllMarkets() external view returns (IMToken[] memory);\n\n /**\n * @notice Returns true if market is listed in Supervisor\n */\n function isMarketListed(IMToken) external view returns (bool);\n\n /**\n * @notice Check that account is not in the black list and protocol operations are available.\n * @param account The address of the account to check\n */\n function isNotBlacklisted(address account) external view returns (bool);\n\n /**\n * @notice Check if transfer of MNT is allowed for accounts.\n * @param from The source account address to check\n * @param to The destination account address to check\n */\n function isMntTransferAllowed(address from, address to) external view returns (bool);\n\n /**\n * @notice Returns block number\n */\n function getBlockNumber() external view returns (uint256);\n}\n" }, "contracts/interfaces/IRewardsHub.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./IMToken.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IRewardsHub is ILinkageLeaf {\n event DistributedSupplierMnt(\n IMToken indexed mToken,\n address indexed supplier,\n uint256 mntDelta,\n uint256 mntSupplyIndex\n );\n event DistributedBorrowerMnt(\n IMToken indexed mToken,\n address indexed borrower,\n uint256 mntDelta,\n uint256 mntBorrowIndex\n );\n event EmissionRewardAccrued(address indexed account, uint256 regularAmount, uint256 delayedAmount);\n event RepresentativeRewardAccrued(\n address indexed account,\n address provider,\n uint256 regularAmount,\n uint256 delayedAmount\n );\n event BuybackRewardAccrued(address indexed account, uint256 regularAmount, uint256 delayedAmount);\n event Withdraw(address indexed account, uint256 amount);\n event MntGranted(address recipient, uint256 amount);\n\n event MntSupplyEmissionRateUpdated(IMToken indexed mToken, uint256 newSupplyEmissionRate);\n event MntBorrowEmissionRateUpdated(IMToken indexed mToken, uint256 newBorrowEmissionRate);\n\n struct DelayEntry {\n uint256 delayed;\n uint224 claimRate;\n uint32 lastClaim;\n }\n\n /**\n * @notice get keccak-256 hash of gatekeeper\n */\n function GATEKEEPER() external view returns (bytes32);\n\n /**\n * @notice get keccak-256 hash of timelock\n */\n function TIMELOCK() external view returns (bytes32);\n\n /**\n * @dev Gets amounts of regular rewards for individual accounts.\n */\n function balances(address account) external view returns (uint256);\n\n /**\n * @notice Gets the rate at which MNT is distributed to the corresponding supply market (per block)\n */\n function mntSupplyEmissionRate(IMToken) external view returns (uint256);\n\n /**\n * @notice Gets the rate at which MNT is distributed to the corresponding borrow market (per block)\n */\n function mntBorrowEmissionRate(IMToken) external view returns (uint256);\n\n /**\n * @notice Gets the MNT market supply state for each market\n */\n function mntSupplyState(IMToken) external view returns (uint224 index, uint32 blockN);\n\n /**\n * @notice Gets the MNT market borrow state for each market\n */\n function mntBorrowState(IMToken) external view returns (uint224 index, uint32 blockN);\n\n /**\n * @notice Gets the MNT supply index and block number for each market\n */\n function mntSupplierState(IMToken, address) external view returns (uint224 index, uint32 blockN);\n\n /**\n * @notice Gets the MNT borrow index and block number for each market\n */\n function mntBorrowerState(IMToken, address) external view returns (uint224 index, uint32 blockN);\n\n /**\n * @notice Gets summary amount of available and delayed balances of an account.\n */\n function totalBalanceOf(address account) external view returns (uint256);\n\n /**\n * @notice Gets amount of MNT that can be withdrawn from an account at this block.\n */\n function availableBalanceOf(address account) external view returns (uint256);\n\n /**\n * @notice Gets amount of delayed MNT of an account.\n */\n function delayedBalanceOf(address account) external view returns (DelayEntry memory);\n\n /**\n * @notice Gets delay period start, claim period start and claim period end timestamps.\n */\n function delayParameters()\n external\n view\n returns (\n uint32 delayStart,\n uint32 claimStart,\n uint32 claimEnd\n );\n\n /**\n * @notice Initializes market in RewardsHub. Should be called once from Supervisor.supportMarket\n * @dev RESTRICTION: Supervisor only\n */\n function initMarket(IMToken mToken) external;\n\n /**\n * @notice Accrues MNT to the market by updating the borrow and supply indexes\n * @dev This method doesn't update MNT index history in Minterest NFT.\n * @param market The market whose supply and borrow index to update\n * @return (MNT supply index, MNT borrow index)\n */\n function updateAndGetMntIndexes(IMToken market) external returns (uint224, uint224);\n\n /**\n * @notice Shorthand function to distribute MNT emissions from supplies of one market.\n */\n function distributeSupplierMnt(IMToken mToken, address account) external;\n\n /**\n * @notice Shorthand function to distribute MNT emissions from borrows of one market.\n */\n function distributeBorrowerMnt(IMToken mToken, address account) external;\n\n /**\n * @notice Updates market indices and distributes tokens (if any) for holder\n * @dev Updates indices and distributes only for those markets where the holder have a\n * non-zero supply or borrow balance.\n * @param account The address to distribute MNT for\n */\n function distributeAllMnt(address account) external;\n\n /**\n * @notice Distribute all MNT accrued by the accounts\n * @param accounts The addresses to distribute MNT for\n * @param mTokens The list of markets to distribute MNT in\n * @param borrowers Whether or not to distribute MNT earned by borrowing\n * @param suppliers Whether or not to distribute MNT earned by supplying\n */\n function distributeMnt(\n address[] memory accounts,\n IMToken[] memory mTokens,\n bool borrowers,\n bool suppliers\n ) external;\n\n /**\n * @notice Accrues buyback reward\n * @dev RESTRICTION: Buyback only\n */\n function accrueBuybackReward(\n address account,\n uint256 buybackIndex,\n uint256 accountIndex,\n uint256 accountWeight\n ) external;\n\n /**\n * @notice Gets part of delayed rewards that have become available.\n */\n function getClaimableDelayed(address account) external view returns (uint256);\n\n /**\n * @notice Transfers available part of MNT rewards to the sender.\n * This will decrease accounts buyback and voting weights.\n */\n function withdraw(uint256 amount) external;\n\n /**\n * @notice Transfers\n * @dev RESTRICTION: Admin only\n */\n function grant(address recipient, uint256 amount) external;\n\n /**\n * @notice Set MNT borrow and supply emission rates for a single market\n * @param mToken The market whose MNT emission rate to update\n * @param newMntSupplyEmissionRate New supply MNT emission rate for market\n * @param newMntBorrowEmissionRate New borrow MNT emission rate for market\n * @dev RESTRICTION Timelock only\n */\n function setMntEmissionRates(\n IMToken mToken,\n uint256 newMntSupplyEmissionRate,\n uint256 newMntBorrowEmissionRate\n ) external;\n}\n" }, "contracts/interfaces/IBuyback.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface IBuyback is IAccessControl, ILinkageLeaf {\n event Stake(address who, uint256 amount, uint256 discounted);\n event Unstake(address who, uint256 amount);\n event NewBuyback(uint256 amount, uint256 share);\n event ParticipateBuyback(address who);\n event LeaveBuyback(address who, uint256 currentStaked);\n event BuybackWeightChanged(address who, uint256 newWeight, uint256 oldWeight, uint256 newTotalWeight);\n\n /**\n * @notice Gets parameters used to calculate the discount curve.\n * @return start The timestamp from which the discount starts\n * @return flatSeconds Seconds from protocol start when approximation function has minimum value\n * ~ 4.44 years of the perfect year, at this point df/dx == 0\n * @return flatRate Flat rate of the discounted MNTs after the kink point.\n * Equal to the percentage at flatSeconds time\n */\n function discountParameters()\n external\n view\n returns (\n uint256 start,\n uint256 flatSeconds,\n uint256 flatRate\n );\n\n /**\n * @notice Applies current discount rate to the supplied amount\n * @param amount The amount to discount\n * @return Discounted amount in range [0; amount]\n */\n function discountAmount(uint256 amount) external view returns (uint256);\n\n /**\n * @notice Calculates value of polynomial approximation of e^-kt, k = 0.725, t in seconds of a perfect year\n * function follows e^(-0.725*t) ~ 1 - 0.7120242*x + 0.2339357*x^2 - 0.04053335*x^3 + 0.00294642*x^4\n * up to the minimum and then continues with a flat rate\n * @param secondsElapsed Seconds elapsed from the start block\n * @return Discount rate in range [0..1] with precision mantissa 1e18\n */\n function getPolynomialFactor(uint256 secondsElapsed) external pure returns (uint256);\n\n /**\n * @notice Gets all info about account membership in Buyback\n */\n function getMemberInfo(address account)\n external\n view\n returns (\n bool participating,\n uint256 weight,\n uint256 lastIndex,\n uint256 rawStake,\n uint256 discountedStake\n );\n\n /**\n * @notice Gets if an account is participating in Buyback\n */\n function isParticipating(address account) external view returns (bool);\n\n /**\n * @notice Gets discounted stake of the account\n */\n function getDiscountedStake(address account) external view returns (uint256);\n\n /**\n * @notice Gets buyback weight of an account\n */\n function getWeight(address account) external view returns (uint256);\n\n /**\n * @notice Gets total Buyback weight, which is the sum of weights of all accounts.\n */\n function getTotalWeight() external view returns (uint256);\n\n /**\n * @notice Gets current Buyback index.\n * Its the accumulated sum of MNTs shares that are given for each weight of an account.\n */\n function getBuybackIndex() external view returns (uint256);\n\n /**\n * @notice Stakes the specified amount of MNT and transfers them to this contract.\n * Sender's weight would increase by the discounted amount of staked funds.\n * @notice This contract should be approved to transfer MNT from sender account\n * @param amount The amount of MNT to stake\n */\n function stake(uint256 amount) external;\n\n /**\n * @notice Unstakes the specified amount of MNT and transfers them back to sender if he participates\n * in the Buyback system, otherwise just transfers MNT tokens to the sender.\n * Sender's weight would decrease by discounted amount of unstaked funds, but resulting weight\n * would not be greater than staked amount left. If `amount == MaxUint256` unstakes all staked tokens.\n * @param amount The amount of MNT to unstake\n */\n function unstake(uint256 amount) external;\n\n /**\n * @notice Claims buyback rewards, updates buyback weight and voting power.\n * Does nothing if account is not participating. Reverts if operation is paused.\n * @param account Address to update weights for\n */\n function updateBuybackAndVotingWeights(address account) external;\n\n /**\n * @notice Claims buyback rewards, updates buyback weight and voting power.\n * Does nothing if account is not participating or update is paused.\n * @param account Address to update weights for\n */\n function updateBuybackAndVotingWeightsRelaxed(address account) external;\n\n /**\n * @notice Does a buyback using the specified amount of MNT from sender's account\n * @param amount The amount of MNT to take and distribute as buyback\n * @dev RESTRICTION: Distributor only\n */\n function buyback(uint256 amount) external;\n\n /**\n * @notice Make account participating in the buyback. If the sender has a staked balance, then\n * the weight will be equal to the discounted amount of staked funds.\n */\n function participate() external;\n\n /**\n *@notice Make accounts participate in buyback before its start.\n * @param accounts Address to make participate in buyback.\n * @dev RESTRICTION: Admin only\n */\n function participateOnBehalf(address[] memory accounts) external;\n\n /**\n * @notice Leave buyback participation, claim any MNTs rewarded by the buyback.\n * Leaving does not withdraw staked MNTs but reduces weight of the account to zero\n */\n function leave() external;\n\n /**\n * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and\n * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available\n * for their owner to be claimed\n * @dev Admin function to leave on behalf.\n * Can only be called if (timestamp > participantLastVoteTimestamp + maxNonVotingPeriod).\n * @param participant Address to leave for\n * @dev RESTRICTION: Admin only\n */\n function leaveOnBehalf(address participant) external;\n\n /**\n * @notice Leave buyback participation on behalf, claim any MNTs rewarded by the buyback and\n * reduce the weight of account to zero. All staked MNTs remain on the buyback contract and available\n * for their owner to be claimed.\n * @dev Function to leave sanctioned accounts from Buyback system\n * Can only be called if the participant is sanctioned by the AML system.\n * @param participant Address to leave for\n */\n function leaveByAmlDecision(address participant) external;\n}\n" }, "contracts/interfaces/IVesting.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"./IBuyback.sol\";\n\n/**\n * @title Vesting contract provides unlocking of tokens on a schedule. It uses the *graded vesting* way,\n * which unlocks a specific amount of balance every period of time, until all balance unlocked.\n *\n * Vesting Schedule.\n *\n * The schedule of a vesting is described by data structure `VestingSchedule`: starting from the start timestamp\n * throughout the duration, the entire amount of totalAmount tokens will be unlocked.\n */\n\ninterface IVesting is IAccessControl {\n /**\n * @notice An event that's emitted when a new vesting schedule for a account is created.\n */\n event VestingScheduleAdded(address target, VestingSchedule schedule);\n\n /**\n * @notice An event that's emitted when a vesting schedule revoked.\n */\n event VestingScheduleRevoked(address target, uint256 unreleased, uint256 locked);\n\n /**\n * @notice An event that's emitted when the account Withdrawn the released tokens.\n */\n event Withdrawn(address target, uint256 withdrawn);\n\n /**\n * @notice Emitted when an account is added to the delay list\n */\n event AddedToDelayList(address account);\n\n /**\n * @notice Emitted when an account is removed from the delay list\n */\n event RemovedFromDelayList(address account);\n\n /**\n * @notice The structure is used in the contract constructor for create vesting schedules\n * during contract deploying.\n * @param totalAmount the number of tokens to be vested during the vesting duration.\n * @param target the address that will receive tokens according to schedule parameters.\n * @param start offset in minutes at which vesting starts. Zero will vesting immediately.\n * @param duration duration in minutes of the period in which the tokens will vest.\n * @param revocable whether the vesting is revocable or not.\n */\n struct ScheduleData {\n uint256 totalAmount;\n address target;\n uint32 start;\n uint32 duration;\n bool revocable;\n }\n\n /**\n * @notice Vesting schedules of an account.\n * @param totalAmount the number of tokens to be vested during the vesting duration.\n * @param released the amount of the token released. It means that the account has called withdraw() and received\n * @param start the timestamp in minutes at which vesting starts. Must not be equal to zero, as it is used to\n * check for the existence of a vesting schedule.\n * @param duration duration in minutes of the period in which the tokens will vest.\n * `released amount` of tokens to his address.\n * @param revocable whether the vesting is revocable or not.\n */\n struct VestingSchedule {\n uint256 totalAmount;\n uint256 released;\n uint32 created;\n uint32 start;\n uint32 duration;\n bool revocable;\n }\n\n /// @notice get keccak-256 hash of GATEKEEPER role\n function GATEKEEPER() external view returns (bytes32);\n\n /// @notice get keccak-256 hash of TOKEN_PROVIDER role\n function TOKEN_PROVIDER() external view returns (bytes32);\n\n /**\n * @notice get vesting schedule of an account.\n */\n function schedules(address)\n external\n view\n returns (\n uint256 totalAmount,\n uint256 released,\n uint32 created,\n uint32 start,\n uint32 duration,\n bool revocable\n );\n\n /**\n * @notice Gets the amount of MNT that was transferred to Vesting contract\n * and can be transferred to other accounts via vesting process.\n * Transferring rewards from Vesting via withdraw method will decrease this amount.\n */\n function allocation() external view returns (uint256);\n\n /**\n * @notice Gets the amount of allocated MNT tokens that are not used in any vesting schedule yet.\n * Creation of new vesting schedules will decrease this amount.\n */\n function freeAllocation() external view returns (uint256);\n\n /**\n * @notice get Whether or not the account is in the delay list\n */\n function delayList(address) external view returns (bool);\n\n /**\n * @notice Withdraw the specified number of tokens. For a successful transaction, the requirement\n * `amount_ > 0 && amount_ <= unreleased` must be met.\n * If `amount_ == MaxUint256` withdraw all unreleased tokens.\n * @param amount_ The number of tokens to withdraw.\n */\n function withdraw(uint256 amount_) external;\n\n /**\n * @notice Increases vesting schedule allocation and transfers MNT into Vesting.\n * @dev RESTRICTION: TOKEN_PROVIDER only\n */\n function refill(uint256 amount) external;\n\n /**\n * @notice Transfers MNT that were added to the contract without calling the refill and are unallocated.\n * @dev RESTRICTION: Admin only\n */\n function sweep(address recipient, uint256 amount) external;\n\n /**\n * @notice Allows the admin to create a new vesting schedules.\n * @param schedulesData an array of vesting schedules that will be created.\n * @dev RESTRICTION: Admin only.\n */\n function createVestingScheduleBatch(ScheduleData[] memory schedulesData) external;\n\n /**\n * @notice Allows the admin to revoke the vesting schedule. Tokens already vested\n * transfer to the account, the rest are returned to the vesting contract.\n * @param target_ the address from which the vesting schedule is revoked.\n * @dev RESTRICTION: Gatekeeper only.\n */\n function revokeVestingSchedule(address target_) external;\n\n /**\n * @notice Calculates the end of the vesting.\n * @param who_ account address for which the parameter is returned.\n * @return the end of the vesting.\n */\n function endOfVesting(address who_) external view returns (uint256);\n\n /**\n * @notice Calculates locked amount for a given `time`.\n * @param who_ account address for which the parameter is returned.\n * @return locked amount for a given `time`.\n */\n function lockedAmount(address who_) external view returns (uint256);\n\n /**\n * @notice Calculates the amount that has already vested.\n * @param who_ account address for which the parameter is returned.\n * @return the amount that has already vested.\n */\n function vestedAmount(address who_) external view returns (uint256);\n\n /**\n * @notice Calculates the amount that has already vested but hasn't been released yet.\n * @param who_ account address for which the parameter is returned.\n * @return the amount that has already vested but hasn't been released yet.\n */\n function releasableAmount(address who_) external view returns (uint256);\n\n /**\n * @notice Gets the amount that has already vested but hasn't been released yet if account\n * schedule had no starting delay (cliff).\n */\n function getReleasableWithoutCliff(address account) external view returns (uint256);\n\n /**\n * @notice Add an account with revocable schedule to the delay list\n * @param who_ The account that is being added to the delay list\n * @dev RESTRICTION: Gatekeeper only.\n */\n function addToDelayList(address who_) external;\n\n /**\n * @notice Remove an account from the delay list\n * @param who_ The account that is being removed from the delay list\n * @dev RESTRICTION: Gatekeeper only.\n */\n function removeFromDelayList(address who_) external;\n}\n" }, "contracts/interfaces/IMinterestNFT.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/token/ERC1155/IERC1155.sol\";\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"./ILinkageLeaf.sol\";\n\ninterface ProxyRegistry {\n function proxies(address) external view returns (address);\n}\n\n/**\n * @title MinterestNFT\n * @dev Contract module which provides functionality to mint new ERC1155 tokens\n * Each token connected with image and metadata. The image and metadata saved\n * on IPFS and this contract stores the CID of the folder where lying metadata.\n * Also each token belongs one of the Minterest tiers, and give some emission\n * boost for Minterest distribution system.\n */\ninterface IMinterestNFT is IAccessControl, IERC1155, ILinkageLeaf {\n /**\n * @notice Emitted when new base URI was installed\n */\n event NewBaseUri(string newBaseUri);\n\n /**\n * @notice get name for Minterst NFT Token\n */\n function name() external view returns (string memory);\n\n /**\n * @notice get symbool for Minterst NFT Token\n */\n function symbol() external view returns (string memory);\n\n /**\n * @notice get address of opensea proxy registry\n */\n function proxyRegistry() external view returns (ProxyRegistry);\n\n /**\n * @notice get keccak-256 hash of GATEKEEPER role\n */\n function GATEKEEPER() external view returns (bytes32);\n\n /**\n * @notice Mint new 1155 standard token\n * @param account_ The address of the owner of minterestNFT\n * @param amount_ Instance count for minterestNFT\n * @param data_ The _data argument MAY be re-purposed for the new context.\n * @param tier_ tier\n */\n function mint(\n address account_,\n uint256 amount_,\n bytes memory data_,\n uint256 tier_\n ) external;\n\n /**\n * @notice Mint new ERC1155 standard tokens in one transaction\n * @param account_ The address of the owner of tokens\n * @param amounts_ Array of instance counts for tokens\n * @param data_ The _data argument MAY be re-purposed for the new context.\n * @param tiers_ Array of tiers\n * @dev RESTRICTION: Gatekeeper only\n */\n function mintBatch(\n address account_,\n uint256[] memory amounts_,\n bytes memory data_,\n uint256[] memory tiers_\n ) external;\n\n /**\n * @notice Transfer token to another account\n * @param to_ The address of the token receiver\n * @param id_ token id\n * @param amount_ Count of tokens\n * @param data_ The _data argument MAY be re-purposed for the new context.\n */\n function safeTransfer(\n address to_,\n uint256 id_,\n uint256 amount_,\n bytes memory data_\n ) external;\n\n /**\n * @notice Transfer tokens to another account\n * @param to_ The address of the tokens receiver\n * @param ids_ Array of token ids\n * @param amounts_ Array of tokens count\n * @param data_ The _data argument MAY be re-purposed for the new context.\n */\n function safeBatchTransfer(\n address to_,\n uint256[] memory ids_,\n uint256[] memory amounts_,\n bytes memory data_\n ) external;\n\n /**\n * @notice Set new base URI\n * @param newBaseUri Base URI\n * @dev RESTRICTION: Admin only\n */\n function setURI(string memory newBaseUri) external;\n\n /**\n * @notice Override function to return image URL, opensea requirement\n * @param tokenId_ Id of token to get URL\n * @return IPFS URI for token id, opensea requirement\n */\n function uri(uint256 tokenId_) external view returns (string memory);\n\n /**\n * @notice Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.\n * @param _owner Owner of tokens\n * @param _operator Address to check if the `operator` is the operator for `owner` tokens\n * @return isOperator return true if `operator` is the operator for `owner` tokens otherwise true *\n */\n function isApprovedForAll(address _owner, address _operator) external view returns (bool);\n\n /**\n * @dev Returns the next token ID to be minted\n * @return the next token ID to be minted\n */\n function nextIdToBeMinted() external view returns (uint256);\n}\n" }, "contracts/interfaces/IPriceOracle.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\nimport \"./IMToken.sol\";\n\ninterface IPriceOracle {\n /**\n * @notice Get the underlying price of a mToken asset\n * @param mToken The mToken to get the underlying price of\n * @return The underlying asset price mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n *\n * @dev Price should be scaled to 1e18 for tokens with tokenDecimals = 1e18\n * and for 1e30 for tokens with tokenDecimals = 1e6.\n */\n function getUnderlyingPrice(IMToken mToken) external view returns (uint256);\n\n /**\n * @notice Return price for an asset\n * @param asset address of token\n * @return The underlying asset price mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n * @dev Price should be scaled to 1e18 for tokens with tokenDecimals = 1e18\n * and for 1e30 for tokens with tokenDecimals = 1e6.\n */\n function getAssetPrice(address asset) external view returns (uint256);\n}\n" }, "contracts/interfaces/ILiquidation.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\n\nimport \"./IMToken.sol\";\nimport \"./IDeadDrop.sol\";\nimport \"./ILinkageLeaf.sol\";\nimport \"./IPriceOracle.sol\";\n\n/**\n * This contract provides the liquidation functionality.\n */\ninterface ILiquidation is IAccessControl, ILinkageLeaf {\n event HealthyFactorLimitChanged(uint256 oldValue, uint256 newValue);\n event NewDeadDrop(IDeadDrop oldDeadDrop, IDeadDrop newDeadDrop);\n event NewInsignificantLoanThreshold(uint256 oldValue, uint256 newValue);\n event ReliableLiquidation(\n bool isManualLiquidation,\n bool isDebtHealthy,\n address liquidator,\n address borrower,\n IMToken[] marketAddresses,\n uint256[] seizeIndexes,\n uint256[] debtRates\n );\n\n /**\n * @dev Local accountState for avoiding stack-depth limits in calculating liquidation amounts.\n */\n struct AccountLiquidationAmounts {\n uint256 accountTotalSupplyUsd;\n uint256 accountTotalCollateralUsd;\n uint256 accountPresumedTotalSeizeUsd;\n uint256 accountTotalBorrowUsd;\n uint256[] repayAmounts;\n uint256[] seizeAmounts;\n }\n\n /**\n * @notice GET The maximum allowable value of a healthy factor after liquidation, scaled by 1e18\n */\n function healthyFactorLimit() external view returns (uint256);\n\n /**\n * @notice GET Maximum sum in USD for internal liquidation. Collateral for loans that are less\n * than this parameter will be counted as protocol interest, scaled by 1e18\n */\n function insignificantLoanThreshold() external view returns (uint256);\n\n /**\n * @notice get keccak-256 hash of TRUSTED_LIQUIDATOR role\n */\n function TRUSTED_LIQUIDATOR() external view returns (bytes32);\n\n /**\n * @notice get keccak-256 hash of MANUAL_LIQUIDATOR role\n */\n function MANUAL_LIQUIDATOR() external view returns (bytes32);\n\n /**\n * @notice get keccak-256 hash of TIMELOCK role\n */\n function TIMELOCK() external view returns (bytes32);\n\n /**\n * @notice Liquidate insolvent debt position\n * @param borrower_ Account which is being liquidated\n * @param seizeIndexes_ An array with market indexes that will be used as collateral.\n * Each element corresponds to the market index in the accountAssets array\n * @param debtRates_ An array of debt redemption rates for each debt markets (scaled by 1e18).\n * @dev RESTRICTION: Trusted liquidator only\n */\n function liquidateUnsafeLoan(\n address borrower_,\n uint256[] memory seizeIndexes_,\n uint256[] memory debtRates_\n ) external;\n\n /**\n * @notice Accrues interest for all required borrower's markets\n * @dev Accrue is required if market is used as borrow (debtRate > 0)\n * or collateral (seizeIndex arr contains market index)\n * The caller must ensure that the lengths of arrays 'accountAssets' and 'debtRates' are the same,\n * array 'seizeIndexes' does not contain duplicates and none of the indexes exceeds the value\n * (accountAssets.length - 1).\n * @param accountAssets An array with addresses of markets where the debtor is in\n * @param seizeIndexes_ An array with market indexes that will be used as collateral\n * Each element corresponds to the market index in the accountAssets array\n * @param debtRates_ An array of debt redemption rates for each debt markets (scaled by 1e18)\n */\n function accrue(\n IMToken[] memory accountAssets,\n uint256[] memory seizeIndexes_,\n uint256[] memory debtRates_\n ) external;\n\n /**\n * @notice For each market calculates the liquidation amounts based on borrower's state.\n * @param account_ The address of the borrower\n * @param marketAddresses An array with addresses of markets where the debtor is in\n * @param seizeIndexes_ An array with market indexes that will be used as collateral\n * Each element corresponds to the market index in the accountAssets array\n * @param debtRates_ An array of debt redemption rates for each debt markets (scaled by 1e18)\n * @return accountState Struct that contains all balance parameters\n * All arrays calculated in underlying assets, all total values calculated in USD.\n * (the array indexes match each other)\n */\n function calculateLiquidationAmounts(\n address account_,\n IMToken[] memory marketAddresses,\n uint256[] memory seizeIndexes_,\n uint256[] memory debtRates_\n ) external view returns (AccountLiquidationAmounts memory);\n\n /**\n * @notice Sets a new value for healthyFactorLimit\n * @dev RESTRICTION: Timelock only\n */\n function setHealthyFactorLimit(uint256 newValue_) external;\n\n /**\n * @notice Sets a new minterest deadDrop\n * @dev RESTRICTION: Admin only\n */\n function setDeadDrop(IDeadDrop newDeadDrop_) external;\n\n /**\n * @notice Sets a new insignificantLoanThreshold\n * @dev RESTRICTION: Timelock only\n */\n function setInsignificantLoanThreshold(uint256 newValue_) external;\n}\n" }, "contracts/interfaces/IWeightAggregator.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\ninterface IWeightAggregator {\n /**\n * @notice Returns Buyback weight for the user\n */\n function getBuybackWeight(address account) external view returns (uint256);\n\n /**\n * @notice Return voting weight for the user\n */\n function getVotingWeight(address account) external view returns (uint256);\n}\n" }, "contracts/interfaces/IWhitelist.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/token/ERC1155/IERC1155.sol\";\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\n\ninterface IWhitelist is IAccessControl {\n /**\n * @notice The given member was added to the whitelist\n */\n event MemberAdded(address);\n\n /**\n * @notice The given member was removed from the whitelist\n */\n event MemberRemoved(address);\n\n /**\n * @notice Protocol operation mode switched\n */\n event WhitelistModeWasTurnedOff();\n\n /**\n * @notice Amount of maxMembers changed\n */\n event MaxMemberAmountChanged(uint256);\n\n /**\n * @notice get maximum number of members.\n * When membership reaches this number, no new members may join.\n */\n function maxMembers() external view returns (uint256);\n\n /**\n * @notice get the total number of members stored in the map.\n */\n function memberCount() external view returns (uint256);\n\n /**\n * @notice get protocol operation mode.\n */\n function whitelistModeEnabled() external view returns (bool);\n\n /**\n * @notice get is account member of whitelist\n */\n function accountMembership(address) external view returns (bool);\n\n /**\n * @notice get keccak-256 hash of GATEKEEPER role\n */\n function GATEKEEPER() external view returns (bytes32);\n\n /**\n * @notice Add a new member to the whitelist.\n * @param newAccount The account that is being added to the whitelist.\n * @dev RESTRICTION: Gatekeeper only.\n */\n function addMember(address newAccount) external;\n\n /**\n * @notice Remove a member from the whitelist.\n * @param accountToRemove The account that is being removed from the whitelist.\n * @dev RESTRICTION: Gatekeeper only.\n */\n function removeMember(address accountToRemove) external;\n\n /**\n * @notice Disables whitelist mode and enables emission boost mode.\n * @dev RESTRICTION: Admin only.\n */\n function turnOffWhitelistMode() external;\n\n /**\n * @notice Set a new threshold of participants.\n * @param newThreshold New number of participants.\n * @dev RESTRICTION: Gatekeeper only.\n */\n function setMaxMembers(uint256 newThreshold) external;\n\n /**\n * @notice Check protocol operation mode. In whitelist mode, only members from whitelist and who have\n * EmissionBooster can work with protocol.\n * @param who The address of the account to check for participation.\n */\n function isWhitelisted(address who) external view returns (bool);\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" }, "contracts/interfaces/IInterestRateModel.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @title Minterest InterestRateModel Interface\n * @author Minterest\n */\ninterface IInterestRateModel {\n /**\n * @notice Calculates the current borrow interest rate per block\n * @param cash The total amount of cash the market has\n * @param borrows The total amount of borrows the market has outstanding\n * @param protocolInterest The total amount of protocol interest the market has\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\n */\n function getBorrowRate(\n uint256 cash,\n uint256 borrows,\n uint256 protocolInterest\n ) external view returns (uint256);\n\n /**\n * @notice Calculates the current supply interest rate per block\n * @param cash The total amount of cash the market has\n * @param borrows The total amount of borrows the market has outstanding\n * @param protocolInterest The total amount of protocol interest the market has\n * @param protocolInterestFactorMantissa The current protocol interest factor the market has\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\n */\n function getSupplyRate(\n uint256 cash,\n uint256 borrows,\n uint256 protocolInterest,\n uint256 protocolInterestFactorMantissa\n ) external view returns (uint256);\n}\n" }, "@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC3156FlashLender.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC3156FlashBorrower.sol\";\n\n/**\n * @dev Interface of the ERC3156 FlashLender, as defined in\n * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].\n *\n * _Available since v4.1._\n */\ninterface IERC3156FlashLender {\n /**\n * @dev The amount of currency available to be lended.\n * @param token The loan currency.\n * @return The amount of `token` that can be borrowed.\n */\n function maxFlashLoan(address token) external view returns (uint256);\n\n /**\n * @dev The fee to be charged for a given loan.\n * @param token The loan currency.\n * @param amount The amount of tokens lent.\n * @return The amount of `token` to be charged for the loan, on top of the returned principal.\n */\n function flashFee(address token, uint256 amount) external view returns (uint256);\n\n /**\n * @dev Initiate a flash loan.\n * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.\n * @param token The loan currency.\n * @param amount The amount of tokens lent.\n * @param data Arbitrary data structure, intended to contain user-defined parameters.\n */\n function flashLoan(\n IERC3156FlashBorrower receiver,\n address token,\n uint256 amount,\n bytes calldata data\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/utils/introspection/IERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" }, "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC3156FlashBorrower.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC3156 FlashBorrower, as defined in\n * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].\n *\n * _Available since v4.1._\n */\ninterface IERC3156FlashBorrower {\n /**\n * @dev Receive a flash loan.\n * @param initiator The initiator of the loan.\n * @param token The loan currency.\n * @param amount The amount of tokens lent.\n * @param fee The additional amount of tokens to repay.\n * @param data Arbitrary data structure, intended to contain user-defined parameters.\n * @return The keccak256 hash of \"IERC3156FlashBorrower.onFlashLoan\"\n */\n function onFlashLoan(\n address initiator,\n address token,\n uint256 amount,\n uint256 fee,\n bytes calldata data\n ) external returns (bytes32);\n}\n" }, "contracts/interfaces/ILinkageRoot.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\ninterface ILinkageRoot {\n /**\n * @notice Emitted when new root contract connected to all leafs\n */\n event LinkageRootSwitch(ILinkageRoot newRoot);\n\n /**\n * @notice Emitted when root interconnects its contracts\n */\n event LinkageRootInterconnected();\n\n /**\n * @notice Connects new root to all leafs contracts\n * @param newRoot New root contract address\n */\n function switchLinkageRoot(ILinkageRoot newRoot) external;\n\n /**\n * @notice Update root for all leaf contracts\n * @dev Should include only leaf contracts\n */\n function interconnect() external;\n}\n" }, "@openzeppelin/contracts/token/ERC1155/IERC1155.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155 is IERC165 {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n" }, "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.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 IAccessControlUpgradeable {\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-upgradeable/token/ERC20/IERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface 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(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "contracts/interfaces/IDeadDrop.sol": { "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity 0.8.17;\n\nimport \"./IMToken.sol\";\nimport \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol\";\n\ninterface IDeadDrop is IAccessControl {\n event WithdrewToProtocolInterest(uint256 amount, IERC20 token, IMToken market);\n event Withdraw(address token, address to, uint256 amount);\n event NewSwapRouter(ISwapRouter router);\n event NewAllowedWithdrawReceiver(address receiver);\n event NewAllowedBot(address bot);\n event NewAllowedMarket(IERC20 token, IMToken market);\n event AllowedWithdrawReceiverRemoved(address receiver);\n event AllowedBotRemoved(address bot);\n event AllowedMarketRemoved(IERC20 token, IMToken market);\n event Swap(IERC20 tokenIn, IERC20 tokenOut, uint256 spentAmount, uint256 receivedAmount);\n event NewProcessingState(address target, uint256 hashValue, uint256 oldState, uint256 newState);\n\n /**\n * @notice get Uniswap SwapRouter\n */\n function swapRouter() external view returns (ISwapRouter);\n\n /**\n * @notice get Whitelist for markets allowed as a withdrawal destination.\n */\n function allowedMarkets(IERC20) external view returns (IMToken);\n\n /**\n * @notice get whitelist for users who can be a withdrawal recipients\n */\n function allowedWithdrawReceivers(address) external view returns (bool);\n\n /**\n * @notice get keccak-256 hash of gatekeeper role\n */\n function GATEKEEPER() external view returns (bytes32);\n\n /**\n * @notice Perform swap on Uniswap DEX\n * @param tokenIn input token\n * @param tokenInAmount amount of input token\n * @param tokenOut output token\n * @param data Uniswap calldata\n * @dev RESTRICTION: Gatekeeper only\n */\n function performSwap(\n IERC20 tokenIn,\n uint256 tokenInAmount,\n IERC20 tokenOut,\n bytes calldata data\n ) external;\n\n /**\n * @notice Withdraw underlying asset to market's protocol interest\n * @param amount Amount to withdraw\n * @param underlying Token to withdraw\n * @dev RESTRICTION: Gatekeeper only\n */\n function withdrawToProtocolInterest(uint256 amount, IERC20 underlying) external;\n\n /**\n * @notice Update processing state of ongoing liquidation\n * @param target Address of the account under liquidation\n * @param hashValue Liquidation identity hash\n * @param targetValue New state value of the liquidation\n * @dev RESTRICTION: Gatekeeper only\n */\n function updateProcessingState(\n address target,\n uint256 hashValue,\n uint256 targetValue\n ) external;\n\n /**\n * @notice Withdraw tokens to the wallet\n * @param amount Amount to withdraw\n * @param underlying Token to withdraw\n * @param to Receipient address\n * @dev RESTRICTION: Admin only\n */\n function withdraw(\n uint256 amount,\n IERC20 underlying,\n address to\n ) external;\n\n /**\n * @notice Add new market to the whitelist\n * @dev RESTRICTION: Admin only\n */\n function addAllowedMarket(IMToken market) external;\n\n /**\n * @notice Set new ISwapRouter router\n * @dev RESTRICTION: Admin only\n */\n function setRouterAddress(ISwapRouter router) external;\n\n /**\n * @notice Add new withdraw receiver address to the whitelist\n * @dev RESTRICTION: Admin only\n */\n function addAllowedReceiver(address receiver) external;\n\n /**\n * @notice Add new bot address to the whitelist\n * @dev RESTRICTION: Admin only\n */\n function addAllowedBot(address bot) external;\n\n /**\n * @notice Remove market from the whitelist\n * @dev RESTRICTION: Admin only\n */\n function removeAllowedMarket(IERC20 underlying) external;\n\n /**\n * @notice Remove withdraw receiver address from the whitelist\n */\n function removeAllowedReceiver(address receiver) external;\n\n /**\n * @notice Remove withdraw bot address from the whitelist\n * @dev RESTRICTION: Admin only\n */\n function removeAllowedBot(address bot) external;\n}\n" }, "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter is IUniswapV3SwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n" }, "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol": { "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary 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 *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev 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 require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/StorageSlot.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\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 * ```\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`, and `uint256`._\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 /**\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" }, "@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/Strings.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n" }, "@openzeppelin/contracts/utils/introspection/ERC165.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165 is IERC165 {\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165).interfaceId;\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} } }