creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "node_modules/@gearbox-protocol/core-v3/contracts/credit/CreditManagerV3.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\n// THIRD-PARTY\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n// LIBS & TRAITS\nimport {UNDERLYING_TOKEN_MASK, BitMask} from \"../libraries/BitMask.sol\";\nimport {CreditLogic} from \"../libraries/CreditLogic.sol\";\nimport {CollateralLogic} from \"../libraries/CollateralLogic.sol\";\nimport {CreditAccountHelper} from \"../libraries/CreditAccountHelper.sol\";\n\nimport {ReentrancyGuardTrait} from \"../traits/ReentrancyGuardTrait.sol\";\nimport {SanityCheckTrait} from \"../traits/SanityCheckTrait.sol\";\n\n// INTERFACES\nimport {IAccountFactoryBase} from \"../interfaces/IAccountFactoryV3.sol\";\nimport {ICreditAccountBase} from \"../interfaces/ICreditAccountV3.sol\";\nimport {IPoolV3} from \"../interfaces/IPoolV3.sol\";\nimport {\n    ICreditManagerV3,\n    CollateralTokenData,\n    ManageDebtAction,\n    CreditAccountInfo,\n    RevocationPair,\n    CollateralDebtData,\n    CollateralCalcTask,\n    DEFAULT_MAX_ENABLED_TOKENS,\n    INACTIVE_CREDIT_ACCOUNT_ADDRESS\n} from \"../interfaces/ICreditManagerV3.sol\";\nimport \"../interfaces/IAddressProviderV3.sol\";\nimport {IPriceOracleV3} from \"../interfaces/IPriceOracleV3.sol\";\nimport {IPoolQuotaKeeperV3} from \"../interfaces/IPoolQuotaKeeperV3.sol\";\n\n// CONSTANTS\nimport {PERCENTAGE_FACTOR} from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\n// EXCEPTIONS\nimport \"../interfaces/IExceptions.sol\";\n\n/// @title Credit manager V3\n/// @notice Credit manager implements core logic for credit accounts management.\n///         The contract itself is not open to neither external users nor the DAO: users should use `CreditFacadeV3`\n///         to open accounts and perform interactions with external protocols, while the DAO can configure manager\n///         params using `CreditConfiguratorV3`. Both mentioned contracts perform some important safety checks.\ncontract CreditManagerV3 is ICreditManagerV3, SanityCheckTrait, ReentrancyGuardTrait {\n    using EnumerableSet for EnumerableSet.AddressSet;\n    using BitMask for uint256;\n    using Math for uint256;\n    using CreditLogic for CollateralDebtData;\n    using CollateralLogic for CollateralDebtData;\n    using SafeERC20 for IERC20;\n    using CreditAccountHelper for ICreditAccountBase;\n\n    /// @notice Contract version\n    uint256 public constant override version = 3_01;\n\n    /// @notice Address provider contract address\n    address public immutable override addressProvider;\n\n    /// @notice Account factory contract address\n    address public immutable override accountFactory;\n\n    /// @notice Underlying token address\n    address public immutable override underlying;\n\n    /// @notice Address of the pool credit manager is connected to\n    address public immutable override pool;\n\n    /// @notice Address of the connected credit facade\n    address public override creditFacade;\n\n    /// @notice Address of the connected credit configurator\n    address public override creditConfigurator;\n\n    /// @notice Price oracle contract address\n    address public override priceOracle;\n\n    /// @notice Maximum number of tokens that a credit account can have enabled as collateral\n    uint8 public override maxEnabledTokens = DEFAULT_MAX_ENABLED_TOKENS;\n\n    /// @notice Number of known collateral tokens\n    uint8 public override collateralTokensCount;\n\n    /// @dev Liquidation threshold for the underlying token in bps\n    uint16 internal ltUnderlying;\n\n    /// @dev Percentage of accrued interest in bps taken by the protocol as profit\n    uint16 internal feeInterest;\n\n    /// @dev Percentage of liquidated account value in bps taken by the protocol as profit\n    uint16 internal feeLiquidation;\n\n    /// @dev Percentage of liquidated account value in bps that is used to repay debt\n    uint16 internal liquidationDiscount;\n\n    /// @dev Percentage of liquidated expired account value in bps taken by the protocol as profit\n    uint16 internal feeLiquidationExpired;\n\n    /// @dev Percentage of liquidated expired account value in bps that is used to repay debt\n    uint16 internal liquidationDiscountExpired;\n\n    /// @dev Active credit account which is an account adapters can interfact with\n    address internal _activeCreditAccount = INACTIVE_CREDIT_ACCOUNT_ADDRESS;\n\n    /// @notice Bitmask of quoted tokens\n    uint256 public override quotedTokensMask;\n\n    /// @dev Mapping collateral token mask => data (packed address and LT parameters)\n    mapping(uint256 => CollateralTokenData) internal collateralTokensData;\n\n    /// @dev Mapping collateral token address => mask\n    mapping(address => uint256) internal tokenMasksMapInternal;\n\n    /// @notice Mapping adapter => target contract\n    mapping(address => address) public override adapterToContract;\n\n    /// @notice Mapping target contract => adapter\n    mapping(address => address) public override contractToAdapter;\n\n    /// @notice Mapping credit account => account info (owner, debt amount, etc.)\n    mapping(address => CreditAccountInfo) public override creditAccountInfo;\n\n    /// @dev Set of all credit accounts opened in this credit manager\n    EnumerableSet.AddressSet internal creditAccountsSet;\n\n    /// @notice Credit manager name\n    string public override name;\n\n    /// @dev Ensures that function caller is the credit facade\n    modifier creditFacadeOnly() {\n        _checkCreditFacade();\n        _;\n    }\n\n    /// @dev Ensures that function caller is the credit configurator\n    modifier creditConfiguratorOnly() {\n        _checkCreditConfigurator();\n        _;\n    }\n\n    /// @notice Constructor\n    /// @param _addressProvider Address provider contract address\n    /// @param _pool Address of the lending pool to connect this credit manager to\n    /// @param _name Credit manager name\n    /// @dev Adds pool's underlying as collateral token with LT = 0\n    /// @dev Sets `msg.sender` as credit configurator\n    constructor(address _addressProvider, address _pool, string memory _name) {\n        addressProvider = _addressProvider;\n        pool = _pool; // U:[CM-1]\n\n        underlying = IPoolV3(_pool).underlyingToken(); // U:[CM-1]\n        _addToken(underlying); // U:[CM-1]\n\n        priceOracle = IAddressProviderV3(addressProvider).getAddressOrRevert(AP_PRICE_ORACLE, 3_00); // U:[CM-1]\n        accountFactory = IAddressProviderV3(addressProvider).getAddressOrRevert(AP_ACCOUNT_FACTORY, NO_VERSION_CONTROL); // U:[CM-1]\n\n        creditConfigurator = msg.sender; // U:[CM-1]\n\n        name = _name;\n    }\n\n    // ------------------ //\n    // ACCOUNT MANAGEMENT //\n    // ------------------ //\n\n    /// @notice Opens a new credit account\n    /// @param onBehalfOf Owner of a newly opened credit account\n    /// @return creditAccount Address of the newly opened credit account\n    function openCreditAccount(address onBehalfOf)\n        external\n        override\n        nonZeroAddress(onBehalfOf)\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (address creditAccount)\n    {\n        creditAccount = IAccountFactoryBase(accountFactory).takeCreditAccount(0, 0); // U:[CM-6]\n\n        CreditAccountInfo storage newCreditAccountInfo = creditAccountInfo[creditAccount];\n\n        // newCreditAccountInfo.flags = 0;\n        // newCreditAccountInfo.lastDebtUpdate = 0;\n        // newCreditAccountInfo.borrower = onBehalfOf;\n        assembly {\n            let slot := add(newCreditAccountInfo.slot, 4)\n            let value := shl(80, onBehalfOf)\n            sstore(slot, value)\n        } // U:[CM-6]\n\n        // newCreditAccountInfo.cumulativeQuotaInterest = 1;\n        // newCreditAccountInfo.quotaFees = 0;\n        assembly {\n            let slot := add(newCreditAccountInfo.slot, 2)\n            sstore(slot, 1)\n        } // U:[CM-6]\n\n        creditAccountsSet.add(creditAccount); // U:[CM-6]\n    }\n\n    /// @notice Closes a credit account\n    /// @param creditAccount Account to close\n    /// @custom:expects Credit facade ensures that `creditAccount` is opened in this credit manager\n    function closeCreditAccount(address creditAccount)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n    {\n        CreditAccountInfo storage currentCreditAccountInfo = creditAccountInfo[creditAccount];\n        if (currentCreditAccountInfo.debt != 0) {\n            revert CloseAccountWithNonZeroDebtException(); // U:[CM-7]\n        }\n\n        // currentCreditAccountInfo.borrower = address(0);\n        // currentCreditAccountInfo.lastDebtUpdate = 0;\n        // currentCreditAccountInfo.flags = 0;\n        assembly {\n            let slot := add(currentCreditAccountInfo.slot, 4)\n            sstore(slot, 0)\n        } // U:[CM-7]\n\n        currentCreditAccountInfo.enabledTokensMask = 0; // U:[CM-7]\n\n        IAccountFactoryBase(accountFactory).returnCreditAccount({creditAccount: creditAccount}); // U:[CM-7]\n        creditAccountsSet.remove(creditAccount); // U:[CM-7]\n    }\n\n    /// @notice Liquidates a credit account\n    ///         - Removes account's quotas, and, if there's loss incurred on liquidation,\n    ///           also zeros out limits for account's quoted tokens in the quota keeper\n    ///         - Repays debt to the pool\n    ///         - Ensures that the value of funds remaining on the account is sufficient\n    ///         - Transfers underlying surplus (if any) to the liquidator\n    ///         - Resets account's debt, quota interest and fees to zero\n    /// @param creditAccount Account to liquidate\n    /// @param collateralDebtData A struct with account's debt and collateral data\n    /// @param to Address to transfer underlying left after liquidation\n    /// @return remainingFunds Total value of assets left on the account after liquidation\n    /// @return loss Loss incurred on liquidation\n    /// @custom:expects Credit facade ensures that `creditAccount` is opened in this credit manager\n    /// @custom:expects `collateralDebtData` is a result of `calcDebtAndCollateral` in `DEBT_COLLATERAL` mode\n    function liquidateCreditAccount(\n        address creditAccount,\n        CollateralDebtData calldata collateralDebtData,\n        address to,\n        bool isExpired\n    )\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 remainingFunds, uint256 loss)\n    {\n        uint256 amountToPool;\n        uint256 minRemainingFunds;\n        uint256 profit;\n        (amountToPool, minRemainingFunds, profit, loss) = collateralDebtData.calcLiquidationPayments({\n            liquidationDiscount: isExpired ? liquidationDiscountExpired : liquidationDiscount,\n            feeLiquidation: isExpired ? feeLiquidationExpired : feeLiquidation,\n            amountWithFeeFn: _amountWithFee,\n            amountMinusFeeFn: _amountMinusFee\n        }); // U:[CM-8]\n\n        if (collateralDebtData.quotedTokens.length != 0) {\n            IPoolQuotaKeeperV3(collateralDebtData._poolQuotaKeeper).removeQuotas({\n                creditAccount: creditAccount,\n                tokens: collateralDebtData.quotedTokens,\n                setLimitsToZero: loss > 0\n            }); // U:[CM-8]\n        }\n\n        if (amountToPool != 0) {\n            ICreditAccountBase(creditAccount).transfer({token: underlying, to: pool, amount: amountToPool}); // U:[CM-8]\n        }\n        _poolRepayCreditAccount(collateralDebtData.debt, profit, loss); // U:[CM-8]\n\n        uint256 underlyingBalance;\n        (remainingFunds, underlyingBalance) =\n            _getRemainingFunds({creditAccount: creditAccount, enabledTokensMask: collateralDebtData.enabledTokensMask}); // U:[CM-8]\n\n        if (remainingFunds < minRemainingFunds) {\n            revert InsufficientRemainingFundsException(); // U:[CM-8]\n        }\n\n        unchecked {\n            uint256 amountToLiquidator = Math.min(remainingFunds - minRemainingFunds, underlyingBalance);\n\n            if (amountToLiquidator != 0) {\n                ICreditAccountBase(creditAccount).transfer({token: underlying, to: to, amount: amountToLiquidator}); // U:[CM-8]\n\n                remainingFunds -= amountToLiquidator; // U:[CM-8]\n            }\n        }\n\n        CreditAccountInfo storage currentCreditAccountInfo = creditAccountInfo[creditAccount];\n        if (currentCreditAccountInfo.lastDebtUpdate == block.number) {\n            revert DebtUpdatedTwiceInOneBlockException(); // U:[CM-9]\n        }\n\n        currentCreditAccountInfo.debt = 0; // U:[CM-8]\n        currentCreditAccountInfo.lastDebtUpdate = uint64(block.number); // U:[CM-8]\n        currentCreditAccountInfo.enabledTokensMask =\n            collateralDebtData.enabledTokensMask.disable(collateralDebtData.quotedTokensMask); // U:[CM-8]\n\n        // currentCreditAccountInfo.cumulativeQuotaInterest = 1;\n        // currentCreditAccountInfo.quotaFees = 0;\n        assembly {\n            let slot := add(currentCreditAccountInfo.slot, 2)\n            sstore(slot, 1)\n        } // U:[CM-8]\n    }\n\n    /// @notice Increases or decreases credit account's debt\n    /// @param creditAccount Account to increase/decrease debr for\n    /// @param amount Amount of underlying to change the total debt by\n    /// @param enabledTokensMask  Bitmask of account's enabled collateral tokens\n    /// @param action Manage debt type, see `ManageDebtAction`\n    /// @return newDebt Debt principal after update\n    /// @return tokensToEnable Tokens that should be enabled after the operation\n    ///         (underlying mask on increase, zero on decrease)\n    /// @return tokensToDisable Tokens that should be disabled after the operation\n    ///         (zero on increase, underlying mask on decrease if account has no underlying after repayment)\n    /// @custom:expects Credit facade ensures that `creditAccount` is opened in this credit manager\n    function manageDebt(address creditAccount, uint256 amount, uint256 enabledTokensMask, ManageDebtAction action)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 newDebt, uint256 tokensToEnable, uint256 tokensToDisable)\n    {\n        CreditAccountInfo storage currentCreditAccountInfo = creditAccountInfo[creditAccount];\n        if (currentCreditAccountInfo.lastDebtUpdate == block.number) {\n            revert DebtUpdatedTwiceInOneBlockException(); // U:[CM-12A]\n        }\n        if (amount == 0) return (currentCreditAccountInfo.debt, 0, 0); // U:[CM-12B]\n\n        uint256[] memory collateralHints;\n        CollateralDebtData memory collateralDebtData = _calcDebtAndCollateral({\n            creditAccount: creditAccount,\n            enabledTokensMask: enabledTokensMask,\n            collateralHints: collateralHints,\n            minHealthFactor: PERCENTAGE_FACTOR,\n            task: (action == ManageDebtAction.INCREASE_DEBT)\n                ? CollateralCalcTask.GENERIC_PARAMS\n                : CollateralCalcTask.DEBT_ONLY,\n            useSafePrices: false\n        });\n\n        uint256 newCumulativeIndex;\n        if (action == ManageDebtAction.INCREASE_DEBT) {\n            (newDebt, newCumulativeIndex) = CreditLogic.calcIncrease({\n                amount: amount,\n                debt: collateralDebtData.debt,\n                cumulativeIndexNow: collateralDebtData.cumulativeIndexNow,\n                cumulativeIndexLastUpdate: collateralDebtData.cumulativeIndexLastUpdate\n            }); // U:[CM-10]\n\n            _poolLendCreditAccount(amount, creditAccount); // U:[CM-10]\n            tokensToEnable = UNDERLYING_TOKEN_MASK; // U:[CM-12C]\n        } else {\n            uint256 maxRepayment = _amountWithFee(collateralDebtData.calcTotalDebt());\n            if (amount >= maxRepayment) {\n                amount = maxRepayment; // U:[CM-11]\n            }\n\n            ICreditAccountBase(creditAccount).transfer({token: underlying, to: pool, amount: amount}); // U:[CM-11]\n\n            uint128 newCumulativeQuotaInterest;\n            uint256 profit;\n            if (amount == maxRepayment) {\n                newDebt = 0;\n                newCumulativeIndex = collateralDebtData.cumulativeIndexNow;\n                profit = collateralDebtData.accruedFees;\n                newCumulativeQuotaInterest = 0;\n                currentCreditAccountInfo.quotaFees = 0;\n            } else {\n                (newDebt, newCumulativeIndex, profit, newCumulativeQuotaInterest, currentCreditAccountInfo.quotaFees) =\n                CreditLogic.calcDecrease({\n                    amount: _amountMinusFee(amount),\n                    debt: collateralDebtData.debt,\n                    cumulativeIndexNow: collateralDebtData.cumulativeIndexNow,\n                    cumulativeIndexLastUpdate: collateralDebtData.cumulativeIndexLastUpdate,\n                    cumulativeQuotaInterest: collateralDebtData.cumulativeQuotaInterest,\n                    quotaFees: currentCreditAccountInfo.quotaFees,\n                    feeInterest: feeInterest\n                }); // U:[CM-11]\n            }\n\n            if (collateralDebtData.quotedTokens.length != 0) {\n                // zero-debt is a special state that disables collateral checks so having quotas on\n                // the account should be forbidden as they entail debt in a form of quota interest\n                if (newDebt == 0) revert DebtToZeroWithActiveQuotasException(); // U:[CM-11A]\n\n                // quota interest is accrued in credit manager regardless of whether anything has been repaid,\n                // so they are also accrued in the quota keeper to keep the contracts in sync\n                IPoolQuotaKeeperV3(collateralDebtData._poolQuotaKeeper).accrueQuotaInterest({\n                    creditAccount: creditAccount,\n                    tokens: collateralDebtData.quotedTokens\n                }); // U:[CM-11A]\n            }\n\n            _poolRepayCreditAccount(collateralDebtData.debt - newDebt, profit, 0); // U:[CM-11]\n\n            currentCreditAccountInfo.cumulativeQuotaInterest = newCumulativeQuotaInterest + 1; // U:[CM-11]\n\n            if (IERC20(underlying).safeBalanceOf({account: creditAccount}) <= 1) {\n                tokensToDisable = UNDERLYING_TOKEN_MASK; // U:[CM-12C]\n            }\n        }\n\n        currentCreditAccountInfo.debt = newDebt; // U:[CM-10,11]\n        currentCreditAccountInfo.lastDebtUpdate = uint64(block.number); // U:[CM-10,11]\n        currentCreditAccountInfo.cumulativeIndexLastUpdate = newCumulativeIndex; // U:[CM-10,11]\n    }\n\n    /// @notice Adds `amount` of `payer`'s `token` as collateral to `creditAccount`\n    /// @param payer Address to transfer token from\n    /// @param creditAccount Account to add collateral to\n    /// @param token Token to add as collateral\n    /// @param amount Amount to add\n    /// @return tokensToEnable Mask of tokens that should be enabled after the operation (always `token` mask)\n    /// @dev Requires approval for `token` from `payer` to this contract\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function addCollateral(address payer, address creditAccount, address token, uint256 amount)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 tokensToEnable)\n    {\n        tokensToEnable = getTokenMaskOrRevert({token: token}); // U:[CM-13]\n        IERC20(token).safeTransferFrom({from: payer, to: creditAccount, amount: amount}); // U:[CM-13]\n    }\n\n    /// @notice Withdraws `amount` of `token` collateral from `creditAccount` to `to`\n    /// @param creditAccount Credit account to withdraw collateral from\n    /// @param token Token to withdraw\n    /// @param amount Amount to withdraw\n    /// @param to Address to transfer token to\n    /// @return tokensToDisable Mask of tokens that should be disabled after the operation\n    ///         (`token` mask if withdrawing the entire balance, zero otherwise)\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function withdrawCollateral(address creditAccount, address token, uint256 amount, address to)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 tokensToDisable)\n    {\n        uint256 tokenMask = getTokenMaskOrRevert({token: token}); // U:[CM-26]\n\n        ICreditAccountBase(creditAccount).transfer({token: token, to: to, amount: amount}); // U:[CM-27]\n\n        if (IERC20(token).safeBalanceOf({account: creditAccount}) <= 1) {\n            tokensToDisable = tokenMask; // U:[CM-27]\n        }\n    }\n\n    /// @notice Instructs `creditAccount` to make an external call to target with `callData`\n    function externalCall(address creditAccount, address target, bytes calldata callData)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (bytes memory result)\n    {\n        return _execute(creditAccount, target, callData);\n    }\n\n    /// @notice Instructs `creditAccount` to approve `amount` of `token` to `spender`\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function approveToken(address creditAccount, address token, address spender, uint256 amount)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n    {\n        _approveSpender({creditAccount: creditAccount, token: token, spender: spender, amount: amount});\n    }\n\n    /// @notice Revokes credit account's allowances for specified spender/token pairs\n    /// @param creditAccount Account to revoke allowances for\n    /// @param revocations Array of spender/token pairs\n    /// @dev Exists primarily to allow users to revoke allowances on accounts from old account factory on mainnet\n    /// @dev Reverts if any of provided tokens is not recognized as collateral in the credit manager\n    function revokeAdapterAllowances(address creditAccount, RevocationPair[] calldata revocations)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n    {\n        uint256 numRevocations = revocations.length;\n        unchecked {\n            for (uint256 i; i < numRevocations; ++i) {\n                address spender = revocations[i].spender;\n                address token = revocations[i].token;\n                if (spender == address(0) || token == address(0)) {\n                    revert ZeroAddressException(); // U:[CM-15]\n                }\n                _approveSpender({creditAccount: creditAccount, token: token, spender: spender, amount: 0}); // U:[CM-15]\n            }\n        }\n    }\n\n    // -------- //\n    // ADAPTERS //\n    // -------- //\n\n    /// @notice Instructs active credit account to approve `amount` of `token` to adater's target contract\n    /// @param token Token to approve\n    /// @param amount Amount to approve\n    /// @dev Reverts if active credit account is not set\n    /// @dev Reverts if `msg.sender` is not a registered adapter\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function approveCreditAccount(address token, uint256 amount)\n        external\n        override\n        nonReentrant // U:[CM-5]\n    {\n        address targetContract = _getTargetContractOrRevert(); // U:[CM-3]\n        address creditAccount = getActiveCreditAccountOrRevert(); // U:[CM-14]\n        _approveSpender({creditAccount: creditAccount, token: token, spender: targetContract, amount: amount}); // U:[CM-14]\n    }\n\n    /// @notice Instructs active credit account to call adapter's target contract with provided data\n    /// @param data Data to call the target contract with\n    /// @return result Call result\n    /// @dev Reverts if active credit account is not set\n    /// @dev Reverts if `msg.sender` is not a registered adapter\n    function execute(bytes calldata data)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        returns (bytes memory result)\n    {\n        address targetContract = _getTargetContractOrRevert(); // U:[CM-3]\n        address creditAccount = getActiveCreditAccountOrRevert(); // U:[CM-16]\n        return _execute(creditAccount, targetContract, data); // U:[CM-16]\n    }\n\n    /// @dev Returns adapter's target contract, reverts if `msg.sender` is not a registered adapter\n    function _getTargetContractOrRevert() internal view returns (address targetContract) {\n        targetContract = adapterToContract[msg.sender]; // U:[CM-15, 16]\n        if (targetContract == address(0)) {\n            revert CallerNotAdapterException(); // U:[CM-3]\n        }\n    }\n\n    /// @notice Sets/unsets active credit account adapters can interact with\n    /// @param creditAccount Credit account to set as active or `INACTIVE_CREDIT_ACCOUNT_ADDRESS` to unset it\n    function setActiveCreditAccount(address creditAccount)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n    {\n        if (_activeCreditAccount != INACTIVE_CREDIT_ACCOUNT_ADDRESS && creditAccount != INACTIVE_CREDIT_ACCOUNT_ADDRESS)\n        {\n            revert ActiveCreditAccountOverridenException();\n        }\n        _activeCreditAccount = creditAccount;\n    }\n\n    /// @notice Returns active credit account, reverts if it is not set\n    function getActiveCreditAccountOrRevert() public view override returns (address creditAccount) {\n        creditAccount = _activeCreditAccount;\n        if (creditAccount == INACTIVE_CREDIT_ACCOUNT_ADDRESS) {\n            revert ActiveCreditAccountNotSetException();\n        }\n    }\n\n    // ----------------- //\n    // COLLATERAL CHECKS //\n    // ----------------- //\n\n    /// @notice Performs full check of `creditAccount`'s collateral to ensure it is sufficiently collateralized,\n    ///         might disable tokens with zero balances\n    /// @param creditAccount Credit account to check\n    /// @param enabledTokensMask Bitmask of account's enabled collateral tokens\n    /// @param collateralHints Optional array of token masks to check first to reduce the amount of computation\n    ///        when known subset of account's collateral tokens covers all the debt\n    /// @param minHealthFactor Health factor threshold in bps, the check fails if `twvUSD < minHealthFactor * totalDebtUSD`\n    /// @param useSafePrices Whether to use safe prices when evaluating collateral\n    /// @return enabledTokensMaskAfter Bitmask of account's enabled collateral tokens after potential cleanup\n    /// @dev Even when `collateralHints` are specified, quoted tokens are evaluated before non-quoted ones\n    /// @custom:expects Credit facade ensures that `creditAccount` is opened in this credit manager\n    function fullCollateralCheck(\n        address creditAccount,\n        uint256 enabledTokensMask,\n        uint256[] calldata collateralHints,\n        uint16 minHealthFactor,\n        bool useSafePrices\n    )\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 enabledTokensMaskAfter)\n    {\n        CollateralDebtData memory cdd = _calcDebtAndCollateral({\n            creditAccount: creditAccount,\n            minHealthFactor: minHealthFactor,\n            collateralHints: collateralHints,\n            enabledTokensMask: enabledTokensMask,\n            task: CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY,\n            useSafePrices: useSafePrices\n        }); // U:[CM-18]\n\n        if (cdd.twvUSD < cdd.totalDebtUSD * minHealthFactor / PERCENTAGE_FACTOR) {\n            revert NotEnoughCollateralException(); // U:[CM-18B]\n        }\n\n        enabledTokensMaskAfter = cdd.enabledTokensMask;\n        _saveEnabledTokensMask(creditAccount, enabledTokensMaskAfter); // U:[CM-18]\n    }\n\n    /// @notice Whether `creditAccount`'s health factor is below `minHealthFactor`\n    /// @param creditAccount Credit account to check\n    /// @param minHealthFactor Health factor threshold in bps\n    /// @dev Reverts if account is not opened in this credit manager\n    function isLiquidatable(address creditAccount, uint16 minHealthFactor) external view override returns (bool) {\n        getBorrowerOrRevert(creditAccount); // U:[CM-17]\n\n        uint256[] memory collateralHints;\n        CollateralDebtData memory cdd = _calcDebtAndCollateral({\n            creditAccount: creditAccount,\n            enabledTokensMask: enabledTokensMaskOf(creditAccount),\n            collateralHints: collateralHints,\n            minHealthFactor: minHealthFactor,\n            task: CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY,\n            useSafePrices: false\n        }); // U:[CM-18]\n\n        return cdd.twvUSD < cdd.totalDebtUSD * minHealthFactor / PERCENTAGE_FACTOR; // U:[CM-18B]\n    }\n\n    /// @notice Returns `creditAccount`'s debt and collateral data with level of detail controlled by `task`\n    /// @param creditAccount Credit account to return data for\n    /// @param task Calculation mode, see `CollateralCalcTask` for details, can't be `FULL_COLLATERAL_CHECK_LAZY`\n    /// @return cdd A struct with debt and collateral data\n    /// @dev Reverts if account is not opened in this credit manager\n    function calcDebtAndCollateral(address creditAccount, CollateralCalcTask task)\n        external\n        view\n        override\n        returns (CollateralDebtData memory cdd)\n    {\n        if (task == CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY) {\n            revert IncorrectParameterException(); // U:[CM-19]\n        }\n\n        bool useSafePrices;\n        if (task == CollateralCalcTask.DEBT_COLLATERAL_SAFE_PRICES) {\n            task = CollateralCalcTask.DEBT_COLLATERAL;\n            useSafePrices = true;\n        }\n\n        getBorrowerOrRevert(creditAccount); // U:[CM-17]\n\n        uint256[] memory collateralHints;\n        cdd = _calcDebtAndCollateral({\n            creditAccount: creditAccount,\n            enabledTokensMask: enabledTokensMaskOf(creditAccount),\n            collateralHints: collateralHints,\n            minHealthFactor: PERCENTAGE_FACTOR,\n            task: task,\n            useSafePrices: useSafePrices\n        }); // U:[CM-20]\n    }\n\n    /// @dev `calcDebtAndCollateral` implementation\n    /// @param creditAccount Credit account to return data for\n    /// @param enabledTokensMask Bitmask of account's enabled collateral tokens\n    /// @param collateralHints Optional array of token masks specifying the order of checking collateral tokens\n    /// @param minHealthFactor Health factor in bps to stop the calculations after when performing collateral check\n    /// @param task Calculation mode, see `CollateralCalcTask` for details\n    /// @param useSafePrices Whether to use safe prices when evaluating collateral\n    /// @return cdd A struct with debt and collateral data\n    function _calcDebtAndCollateral(\n        address creditAccount,\n        uint256 enabledTokensMask,\n        uint256[] memory collateralHints,\n        uint16 minHealthFactor,\n        CollateralCalcTask task,\n        bool useSafePrices\n    ) internal view returns (CollateralDebtData memory cdd) {\n        CreditAccountInfo storage currentCreditAccountInfo = creditAccountInfo[creditAccount];\n\n        cdd.debt = currentCreditAccountInfo.debt; // U:[CM-20]\n        cdd.cumulativeIndexLastUpdate = currentCreditAccountInfo.cumulativeIndexLastUpdate; // U:[CM-20]\n        cdd.cumulativeIndexNow = IPoolV3(pool).baseInterestIndex(); // U:[CM-20]\n\n        if (task == CollateralCalcTask.GENERIC_PARAMS) {\n            return cdd; // U:[CM-20]\n        }\n\n        cdd.enabledTokensMask = enabledTokensMask; // U:[CM-21]\n        cdd._poolQuotaKeeper = poolQuotaKeeper(); // U:[CM-21]\n\n        uint256[] memory quotasPacked;\n        (cdd.quotedTokens, cdd.cumulativeQuotaInterest, quotasPacked, cdd.quotedTokensMask) = _getQuotedTokensData({\n            creditAccount: creditAccount,\n            enabledTokensMask: enabledTokensMask,\n            collateralHints: collateralHints,\n            _poolQuotaKeeper: cdd._poolQuotaKeeper\n        }); // U:[CM-21]\n        cdd.cumulativeQuotaInterest += currentCreditAccountInfo.cumulativeQuotaInterest - 1; // U:[CM-21]\n\n        cdd.accruedInterest = CreditLogic.calcAccruedInterest({\n            amount: cdd.debt,\n            cumulativeIndexLastUpdate: cdd.cumulativeIndexLastUpdate,\n            cumulativeIndexNow: cdd.cumulativeIndexNow\n        });\n        cdd.accruedFees = currentCreditAccountInfo.quotaFees + cdd.accruedInterest * feeInterest / PERCENTAGE_FACTOR;\n\n        cdd.accruedInterest += cdd.cumulativeQuotaInterest; // U:[CM-21]\n        cdd.accruedFees += cdd.cumulativeQuotaInterest * feeInterest / PERCENTAGE_FACTOR; // U:[CM-21]\n\n        if (task == CollateralCalcTask.DEBT_ONLY) {\n            return cdd; // U:[CM-21]\n        }\n\n        address _priceOracle = priceOracle;\n\n        {\n            uint256 totalDebt = _amountWithFee(cdd.calcTotalDebt());\n            if (totalDebt != 0) {\n                cdd.totalDebtUSD = _convertToUSD(_priceOracle, totalDebt, underlying); // U:[CM-22]\n            } else if (task == CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY) {\n                return cdd; // U:[CM-18A]\n            }\n        }\n\n        uint256 targetUSD = (task == CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY)\n            ? cdd.totalDebtUSD * minHealthFactor / PERCENTAGE_FACTOR\n            : type(uint256).max;\n\n        uint256 tokensToDisable;\n        (cdd.totalValueUSD, cdd.twvUSD, tokensToDisable) = cdd.calcCollateral({\n            creditAccount: creditAccount,\n            underlying: underlying,\n            twvUSDTarget: targetUSD,\n            collateralHints: collateralHints,\n            quotasPacked: quotasPacked,\n            priceOracle: _priceOracle,\n            collateralTokenByMaskFn: _collateralTokenByMask,\n            convertToUSDFn: useSafePrices ? _safeConvertToUSD : _convertToUSD\n        }); // U:[CM-22]\n        cdd.enabledTokensMask = enabledTokensMask.disable(tokensToDisable); // U:[CM-22]\n\n        if (task == CollateralCalcTask.FULL_COLLATERAL_CHECK_LAZY) {\n            return cdd;\n        }\n\n        cdd.totalValue = _convertFromUSD(_priceOracle, cdd.totalValueUSD, underlying); // U:[CM-22,23]\n    }\n\n    /// @dev Returns quotas data for credit manager and credit account\n    /// @param creditAccount Credit account to return quotas data for\n    /// @param enabledTokensMask Bitmask of account's enabled collateral tokens\n    /// @param collateralHints Optional array of token masks specifying tokens order\n    /// @param _poolQuotaKeeper Cached quota keeper address\n    /// @return quotedTokens Array of quoted tokens enabled as collateral on the account,\n    ///         sorted according to `collateralHints` if specified\n    /// @return outstandingQuotaInterest Account's quota interest that has not yet been accounted for\n    /// @return quotasPacked Array of quotas packed with tokens' LTs\n    /// @return _quotedTokensMask The bitmask of all quoted tokens in the credit manager\n    function _getQuotedTokensData(\n        address creditAccount,\n        uint256 enabledTokensMask,\n        uint256[] memory collateralHints,\n        address _poolQuotaKeeper\n    )\n        internal\n        view\n        returns (\n            address[] memory quotedTokens,\n            uint128 outstandingQuotaInterest,\n            uint256[] memory quotasPacked,\n            uint256 _quotedTokensMask\n        )\n    {\n        _quotedTokensMask = quotedTokensMask; // U:[CM-24]\n\n        uint256 tokensToCheckMask = enabledTokensMask & _quotedTokensMask; // U:[CM-24]\n        if (tokensToCheckMask == 0) {\n            return (quotedTokens, 0, quotasPacked, _quotedTokensMask);\n        }\n\n        uint256 tokensIdx;\n        uint256 tokensLen = tokensToCheckMask.calcEnabledTokens(); // U:[CM-24]\n        quotedTokens = new address[](tokensLen); // U:[CM-24]\n        quotasPacked = new uint256[](tokensLen); // U:[CM-24]\n\n        uint256 hintsIdx;\n        uint256 hintsLen = collateralHints.length;\n\n        // puts credit account on top of the stack to avoid the \"stack too deep\" error\n        address _creditAccount = creditAccount;\n\n        unchecked {\n            while (tokensToCheckMask != 0) {\n                uint256 tokenMask;\n                if (hintsIdx < hintsLen) {\n                    tokenMask = collateralHints[hintsIdx++];\n                    if (tokensToCheckMask & tokenMask == 0) continue;\n                } else {\n                    // mask with only the LSB of `tokensToCheckMask` enabled\n                    tokenMask = tokensToCheckMask & uint256(-int256(tokensToCheckMask));\n                }\n\n                (address token, uint16 lt) = _collateralTokenByMask({tokenMask: tokenMask, calcLT: true}); // U:[CM-24]\n\n                (uint256 quota, uint128 outstandingInterestDelta) =\n                    IPoolQuotaKeeperV3(_poolQuotaKeeper).getQuotaAndOutstandingInterest(_creditAccount, token); // U:[CM-24]\n\n                quotedTokens[tokensIdx] = token; // U:[CM-24]\n                quotasPacked[tokensIdx] = CollateralLogic.packQuota(uint96(quota), lt);\n\n                // quota interest is of roughly the same scale as quota, which is stored as `uint96`,\n                // thus this addition is very unlikely to overflow and can be unchecked\n                outstandingQuotaInterest += outstandingInterestDelta; // U:[CM-24]\n\n                ++tokensIdx;\n                tokensToCheckMask = tokensToCheckMask.disable(tokenMask);\n            }\n        }\n    }\n\n    /// @dev Returns total value of funds remaining on the credit account after liquidation, which consists of underlying\n    ///      token balance and total value of other enabled tokens remaining after transferring specified tokens\n    /// @param creditAccount Account to compute value for\n    /// @param enabledTokensMask Bit mask of tokens enabled on the account\n    /// @return remainingFunds Remaining funds denominated in underlying\n    /// @return underlyingBalance Balance of underlying token\n    function _getRemainingFunds(address creditAccount, uint256 enabledTokensMask)\n        internal\n        view\n        returns (uint256 remainingFunds, uint256 underlyingBalance)\n    {\n        underlyingBalance = IERC20(underlying).safeBalanceOf({account: creditAccount});\n        remainingFunds = underlyingBalance;\n\n        uint256 remainingTokensMask = enabledTokensMask.disable(UNDERLYING_TOKEN_MASK);\n        if (remainingTokensMask == 0) return (remainingFunds, underlyingBalance);\n\n        address _priceOracle = priceOracle;\n        uint256 totalValueUSD;\n        while (remainingTokensMask != 0) {\n            uint256 tokenMask = remainingTokensMask & uint256(-int256(remainingTokensMask));\n            remainingTokensMask ^= tokenMask;\n\n            address token = getTokenByMask(tokenMask);\n            uint256 balance = IERC20(token).safeBalanceOf({account: creditAccount});\n            if (balance > 1) {\n                totalValueUSD += _convertToUSD(_priceOracle, balance, token);\n            }\n        }\n\n        if (totalValueUSD != 0) {\n            remainingFunds += _convertFromUSD(_priceOracle, totalValueUSD, underlying);\n        }\n    }\n\n    // ------ //\n    // QUOTAS //\n    // ------ //\n\n    /// @notice Returns address of the quota keeper connected to the pool\n    function poolQuotaKeeper() public view override returns (address) {\n        return IPoolV3(pool).poolQuotaKeeper(); // U:[CM-47]\n    }\n\n    /// @notice Requests quota keeper to update credit account's quota for a given token\n    /// @param creditAccount Account to update the quota for\n    /// @param token Token to update the quota for\n    /// @param quotaChange Requested quota change\n    /// @param minQuota Minimum resulting account's quota for token required not to revert\n    ///        (set by the user to prevent slippage)\n    /// @param maxQuota Maximum resulting account's quota for token required not to revert\n    ///        (set by the credit facade to prevent pool's diesel rate manipulation)\n    /// @return tokensToEnable Mask of tokens that should be enabled after the operation\n    ///         (equals `token`'s mask if changing quota from zero to non-zero value, zero otherwise)\n    /// @return tokensToDisable Mask of tokens that should be disabled after the operation\n    ///         (equals `token`'s mask if changing quota from non-zero value to zero, zero otherwise)\n    /// @dev Accounts with zero debt are not allowed to increase quotas\n    function updateQuota(address creditAccount, address token, int96 quotaChange, uint96 minQuota, uint96 maxQuota)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n        returns (uint256 tokensToEnable, uint256 tokensToDisable)\n    {\n        CreditAccountInfo storage currentCreditAccountInfo = creditAccountInfo[creditAccount];\n        if (currentCreditAccountInfo.debt == 0) {\n            revert UpdateQuotaOnZeroDebtAccountException();\n        }\n\n        (uint128 caInterestChange, uint128 quotaFees, bool enable, bool disable) = IPoolQuotaKeeperV3(poolQuotaKeeper())\n            .updateQuota({\n            creditAccount: creditAccount,\n            token: token,\n            requestedChange: quotaChange,\n            minQuota: minQuota,\n            maxQuota: maxQuota\n        }); // U:[CM-25]\n\n        if (enable) {\n            tokensToEnable = getTokenMaskOrRevert(token); // U:[CM-25]\n        } else if (disable) {\n            tokensToDisable = getTokenMaskOrRevert(token); // U:[CM-25]\n        }\n\n        currentCreditAccountInfo.cumulativeQuotaInterest += caInterestChange; // U:[CM-25]\n        if (quotaFees != 0) {\n            currentCreditAccountInfo.quotaFees += quotaFees;\n        }\n    }\n\n    // --------------------- //\n    // CREDIT MANAGER PARAMS //\n    // --------------------- //\n\n    /// @notice Returns `token`'s collateral mask in the credit manager\n    /// @param token Token address\n    /// @return tokenMask Collateral token mask in the credit manager\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function getTokenMaskOrRevert(address token) public view override returns (uint256 tokenMask) {\n        if (token == underlying) return UNDERLYING_TOKEN_MASK; // U:[CM-34]\n\n        tokenMask = tokenMasksMapInternal[token]; // U:[CM-34]\n        if (tokenMask == 0) revert TokenNotAllowedException(); // U:[CM-34]\n    }\n\n    /// @notice Returns collateral token's address by its mask in the credit manager\n    /// @param tokenMask Collateral token mask in the credit manager\n    /// @return token Token address\n    /// @dev Reverts if `tokenMask` doesn't correspond to any known collateral token\n    function getTokenByMask(uint256 tokenMask) public view override returns (address token) {\n        (token,) = _collateralTokenByMask({tokenMask: tokenMask, calcLT: false}); // U:[CM-34]\n    }\n\n    /// @notice Returns collateral token's liquidation threshold\n    /// @param token Token address\n    /// @return lt Token's liquidation threshold in bps\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function liquidationThresholds(address token) public view override returns (uint16 lt) {\n        uint256 tokenMask = getTokenMaskOrRevert(token);\n        (, lt) = _collateralTokenByMask({tokenMask: tokenMask, calcLT: true}); // U:[CM-42]\n    }\n\n    /// @notice Returns `token`'s liquidation threshold ramp parameters\n    /// @param token Token to get parameters for\n    /// @return ltInitial LT at the beginning of the ramp in bps\n    /// @return ltFinal LT at the end of the ramp in bps\n    /// @return timestampRampStart Timestamp of the beginning of the ramp\n    /// @return rampDuration Ramp duration in seconds\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function ltParams(address token)\n        external\n        view\n        override\n        returns (uint16 ltInitial, uint16 ltFinal, uint40 timestampRampStart, uint24 rampDuration)\n    {\n        uint256 tokenMask = getTokenMaskOrRevert(token);\n        CollateralTokenData memory tokenData = collateralTokensData[tokenMask];\n\n        return (tokenData.ltInitial, tokenData.ltFinal, tokenData.timestampRampStart, tokenData.rampDuration);\n    }\n\n    /// @notice Returns collateral token's address and liquidation threshold by its mask\n    /// @param tokenMask Collateral token mask in the credit manager\n    /// @return token Token address\n    /// @return liquidationThreshold Token's liquidation threshold in bps\n    /// @dev Reverts if `tokenMask` doesn't correspond to any known collateral token\n    function collateralTokenByMask(uint256 tokenMask)\n        public\n        view\n        override\n        returns (address token, uint16 liquidationThreshold)\n    {\n        return _collateralTokenByMask({tokenMask: tokenMask, calcLT: true}); // U:[CM-34, 42]\n    }\n\n    /// @dev Returns collateral token's address by its mask, optionally returns its liquidation threshold\n    /// @dev Reverts if `tokenMask` doesn't correspond to any known collateral token\n    function _collateralTokenByMask(uint256 tokenMask, bool calcLT)\n        internal\n        view\n        returns (address token, uint16 liquidationThreshold)\n    {\n        if (tokenMask == UNDERLYING_TOKEN_MASK) {\n            token = underlying; // U:[CM-34]\n            if (calcLT) liquidationThreshold = ltUnderlying; // U:[CM-35]\n        } else {\n            CollateralTokenData storage tokenData = collateralTokensData[tokenMask]; // U:[CM-34]\n\n            bytes32 rawData;\n            assembly {\n                rawData := sload(tokenData.slot)\n                token := and(rawData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) // U:[CM-34]\n            }\n\n            if (token == address(0)) {\n                revert TokenNotAllowedException(); // U:[CM-34]\n            }\n\n            if (calcLT) {\n                uint16 ltInitial;\n                uint16 ltFinal;\n                uint40 timestampRampStart;\n                uint24 rampDuration;\n\n                assembly {\n                    ltInitial := and(shr(160, rawData), 0xFFFF)\n                    ltFinal := and(shr(176, rawData), 0xFFFF)\n                    timestampRampStart := and(shr(192, rawData), 0xFFFFFFFFFF)\n                    rampDuration := and(shr(232, rawData), 0xFFFFFF)\n                }\n\n                liquidationThreshold = CreditLogic.getLiquidationThreshold({\n                    ltInitial: ltInitial,\n                    ltFinal: ltFinal,\n                    timestampRampStart: timestampRampStart,\n                    rampDuration: rampDuration\n                }); // U:[CM-42]\n            }\n        }\n    }\n\n    /// @notice Returns credit manager's fee parameters (all fields in bps)\n    /// @return _feeInterest Percentage of accrued interest taken by the protocol as profit\n    /// @return _feeLiquidation Percentage of liquidated account value taken by the protocol as profit\n    /// @return _liquidationDiscount Percentage of liquidated account value that is used to repay debt\n    /// @return _feeLiquidationExpired Percentage of liquidated expired account value taken by the protocol as profit\n    /// @return _liquidationDiscountExpired Percentage of liquidated expired account value that is used to repay debt\n    function fees()\n        external\n        view\n        override\n        returns (\n            uint16 _feeInterest,\n            uint16 _feeLiquidation,\n            uint16 _liquidationDiscount,\n            uint16 _feeLiquidationExpired,\n            uint16 _liquidationDiscountExpired\n        )\n    {\n        _feeInterest = feeInterest; // U:[CM-41]\n        _feeLiquidation = feeLiquidation; // U:[CM-41]\n        _liquidationDiscount = liquidationDiscount; // U:[CM-41]\n        _feeLiquidationExpired = feeLiquidationExpired; // U:[CM-41]\n        _liquidationDiscountExpired = liquidationDiscountExpired; // U:[CM-41]\n    }\n\n    // ------------ //\n    // ACCOUNT INFO //\n    // ------------ //\n\n    /// @notice Returns `creditAccount`'s owner or reverts if account is not opened in this credit manager\n    function getBorrowerOrRevert(address creditAccount) public view override returns (address borrower) {\n        borrower = creditAccountInfo[creditAccount].borrower; // U:[CM-35]\n        if (borrower == address(0)) revert CreditAccountDoesNotExistException(); // U:[CM-35]\n    }\n\n    /// @notice Returns `creditAccount`'s flags as a bit mask\n    /// @dev Does not revert if `creditAccount` is not opened in this credit manager\n    function flagsOf(address creditAccount) public view override returns (uint16) {\n        return creditAccountInfo[creditAccount].flags; // U:[CM-35]\n    }\n\n    /// @notice Sets `creditAccount`'s flag to a given value\n    /// @param creditAccount Account to set a flag for\n    /// @param flag Flag to set\n    /// @param value The new flag value\n    /// @custom:expects Credit facade ensures that `creditAccount` is opened in this credit manager\n    function setFlagFor(address creditAccount, uint16 flag, bool value)\n        external\n        override\n        nonReentrant // U:[CM-5]\n        creditFacadeOnly // U:[CM-2]\n    {\n        if (value) {\n            _enableFlag(creditAccount, flag); // U:[CM-36]\n        } else {\n            _disableFlag(creditAccount, flag); // U:[CM-36]\n        }\n    }\n\n    /// @dev Enables `creditAccount`'s flag\n    function _enableFlag(address creditAccount, uint16 flag) internal {\n        creditAccountInfo[creditAccount].flags |= flag; // U:[CM-36]\n    }\n\n    /// @dev Disables `creditAccount`'s flag\n    function _disableFlag(address creditAccount, uint16 flag) internal {\n        creditAccountInfo[creditAccount].flags &= ~flag; // U:[CM-36]\n    }\n\n    /// @notice Returns `creditAccount`'s enabled tokens mask\n    /// @dev Does not revert if `creditAccount` is not opened to this credit manager\n    function enabledTokensMaskOf(address creditAccount) public view override returns (uint256) {\n        return creditAccountInfo[creditAccount].enabledTokensMask; // U:[CM-37]\n    }\n\n    /// @dev Saves `creditAccount`'s `enabledTokensMask` in the storage\n    /// @dev Ensures that the number of enabled tokens excluding underlying does not exceed `maxEnabledTokens`\n    function _saveEnabledTokensMask(address creditAccount, uint256 enabledTokensMask) internal {\n        if (enabledTokensMask.disable(UNDERLYING_TOKEN_MASK).calcEnabledTokens() > maxEnabledTokens) {\n            revert TooManyEnabledTokensException(); // U:[CM-37]\n        }\n\n        creditAccountInfo[creditAccount].enabledTokensMask = enabledTokensMask; // U:[CM-37]\n    }\n\n    /// @notice Returns an array of all credit accounts opened in this credit manager\n    function creditAccounts() external view override returns (address[] memory) {\n        return creditAccountsSet.values();\n    }\n\n    /// @notice Returns chunk of up to `limit` credit accounts opened in this credit manager starting from `offset`\n    function creditAccounts(uint256 offset, uint256 limit) external view override returns (address[] memory result) {\n        uint256 len = creditAccountsSet.length();\n        uint256 resultLen = offset + limit > len ? (offset > len ? 0 : len - offset) : limit;\n\n        result = new address[](resultLen);\n        unchecked {\n            for (uint256 i = 0; i < resultLen; ++i) {\n                result[i] = creditAccountsSet.at(offset + i);\n            }\n        }\n    }\n\n    /// @notice Returns the number of open credit accounts opened in this credit manager\n    function creditAccountsLen() external view override returns (uint256) {\n        return creditAccountsSet.length();\n    }\n\n    // ------------- //\n    // CONFIGURATION //\n    // ------------- //\n\n    /// @notice Adds `token` to the list of collateral tokens, see `_addToken` for details\n    function addToken(address token)\n        external\n        override\n        creditConfiguratorOnly // U:[CM-4]\n    {\n        _addToken(token); // U:[CM-38, 39]\n    }\n\n    /// @dev `addToken` implementation:\n    ///      - Ensures that token is not already added\n    ///      - Forbids adding more than 255 collateral tokens\n    ///      - Adds token with LT = 0\n    ///      - Increases the number of collateral tokens\n    /// @param token Address of the token to add\n    function _addToken(address token) internal {\n        if (tokenMasksMapInternal[token] != 0) {\n            revert TokenAlreadyAddedException(); // U:[CM-38]\n        }\n        if (collateralTokensCount >= 255) {\n            revert TooManyTokensException(); // U:[CM-38]\n        }\n\n        uint256 tokenMask = 1 << collateralTokensCount; // U:[CM-39]\n        tokenMasksMapInternal[token] = tokenMask; // U:[CM-39]\n\n        collateralTokensData[tokenMask].token = token; // U:[CM-39]\n        collateralTokensData[tokenMask].timestampRampStart = type(uint40).max; // U:[CM-39]\n\n        unchecked {\n            ++collateralTokensCount; // U:[CM-39]\n        }\n    }\n\n    /// @notice Sets credit manager's fee parameters (all fields in bps)\n    /// @param _feeInterest Percentage of accrued interest taken by the protocol as profit\n    /// @param _feeLiquidation Percentage of liquidated account value taken by the protocol as profit\n    /// @param _liquidationDiscount Percentage of liquidated account value that is used to repay debt\n    /// @param _feeLiquidationExpired Percentage of liquidated expired account value taken by the protocol as profit\n    /// @param _liquidationDiscountExpired Percentage of liquidated expired account value that is used to repay debt\n    function setFees(\n        uint16 _feeInterest,\n        uint16 _feeLiquidation,\n        uint16 _liquidationDiscount,\n        uint16 _feeLiquidationExpired,\n        uint16 _liquidationDiscountExpired\n    )\n        external\n        override\n        creditConfiguratorOnly // U:[CM-4]\n    {\n        feeInterest = _feeInterest; // U:[CM-40]\n        feeLiquidation = _feeLiquidation; // U:[CM-40]\n        liquidationDiscount = _liquidationDiscount; // U:[CM-40]\n        feeLiquidationExpired = _feeLiquidationExpired; // U:[CM-40]\n        liquidationDiscountExpired = _liquidationDiscountExpired; // U:[CM-40]\n    }\n\n    /// @notice Sets `token`'s liquidation threshold ramp parameters\n    /// @param token Token to set parameters for\n    /// @param ltInitial LT at the beginning of the ramp in bps\n    /// @param ltFinal LT at the end of the ramp in bps\n    /// @param timestampRampStart Timestamp of the beginning of the ramp\n    /// @param rampDuration Ramp duration in seconds\n    /// @dev If `token` is `underlying`, sets LT to `ltInitial` and ignores other parameters\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function setCollateralTokenData(\n        address token,\n        uint16 ltInitial,\n        uint16 ltFinal,\n        uint40 timestampRampStart,\n        uint24 rampDuration\n    )\n        external\n        override\n        creditConfiguratorOnly // U:[CM-4]\n    {\n        if (token == underlying) {\n            ltUnderlying = ltInitial; // U:[CM-42]\n        } else {\n            uint256 tokenMask = getTokenMaskOrRevert({token: token}); // U:[CM-41]\n            CollateralTokenData storage tokenData = collateralTokensData[tokenMask];\n\n            tokenData.ltInitial = ltInitial; // U:[CM-42]\n            tokenData.ltFinal = ltFinal; // U:[CM-42]\n            tokenData.timestampRampStart = timestampRampStart; // U:[CM-42]\n            tokenData.rampDuration = rampDuration; // U:[CM-42]\n        }\n    }\n\n    /// @notice Sets a new quoted token mask\n    /// @param _quotedTokensMask The new quoted tokens mask\n    /// @dev Excludes underlying token from the new mask\n    function setQuotedMask(uint256 _quotedTokensMask)\n        external\n        override\n        creditConfiguratorOnly // U:[CM-4]\n    {\n        quotedTokensMask = _quotedTokensMask.disable(UNDERLYING_TOKEN_MASK); // U:[CM-43]\n    }\n\n    /// @notice Sets a new max number of enabled tokens\n    /// @param _maxEnabledTokens The new max number of enabled tokens\n    function setMaxEnabledTokens(uint8 _maxEnabledTokens)\n        external\n        override\n        creditConfiguratorOnly // U: [CM-4]\n    {\n        maxEnabledTokens = _maxEnabledTokens; // U:[CM-44]\n    }\n\n    /// @notice Sets the link between the adapter and the target contract\n    /// @param adapter Address of the adapter contract to use to access the third-party contract,\n    ///        passing `address(0)` will forbid accessing `targetContract`\n    /// @param targetContract Address of the third-pary contract for which the adapter is set,\n    ///        passing `address(0)` will forbid using `adapter`\n    /// @dev Reverts if `targetContract` or `adapter` is this contract's address\n    function setContractAllowance(address adapter, address targetContract)\n        external\n        override\n        creditConfiguratorOnly // U: [CM-4]\n    {\n        if (targetContract == address(this) || adapter == address(this)) {\n            revert TargetContractNotAllowedException();\n        } // U:[CM-45]\n\n        if (adapter != address(0)) {\n            adapterToContract[adapter] = targetContract; // U:[CM-45]\n        }\n        if (targetContract != address(0)) {\n            contractToAdapter[targetContract] = adapter; // U:[CM-45]\n        }\n    }\n\n    /// @notice Sets a new credit facade\n    /// @param _creditFacade Address of the new credit facade\n    function setCreditFacade(address _creditFacade)\n        external\n        override\n        creditConfiguratorOnly // U: [CM-4]\n    {\n        creditFacade = _creditFacade; // U:[CM-46]\n    }\n\n    /// @notice Sets a new price oracle\n    /// @param _priceOracle Address of the new price oracle\n    function setPriceOracle(address _priceOracle)\n        external\n        override\n        creditConfiguratorOnly // U: [CM-4]\n    {\n        priceOracle = _priceOracle; // U:[CM-46]\n    }\n\n    /// @notice Sets a new credit configurator\n    /// @param _creditConfigurator Address of the new credit configurator\n    function setCreditConfigurator(address _creditConfigurator)\n        external\n        override\n        creditConfiguratorOnly // U: [CM-4]\n    {\n        creditConfigurator = _creditConfigurator; // U:[CM-46]\n        emit SetCreditConfigurator(_creditConfigurator); // U:[CM-46]\n    }\n\n    // --------- //\n    // INTERNALS //\n    // --------- //\n\n    /// @dev Approves `amount` of `token` from `creditAccount` to `spender`\n    /// @dev Reverts if `token` is not recognized as collateral in the credit manager\n    function _approveSpender(address creditAccount, address token, address spender, uint256 amount) internal {\n        getTokenMaskOrRevert({token: token}); // U:[CM-15]\n        ICreditAccountBase(creditAccount).safeApprove({token: token, spender: spender, amount: amount}); // U:[CM-15]\n    }\n\n    /// @dev Returns amount of token that should be transferred to receive `amount`\n    ///      Pools with fee-on-transfer underlying should override this method\n    function _amountWithFee(uint256 amount) internal view virtual returns (uint256) {\n        return amount;\n    }\n\n    /// @dev Returns amount of token that will be received if `amount` is transferred\n    ///      Pools with fee-on-transfer underlying should override this method\n    function _amountMinusFee(uint256 amount) internal view virtual returns (uint256) {\n        return amount;\n    }\n\n    /// @dev Internal wrapper for `creditAccount.execute` call to reduce contract size\n    function _execute(address creditAccount, address target, bytes calldata callData) internal returns (bytes memory) {\n        return ICreditAccountBase(creditAccount).execute(target, callData);\n    }\n\n    /// @dev Internal wrapper for `pool.repayCreditAccount` call to reduce contract size\n    function _poolRepayCreditAccount(uint256 debt, uint256 profit, uint256 loss) internal {\n        IPoolV3(pool).repayCreditAccount(debt, profit, loss);\n    }\n\n    /// @dev Internal wrapper for `pool.lendCreditAccount` call to reduce contract size\n    function _poolLendCreditAccount(uint256 amount, address creditAccount) internal {\n        IPoolV3(pool).lendCreditAccount(amount, creditAccount); // F:[CM-20]\n    }\n\n    /// @dev Internal wrapper for `priceOracle.convertToUSD` call to reduce contract size\n    function _convertToUSD(address _priceOracle, uint256 amountInToken, address token)\n        internal\n        view\n        returns (uint256 amountInUSD)\n    {\n        amountInUSD = IPriceOracleV3(_priceOracle).convertToUSD(amountInToken, token);\n    }\n\n    /// @dev Internal wrapper for `priceOracle.convertFromUSD` call to reduce contract size\n    function _convertFromUSD(address _priceOracle, uint256 amountInUSD, address token)\n        internal\n        view\n        returns (uint256 amountInToken)\n    {\n        amountInToken = IPriceOracleV3(_priceOracle).convertFromUSD(amountInUSD, token);\n    }\n\n    /// @dev Internal wrapper for `priceOracle.safeConvertToUSD` call to reduce contract size\n    /// @dev `underlying` is always converted with default conversion function\n    function _safeConvertToUSD(address _priceOracle, uint256 amountInToken, address token)\n        internal\n        view\n        returns (uint256 amountInUSD)\n    {\n        amountInUSD = (token == underlying)\n            ? _convertToUSD(_priceOracle, amountInToken, token)\n            : IPriceOracleV3(_priceOracle).safeConvertToUSD(amountInToken, token);\n    }\n\n    /// @dev Reverts if `msg.sender` is not the credit facade\n    function _checkCreditFacade() private view {\n        if (msg.sender != creditFacade) revert CallerNotCreditFacadeException();\n    }\n\n    /// @dev Reverts if `msg.sender` is not the credit configurator\n    function _checkCreditConfigurator() private view {\n        if (msg.sender != creditConfigurator) revert CallerNotConfiguratorException();\n    }\n}\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "node_modules/@1inch/solidity-utils/contracts/libraries/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol\";\nimport \"../interfaces/IDaiLikePermit.sol\";\nimport \"../interfaces/IPermit2.sol\";\nimport \"../interfaces/IWETH.sol\";\nimport \"../libraries/RevertReasonForwarder.sol\";\n\n/// @title Implements efficient safe methods for ERC20 interface.\nlibrary SafeERC20 {\n    error SafeTransferFailed();\n    error SafeTransferFromFailed();\n    error ForceApproveFailed();\n    error SafeIncreaseAllowanceFailed();\n    error SafeDecreaseAllowanceFailed();\n    error SafePermitBadLength();\n    error Permit2TransferAmountTooHigh();\n\n    address private constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;\n    bytes4 private constant _PERMIT_LENGTH_ERROR = 0x68275857;  // SafePermitBadLength.selector\n    uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;\n\n    function safeBalanceOf(\n        IERC20 token,\n        address account\n    ) internal view returns(uint256 tokenBalance) {\n        bytes4 selector = IERC20.balanceOf.selector;\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            mstore(0x00, selector)\n            mstore(0x04, account)\n            let success := staticcall(gas(), token, 0x00, 0x24, 0x00, 0x20)\n            tokenBalance := mload(0)\n\n            if or(iszero(success), lt(returndatasize(), 0x20)) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n        }\n    }\n\n    /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.\n    function safeTransferFromUniversal(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 amount,\n        bool permit2\n    ) internal {\n        if (permit2) {\n            safeTransferFromPermit2(token, from, to, amount);\n        } else {\n            safeTransferFrom(token, from, to, amount);\n        }\n    }\n\n    /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.\n    function safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bytes4 selector = token.transferFrom.selector;\n        bool success;\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            let data := mload(0x40)\n\n            mstore(data, selector)\n            mstore(add(data, 0x04), from)\n            mstore(add(data, 0x24), to)\n            mstore(add(data, 0x44), amount)\n            success := call(gas(), token, 0, data, 100, 0x0, 0x20)\n            if success {\n                switch returndatasize()\n                case 0 {\n                    success := gt(extcodesize(token), 0)\n                }\n                default {\n                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))\n                }\n            }\n        }\n        if (!success) revert SafeTransferFromFailed();\n    }\n\n    /// @dev Permit2 version of safeTransferFrom above.\n    function safeTransferFromPermit2(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        if (amount > type(uint160).max) revert Permit2TransferAmountTooHigh();\n        bytes4 selector = IPermit2.transferFrom.selector;\n        bool success;\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            let data := mload(0x40)\n\n            mstore(data, selector)\n            mstore(add(data, 0x04), from)\n            mstore(add(data, 0x24), to)\n            mstore(add(data, 0x44), amount)\n            mstore(add(data, 0x64), token)\n            success := call(gas(), _PERMIT2, 0, data, 0x84, 0x0, 0x0)\n            if success {\n                success := gt(extcodesize(_PERMIT2), 0)\n            }\n        }\n        if (!success) revert SafeTransferFromFailed();\n    }\n\n    /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.\n    function safeTransfer(\n        IERC20 token,\n        address to,\n        uint256 value\n    ) internal {\n        if (!_makeCall(token, token.transfer.selector, to, value)) {\n            revert SafeTransferFailed();\n        }\n    }\n\n    /// @dev If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry.\n    function forceApprove(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        if (!_makeCall(token, token.approve.selector, spender, value)) {\n            if (\n                !_makeCall(token, token.approve.selector, spender, 0) ||\n                !_makeCall(token, token.approve.selector, spender, value)\n            ) {\n                revert ForceApproveFailed();\n            }\n        }\n    }\n\n    /// @dev Allowance increase with safe math check.\n    function safeIncreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 allowance = token.allowance(address(this), spender);\n        if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();\n        forceApprove(token, spender, allowance + value);\n    }\n\n    /// @dev Allowance decrease with safe math check.\n    function safeDecreaseAllowance(\n        IERC20 token,\n        address spender,\n        uint256 value\n    ) internal {\n        uint256 allowance = token.allowance(address(this), spender);\n        if (value > allowance) revert SafeDecreaseAllowanceFailed();\n        forceApprove(token, spender, allowance - value);\n    }\n\n    function safePermit(IERC20 token, bytes calldata permit) internal {\n        if (!tryPermit(token, msg.sender, address(this), permit)) RevertReasonForwarder.reRevert();\n    }\n\n    function safePermit(IERC20 token, address owner, address spender, bytes calldata permit) internal {\n        if (!tryPermit(token, owner, spender, permit)) RevertReasonForwarder.reRevert();\n    }\n\n    function tryPermit(IERC20 token, bytes calldata permit) internal returns(bool success) {\n        return tryPermit(token, msg.sender, address(this), permit);\n    }\n\n    function tryPermit(IERC20 token, address owner, address spender, bytes calldata permit) internal returns(bool success) {\n        bytes4 permitSelector = IERC20Permit.permit.selector;\n        bytes4 daiPermitSelector = IDaiLikePermit.permit.selector;\n        bytes4 permit2Selector = IPermit2.permit.selector;\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            let ptr := mload(0x40)\n            switch permit.length\n            case 100 {\n                mstore(ptr, permitSelector)\n                mstore(add(ptr, 0x04), owner)\n                mstore(add(ptr, 0x24), spender)\n\n                // Compact IERC20Permit.permit(uint256 value, uint32 deadline, uint256 r, uint256 vs)\n                {  // stack too deep\n                    let deadline := shr(224, calldataload(add(permit.offset, 0x20)))\n                    let vs := calldataload(add(permit.offset, 0x44))\n\n                    calldatacopy(add(ptr, 0x44), permit.offset, 0x20) // value\n                    mstore(add(ptr, 0x64), sub(deadline, 1))\n                    mstore(add(ptr, 0x84), add(27, shr(255, vs)))\n                    calldatacopy(add(ptr, 0xa4), add(permit.offset, 0x24), 0x20) // r\n                    mstore(add(ptr, 0xc4), shr(1, shl(1, vs)))\n                }\n                // IERC20Permit.permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)\n                success := call(gas(), token, 0, ptr, 0xe4, 0, 0)\n            }\n            case 72 {\n                mstore(ptr, daiPermitSelector)\n                mstore(add(ptr, 0x04), owner)\n                mstore(add(ptr, 0x24), spender)\n\n                // Compact IDaiLikePermit.permit(uint32 nonce, uint32 expiry, uint256 r, uint256 vs)\n                {  // stack too deep\n                    let expiry := shr(224, calldataload(add(permit.offset, 0x04)))\n                    let vs := calldataload(add(permit.offset, 0x28))\n\n                    mstore(add(ptr, 0x44), shr(224, calldataload(permit.offset)))\n                    mstore(add(ptr, 0x64), sub(expiry, 1))\n                    mstore(add(ptr, 0x84), true)\n                    mstore(add(ptr, 0xa4), add(27, shr(255, vs)))\n                    calldatacopy(add(ptr, 0xc4), add(permit.offset, 0x08), 0x20) // r\n                    mstore(add(ptr, 0xe4), shr(1, shl(1, vs)))\n                }\n                // IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)\n                success := call(gas(), token, 0, ptr, 0x104, 0, 0)\n            }\n            case 224 {\n                mstore(ptr, permitSelector)\n                calldatacopy(add(ptr, 0x04), permit.offset, permit.length)\n                // IERC20Permit.permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)\n                success := call(gas(), token, 0, ptr, 0xe4, 0, 0)\n            }\n            case 256 {\n                mstore(ptr, daiPermitSelector)\n                calldatacopy(add(ptr, 0x04), permit.offset, permit.length)\n                // IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)\n                success := call(gas(), token, 0, ptr, 0x104, 0, 0)\n            }\n            case 96 {\n                // Compact IPermit2.permit(uint160 amount, uint32 expiration, uint32 nonce, uint32 sigDeadline, uint256 r, uint256 vs)\n                mstore(ptr, permit2Selector)\n                mstore(add(ptr, 0x04), owner)\n                mstore(add(ptr, 0x24), token)\n                calldatacopy(add(ptr, 0x50), permit.offset, 0x14) // amount\n                mstore(add(ptr, 0x64), and(0xffffffffffff, sub(shr(224, calldataload(add(permit.offset, 0x14))), 1))) // expiration\n                mstore(add(ptr, 0x84), shr(224, calldataload(add(permit.offset, 0x18)))) // nonce\n                mstore(add(ptr, 0xa4), spender)\n                mstore(add(ptr, 0xc4), and(0xffffffffffff, sub(shr(224, calldataload(add(permit.offset, 0x1c))), 1))) // sigDeadline\n                mstore(add(ptr, 0xe4), 0x100)\n                mstore(add(ptr, 0x104), 0x40)\n                calldatacopy(add(ptr, 0x124), add(permit.offset, 0x20), 0x20) // r\n                calldatacopy(add(ptr, 0x144), add(permit.offset, 0x40), 0x20) // vs\n                // IPermit2.permit(address owner, PermitSingle calldata permitSingle, bytes calldata signature)\n                success := call(gas(), _PERMIT2, 0, ptr, 0x164, 0, 0)\n            }\n            case 352 {\n                mstore(ptr, permit2Selector)\n                calldatacopy(add(ptr, 0x04), permit.offset, permit.length)\n                // IPermit2.permit(address owner, PermitSingle calldata permitSingle, bytes calldata signature)\n                success := call(gas(), _PERMIT2, 0, ptr, 0x164, 0, 0)\n            }\n            default {\n                mstore(ptr, _PERMIT_LENGTH_ERROR)\n                revert(ptr, 4)\n            }\n        }\n    }\n\n    function _makeCall(\n        IERC20 token,\n        bytes4 selector,\n        address to,\n        uint256 amount\n    ) private returns (bool success) {\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            let data := mload(0x40)\n\n            mstore(data, selector)\n            mstore(add(data, 0x04), to)\n            mstore(add(data, 0x24), amount)\n            success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)\n            if success {\n                switch returndatasize()\n                case 0 {\n                    success := gt(extcodesize(token), 0)\n                }\n                default {\n                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))\n                }\n            }\n        }\n    }\n\n    function safeDeposit(IWETH weth, uint256 amount) internal {\n        if (amount > 0) {\n            bytes4 selector = IWETH.deposit.selector;\n            assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n                mstore(0, selector)\n                if iszero(call(gas(), weth, amount, 0, 4, 0, 0)) {\n                    returndatacopy(0, 0, returndatasize())\n                    revert(0, returndatasize())\n                }\n            }\n        }\n    }\n\n    function safeWithdraw(IWETH weth, uint256 amount) internal {\n        bytes4 selector = IWETH.withdraw.selector;\n        assembly (\"memory-safe\") {  // solhint-disable-line no-inline-assembly\n            mstore(0, selector)\n            mstore(4, amount)\n            if iszero(call(gas(), weth, 0, 0, 0x24, 0, 0)) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n        }\n    }\n\n    function safeWithdrawTo(IWETH weth, uint256 amount, address to) internal {\n        safeWithdraw(weth, amount);\n        if (to != address(this)) {\n            assembly (\"memory-safe\") {  // solhint-disable-line no-inline-assembly\n                if iszero(call(_RAW_CALL_GAS_LIMIT, to, amount, 0, 0, 0, 0)) {\n                    let ptr := mload(0x40)\n                    returndatacopy(ptr, 0, returndatasize())\n                    revert(ptr, returndatasize())\n                }\n            }\n        }\n    }\n}\n"
      },
      "node_modules/@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "node_modules/@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.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(uint256 x, uint256 y, uint256 denominator) 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                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\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(uint256 x, uint256 y, uint256 denominator, Rounding rounding) 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. If 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        //\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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\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        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/libraries/BitMask.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IncorrectParameterException} from \"../interfaces/IExceptions.sol\";\n\nuint256 constant UNDERLYING_TOKEN_MASK = 1;\n\n/// @title Bit mask library\n/// @notice Implements functions that manipulate bit masks\n///         Bit masks are utilized extensively by Gearbox to efficiently store token sets (enabled tokens on accounts\n///         or forbidden tokens) and check for set inclusion. A mask is a uint256 number that has its i-th bit set to\n///         1 if i-th item is included into the set. For example, each token has a mask equal to 2**i, so set inclusion\n///         can be checked by checking tokenMask & setMask != 0.\nlibrary BitMask {\n    /// @dev Calculates an index of an item based on its mask (using a binary search)\n    /// @dev The input should always have only 1 bit set, otherwise the result may be unpredictable\n    function calcIndex(uint256 mask) internal pure returns (uint8 index) {\n        if (mask == 0) revert IncorrectParameterException(); // U:[BM-1]\n        uint16 lb = 0; // U:[BM-2]\n        uint16 ub = 256; // U:[BM-2]\n        uint16 mid = 128; // U:[BM-2]\n\n        unchecked {\n            while (true) {\n                uint256 newMask = 1 << mid;\n                if (newMask & mask != 0) return uint8(mid); // U:[BM-2]\n\n                if (newMask > mask) ub = mid; // U:[BM-2]\n\n                else lb = mid; // U:[BM-2]\n                mid = (lb + ub) >> 1; // U:[BM-2]\n            }\n        }\n    }\n\n    /// @dev Calculates the number of `1` bits\n    /// @param enabledTokensMask Bit mask to compute the number of `1` bits in\n    function calcEnabledTokens(uint256 enabledTokensMask) internal pure returns (uint256 totalTokensEnabled) {\n        unchecked {\n            while (enabledTokensMask > 0) {\n                enabledTokensMask &= enabledTokensMask - 1; // U:[BM-3]\n                ++totalTokensEnabled; // U:[BM-3]\n            }\n        }\n    }\n\n    /// @dev Enables bits from the second mask in the first mask\n    /// @param enabledTokenMask The initial mask\n    /// @param bitsToEnable Mask of bits to enable\n    function enable(uint256 enabledTokenMask, uint256 bitsToEnable) internal pure returns (uint256) {\n        return enabledTokenMask | bitsToEnable; // U:[BM-4]\n    }\n\n    /// @dev Disables bits from the second mask in the first mask\n    /// @param enabledTokenMask The initial mask\n    /// @param bitsToDisable Mask of bits to disable\n    function disable(uint256 enabledTokenMask, uint256 bitsToDisable) internal pure returns (uint256) {\n        return enabledTokenMask & ~bitsToDisable; // U:[BM-4]\n    }\n\n    /// @dev Computes a new mask with sets of new enabled and disabled bits\n    /// @dev bitsToEnable and bitsToDisable are applied sequentially to original mask\n    /// @param enabledTokensMask The initial mask\n    /// @param bitsToEnable Mask with bits to enable\n    /// @param bitsToDisable Mask with bits to disable\n    function enableDisable(uint256 enabledTokensMask, uint256 bitsToEnable, uint256 bitsToDisable)\n        internal\n        pure\n        returns (uint256)\n    {\n        return (enabledTokensMask | bitsToEnable) & (~bitsToDisable); // U:[BM-5]\n    }\n\n    /// @dev Enables bits from the second mask in the first mask, skipping specified bits\n    /// @param enabledTokenMask The initial mask\n    /// @param bitsToEnable Mask with bits to enable\n    /// @param invertedSkipMask An inversion of mask of immutable bits\n    function enable(uint256 enabledTokenMask, uint256 bitsToEnable, uint256 invertedSkipMask)\n        internal\n        pure\n        returns (uint256)\n    {\n        return enabledTokenMask | (bitsToEnable & invertedSkipMask); // U:[BM-6]\n    }\n\n    /// @dev Disables bits from the second mask in the first mask, skipping specified bits\n    /// @param enabledTokenMask The initial mask\n    /// @param bitsToDisable Mask with bits to disable\n    /// @param invertedSkipMask An inversion of mask of immutable bits\n    function disable(uint256 enabledTokenMask, uint256 bitsToDisable, uint256 invertedSkipMask)\n        internal\n        pure\n        returns (uint256)\n    {\n        return enabledTokenMask & (~(bitsToDisable & invertedSkipMask)); // U:[BM-6]\n    }\n\n    /// @dev Computes a new mask with sets of new enabled and disabled bits, skipping some bits\n    /// @dev bitsToEnable and bitsToDisable are applied sequentially to original mask. Skipmask is applied in both cases.\n    /// @param enabledTokensMask The initial mask\n    /// @param bitsToEnable Mask with bits to enable\n    /// @param bitsToDisable Mask with bits to disable\n    /// @param invertedSkipMask An inversion of mask of immutable bits\n    function enableDisable(\n        uint256 enabledTokensMask,\n        uint256 bitsToEnable,\n        uint256 bitsToDisable,\n        uint256 invertedSkipMask\n    ) internal pure returns (uint256) {\n        return (enabledTokensMask | (bitsToEnable & invertedSkipMask)) & (~(bitsToDisable & invertedSkipMask)); // U:[BM-7]\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/libraries/CreditLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {SafeCast} from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport {CollateralDebtData, CollateralTokenData} from \"../interfaces/ICreditManagerV3.sol\";\nimport {SECONDS_PER_YEAR, PERCENTAGE_FACTOR} from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\nimport {BitMask} from \"./BitMask.sol\";\n\nuint256 constant INDEX_PRECISION = 10 ** 9;\n\n/// @title Credit logic library\n/// @notice Implements functions used for debt and repayment calculations\nlibrary CreditLogic {\n    using BitMask for uint256;\n    using SafeCast for uint256;\n\n    // ----------------- //\n    // DEBT AND INTEREST //\n    // ----------------- //\n\n    /// @dev Computes growth since last update given yearly growth\n    function calcLinearGrowth(uint256 value, uint256 timestampLastUpdate) internal view returns (uint256) {\n        return value * (block.timestamp - timestampLastUpdate) / SECONDS_PER_YEAR;\n    }\n\n    /// @dev Computes interest accrued since the last update\n    function calcAccruedInterest(uint256 amount, uint256 cumulativeIndexLastUpdate, uint256 cumulativeIndexNow)\n        internal\n        pure\n        returns (uint256)\n    {\n        if (amount == 0) return 0;\n        return (amount * cumulativeIndexNow) / cumulativeIndexLastUpdate - amount; // U:[CL-1]\n    }\n\n    /// @dev Computes total debt, given raw debt data\n    /// @param collateralDebtData See `CollateralDebtData` (must have debt data filled)\n    function calcTotalDebt(CollateralDebtData memory collateralDebtData) internal pure returns (uint256) {\n        return collateralDebtData.debt + collateralDebtData.accruedInterest + collateralDebtData.accruedFees;\n    }\n\n    // ----------- //\n    // LIQUIDATION //\n    // ----------- //\n\n    /// @dev Computes the amount of underlying tokens to send to the pool on credit account liquidation\n    ///      - First, liquidation premium and fee are subtracted from account's total value\n    ///      - The resulting value is then used to repay the debt to the pool, and any remaining fudns\n    ///        are send back to the account owner\n    ///      - If, however, funds are insufficient to fully repay the debt, the function will first reduce\n    ///        protocol profits before finally reporting a bad debt liquidation with loss\n    /// @param collateralDebtData See `CollateralDebtData` (must have both collateral and debt data filled)\n    /// @param feeLiquidation Liquidation fee charged by the DAO on the account collateral\n    /// @param liquidationDiscount Percentage to discount account collateral by (equals 1 - liquidation premium)\n    /// @param amountWithFeeFn Function that, given the exact amount of underlying tokens to receive,\n    ///        returns the amount that needs to be sent\n    /// @param amountWithFeeFn Function that, given the exact amount of underlying tokens to send,\n    ///        returns the amount that will be received\n    /// @return amountToPool Amount of underlying tokens to send to the pool\n    /// @return remainingFunds Amount of underlying tokens to send to the credit account owner\n    /// @return profit Amount of underlying tokens received as fees by the DAO\n    /// @return loss Portion of account's debt that can't be repaid\n    function calcLiquidationPayments(\n        CollateralDebtData memory collateralDebtData,\n        uint16 feeLiquidation,\n        uint16 liquidationDiscount,\n        function (uint256) view returns (uint256) amountWithFeeFn,\n        function (uint256) view returns (uint256) amountMinusFeeFn\n    ) internal view returns (uint256 amountToPool, uint256 remainingFunds, uint256 profit, uint256 loss) {\n        amountToPool = calcTotalDebt(collateralDebtData); // U:[CL-4]\n\n        uint256 debtWithInterest = collateralDebtData.debt + collateralDebtData.accruedInterest;\n\n        uint256 totalValue = collateralDebtData.totalValue;\n\n        uint256 totalFunds = totalValue * liquidationDiscount / PERCENTAGE_FACTOR;\n\n        amountToPool += totalValue * feeLiquidation / PERCENTAGE_FACTOR; // U:[CL-4]\n\n        uint256 amountToPoolWithFee = amountWithFeeFn(amountToPool);\n        unchecked {\n            if (totalFunds > amountToPoolWithFee) {\n                remainingFunds = totalFunds - amountToPoolWithFee; // U:[CL-4]\n            } else {\n                amountToPoolWithFee = totalFunds;\n                amountToPool = amountMinusFeeFn(totalFunds); // U:[CL-4]\n            }\n\n            if (amountToPool >= debtWithInterest) {\n                profit = amountToPool - debtWithInterest; // U:[CL-4]\n            } else {\n                loss = debtWithInterest - amountToPool; // U:[CL-4]\n            }\n        }\n\n        amountToPool = amountToPoolWithFee; // U:[CL-4]\n    }\n\n    // --------------------- //\n    // LIQUIDATION THRESHOLD //\n    // --------------------- //\n\n    /// @dev Returns the current liquidation threshold based on token data\n    /// @dev GearboxV3 supports liquidation threshold ramping, which means that the LT can be set to change dynamically\n    ///      from one value to another over time. LT changes linearly, starting at `ltInitial` and ending at `ltFinal`.\n    ///      To make LT static, the value can be written to `ltInitial` with ramp start set far in the future.\n    function getLiquidationThreshold(uint16 ltInitial, uint16 ltFinal, uint40 timestampRampStart, uint24 rampDuration)\n        internal\n        view\n        returns (uint16)\n    {\n        uint40 timestampRampEnd = timestampRampStart + rampDuration;\n        if (block.timestamp <= timestampRampStart) {\n            return ltInitial; // U:[CL-5]\n        } else if (block.timestamp < timestampRampEnd) {\n            return _getRampingLiquidationThreshold(ltInitial, ltFinal, timestampRampStart, timestampRampEnd); // U:[CL-5]\n        } else {\n            return ltFinal; // U:[CL-5]\n        }\n    }\n\n    /// @dev Computes the LT during the ramping process\n    function _getRampingLiquidationThreshold(\n        uint16 ltInitial,\n        uint16 ltFinal,\n        uint40 timestampRampStart,\n        uint40 timestampRampEnd\n    ) internal view returns (uint16) {\n        return uint16(\n            (ltInitial * (timestampRampEnd - block.timestamp) + ltFinal * (block.timestamp - timestampRampStart))\n                / (timestampRampEnd - timestampRampStart)\n        ); // U:[CL-5]\n    }\n\n    // ----------- //\n    // MANAGE DEBT //\n    // ----------- //\n\n    /// @dev Computes new debt principal and interest index after increasing debt\n    ///      - The new debt principal is simply `debt + amount`\n    ///      - The new credit account's interest index is a solution to the equation\n    ///        `debt * (indexNow / indexLastUpdate - 1) = (debt + amount) * (indexNow / indexNew - 1)`,\n    ///        which essentially writes that interest accrued since last update remains the same\n    /// @param amount Amount to increase debt by\n    /// @param debt Debt principal before increase\n    /// @param cumulativeIndexNow The current interest index\n    /// @param cumulativeIndexLastUpdate Credit account's interest index as of last update\n    /// @return newDebt Debt principal after increase\n    /// @return newCumulativeIndex New credit account's interest index\n    function calcIncrease(uint256 amount, uint256 debt, uint256 cumulativeIndexNow, uint256 cumulativeIndexLastUpdate)\n        internal\n        pure\n        returns (uint256 newDebt, uint256 newCumulativeIndex)\n    {\n        if (debt == 0) return (amount, cumulativeIndexNow);\n        newDebt = debt + amount; // U:[CL-2]\n        newCumulativeIndex = (\n            (cumulativeIndexNow * newDebt * INDEX_PRECISION)\n                / ((INDEX_PRECISION * cumulativeIndexNow * debt) / cumulativeIndexLastUpdate + INDEX_PRECISION * amount)\n        ); // U:[CL-2]\n    }\n\n    /// @dev Computes new debt principal and interest index (and other values) after decreasing debt\n    ///      - Debt comprises of multiple components which are repaid in the following order:\n    ///        quota update fees => quota interest => base interest => debt principal.\n    ///        New values for all these components depend on what portion of each was repaid.\n    ///      - Debt principal, for example, only decreases if all previous components were fully repaid\n    ///      - The new credit account's interest index stays the same if base interest was not repaid at all,\n    ///        is set to the current interest index if base interest was repaid fully, and is a solution to\n    ///        the equation `debt * (indexNow / indexLastUpdate - 1) - delta = debt * (indexNow / indexNew - 1)`\n    ///        when only `delta` of accrued interest was repaid\n    /// @param amount Amount of debt to repay\n    /// @param debt Debt principal before repayment\n    /// @param cumulativeIndexNow The current interest index\n    /// @param cumulativeIndexLastUpdate Credit account's interest index as of last update\n    /// @param cumulativeQuotaInterest Credit account's quota interest before repayment\n    /// @param quotaFees Accrued quota fees\n    /// @param feeInterest Fee on accrued interest (both base and quota) charged by the DAO\n    /// @return newDebt Debt principal after repayment\n    /// @return newCumulativeIndex Credit account's quota interest after repayment\n    /// @return profit Amount of underlying tokens received as fees by the DAO\n    /// @return newCumulativeQuotaInterest Credit account's accrued quota interest after repayment\n    /// @return newQuotaFees Amount of unpaid quota fees left after repayment\n    function calcDecrease(\n        uint256 amount,\n        uint256 debt,\n        uint256 cumulativeIndexNow,\n        uint256 cumulativeIndexLastUpdate,\n        uint128 cumulativeQuotaInterest,\n        uint128 quotaFees,\n        uint16 feeInterest\n    )\n        internal\n        pure\n        returns (\n            uint256 newDebt,\n            uint256 newCumulativeIndex,\n            uint256 profit,\n            uint128 newCumulativeQuotaInterest,\n            uint128 newQuotaFees\n        )\n    {\n        uint256 amountToRepay = amount;\n\n        unchecked {\n            if (quotaFees != 0) {\n                if (amountToRepay > quotaFees) {\n                    newQuotaFees = 0; // U:[CL-3]\n                    amountToRepay -= quotaFees;\n                    profit = quotaFees; // U:[CL-3]\n                } else {\n                    newQuotaFees = quotaFees - uint128(amountToRepay); // U:[CL-3]\n                    profit = amountToRepay; // U:[CL-3]\n                    amountToRepay = 0;\n                }\n            }\n        }\n\n        if (cumulativeQuotaInterest != 0 && amountToRepay != 0) {\n            uint256 quotaProfit = (cumulativeQuotaInterest * feeInterest) / PERCENTAGE_FACTOR;\n\n            if (amountToRepay >= cumulativeQuotaInterest + quotaProfit) {\n                amountToRepay -= cumulativeQuotaInterest + quotaProfit; // U:[CL-3]\n                profit += quotaProfit; // U:[CL-3]\n\n                newCumulativeQuotaInterest = 0; // U:[CL-3]\n            } else {\n                // If amount is not enough to repay quota interest + DAO fee, then it is split pro-rata between them\n                uint256 amountToPool = (amountToRepay * PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR + feeInterest);\n\n                profit += amountToRepay - amountToPool; // U:[CL-3]\n                amountToRepay = 0; // U:[CL-3]\n\n                newCumulativeQuotaInterest = uint128(cumulativeQuotaInterest - amountToPool); // U:[CL-3]\n            }\n        } else {\n            newCumulativeQuotaInterest = cumulativeQuotaInterest;\n        }\n\n        if (amountToRepay != 0) {\n            uint256 interestAccrued = calcAccruedInterest({\n                amount: debt,\n                cumulativeIndexLastUpdate: cumulativeIndexLastUpdate,\n                cumulativeIndexNow: cumulativeIndexNow\n            }); // U:[CL-3]\n            uint256 profitFromInterest = (interestAccrued * feeInterest) / PERCENTAGE_FACTOR; // U:[CL-3]\n\n            if (amountToRepay >= interestAccrued + profitFromInterest) {\n                amountToRepay -= interestAccrued + profitFromInterest;\n\n                profit += profitFromInterest; // U:[CL-3]\n\n                newCumulativeIndex = cumulativeIndexNow; // U:[CL-3]\n            } else {\n                // If amount is not enough to repay base interest + DAO fee, then it is split pro-rata between them\n                uint256 amountToPool = (amountToRepay * PERCENTAGE_FACTOR) / (PERCENTAGE_FACTOR + feeInterest);\n\n                profit += amountToRepay - amountToPool; // U:[CL-3]\n                amountToRepay = 0; // U:[CL-3]\n\n                newCumulativeIndex = (INDEX_PRECISION * cumulativeIndexNow * cumulativeIndexLastUpdate)\n                    / (\n                        INDEX_PRECISION * cumulativeIndexNow\n                            - (INDEX_PRECISION * amountToPool * cumulativeIndexLastUpdate) / debt\n                    ); // U:[CL-3]\n            }\n        } else {\n            newCumulativeIndex = cumulativeIndexLastUpdate; // U:[CL-3]\n        }\n        newDebt = debt - amountToRepay; // U:[CL-3]\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/libraries/CollateralLogic.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\n\nimport {CollateralDebtData} from \"../interfaces/ICreditManagerV3.sol\";\nimport {PERCENTAGE_FACTOR, RAY} from \"@gearbox-protocol/core-v2/contracts/libraries/Constants.sol\";\n\nimport {BitMask} from \"./BitMask.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n/// @title Collateral logic Library\n/// @notice Implements functions that compute value of collateral on a credit account\nlibrary CollateralLogic {\n    using BitMask for uint256;\n    using SafeERC20 for IERC20;\n\n    /// @dev Computes USD-denominated total value and TWV of a credit account.\n    ///      If finite TWV target is specified, the function will stop processing tokens after cumulative TWV reaches\n    ///      the target, in which case the returned values will be smaller than actual collateral.\n    ///      This is useful to check whether account is sufficiently collateralized. To speed up this check, collateral\n    ///      hints can be used to specify the order to scan tokens in.\n    /// @param collateralDebtData See `CollateralDebtData` (must have enabled and quoted tokens filled)\n    /// @param creditAccount Credit account to compute collateral for\n    /// @param underlying The underlying token of the corresponding credit manager\n    /// @param twvUSDTarget Target twvUSD value to stop calculation after\n    /// @param collateralHints Array of token masks denoting the order to scan tokens in\n    /// @param quotasPacked Array of packed values (quota, LT), in the same order as `collateralDebtData.quotedTokens`\n    /// @param collateralTokenByMaskFn A function that returns collateral token data by its mask. Must accept inputs:\n    ///        * `mask` - mask of the token\n    ///        * `computeLT` - whether to compute the token's LT\n    /// @param convertToUSDFn A function that returns token value in USD and accepts the following inputs:\n    ///        * `priceOracle` - price oracle to convert assets in\n    ///        * `amount` - amount of token to convert\n    ///        * `token` - token to convert\n    /// @param priceOracle Price oracle to convert assets, passed to `convertToUSDFn`\n    /// @return totalValueUSD Total value of credit account's assets\n    /// @return twvUSD Total LT-weighted value of credit account's assets\n    /// @return tokensToDisable Mask of non-quoted tokens that have zero balances and can be disabled\n    function calcCollateral(\n        CollateralDebtData memory collateralDebtData,\n        address creditAccount,\n        address underlying,\n        uint256 twvUSDTarget,\n        uint256[] memory collateralHints,\n        uint256[] memory quotasPacked,\n        function (uint256, bool) view returns (address, uint16) collateralTokenByMaskFn,\n        function (address, uint256, address) view returns(uint256) convertToUSDFn,\n        address priceOracle\n    ) internal view returns (uint256 totalValueUSD, uint256 twvUSD, uint256 tokensToDisable) {\n        // Quoted tokens collateral value\n        if (collateralDebtData.quotedTokens.length != 0) {\n            // The underlying price is required for quotas but only needs to be computed once\n            uint256 underlyingPriceRAY = convertToUSDFn(priceOracle, RAY, underlying);\n\n            (totalValueUSD, twvUSD) = calcQuotedTokensCollateral({\n                quotedTokens: collateralDebtData.quotedTokens,\n                quotasPacked: quotasPacked,\n                creditAccount: creditAccount,\n                underlyingPriceRAY: underlyingPriceRAY,\n                twvUSDTarget: twvUSDTarget,\n                convertToUSDFn: convertToUSDFn,\n                priceOracle: priceOracle\n            }); // U:[CLL-5]\n\n            if (twvUSD >= twvUSDTarget) {\n                return (totalValueUSD, twvUSD, 0); // U:[CLL-5]\n            } else {\n                unchecked {\n                    twvUSDTarget -= twvUSD; // U:[CLL-5]\n                }\n            }\n        }\n\n        // Non-quoted tokens collateral value\n        {\n            uint256 tokensToCheckMask =\n                collateralDebtData.enabledTokensMask.disable(collateralDebtData.quotedTokensMask); // U:[CLL-5]\n\n            uint256 tvDelta;\n            uint256 twvDelta;\n\n            (tvDelta, twvDelta, tokensToDisable) = calcNonQuotedTokensCollateral({\n                tokensToCheckMask: tokensToCheckMask,\n                priceOracle: priceOracle,\n                creditAccount: creditAccount,\n                twvUSDTarget: twvUSDTarget,\n                collateralHints: collateralHints,\n                collateralTokenByMaskFn: collateralTokenByMaskFn,\n                convertToUSDFn: convertToUSDFn\n            }); // U:[CLL-5]\n\n            totalValueUSD += tvDelta; // U:[CLL-5]\n            twvUSD += twvDelta; // U:[CLL-5]\n        }\n    }\n\n    /// @dev Computes USD value of quoted tokens on a credit account\n    /// @param quotedTokens Array of quoted tokens on the account\n    /// @param quotasPacked Array of (quota, LT) tuples packed into uint256\n    /// @param creditAccount Address of the credit account\n    /// @param underlyingPriceRAY USD price of 1 RAY of underlying\n    /// @param twvUSDTarget The twvUSD threshold to stop the computation at\n    /// @param convertToUSDFn Function to convert asset amounts to USD\n    /// @param priceOracle Address of the price oracle\n    /// @return totalValueUSD Total value of credit account's quoted assets\n    /// @return twvUSD Total LT-weighted value of credit account's quoted assets\n    function calcQuotedTokensCollateral(\n        address[] memory quotedTokens,\n        uint256[] memory quotasPacked,\n        address creditAccount,\n        uint256 underlyingPriceRAY,\n        uint256 twvUSDTarget,\n        function (address, uint256, address) view returns(uint256) convertToUSDFn,\n        address priceOracle\n    ) internal view returns (uint256 totalValueUSD, uint256 twvUSD) {\n        uint256 len = quotedTokens.length; // U:[CLL-4]\n\n        for (uint256 i; i < len;) {\n            address token = quotedTokens[i]; // U:[CLL-4]\n\n            {\n                (uint256 quota, uint16 liquidationThreshold) = unpackQuota(quotasPacked[i]); // U:[CLL-4]\n                uint256 quotaUSD = quota * underlyingPriceRAY / RAY; // U:[CLL-4]\n\n                (uint256 valueUSD, uint256 weightedValueUSD,) = calcOneTokenCollateral({\n                    priceOracle: priceOracle,\n                    creditAccount: creditAccount,\n                    token: token,\n                    liquidationThreshold: liquidationThreshold,\n                    quotaUSD: quotaUSD,\n                    convertToUSDFn: convertToUSDFn\n                }); // U:[CLL-4]\n\n                totalValueUSD += valueUSD; // U:[CLL-4]\n                twvUSD += weightedValueUSD; // U:[CLL-4]\n            }\n            if (twvUSD >= twvUSDTarget) {\n                return (totalValueUSD, twvUSD); // U:[CLL-4]\n            }\n\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /// @dev Computes USD value of non-quoted tokens on a credit account\n    /// @param creditAccount Address of the credit account\n    /// @param twvUSDTarget The twvUSD threshold to stop the computation at\n    /// @param collateralHints Array of token masks for order of priority during collateral computation\n    /// @param convertToUSDFn Function to convert asset amounts to USD\n    /// @param collateralTokenByMaskFn Function to retrieve the token's address and LT by its mask\n    /// @param tokensToCheckMask Mask of tokens that need to be included into the computation\n    /// @param priceOracle Address of the price oracle\n    /// @return totalValueUSD Total value of credit account's quoted assets\n    /// @return twvUSD Total LT-weighted value of credit account's quoted assets\n    /// @return tokensToDisable Mask of non-quoted tokens that have zero balances and can be disabled\n    function calcNonQuotedTokensCollateral(\n        address creditAccount,\n        uint256 twvUSDTarget,\n        uint256[] memory collateralHints,\n        function (address, uint256, address) view returns(uint256) convertToUSDFn,\n        function (uint256, bool) view returns (address, uint16) collateralTokenByMaskFn,\n        uint256 tokensToCheckMask,\n        address priceOracle\n    ) internal view returns (uint256 totalValueUSD, uint256 twvUSD, uint256 tokensToDisable) {\n        uint256 len = collateralHints.length; // U:[CLL-3]\n\n        address ca = creditAccount; // U:[CLL-3]\n        uint256 i;\n        while (tokensToCheckMask != 0) {\n            uint256 tokenMask;\n\n            if (i < len) {\n                tokenMask = collateralHints[i];\n                unchecked {\n                    ++i;\n                }\n                if (tokensToCheckMask & tokenMask == 0) continue;\n            } else {\n                tokenMask = tokensToCheckMask & uint256(-int256(tokensToCheckMask));\n            }\n\n            bool nonZero;\n            {\n                uint256 valueUSD;\n                uint256 weightedValueUSD;\n                (valueUSD, weightedValueUSD, nonZero) = calcOneNonQuotedCollateral({\n                    priceOracle: priceOracle,\n                    creditAccount: ca,\n                    tokenMask: tokenMask,\n                    convertToUSDFn: convertToUSDFn,\n                    collateralTokenByMaskFn: collateralTokenByMaskFn\n                }); // U:[CLL-3]\n                totalValueUSD += valueUSD; // U:[CLL-3]\n                twvUSD += weightedValueUSD; // U:[CLL-3]\n            }\n            if (nonZero) {\n                if (twvUSD >= twvUSDTarget) {\n                    break; // U:[CLL-3]\n                }\n            } else {\n                // Zero balance tokens are disabled after the collateral computation\n                tokensToDisable = tokensToDisable.enable(tokenMask); // U:[CLL-3]\n            }\n            tokensToCheckMask = tokensToCheckMask.disable(tokenMask);\n        }\n    }\n\n    /// @dev Computes value of a single non-quoted asset on a credit account\n    /// @param creditAccount Address of the credit account\n    /// @param convertToUSDFn Function to convert asset amounts to USD\n    /// @param collateralTokenByMaskFn Function to retrieve the token's address and LT by its mask\n    /// @param tokenMask Mask of the token\n    /// @param priceOracle Address of the price oracle\n    /// @return valueUSD Value of the token\n    /// @return weightedValueUSD LT-weighted value of the token\n    /// @return nonZeroBalance Whether the token has a zero balance\n    function calcOneNonQuotedCollateral(\n        address creditAccount,\n        function (address, uint256, address) view returns(uint256) convertToUSDFn,\n        function (uint256, bool) view returns (address, uint16) collateralTokenByMaskFn,\n        uint256 tokenMask,\n        address priceOracle\n    ) internal view returns (uint256 valueUSD, uint256 weightedValueUSD, bool nonZeroBalance) {\n        (address token, uint16 liquidationThreshold) = collateralTokenByMaskFn(tokenMask, true); // U:[CLL-2]\n\n        (valueUSD, weightedValueUSD, nonZeroBalance) = calcOneTokenCollateral({\n            priceOracle: priceOracle,\n            creditAccount: creditAccount,\n            token: token,\n            liquidationThreshold: liquidationThreshold,\n            quotaUSD: type(uint256).max,\n            convertToUSDFn: convertToUSDFn\n        }); // U:[CLL-2]\n    }\n\n    /// @dev Computes USD value of a single asset on a credit account\n    /// @param creditAccount Address of the credit account\n    /// @param convertToUSDFn Function to convert asset amounts to USD\n    /// @param priceOracle Address of the price oracle\n    /// @param token Address of the token\n    /// @param liquidationThreshold LT of the token\n    /// @param quotaUSD Quota of the token converted to USD\n    /// @return valueUSD Value of the token\n    /// @return weightedValueUSD LT-weighted value of the token\n    /// @return nonZeroBalance Whether the token has a zero balance\n    function calcOneTokenCollateral(\n        address creditAccount,\n        function (address, uint256, address) view returns(uint256) convertToUSDFn,\n        address priceOracle,\n        address token,\n        uint16 liquidationThreshold,\n        uint256 quotaUSD\n    ) internal view returns (uint256 valueUSD, uint256 weightedValueUSD, bool nonZeroBalance) {\n        uint256 balance = IERC20(token).safeBalanceOf({account: creditAccount}); // U:[CLL-1]\n\n        if (balance > 1) {\n            unchecked {\n                valueUSD = convertToUSDFn(priceOracle, balance - 1, token); // U:[CLL-1]\n            }\n            weightedValueUSD = Math.min(valueUSD * liquidationThreshold / PERCENTAGE_FACTOR, quotaUSD); // U:[CLL-1]\n            nonZeroBalance = true; // U:[CLL-1]\n        }\n    }\n\n    /// @dev Packs quota and LT into one word\n    function packQuota(uint96 quota, uint16 lt) internal pure returns (uint256) {\n        return (uint256(lt) << 96) | quota;\n    }\n\n    /// @dev Unpacks one word into quota and LT\n    function unpackQuota(uint256 packedQuota) internal pure returns (uint256 quota, uint16 lt) {\n        lt = uint16(packedQuota >> 96);\n        quota = uint96(packedQuota);\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/libraries/CreditAccountHelper.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\n\nimport {ICreditAccountBase} from \"../interfaces/ICreditAccountV3.sol\";\nimport {AllowanceFailedException} from \"../interfaces/IExceptions.sol\";\n\n/// @title Credit account helper library\n/// @notice Implements functions that help manage assets on a credit account\nlibrary CreditAccountHelper {\n    using SafeERC20 for IERC20;\n\n    /// @dev Requests a credit account to do an approval with support for various kinds of tokens\n    /// @dev Supports up-to-spec ERC20 tokens, ERC20 tokens that revert on transfer failure,\n    ///      tokens that require 0 allowance before changing to non-zero value, and non-ERC20 tokens\n    ///      that do not return a `success` value\n    /// @param creditAccount Credit account to approve tokens from\n    /// @param token Token to approve\n    /// @param spender Address to approve to\n    /// @param amount Amount to approve\n    function safeApprove(ICreditAccountBase creditAccount, address token, address spender, uint256 amount) internal {\n        if (!_approve(creditAccount, token, spender, amount, false)) {\n            _approve(creditAccount, token, spender, 0, true); //U:[CAH-1,2]\n            _approve(creditAccount, token, spender, amount, true); // U:[CAH-1,2]\n        }\n    }\n\n    /// @dev Internal function used to approve tokens from a credit account to a third-party contrat.\n    ///      Uses credit account's `execute` to properly handle both ERC20-compliant and on-compliant\n    ///      (no returned value from \"approve\") tokens\n    /// @param creditAccount Credit account to approve tokens from\n    /// @param token Token to approve\n    /// @param spender Address to approve to\n    /// @param amount Amount to approve\n    /// @param revertIfFailed Whether to revert or return `false` on receiving `false` or an error from `approve`\n    function _approve(\n        ICreditAccountBase creditAccount,\n        address token,\n        address spender,\n        uint256 amount,\n        bool revertIfFailed\n    ) private returns (bool) {\n        // Makes a low-level call to approve from the credit account and parses the value.\n        // If nothing or true was returned, assumes that the call succeeded.\n        try creditAccount.execute(token, abi.encodeCall(IERC20.approve, (spender, amount))) returns (\n            bytes memory result\n        ) {\n            if (result.length == 0 || abi.decode(result, (bool))) return true;\n        } catch {}\n\n        // On the first try, failure is allowed to handle tokens that prohibit changing allowance from non-zero value.\n        // After that, failure results in a revert.\n        if (revertIfFailed) revert AllowanceFailedException();\n        return false;\n    }\n\n    /// @dev Performs a token transfer from a credit account, accounting for non-ERC20 tokens\n    /// @param creditAccount Credit account to send tokens from\n    /// @param token Token to send\n    /// @param to Address to send to\n    /// @param amount Amount to send\n    function transfer(ICreditAccountBase creditAccount, address token, address to, uint256 amount) internal {\n        creditAccount.safeTransfer(token, to, amount);\n    }\n\n    /// @dev Performs a token transfer from a Credit account and returns the actual amount of token transferred\n    /// @dev For some tokens, such as stETH or USDT (with fee enabled), the amount that arrives to the recipient can\n    ///      differ from the sent amount. This ensures that calculations are correct in such cases.\n    /// @param creditAccount Credit account to send tokens from\n    /// @param token Token to send\n    /// @param to Address to send to\n    /// @param amount Amount to send\n    /// @return delivered The actual amount that the `to` address received\n    function transferDeliveredBalanceControl(\n        ICreditAccountBase creditAccount,\n        address token,\n        address to,\n        uint256 amount\n    ) internal returns (uint256 delivered) {\n        uint256 balanceBefore = IERC20(token).safeBalanceOf({account: to});\n        transfer(creditAccount, token, to, amount);\n        delivered = IERC20(token).safeBalanceOf({account: to}) - balanceBefore;\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/traits/ReentrancyGuardTrait.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nuint8 constant NOT_ENTERED = 1;\nuint8 constant ENTERED = 2;\n\n/// @title Reentrancy guard trait\n/// @notice Same as OpenZeppelin's `ReentrancyGuard` but only uses 1 byte of storage instead of 32\nabstract contract ReentrancyGuardTrait {\n    uint8 internal _reentrancyStatus = NOT_ENTERED;\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    modifier nonReentrant() {\n        // On the first call to nonReentrant, _notEntered will be true\n        _ensureNotEntered();\n\n        // Any calls to nonReentrant after this point will fail\n        _reentrancyStatus = 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        _reentrancyStatus = NOT_ENTERED;\n    }\n\n    /// @dev Reverts if the contract is currently entered\n    /// @dev Used to cut contract size on modifiers\n    function _ensureNotEntered() internal view {\n        require(_reentrancyStatus != ENTERED, \"ReentrancyGuard: reentrant call\");\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/traits/SanityCheckTrait.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {ZeroAddressException} from \"../interfaces/IExceptions.sol\";\n\n/// @title Sanity check trait\nabstract contract SanityCheckTrait {\n    /// @dev Ensures that passed address is non-zero\n    modifier nonZeroAddress(address addr) {\n        _revertIfZeroAddress(addr);\n        _;\n    }\n\n    /// @dev Reverts if address is zero\n    function _revertIfZeroAddress(address addr) private pure {\n        if (addr == address(0)) revert ZeroAddressException();\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IAccountFactoryV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\n/// @title Account factory base interface\n/// @notice Functions shared accross newer and older versions\ninterface IAccountFactoryBase is IVersion {\n    function takeCreditAccount(uint256, uint256) external returns (address creditAccount);\n    function returnCreditAccount(address creditAccount) external;\n}\n\ninterface IAccountFactoryV3Events {\n    /// @notice Emitted when new credit account is deployed\n    event DeployCreditAccount(address indexed creditAccount, address indexed creditManager);\n\n    /// @notice Emitted when credit account is taken by the credit manager\n    event TakeCreditAccount(address indexed creditAccount, address indexed creditManager);\n\n    /// @notice Emitted when used credit account is returned to the queue\n    event ReturnCreditAccount(address indexed creditAccount, address indexed creditManager);\n\n    /// @notice Emitted when new credit manager is added to the factory\n    event AddCreditManager(address indexed creditManager, address masterCreditAccount);\n\n    /// @notice Emitted when the DAO performs a proxy call from Credit Account to rescue funds\n    event Rescue(address indexed creditAccount, address indexed target, bytes data);\n}\n\n/// @title Account factory V3 interface\ninterface IAccountFactoryV3 is IAccountFactoryBase, IAccountFactoryV3Events {\n    function delay() external view returns (uint40);\n\n    function takeCreditAccount(uint256, uint256) external override returns (address creditAccount);\n\n    function returnCreditAccount(address creditAccount) external override;\n\n    function addCreditManager(address creditManager) external;\n\n    function rescue(address creditAccount, address target, bytes calldata data) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/ICreditAccountV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\n/// @title Credit account base interface\n/// @notice Functions shared accross newer and older versions\ninterface ICreditAccountBase is IVersion {\n    function creditManager() external view returns (address);\n    function safeTransfer(address token, address to, uint256 amount) external;\n    function execute(address target, bytes calldata data) external returns (bytes memory result);\n}\n\n/// @title Credit account V3 interface\ninterface ICreditAccountV3 is ICreditAccountBase {\n    function factory() external view returns (address);\n\n    function creditManager() external view override returns (address);\n\n    function safeTransfer(address token, address to, uint256 amount) external override;\n\n    function execute(address target, bytes calldata data) external override returns (bytes memory result);\n\n    function rescue(address target, bytes calldata data) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IPoolV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\npragma abicoder v1;\n\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {IERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\";\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\ninterface IPoolV3Events {\n    /// @notice Emitted when depositing liquidity with referral code\n    event Refer(address indexed onBehalfOf, uint256 indexed referralCode, uint256 amount);\n\n    /// @notice Emitted when credit account borrows funds from the pool\n    event Borrow(address indexed creditManager, address indexed creditAccount, uint256 amount);\n\n    /// @notice Emitted when credit account's debt is repaid to the pool\n    event Repay(address indexed creditManager, uint256 borrowedAmount, uint256 profit, uint256 loss);\n\n    /// @notice Emitted when incurred loss can't be fully covered by burning treasury's shares\n    event IncurUncoveredLoss(address indexed creditManager, uint256 loss);\n\n    /// @notice Emitted when new interest rate model contract is set\n    event SetInterestRateModel(address indexed newInterestRateModel);\n\n    /// @notice Emitted when new pool quota keeper contract is set\n    event SetPoolQuotaKeeper(address indexed newPoolQuotaKeeper);\n\n    /// @notice Emitted when new total debt limit is set\n    event SetTotalDebtLimit(uint256 limit);\n\n    /// @notice Emitted when new credit manager is connected to the pool\n    event AddCreditManager(address indexed creditManager);\n\n    /// @notice Emitted when new debt limit is set for a credit manager\n    event SetCreditManagerDebtLimit(address indexed creditManager, uint256 newLimit);\n\n    /// @notice Emitted when new withdrawal fee is set\n    event SetWithdrawFee(uint256 fee);\n}\n\n/// @title Pool V3 interface\ninterface IPoolV3 is IVersion, IPoolV3Events, IERC4626, IERC20Permit {\n    function addressProvider() external view returns (address);\n\n    function underlyingToken() external view returns (address);\n\n    function treasury() external view returns (address);\n\n    function withdrawFee() external view returns (uint16);\n\n    function creditManagers() external view returns (address[] memory);\n\n    function availableLiquidity() external view returns (uint256);\n\n    function expectedLiquidity() external view returns (uint256);\n\n    function expectedLiquidityLU() external view returns (uint256);\n\n    // ---------------- //\n    // ERC-4626 LENDING //\n    // ---------------- //\n\n    function depositWithReferral(uint256 assets, address receiver, uint256 referralCode)\n        external\n        returns (uint256 shares);\n\n    function mintWithReferral(uint256 shares, address receiver, uint256 referralCode)\n        external\n        returns (uint256 assets);\n\n    // --------- //\n    // BORROWING //\n    // --------- //\n\n    function totalBorrowed() external view returns (uint256);\n\n    function totalDebtLimit() external view returns (uint256);\n\n    function creditManagerBorrowed(address creditManager) external view returns (uint256);\n\n    function creditManagerDebtLimit(address creditManager) external view returns (uint256);\n\n    function creditManagerBorrowable(address creditManager) external view returns (uint256 borrowable);\n\n    function lendCreditAccount(uint256 borrowedAmount, address creditAccount) external;\n\n    function repayCreditAccount(uint256 repaidAmount, uint256 profit, uint256 loss) external;\n\n    // ------------- //\n    // INTEREST RATE //\n    // ------------- //\n\n    function interestRateModel() external view returns (address);\n\n    function baseInterestRate() external view returns (uint256);\n\n    function supplyRate() external view returns (uint256);\n\n    function baseInterestIndex() external view returns (uint256);\n\n    function baseInterestIndexLU() external view returns (uint256);\n\n    function lastBaseInterestUpdate() external view returns (uint40);\n\n    // ------ //\n    // QUOTAS //\n    // ------ //\n\n    function poolQuotaKeeper() external view returns (address);\n\n    function quotaRevenue() external view returns (uint256);\n\n    function lastQuotaRevenueUpdate() external view returns (uint40);\n\n    function updateQuotaRevenue(int256 quotaRevenueDelta) external;\n\n    function setQuotaRevenue(uint256 newQuotaRevenue) external;\n\n    // ------------- //\n    // CONFIGURATION //\n    // ------------- //\n\n    function setInterestRateModel(address newInterestRateModel) external;\n\n    function setPoolQuotaKeeper(address newPoolQuotaKeeper) external;\n\n    function setTotalDebtLimit(uint256 newLimit) external;\n\n    function setCreditManagerDebtLimit(address creditManager, uint256 newLimit) external;\n\n    function setWithdrawFee(uint256 newWithdrawFee) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\nuint8 constant BOT_PERMISSIONS_SET_FLAG = 1;\n\nuint8 constant DEFAULT_MAX_ENABLED_TOKENS = 4;\naddress constant INACTIVE_CREDIT_ACCOUNT_ADDRESS = address(1);\n\n/// @notice Debt management type\n///         - `INCREASE_DEBT` borrows additional funds from the pool, updates account's debt and cumulative interest index\n///         - `DECREASE_DEBT` repays debt components (quota interest and fees -> base interest and fees -> debt principal)\n///           and updates all corresponding state varibles (base interest index, quota interest and fees, debt).\n///           When repaying all the debt, ensures that account has no enabled quotas.\nenum ManageDebtAction {\n    INCREASE_DEBT,\n    DECREASE_DEBT\n}\n\n/// @notice Collateral/debt calculation mode\n///         - `GENERIC_PARAMS` returns generic data like account debt and cumulative indexes\n///         - `DEBT_ONLY` is same as `GENERIC_PARAMS` but includes more detailed debt info, like accrued base/quota\n///           interest and fees\n///         - `FULL_COLLATERAL_CHECK_LAZY` checks whether account is sufficiently collateralized in a lazy fashion,\n///           i.e. it stops iterating over collateral tokens once TWV reaches the desired target.\n///           Since it may return underestimated TWV, it's only available for internal use.\n///         - `DEBT_COLLATERAL` is same as `DEBT_ONLY` but also returns total value and total LT-weighted value of\n///           account's tokens, this mode is used during account liquidation\n///         - `DEBT_COLLATERAL_SAFE_PRICES` is same as `DEBT_COLLATERAL` but uses safe prices from price oracle\nenum CollateralCalcTask {\n    GENERIC_PARAMS,\n    DEBT_ONLY,\n    FULL_COLLATERAL_CHECK_LAZY,\n    DEBT_COLLATERAL,\n    DEBT_COLLATERAL_SAFE_PRICES\n}\n\nstruct CreditAccountInfo {\n    uint256 debt;\n    uint256 cumulativeIndexLastUpdate;\n    uint128 cumulativeQuotaInterest;\n    uint128 quotaFees;\n    uint256 enabledTokensMask;\n    uint16 flags;\n    uint64 lastDebtUpdate;\n    address borrower;\n}\n\nstruct CollateralDebtData {\n    uint256 debt;\n    uint256 cumulativeIndexNow;\n    uint256 cumulativeIndexLastUpdate;\n    uint128 cumulativeQuotaInterest;\n    uint256 accruedInterest;\n    uint256 accruedFees;\n    uint256 totalDebtUSD;\n    uint256 totalValue;\n    uint256 totalValueUSD;\n    uint256 twvUSD;\n    uint256 enabledTokensMask;\n    uint256 quotedTokensMask;\n    address[] quotedTokens;\n    address _poolQuotaKeeper;\n}\n\nstruct CollateralTokenData {\n    address token;\n    uint16 ltInitial;\n    uint16 ltFinal;\n    uint40 timestampRampStart;\n    uint24 rampDuration;\n}\n\nstruct RevocationPair {\n    address spender;\n    address token;\n}\n\ninterface ICreditManagerV3Events {\n    /// @notice Emitted when new credit configurator is set\n    event SetCreditConfigurator(address indexed newConfigurator);\n}\n\n/// @title Credit manager V3 interface\ninterface ICreditManagerV3 is IVersion, ICreditManagerV3Events {\n    function pool() external view returns (address);\n\n    function underlying() external view returns (address);\n\n    function creditFacade() external view returns (address);\n\n    function creditConfigurator() external view returns (address);\n\n    function addressProvider() external view returns (address);\n\n    function accountFactory() external view returns (address);\n\n    function name() external view returns (string memory);\n\n    // ------------------ //\n    // ACCOUNT MANAGEMENT //\n    // ------------------ //\n\n    function openCreditAccount(address onBehalfOf) external returns (address);\n\n    function closeCreditAccount(address creditAccount) external;\n\n    function liquidateCreditAccount(\n        address creditAccount,\n        CollateralDebtData calldata collateralDebtData,\n        address to,\n        bool isExpired\n    ) external returns (uint256 remainingFunds, uint256 loss);\n\n    function manageDebt(address creditAccount, uint256 amount, uint256 enabledTokensMask, ManageDebtAction action)\n        external\n        returns (uint256 newDebt, uint256 tokensToEnable, uint256 tokensToDisable);\n\n    function addCollateral(address payer, address creditAccount, address token, uint256 amount)\n        external\n        returns (uint256 tokensToEnable);\n\n    function withdrawCollateral(address creditAccount, address token, uint256 amount, address to)\n        external\n        returns (uint256 tokensToDisable);\n\n    function externalCall(address creditAccount, address target, bytes calldata callData)\n        external\n        returns (bytes memory result);\n\n    function approveToken(address creditAccount, address token, address spender, uint256 amount) external;\n\n    function revokeAdapterAllowances(address creditAccount, RevocationPair[] calldata revocations) external;\n\n    // -------- //\n    // ADAPTERS //\n    // -------- //\n\n    function adapterToContract(address adapter) external view returns (address targetContract);\n\n    function contractToAdapter(address targetContract) external view returns (address adapter);\n\n    function execute(bytes calldata data) external returns (bytes memory result);\n\n    function approveCreditAccount(address token, uint256 amount) external;\n\n    function setActiveCreditAccount(address creditAccount) external;\n\n    function getActiveCreditAccountOrRevert() external view returns (address creditAccount);\n\n    // ----------------- //\n    // COLLATERAL CHECKS //\n    // ----------------- //\n\n    function priceOracle() external view returns (address);\n\n    function fullCollateralCheck(\n        address creditAccount,\n        uint256 enabledTokensMask,\n        uint256[] calldata collateralHints,\n        uint16 minHealthFactor,\n        bool useSafePrices\n    ) external returns (uint256 enabledTokensMaskAfter);\n\n    function isLiquidatable(address creditAccount, uint16 minHealthFactor) external view returns (bool);\n\n    function calcDebtAndCollateral(address creditAccount, CollateralCalcTask task)\n        external\n        view\n        returns (CollateralDebtData memory cdd);\n\n    // ------ //\n    // QUOTAS //\n    // ------ //\n\n    function poolQuotaKeeper() external view returns (address);\n\n    function quotedTokensMask() external view returns (uint256);\n\n    function updateQuota(address creditAccount, address token, int96 quotaChange, uint96 minQuota, uint96 maxQuota)\n        external\n        returns (uint256 tokensToEnable, uint256 tokensToDisable);\n\n    // --------------------- //\n    // CREDIT MANAGER PARAMS //\n    // --------------------- //\n\n    function maxEnabledTokens() external view returns (uint8);\n\n    function fees()\n        external\n        view\n        returns (\n            uint16 feeInterest,\n            uint16 feeLiquidation,\n            uint16 liquidationDiscount,\n            uint16 feeLiquidationExpired,\n            uint16 liquidationDiscountExpired\n        );\n\n    function collateralTokensCount() external view returns (uint8);\n\n    function getTokenMaskOrRevert(address token) external view returns (uint256 tokenMask);\n\n    function getTokenByMask(uint256 tokenMask) external view returns (address token);\n\n    function liquidationThresholds(address token) external view returns (uint16 lt);\n\n    function ltParams(address token)\n        external\n        view\n        returns (uint16 ltInitial, uint16 ltFinal, uint40 timestampRampStart, uint24 rampDuration);\n\n    function collateralTokenByMask(uint256 tokenMask)\n        external\n        view\n        returns (address token, uint16 liquidationThreshold);\n\n    // ------------ //\n    // ACCOUNT INFO //\n    // ------------ //\n\n    function creditAccountInfo(address creditAccount)\n        external\n        view\n        returns (\n            uint256 debt,\n            uint256 cumulativeIndexLastUpdate,\n            uint128 cumulativeQuotaInterest,\n            uint128 quotaFees,\n            uint256 enabledTokensMask,\n            uint16 flags,\n            uint64 lastDebtUpdate,\n            address borrower\n        );\n\n    function getBorrowerOrRevert(address creditAccount) external view returns (address borrower);\n\n    function flagsOf(address creditAccount) external view returns (uint16);\n\n    function setFlagFor(address creditAccount, uint16 flag, bool value) external;\n\n    function enabledTokensMaskOf(address creditAccount) external view returns (uint256);\n\n    function creditAccounts() external view returns (address[] memory);\n\n    function creditAccounts(uint256 offset, uint256 limit) external view returns (address[] memory);\n\n    function creditAccountsLen() external view returns (uint256);\n\n    // ------------- //\n    // CONFIGURATION //\n    // ------------- //\n\n    function addToken(address token) external;\n\n    function setCollateralTokenData(\n        address token,\n        uint16 ltInitial,\n        uint16 ltFinal,\n        uint40 timestampRampStart,\n        uint24 rampDuration\n    ) external;\n\n    function setFees(\n        uint16 feeInterest,\n        uint16 feeLiquidation,\n        uint16 liquidationDiscount,\n        uint16 feeLiquidationExpired,\n        uint16 liquidationDiscountExpired\n    ) external;\n\n    function setQuotedMask(uint256 quotedTokensMask) external;\n\n    function setMaxEnabledTokens(uint8 maxEnabledTokens) external;\n\n    function setContractAllowance(address adapter, address targetContract) external;\n\n    function setCreditFacade(address creditFacade) external;\n\n    function setPriceOracle(address priceOracle) external;\n\n    function setCreditConfigurator(address creditConfigurator) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IAddressProviderV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\nuint256 constant NO_VERSION_CONTROL = 0;\n\nbytes32 constant AP_CONTRACTS_REGISTER = \"CONTRACTS_REGISTER\";\nbytes32 constant AP_ACL = \"ACL\";\nbytes32 constant AP_PRICE_ORACLE = \"PRICE_ORACLE\";\nbytes32 constant AP_ACCOUNT_FACTORY = \"ACCOUNT_FACTORY\";\nbytes32 constant AP_DATA_COMPRESSOR = \"DATA_COMPRESSOR\";\nbytes32 constant AP_TREASURY = \"TREASURY\";\nbytes32 constant AP_GEAR_TOKEN = \"GEAR_TOKEN\";\nbytes32 constant AP_WETH_TOKEN = \"WETH_TOKEN\";\nbytes32 constant AP_WETH_GATEWAY = \"WETH_GATEWAY\";\nbytes32 constant AP_ROUTER = \"ROUTER\";\nbytes32 constant AP_BOT_LIST = \"BOT_LIST\";\nbytes32 constant AP_GEAR_STAKING = \"GEAR_STAKING\";\nbytes32 constant AP_ZAPPER_REGISTER = \"ZAPPER_REGISTER\";\n\ninterface IAddressProviderV3Events {\n    /// @notice Emitted when an address is set for a contract key\n    event SetAddress(bytes32 indexed key, address indexed value, uint256 indexed version);\n}\n\n/// @title Address provider V3 interface\ninterface IAddressProviderV3 is IAddressProviderV3Events, IVersion {\n    function addresses(bytes32 key, uint256 _version) external view returns (address);\n\n    function getAddressOrRevert(bytes32 key, uint256 _version) external view returns (address result);\n\n    function setAddress(bytes32 key, address value, bool saveVersion) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IPriceOracleV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IPriceOracleBase} from \"@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracleBase.sol\";\n\nstruct PriceFeedParams {\n    address priceFeed;\n    uint32 stalenessPeriod;\n    bool skipCheck;\n    uint8 decimals;\n    bool useReserve;\n    bool trusted;\n}\n\ninterface IPriceOracleV3Events {\n    /// @notice Emitted when new price feed is set for token\n    event SetPriceFeed(\n        address indexed token, address indexed priceFeed, uint32 stalenessPeriod, bool skipCheck, bool trusted\n    );\n\n    /// @notice Emitted when new reserve price feed is set for token\n    event SetReservePriceFeed(address indexed token, address indexed priceFeed, uint32 stalenessPeriod, bool skipCheck);\n\n    /// @notice Emitted when new reserve price feed status is set for a token\n    event SetReservePriceFeedStatus(address indexed token, bool active);\n}\n\n/// @title Price oracle V3 interface\ninterface IPriceOracleV3 is IPriceOracleBase, IPriceOracleV3Events {\n    function getPriceSafe(address token) external view returns (uint256);\n\n    function getPriceRaw(address token, bool reserve) external view returns (uint256);\n\n    function priceFeedsRaw(address token, bool reserve) external view returns (address);\n\n    function priceFeedParams(address token)\n        external\n        view\n        returns (address priceFeed, uint32 stalenessPeriod, bool skipCheck, uint8 decimals, bool trusted);\n\n    function safeConvertToUSD(uint256 amount, address token) external view returns (uint256);\n\n    // ------------- //\n    // CONFIGURATION //\n    // ------------- //\n\n    function setPriceFeed(address token, address priceFeed, uint32 stalenessPeriod, bool trusted) external;\n\n    function setReservePriceFeed(address token, address priceFeed, uint32 stalenessPeriod) external;\n\n    function setReservePriceFeedStatus(address token, bool active) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IPoolQuotaKeeperV3.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\nimport {IVersion} from \"@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol\";\n\nstruct TokenQuotaParams {\n    uint16 rate;\n    uint192 cumulativeIndexLU;\n    uint16 quotaIncreaseFee;\n    uint96 totalQuoted;\n    uint96 limit;\n}\n\nstruct AccountQuota {\n    uint96 quota;\n    uint192 cumulativeIndexLU;\n}\n\ninterface IPoolQuotaKeeperV3Events {\n    /// @notice Emitted when account's quota for a token is updated\n    event UpdateQuota(address indexed creditAccount, address indexed token, int96 quotaChange);\n\n    /// @notice Emitted when token's quota rate is updated\n    event UpdateTokenQuotaRate(address indexed token, uint16 rate);\n\n    /// @notice Emitted when the gauge is updated\n    event SetGauge(address indexed newGauge);\n\n    /// @notice Emitted when a new credit manager is allowed\n    event AddCreditManager(address indexed creditManager);\n\n    /// @notice Emitted when a new token is added as quoted\n    event AddQuotaToken(address indexed token);\n\n    /// @notice Emitted when a new total quota limit is set for a token\n    event SetTokenLimit(address indexed token, uint96 limit);\n\n    /// @notice Emitted when a new one-time quota increase fee is set for a token\n    event SetQuotaIncreaseFee(address indexed token, uint16 fee);\n}\n\n/// @title Pool quota keeper V3 interface\ninterface IPoolQuotaKeeperV3 is IPoolQuotaKeeperV3Events, IVersion {\n    function pool() external view returns (address);\n\n    function underlying() external view returns (address);\n\n    // ----------------- //\n    // QUOTAS MANAGEMENT //\n    // ----------------- //\n\n    function updateQuota(address creditAccount, address token, int96 requestedChange, uint96 minQuota, uint96 maxQuota)\n        external\n        returns (uint128 caQuotaInterestChange, uint128 fees, bool enableToken, bool disableToken);\n\n    function removeQuotas(address creditAccount, address[] calldata tokens, bool setLimitsToZero) external;\n\n    function accrueQuotaInterest(address creditAccount, address[] calldata tokens) external;\n\n    function getQuotaRate(address) external view returns (uint16);\n\n    function cumulativeIndex(address token) external view returns (uint192);\n\n    function isQuotedToken(address token) external view returns (bool);\n\n    function getQuota(address creditAccount, address token)\n        external\n        view\n        returns (uint96 quota, uint192 cumulativeIndexLU);\n\n    function getTokenQuotaParams(address token)\n        external\n        view\n        returns (\n            uint16 rate,\n            uint192 cumulativeIndexLU,\n            uint16 quotaIncreaseFee,\n            uint96 totalQuoted,\n            uint96 limit,\n            bool isActive\n        );\n\n    function getQuotaAndOutstandingInterest(address creditAccount, address token)\n        external\n        view\n        returns (uint96 quoted, uint128 outstandingInterest);\n\n    function poolQuotaRevenue() external view returns (uint256);\n\n    function lastQuotaRateUpdate() external view returns (uint40);\n\n    // ------------- //\n    // CONFIGURATION //\n    // ------------- //\n\n    function gauge() external view returns (address);\n\n    function setGauge(address _gauge) external;\n\n    function creditManagers() external view returns (address[] memory);\n\n    function addCreditManager(address _creditManager) external;\n\n    function quotedTokens() external view returns (address[] memory);\n\n    function addQuotaToken(address token) external;\n\n    function updateRates() external;\n\n    function setTokenLimit(address token, uint96 limit) external;\n\n    function setTokenQuotaIncreaseFee(address token, uint16 fee) external;\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v2/contracts/libraries/Constants.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n// Denominations\n\nuint256 constant WAD = 1e18;\nuint256 constant RAY = 1e27;\nuint16 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals\n\n// 25% of type(uint256).max\nuint256 constant ALLOWANCE_THRESHOLD = type(uint96).max >> 3;\n\n// FEE = 50%\nuint16 constant DEFAULT_FEE_INTEREST = 50_00; // 50%\n\n// LIQUIDATION_FEE 1.5%\nuint16 constant DEFAULT_FEE_LIQUIDATION = 1_50; // 1.5%\n\n// LIQUIDATION PREMIUM 4%\nuint16 constant DEFAULT_LIQUIDATION_PREMIUM = 4_00; // 4%\n\n// LIQUIDATION_FEE_EXPIRED 2%\nuint16 constant DEFAULT_FEE_LIQUIDATION_EXPIRED = 1_00; // 2%\n\n// LIQUIDATION PREMIUM EXPIRED 2%\nuint16 constant DEFAULT_LIQUIDATION_PREMIUM_EXPIRED = 2_00; // 2%\n\n// DEFAULT PROPORTION OF MAX BORROWED PER BLOCK TO MAX BORROWED PER ACCOUNT\nuint16 constant DEFAULT_LIMIT_PER_BLOCK_MULTIPLIER = 2;\n\n// Seconds in a year\nuint256 constant SECONDS_PER_YEAR = 365 days;\nuint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = (SECONDS_PER_YEAR * 3) / 2;\n\n// OPERATIONS\n\n// Leverage decimals - 100 is equal to 2x leverage (100% * collateral amount + 100% * borrowed amount)\nuint8 constant LEVERAGE_DECIMALS = 100;\n\n// Maximum withdraw fee for pool in PERCENTAGE_FACTOR format\nuint8 constant MAX_WITHDRAW_FEE = 100;\n\nuint256 constant EXACT_INPUT = 1;\nuint256 constant EXACT_OUTPUT = 2;\n\naddress constant UNIVERSAL_CONTRACT = 0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC;\n"
      },
      "node_modules/@gearbox-protocol/core-v3/contracts/interfaces/IExceptions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Foundation, 2023.\npragma solidity ^0.8.17;\n\n// ------- //\n// GENERAL //\n// ------- //\n\n/// @notice Thrown on attempting to set an important address to zero address\nerror ZeroAddressException();\n\n/// @notice Thrown when attempting to pass a zero amount to a funding-related operation\nerror AmountCantBeZeroException();\n\n/// @notice Thrown on incorrect input parameter\nerror IncorrectParameterException();\n\n/// @notice Thrown when balance is insufficient to perform an operation\nerror InsufficientBalanceException();\n\n/// @notice Thrown if parameter is out of range\nerror ValueOutOfRangeException();\n\n/// @notice Thrown when trying to send ETH to a contract that is not allowed to receive ETH directly\nerror ReceiveIsNotAllowedException();\n\n/// @notice Thrown on attempting to set an EOA as an important contract in the system\nerror AddressIsNotContractException(address);\n\n/// @notice Thrown on attempting to receive a token that is not a collateral token or was forbidden\nerror TokenNotAllowedException();\n\n/// @notice Thrown on attempting to add a token that is already in a collateral list\nerror TokenAlreadyAddedException();\n\n/// @notice Thrown when attempting to use quota-related logic for a token that is not quoted in quota keeper\nerror TokenIsNotQuotedException();\n\n/// @notice Thrown on attempting to interact with an address that is not a valid target contract\nerror TargetContractNotAllowedException();\n\n/// @notice Thrown if function is not implemented\nerror NotImplementedException();\n\n// ------------------ //\n// CONTRACTS REGISTER //\n// ------------------ //\n\n/// @notice Thrown when an address is expected to be a registered credit manager, but is not\nerror RegisteredCreditManagerOnlyException();\n\n/// @notice Thrown when an address is expected to be a registered pool, but is not\nerror RegisteredPoolOnlyException();\n\n// ---------------- //\n// ADDRESS PROVIDER //\n// ---------------- //\n\n/// @notice Reverts if address key isn't found in address provider\nerror AddressNotFoundException();\n\n// ----------------- //\n// POOL, PQK, GAUGES //\n// ----------------- //\n\n/// @notice Thrown by pool-adjacent contracts when a credit manager being connected has a wrong pool address\nerror IncompatibleCreditManagerException();\n\n/// @notice Thrown when attempting to set an incompatible successor staking contract\nerror IncompatibleSuccessorException();\n\n/// @notice Thrown when attempting to vote in a non-approved contract\nerror VotingContractNotAllowedException();\n\n/// @notice Thrown when attempting to unvote more votes than there are\nerror InsufficientVotesException();\n\n/// @notice Thrown when attempting to borrow more than the second point on a two-point curve\nerror BorrowingMoreThanU2ForbiddenException();\n\n/// @notice Thrown when a credit manager attempts to borrow more than its limit in the current block, or in general\nerror CreditManagerCantBorrowException();\n\n/// @notice Thrown when attempting to connect a quota keeper to an incompatible pool\nerror IncompatiblePoolQuotaKeeperException();\n\n/// @notice Thrown when the quota is outside of min/max bounds\nerror QuotaIsOutOfBoundsException();\n\n// -------------- //\n// CREDIT MANAGER //\n// -------------- //\n\n/// @notice Thrown on failing a full collateral check after multicall\nerror NotEnoughCollateralException();\n\n/// @notice Thrown if an attempt to approve a collateral token to adapter's target contract fails\nerror AllowanceFailedException();\n\n/// @notice Thrown on attempting to perform an action for a credit account that does not exist\nerror CreditAccountDoesNotExistException();\n\n/// @notice Thrown on configurator attempting to add more than 255 collateral tokens\nerror TooManyTokensException();\n\n/// @notice Thrown if more than the maximum number of tokens were enabled on a credit account\nerror TooManyEnabledTokensException();\n\n/// @notice Thrown when attempting to execute a protocol interaction without active credit account set\nerror ActiveCreditAccountNotSetException();\n\n/// @notice Thrown when trying to update credit account's debt more than once in the same block\nerror DebtUpdatedTwiceInOneBlockException();\n\n/// @notice Thrown when trying to repay all debt while having active quotas\nerror DebtToZeroWithActiveQuotasException();\n\n/// @notice Thrown when a zero-debt account attempts to update quota\nerror UpdateQuotaOnZeroDebtAccountException();\n\n/// @notice Thrown when attempting to close an account with non-zero debt\nerror CloseAccountWithNonZeroDebtException();\n\n/// @notice Thrown when value of funds remaining on the account after liquidation is insufficient\nerror InsufficientRemainingFundsException();\n\n/// @notice Thrown when Credit Facade tries to write over a non-zero active Credit Account\nerror ActiveCreditAccountOverridenException();\n\n// ------------------- //\n// CREDIT CONFIGURATOR //\n// ------------------- //\n\n/// @notice Thrown on attempting to use a non-ERC20 contract or an EOA as a token\nerror IncorrectTokenContractException();\n\n/// @notice Thrown if the newly set LT if zero or greater than the underlying's LT\nerror IncorrectLiquidationThresholdException();\n\n/// @notice Thrown if borrowing limits are incorrect: minLimit > maxLimit or maxLimit > blockLimit\nerror IncorrectLimitsException();\n\n/// @notice Thrown if the new expiration date is less than the current expiration date or current timestamp\nerror IncorrectExpirationDateException();\n\n/// @notice Thrown if a contract returns a wrong credit manager or reverts when trying to retrieve it\nerror IncompatibleContractException();\n\n/// @notice Thrown if attempting to forbid an adapter that is not registered in the credit manager\nerror AdapterIsNotRegisteredException();\n\n// ------------- //\n// CREDIT FACADE //\n// ------------- //\n\n/// @notice Thrown when attempting to perform an action that is forbidden in whitelisted mode\nerror ForbiddenInWhitelistedModeException();\n\n/// @notice Thrown if credit facade is not expirable, and attempted aciton requires expirability\nerror NotAllowedWhenNotExpirableException();\n\n/// @notice Thrown if a selector that doesn't match any allowed function is passed to the credit facade in a multicall\nerror UnknownMethodException();\n\n/// @notice Thrown when trying to close an account with enabled tokens\nerror CloseAccountWithEnabledTokensException();\n\n/// @notice Thrown if a liquidator tries to liquidate an account with a health factor above 1\nerror CreditAccountNotLiquidatableException();\n\n/// @notice Thrown if too much new debt was taken within a single block\nerror BorrowedBlockLimitException();\n\n/// @notice Thrown if the new debt principal for a credit account falls outside of borrowing limits\nerror BorrowAmountOutOfLimitsException();\n\n/// @notice Thrown if a user attempts to open an account via an expired credit facade\nerror NotAllowedAfterExpirationException();\n\n/// @notice Thrown if expected balances are attempted to be set twice without performing a slippage check\nerror ExpectedBalancesAlreadySetException();\n\n/// @notice Thrown if attempting to perform a slippage check when excepted balances are not set\nerror ExpectedBalancesNotSetException();\n\n/// @notice Thrown if balance of at least one token is less than expected during a slippage check\nerror BalanceLessThanExpectedException();\n\n/// @notice Thrown when trying to perform an action that is forbidden when credit account has enabled forbidden tokens\nerror ForbiddenTokensException();\n\n/// @notice Thrown when new forbidden tokens are enabled during the multicall\nerror ForbiddenTokenEnabledException();\n\n/// @notice Thrown when enabled forbidden token balance is increased during the multicall\nerror ForbiddenTokenBalanceIncreasedException();\n\n/// @notice Thrown when the remaining token balance is increased during the liquidation\nerror RemainingTokenBalanceIncreasedException();\n\n/// @notice Thrown if `botMulticall` is called by an address that is not approved by account owner or is forbidden\nerror NotApprovedBotException();\n\n/// @notice Thrown when attempting to perform a multicall action with no permission for it\nerror NoPermissionException(uint256 permission);\n\n/// @notice Thrown when attempting to give a bot unexpected permissions\nerror UnexpectedPermissionsException();\n\n/// @notice Thrown when a custom HF parameter lower than 10000 is passed into the full collateral check\nerror CustomHealthFactorTooLowException();\n\n/// @notice Thrown when submitted collateral hint is not a valid token mask\nerror InvalidCollateralHintException();\n\n// ------ //\n// ACCESS //\n// ------ //\n\n/// @notice Thrown on attempting to call an access restricted function not as credit account owner\nerror CallerNotCreditAccountOwnerException();\n\n/// @notice Thrown on attempting to call an access restricted function not as configurator\nerror CallerNotConfiguratorException();\n\n/// @notice Thrown on attempting to call an access-restructed function not as account factory\nerror CallerNotAccountFactoryException();\n\n/// @notice Thrown on attempting to call an access restricted function not as credit manager\nerror CallerNotCreditManagerException();\n\n/// @notice Thrown on attempting to call an access restricted function not as credit facade\nerror CallerNotCreditFacadeException();\n\n/// @notice Thrown on attempting to call an access restricted function not as controller or configurator\nerror CallerNotControllerException();\n\n/// @notice Thrown on attempting to pause a contract without pausable admin rights\nerror CallerNotPausableAdminException();\n\n/// @notice Thrown on attempting to unpause a contract without unpausable admin rights\nerror CallerNotUnpausableAdminException();\n\n/// @notice Thrown on attempting to call an access restricted function not as gauge\nerror CallerNotGaugeException();\n\n/// @notice Thrown on attempting to call an access restricted function not as quota keeper\nerror CallerNotPoolQuotaKeeperException();\n\n/// @notice Thrown on attempting to call an access restricted function not as voter\nerror CallerNotVoterException();\n\n/// @notice Thrown on attempting to call an access restricted function not as allowed adapter\nerror CallerNotAdapterException();\n\n/// @notice Thrown on attempting to call an access restricted function not as migrator\nerror CallerNotMigratorException();\n\n/// @notice Thrown when an address that is not the designated executor attempts to execute a transaction\nerror CallerNotExecutorException();\n\n/// @notice Thrown on attempting to call an access restricted function not as veto admin\nerror CallerNotVetoAdminException();\n\n// ------------------- //\n// CONTROLLER TIMELOCK //\n// ------------------- //\n\n/// @notice Thrown when the new parameter values do not satisfy required conditions\nerror ParameterChecksFailedException();\n\n/// @notice Thrown when attempting to execute a non-queued transaction\nerror TxNotQueuedException();\n\n/// @notice Thrown when attempting to execute a transaction that is either immature or stale\nerror TxExecutedOutsideTimeWindowException();\n\n/// @notice Thrown when execution of a transaction fails\nerror TxExecutionRevertedException();\n\n/// @notice Thrown when the value of a parameter on execution is different from the value on queue\nerror ParameterChangedAfterQueuedTxException();\n\n// -------- //\n// BOT LIST //\n// -------- //\n\n/// @notice Thrown when attempting to set non-zero permissions for a forbidden or special bot\nerror InvalidBotException();\n\n// --------------- //\n// ACCOUNT FACTORY //\n// --------------- //\n\n/// @notice Thrown when trying to deploy second master credit account for a credit manager\nerror MasterCreditAccountAlreadyDeployedException();\n\n/// @notice Thrown when trying to rescue funds from a credit account that is currently in use\nerror CreditAccountIsInUseException();\n\n// ------------ //\n// PRICE ORACLE //\n// ------------ //\n\n/// @notice Thrown on attempting to set a token price feed to an address that is not a correct price feed\nerror IncorrectPriceFeedException();\n\n/// @notice Thrown on attempting to interact with a price feed for a token not added to the price oracle\nerror PriceFeedDoesNotExistException();\n\n/// @notice Thrown when price feed returns incorrect price for a token\nerror IncorrectPriceException();\n\n/// @notice Thrown when token's price feed becomes stale\nerror StalePriceException();\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n// EIP-2612 is Final as of 2022-11-01. This file is deprecated.\n\nimport \"./IERC20Permit.sol\";\n"
      },
      "node_modules/@1inch/solidity-utils/contracts/interfaces/IDaiLikePermit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IDaiLikePermit {\n    function permit(\n        address holder,\n        address spender,\n        uint256 nonce,\n        uint256 expiry,\n        bool allowed,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n}\n"
      },
      "node_modules/@1inch/solidity-utils/contracts/interfaces/IPermit2.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPermit2 {\n    struct PermitDetails {\n        // ERC20 token address\n        address token;\n        // the maximum amount allowed to spend\n        uint160 amount;\n        // timestamp at which a spender's token allowances become invalid\n        uint48 expiration;\n        // an incrementing value indexed per owner,token,and spender for each signature\n        uint48 nonce;\n    }\n    /// @notice The permit message signed for a single token allownce\n    struct PermitSingle {\n        // the permit data for a single token alownce\n        PermitDetails details;\n        // address permissioned on the allowed tokens\n        address spender;\n        // deadline on the permit signature\n        uint256 sigDeadline;\n    }\n    /// @notice Packed allowance\n    struct PackedAllowance {\n        // amount allowed\n        uint160 amount;\n        // permission expiry\n        uint48 expiration;\n        // an incrementing value indexed per owner,token,and spender for each signature\n        uint48 nonce;\n    }\n\n    function transferFrom(address user, address spender, uint160 amount, address token) external;\n\n    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;\n\n    function allowance(address user, address token, address spender) external view returns (PackedAllowance memory);\n}\n"
      },
      "node_modules/@1inch/solidity-utils/contracts/interfaces/IWETH.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IWETH is IERC20 {\n    function deposit() external payable;\n\n    function withdraw(uint256 amount) external;\n}\n"
      },
      "node_modules/@1inch/solidity-utils/contracts/libraries/RevertReasonForwarder.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @title Revert reason forwarder.\nlibrary RevertReasonForwarder {\n    /// @dev Forwards latest externall call revert.\n    function reRevert() internal pure {\n        // bubble up revert reason from latest external call\n        assembly (\"memory-safe\") { // solhint-disable-line no-inline-assembly\n            let ptr := mload(0x40)\n            returndatacopy(ptr, 0, returndatasize())\n            revert(ptr, returndatasize())\n        }\n    }\n}\n"
      },
      "node_modules/@openzeppelin/contracts/utils/math/SafeCast.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary 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 downcasted) {\n        downcasted = int248(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     *\n     * _Available since v4.7._\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     *\n     * _Available since v3.1._\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     *\n     * _Available since v3.0._\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n        return int256(value);\n    }\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\n/// @title Version interface\n/// @notice Defines contract version\ninterface IVersion {\n    /// @notice Contract version\n    function version() external view returns (uint256);\n}\n"
      },
      "node_modules/@openzeppelin/contracts/interfaces/IERC4626.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20.sol\";\nimport \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n *\n * _Available since v4.7._\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed sender,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /**\n     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function asset() external view returns (address assetTokenAddress);\n\n    /**\n     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n     *\n     * - SHOULD include any compounding that occurs from yield.\n     * - MUST be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT revert.\n     */\n    function totalAssets() external view returns (uint256 totalManagedAssets);\n\n    /**\n     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n     * through a deposit call.\n     *\n     * - MUST return a limited value if receiver is subject to some deposit limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n     * - MUST NOT revert.\n     */\n    function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n     *   in the same transaction.\n     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   deposit execution, and are accounted for during deposit.\n     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n     * - MUST return a limited value if receiver is subject to some mint limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n     * - MUST NOT revert.\n     */\n    function maxMint(address receiver) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n     *   same transaction.\n     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n     *   would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by minting.\n     */\n    function previewMint(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n     *   execution, and are accounted for during mint.\n     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n     * Vault, through a withdraw call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n     *   called\n     *   in the same transaction.\n     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   withdraw execution, and are accounted for during withdraw.\n     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n     * through a redeem call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n     *   same transaction.\n     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n     *   redemption would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n     */\n    function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   redeem execution, and are accounted for during redeem.\n     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "node_modules/@gearbox-protocol/core-v2/contracts/interfaces/IPriceOracleBase.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// Gearbox Protocol. Generalized leverage for DeFi protocols\n// (c) Gearbox Holdings, 2022\npragma solidity ^0.8.10;\n\nimport { IVersion } from \"./IVersion.sol\";\n\n/// @title Price oracle base interface\n/// @notice Functions shared accross newer and older versions\ninterface IPriceOracleBase is IVersion {\n    function getPrice(address token) external view returns (uint256);\n\n    function convertToUSD(\n        uint256 amount,\n        address token\n    ) external view returns (uint256);\n\n    function convertFromUSD(\n        uint256 amount,\n        address token\n    ) external view returns (uint256);\n\n    function convert(\n        uint256 amount,\n        address tokenFrom,\n        address tokenTo\n    ) external view returns (uint256);\n\n    function priceFeeds(\n        address token\n    ) external view returns (address priceFeed);\n}\n"
      },
      "node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@1inch/=node_modules/@1inch/",
        "@arbitrum/=node_modules/@arbitrum/",
        "@chainlink/=node_modules/@chainlink/",
        "@eth-optimism/=node_modules/@eth-optimism/",
        "@gearbox-protocol/=node_modules/@gearbox-protocol/",
        "@openzeppelin/=node_modules/@openzeppelin/",
        "@redstone-finance/=node_modules/@redstone-finance/",
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "eth-gas-reporter/=node_modules/eth-gas-reporter/",
        "forge-std/=lib/forge-std/src/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 1000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs"
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "london",
      "libraries": {}
    }
  }}