creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/Strategy.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.18;\n\nimport {ERC20} from \"@tokenized-strategy/BaseStrategy.sol\";\nimport {BaseHealthCheck} from \"@periphery/Bases/HealthCheck/BaseHealthCheck.sol\";\nimport {Auction, AuctionSwapper} from \"@periphery/swappers/AuctionSwapper.sol\";\n\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport {IERC20Pool} from \"@ajna-core/interfaces/pool/erc20/IERC20Pool.sol\";\nimport {COLLATERALIZATION_FACTOR} from \"@ajna-core/libraries/helpers/PoolHelper.sol\";\nimport {Maths} from \"@ajna-core/libraries/internal/Maths.sol\";\nimport {PoolCommons} from \"@ajna-core/libraries/external/PoolCommons.sol\";\n\nimport {IUniswapV3Pool} from \"@uniswap-v3-core/interfaces/IUniswapV3Pool.sol\";\nimport {IUniswapV3SwapCallback} from \"@uniswap-v3-core/interfaces/callback/IUniswapV3SwapCallback.sol\";\nimport {IUniswapV3Factory} from \"@uniswap-v3-core/interfaces/IUniswapV3Factory.sol\";\n\nimport {IWETH} from \"./interfaces/IWeth.sol\";\nimport {IAccount} from \"./interfaces/summerfi/IAccount.sol\";\nimport {IAccountFactory} from \"./interfaces/summerfi/IAccountFactory.sol\";\nimport {AjnaProxyActions} from \"./interfaces/summerfi/AjnaProxyActions.sol\";\nimport {IAjnaRedeemer} from \"./interfaces/summerfi/IAjnaRedeemer.sol\";\nimport {IChainlinkAggregator} from \"./interfaces/chainlink/IChainlinkAggregator.sol\";\n\ncontract Strategy is BaseHealthCheck, IUniswapV3SwapCallback, AuctionSwapper {\n    using SafeERC20 for ERC20;\n\n    IAccountFactory private constant SUMMERFI_ACCOUNT_FACTORY =\n        IAccountFactory(0xF7B75183A2829843dB06266c114297dfbFaeE2b6);\n    AjnaProxyActions private constant SUMMERFI_AJNA_PROXY_ACTIONS =\n        AjnaProxyActions(0x3637DF43F938b05A71bb828f13D9f14498E6883c);\n    //PoolInfoUtils private constant POOL_INFO_UTILS =\n    //    PoolInfoUtils(0x30c5eF2997d6a882DE52c4ec01B6D0a5e5B4fAAE);\n    IAjnaRedeemer private constant SUMMERFI_REWARDS =\n        IAjnaRedeemer(0xf309EE5603bF05E5614dB930E4EAB661662aCeE6);\n    IUniswapV3Factory private constant UNISWAP_FACTORY =\n        IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);\n\n    address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n    address private constant AJNA_TOKEN =\n        0x9a96ec9B57Fb64FbC60B423d1f4da7691Bd35079;\n\n    IAccount public immutable summerfiAccount;\n    IERC20Pool public immutable ajnaPool;\n    IChainlinkAggregator public immutable chainlinkOracle;\n    bool public immutable oracleWrapped;\n    bytes4 public immutable unwrappedToWrappedSelector;\n    bool private immutable uniswapAsset0Weth1;\n\n    uint96 public minAjnaToAuction = 1_000e18; // 1000 ajna\n    IUniswapV3Pool public uniswapPool;\n    bool public positionOpen;\n    uint16 public slippageAllowedBps = 50; // 0.50%\n    uint64 public maxTendBasefee = 30e9; // 30 gwei\n    uint256 public depositLimit;\n\n    struct LTVConfig {\n        uint64 targetLTV;\n        uint64 minAdjustThreshold;\n        uint64 warningThreshold;\n        uint64 emergencyThreshold;\n    }\n    LTVConfig public ltvs;\n\n    uint256 private constant ONE_WAD = 1e18;\n    uint64 internal constant DEFAULT_MIN_ADJUST_THRESHOLD = 0.005e18;\n    uint64 internal constant DEFAULT_WARNING_THRESHOLD = 0.01e18;\n    uint64 internal constant DEFAULT_EMERGENCY_THRESHOLD = 0.02e18;\n    uint64 internal constant DUST_THRESHOLD = 100; //0.00001e18;\n\n    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n    uint160 internal constant UNISWAP_MIN_SQRT_RATIO = 4295128739;\n    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n    uint160 internal constant UNISWAP_MAX_SQRT_RATIO =\n        1461446703485210103287273052203988822378723970342;\n\n    constructor(\n        address _asset,\n        string memory _name,\n        address _ajnaPool,\n        uint24 _uniswapFee,\n        bytes4 _unwrappedToWrappedSelector,\n        address _chainlinkOracle,\n        bool _oracleWrapped\n    ) BaseHealthCheck(_asset, _name) {\n        require(_asset == IERC20Pool(_ajnaPool).collateralAddress(), \"!collat\"); // dev: asset must be collateral\n        require(WETH == IERC20Pool(_ajnaPool).quoteTokenAddress(), \"!weth\"); // dev: quoteToken must be WETH\n\n        address _summerfiAccount = SUMMERFI_ACCOUNT_FACTORY.createAccount();\n\n        ajnaPool = IERC20Pool(_ajnaPool);\n        summerfiAccount = IAccount(_summerfiAccount);\n        unwrappedToWrappedSelector = _unwrappedToWrappedSelector;\n        chainlinkOracle = IChainlinkAggregator(_chainlinkOracle);\n        oracleWrapped = _oracleWrapped;\n        uniswapAsset0Weth1 = address(asset) < WETH;\n\n        ERC20(_asset).safeApprove(_summerfiAccount, type(uint256).max);\n\n        LTVConfig memory _ltvs;\n        _ltvs.minAdjustThreshold = DEFAULT_MIN_ADJUST_THRESHOLD;\n        _ltvs.warningThreshold = DEFAULT_WARNING_THRESHOLD;\n        _ltvs.emergencyThreshold = DEFAULT_EMERGENCY_THRESHOLD;\n        ltvs = _ltvs;\n\n        _setUniswapFee(_uniswapFee);\n    }\n\n    /*******************************************\n     *          PUBLIC VIEW FUNCTIONS          *\n     *******************************************/\n\n    /**\n     *  @notice Retrieves info related to our debt position\n     *  @return _debt             Current debt owed (`WAD`).\n     *  @return _collateral       Pledged collateral, including encumbered (`WAD`).\n     *  @return _t0Np             `Neutral price` (`WAD`).\n     *  @return _thresholdPrice   Borrower's `Threshold Price` (`WAD`).\n     */\n    function positionInfo()\n        external\n        view\n        returns (\n            uint256 _debt,\n            uint256 _collateral,\n            uint256 _t0Np,\n            uint256 _thresholdPrice\n        )\n    {\n        return _positionInfo();\n    }\n\n    /**\n     *  @return . The strategy's current LTV\n     */\n    function currentLTV() external view returns (uint256) {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        return _calculateLTV(_debt, _collateral, _getAssetPerWeth());\n    }\n\n    /**\n     * @notice A conservative estimate of assets taking into account\n     * the max slippage allowed\n     *\n     * @return . estimated total assets\n     */\n    function estimatedTotalAssets() external view returns (uint256) {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        uint256 _idle = _looseAssets();\n        return\n            _calculateNetPositionWithMaxSlippage(\n                _debt,\n                _collateral,\n                _getAssetPerWeth()\n            ) + _idle;\n    }\n\n    /**\n     * @notice A liberal estimate of assets not taking into account\n     * the max slippage allowed\n     *\n     * @return . estimated total assets\n     */\n    function estimatedTotalAssetsNoSlippage() external view returns (uint256) {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        // increase debt by max slippage, since we must swap all debt to exit our position\n        uint256 _idle = _looseAssets();\n        return\n            _calculateNetPosition(_debt, _collateral, _getAssetPerWeth()) +\n            _idle;\n    }\n\n    /*******************************************\n     *          MANAGEMENT FUNCTIONS           *\n     *******************************************/\n\n    /**\n     * @notice Sets the ltv configuration. Can only be called by management\n     * @param _ltvs The LTV configuration\n     */\n    function setLtvConfig(LTVConfig memory _ltvs) external onlyManagement {\n        require(_ltvs.warningThreshold < _ltvs.emergencyThreshold); // dev: warning must be less than emergency threshold\n        require(_ltvs.minAdjustThreshold < _ltvs.warningThreshold); // dev: minAdjust must be less than warning threshold\n        ltvs = _ltvs;\n    }\n\n    /**\n     * @notice Sets the uniswap fee tier. Can only be called by management\n     * @param _fee The uniswap fee tier to use for Asset<->Weth swaps\n     */\n    function setUniswapFee(uint24 _fee) external onlyManagement {\n        _setUniswapFee(_fee);\n    }\n\n    /**\n     * @notice Sets the deposit limit. Can only be called by management\n     * @param _depositLimit The deposit limit\n     */\n    function setDepositLimit(uint256 _depositLimit) external onlyManagement {\n        depositLimit = _depositLimit;\n    }\n\n    /**\n     * @notice Sets the slippage allowed on swaps. Can only be called by management\n     * @param _slippageAllowedBps The slippage allowed in basis points\n     */\n    function setSlippageAllowedBps(uint16 _slippageAllowedBps)\n        external\n        onlyManagement\n    {\n        require(_slippageAllowedBps <= MAX_BPS); // dev: cannot be more than 100%\n        slippageAllowedBps = _slippageAllowedBps;\n    }\n\n    /**\n     * @notice Sets the max base fee for tends. Can only be called by management\n     * @param _maxTendBasefee The maximum base fee allowed in non-emergency tends\n     */\n    function setMaxTendBasefee(uint64 _maxTendBasefee) external onlyManagement {\n        maxTendBasefee = _maxTendBasefee;\n    }\n\n    function setMinAjnaToAuction(uint96 _minAjnaToAuction)\n        external\n        onlyManagement\n    {\n        minAjnaToAuction = _minAjnaToAuction;\n    }\n\n    function setAuction(address _auction) external onlyEmergencyAuthorized {\n        if (_auction != address(0)) {\n            require(Auction(_auction).want() == address(asset)); // dev: wrong want\n        }\n        auction = _auction;\n    }\n\n    /***********************************************\n     *      BASE STRATEGY OVERRIDE FUNCTIONS       *\n     ***********************************************/\n\n    /**\n     * @dev Should deploy up to '_amount' of 'asset' in the yield source.\n     *\n     * This function is called at the end of a {deposit} or {mint}\n     * call. Meaning that unless a whitelist is implemented it will\n     * be entirely permissionless and thus can be sandwiched or otherwise\n     * manipulated.\n     *\n     * @param _amount The amount of 'asset' that the strategy should attempt\n     * to deposit in the yield source.\n     */\n    function _deployFunds(uint256 _amount) internal override {\n        if (!positionOpen) {\n            return;\n        }\n\n        _depositAndDraw(0, _amount, ONE_WAD, false); // deposit as collateral\n    }\n\n    /**\n     * @dev Will attempt to free the '_amount' of 'asset'.\n     *\n     * The amount of 'asset' that is already loose has already\n     * been accounted for.\n     *\n     * This function is called during {withdraw} and {redeem} calls.\n     * Meaning that unless a whitelist is implemented it will be\n     * entirely permissionless and thus can be sandwiched or otherwise\n     * manipulated.\n     *\n     * Should not rely on asset.balanceOf(address(this)) calls other than\n     * for diff accounting purposes.\n     *\n     * Any difference between `_amount` and what is actually freed will be\n     * counted as a loss and passed on to the withdrawer. This means\n     * care should be taken in times of illiquidity. It may be better to revert\n     * if withdraws are simply illiquid so not to realize incorrect losses.\n     *\n     * @param _amount, The amount of 'asset' to be freed.\n     */\n    function _freeFunds(uint256 _amount) internal override {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        uint256 _price = _getAssetPerWeth();\n        uint256 _positionValue = _calculateNetPosition(\n            _debt,\n            _collateral,\n            _price\n        ) + _looseAssets();\n        uint256 _totalAssets = TokenizedStrategy.totalAssets();\n        uint256 _deployed = _deployedAssets(_totalAssets);\n        if (_amount != _deployed && _positionValue < _totalAssets) {\n            _amount = (_amount * _positionValue) / _totalAssets;\n        }\n\n        LTVConfig memory _ltvs = ltvs;\n\n        _leverDown(_debt, _collateral, _amount, _ltvs, _price, _deployed);\n\n        (_debt, _collateral, , ) = _positionInfo();\n        require(\n            _calculateLTV(_debt, _collateral, _price) <\n                _ltvs.targetLTV + _ltvs.minAdjustThreshold,\n            \"!ltv\"\n        ); // dev: ltv in target\n    }\n\n    /**\n     * @dev Internal function to harvest all rewards, redeploy any idle\n     * funds and return an accurate accounting of all funds currently\n     * held by the Strategy.\n     *\n     * This should do any needed harvesting, rewards selling, accrual,\n     * redepositing etc. to get the most accurate view of current assets.\n     *\n     * NOTE: All applicable assets including loose assets should be\n     * accounted for in this function.\n     *\n     * Care should be taken when relying on oracles or swap values rather\n     * than actual amounts as all Strategy profit/loss accounting will\n     * be done based on this returned value.\n     *\n     * This can still be called post a shutdown, a strategist can check\n     * `TokenizedStrategy.isShutdown()` to decide if funds should be\n     * redeployed or simply realize any profits/losses.\n     *\n     * @return _totalAssets A trusted and accurate account for the total\n     * amount of 'asset' the strategy currently holds including idle funds.\n     */\n    function _harvestAndReport()\n        internal\n        override\n        returns (uint256 _totalAssets)\n    {\n        _adjustPosition(_looseAssets());\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        _totalAssets =\n            _calculateNetPositionWithMaxSlippage(\n                _debt,\n                _collateral,\n                _getAssetPerWeth()\n            ) +\n            _looseAssets();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    OPTIONAL TO OVERRIDE BY STRATEGIST\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev Optional function for strategist to override that can\n     *  be called in between reports.\n     *\n     * If '_tend' is used tendTrigger() will also need to be overridden.\n     *\n     * This call can only be called by a permissioned role so may be\n     * through protected relays.\n     *\n     * This can be used to harvest and compound rewards, deposit idle funds,\n     * perform needed position maintenance or anything else that doesn't need\n     * ssda full report for.\n     *\n     *   EX: A strategy that can not deposit funds without getting\n     *       sandwiched can use the tend when a certain threshold\n     *       of idle to totalAssets has been reached.\n     *\n     * The TokenizedStrategy contract will do all needed debt and idle updates\n     * after this has finished and will have no effect on PPS of the strategy\n     * till report() is called.\n     *\n     * @param _idle The current amount of idle funds that are available to deploy.\n     *\n     */\n    function _tend(uint256 _idle) internal override {\n        _adjustPosition(_idle);\n    }\n\n    /**\n     * @dev Optional trigger to override if tend() will be used by the strategy.\n     * This must be implemented if the strategy hopes to invoke _tend().\n     *\n     * @return . Should return true if tend() should be called by keeper or false if not.\n     *\n     */\n    function _tendTrigger() internal view override returns (bool) {\n        if (TokenizedStrategy.totalAssets() == 0 || !positionOpen) {\n            return false;\n        }\n\n        (\n            uint256 _debt,\n            uint256 _collateral,\n            ,\n            uint256 _thresholdPrice\n        ) = _positionInfo();\n        LTVConfig memory _ltvs = ltvs;\n        uint256 _assetPerWeth = _getAssetPerWeth();\n        uint256 _wethPerAsset = (ONE_WAD**2) / _assetPerWeth;\n        uint256 _currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);\n\n        // We need to lever down if the LTV is past the emergencyThreshold\n        // or the price is below the threshold price\n        if (\n            _currentLtv >= _ltvs.targetLTV + _ltvs.emergencyThreshold ||\n            _wethPerAsset <= _thresholdPrice\n        ) {\n            return true;\n        }\n\n        // All other checks can wait for low gas\n        if (block.basefee >= maxTendBasefee) {\n            return false;\n        }\n\n        // Tend if ltv is higher than the target range\n        if (_currentLtv >= _ltvs.targetLTV + _ltvs.warningThreshold) {\n            return true;\n        }\n\n        if (TokenizedStrategy.isShutdown()) {\n            return false;\n        }\n\n        // Tend if ltv is lower than target range\n        if (\n            _currentLtv != 0 &&\n            _currentLtv <= _ltvs.targetLTV - _ltvs.minAdjustThreshold &&\n            _availableWethBorrow() > DUST_THRESHOLD\n        ) {\n            return true;\n        }\n\n        return false;\n    }\n\n    /**\n     * @notice Gets the max amount of `asset` that an address can deposit.\n     * @dev Defaults to an unlimited amount for any address. But can\n     * be overridden by strategists.\n     *\n     * This function will be called before any deposit or mints to enforce\n     * any limits desired by the strategist. This can be used for either a\n     * traditional deposit limit or for implementing a whitelist etc.\n     *\n     *   EX:\n     *      if(isAllowed[_owner]) return super.availableDepositLimit(_owner);\n     *\n     * This does not need to take into account any conversion rates\n     * from shares to assets. But should know that any non max uint256\n     * amounts may be converted to shares. So it is recommended to keep\n     * custom amounts low enough as not to cause overflow when multiplied\n     * by `totalSupply`.\n     *\n     * @param . The address that is depositing into the strategy.\n     * @return . The available amount the `_owner` can deposit in terms of `asset`\n     *\n     */\n    function availableDepositLimit(\n        address /*_owner */\n    ) public view override returns (uint256) {\n        uint256 _totalAssets = TokenizedStrategy.totalAssets();\n        return _totalAssets >= depositLimit ? 0 : depositLimit - _totalAssets;\n    }\n\n    /**\n     * @dev Optional function for a strategist to override that will\n     * allow management to manually withdraw deployed funds from the\n     * yield source if a strategy is shutdown.\n     *\n     * This should attempt to free `_amount`, noting that `_amount` may\n     * be more than is currently deployed.\n     *\n     * NOTE: This will not realize any profits or losses. A separate\n     * {report} will be needed in order to record any profit/loss. If\n     * a report may need to be called after a shutdown it is important\n     * to check if the strategy is shutdown during {_harvestAndReport}\n     * so that it does not simply re-deploy all funds that had been freed.\n     *\n     * EX:\n     *   if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {\n     *       depositFunds...\n     *    }\n     *\n     * @param _amount The amount of asset to attempt to free.\n     *\n     */\n    function _emergencyWithdraw(uint256 _amount) internal override {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        uint256 _price = _getAssetPerWeth();\n\n        LTVConfig memory _ltvs = ltvs;\n\n        _leverDown(\n            _debt,\n            _collateral,\n            _amount,\n            _ltvs,\n            _price,\n            _deployedAssets()\n        );\n\n        (_debt, _collateral, , ) = _positionInfo();\n        require(\n            _calculateLTV(_debt, _collateral, _price) <\n                _ltvs.targetLTV + _ltvs.minAdjustThreshold,\n            \"!ltv\"\n        ); // dev: ltv in target\n    }\n\n    function _auctionKicked(address _token)\n        internal\n        virtual\n        override\n        returns (uint256 _kicked)\n    {\n        require(_token == AJNA_TOKEN); // dev: only sell ajna\n        _kicked = super._auctionKicked(_token);\n        require(_kicked >= minAjnaToAuction); // dev: too little\n    }\n\n    /**************************************************\n     *      EXTERNAL POSTION MANAGMENT FUNCTIONS      *\n     **************************************************/\n\n    /**\n     * @notice Allows emergency authorized to manually lever down\n     *\n     * @param _toLoose the amount of assets to attempt to loose\n     * @param _targetLTV the LTV ratio to target\n     * @param _force Ignore safety checks\n     */\n    function manualLeverDown(\n        uint256 _toLoose,\n        uint64 _targetLTV,\n        bool _force\n    ) external onlyEmergencyAuthorized {\n        (uint256 _debt, uint256 _collateral, , ) = _positionInfo();\n        uint256 _price = _getAssetPerWeth();\n\n        LTVConfig memory _ltvs = ltvs;\n        require(_force || _targetLTV <= ltvs.targetLTV); // dev: _targetLTV too high\n        _ltvs.targetLTV = _targetLTV;\n\n        _leverDown(\n            _debt,\n            _collateral,\n            _toLoose,\n            _ltvs,\n            _price,\n            _deployedAssets()\n        );\n\n        (_debt, _collateral, , ) = _positionInfo();\n        require(\n            _force ||\n                _calculateLTV(_debt, _collateral, _price) <\n                _ltvs.targetLTV + _ltvs.minAdjustThreshold,\n            \"!ltv\"\n        ); // dev: ltv in target\n    }\n\n    /**\n     * @notice Allows emergency authorized to manually repay and/or withdrwa\n     *\n     * @param  _debtAmount       Amount of debt to repay\n     * @param  _collateralAmount Amount of collateral to withdraw\n     * @param  _stamp            Whether to stamp the loan or not\n     */\n    function manualRepayWithdraw(\n        uint256 _debtAmount,\n        uint256 _collateralAmount,\n        bool _stamp\n    ) external onlyEmergencyAuthorized {\n        _repayWithdraw(_debtAmount, _collateralAmount, _stamp);\n    }\n\n    /**\n     * @notice Allows emergency authorized to manually swap asset<->weth or vice versa\n     *\n     * @param  _amountIn        Amount of input token\n     * @param  _minOut          Minimum output token acceptable\n     * @param  _assetForWeth    Whether to swap asset for weth or weth for asset\n     */\n    function manualSwap(\n        uint256 _amountIn,\n        uint64 _minOut,\n        bool _assetForWeth\n    ) external onlyEmergencyAuthorized {\n        bool zeroForOne = uniswapAsset0Weth1 ? _assetForWeth : !_assetForWeth;\n        bytes memory _data = abi.encode(\n            LeverData(LeverAction.ManualSwap, 0, 0, 0)\n        );\n\n        (int256 amount0, int256 amount1) = uniswapPool.swap(\n            address(this),\n            zeroForOne,\n            int256(_amountIn),\n            (\n                zeroForOne\n                    ? UNISWAP_MIN_SQRT_RATIO + 1\n                    : UNISWAP_MAX_SQRT_RATIO - 1\n            ),\n            _data\n        );\n\n        require(uint256(zeroForOne ? amount1 : amount0) >= _minOut); // dev: !minOut\n    }\n\n    /**\n     * @notice Claims summerfi ajna rewards\n     *\n     * Unguarded because there is no risk claiming\n     *\n     * @param _weeks An array of week numbers for which to claim rewards.\n     * @param _amounts An array of reward amounts to claim.\n     * @param _proofs An array of Merkle proofs, one for each corresponding week and amount given.\n     */\n    function redeemSummerAjnaRewards(\n        uint256[] calldata _weeks,\n        uint256[] calldata _amounts,\n        bytes32[][] calldata _proofs\n    ) external {\n        SUMMERFI_REWARDS.claimMultiple(_weeks, _amounts, _proofs);\n    }\n\n    /**************************************************\n     *      INTERNAL POSTION MANAGMENT FUNCTIONS      *\n     **************************************************/\n\n    /**\n     * @notice Adjusts the leveraged position\n     */\n    function _adjustPosition(uint256 _idle) internal {\n        (\n            uint256 _debt,\n            uint256 _collateral,\n            ,\n            uint256 _thresholdPrice\n        ) = _positionInfo();\n        LTVConfig memory _ltvs = ltvs;\n        uint256 _assetPerWeth = _getAssetPerWeth();\n        uint256 _wethPerAsset = ONE_WAD**2 / _assetPerWeth;\n        uint256 _currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);\n\n        if (\n            positionOpen &&\n            (_wethPerAsset <= _thresholdPrice ||\n                _currentLtv >= _ltvs.targetLTV + _ltvs.minAdjustThreshold)\n        ) {\n            _leverDown(\n                _debt,\n                _collateral,\n                0,\n                _ltvs,\n                _assetPerWeth,\n                _deployedAssets()\n            );\n        } else if (_currentLtv + _ltvs.minAdjustThreshold <= _ltvs.targetLTV) {\n            _leverUp(_debt, _collateral, _idle, _ltvs, _assetPerWeth);\n        } else {\n            return; // bail out if we are doing nothing\n        }\n\n        (_debt, _collateral, , _thresholdPrice) = _positionInfo();\n\n        _currentLtv = _calculateLTV(_debt, _collateral, _assetPerWeth);\n        require(\n            _currentLtv < _ltvs.targetLTV + _ltvs.minAdjustThreshold,\n            \"!ltv\"\n        ); // dev: not safe\n    }\n\n    enum LeverAction {\n        LeverUp,\n        LeverDown,\n        ClosePosition,\n        ManualSwap\n    }\n\n    struct LeverData {\n        LeverAction action;\n        uint256 assetToFree;\n        uint256 assetPerWeth;\n        uint256 totalCollateral;\n    }\n\n    /**\n     * @notice Levers up\n     */\n    function _leverUp(\n        uint256 _debt,\n        uint256 _collateral,\n        uint256 _idle,\n        LTVConfig memory _ltvs,\n        uint256 _assetPerWeth\n    ) internal {\n        uint256 _supply = _calculateNetPosition(\n            _debt,\n            _collateral,\n            _assetPerWeth\n        );\n\n        uint256 _targetBorrow = _getBorrowFromSupply(\n            _supply + _idle,\n            _ltvs.targetLTV,\n            _assetPerWeth\n        );\n\n        require(_targetBorrow > _debt); // dev: something is very wrong\n\n        uint256 _toBorrow = _targetBorrow - _debt;\n        uint256 _availableBorrow = _availableWethBorrow();\n        if (_availableBorrow < _toBorrow) {\n            _toBorrow = _availableBorrow;\n        }\n\n        if (_toBorrow < DUST_THRESHOLD || _debt + _toBorrow < _minLoanSize()) {\n            return;\n        }\n\n        _swapAndLeverUp(_toBorrow, _assetPerWeth);\n    }\n\n    /**\n     * @notice Levers down\n     */\n    function _leverDown(\n        uint256 _debt,\n        uint256 _collateral,\n        uint256 _assetToFree,\n        LTVConfig memory _ltvs,\n        uint256 _assetPerWeth,\n        uint256 _deployedAssets\n    ) internal {\n        uint256 _supply = _calculateNetPosition(\n            _debt,\n            _collateral,\n            _assetPerWeth\n        );\n\n        uint256 _targetBorrow;\n        if (_supply > _assetToFree) {\n            _targetBorrow = _getBorrowFromSupply(\n                _supply - _assetToFree,\n                _ltvs.targetLTV,\n                _assetPerWeth\n            );\n        } else {\n            _assetToFree = _supply;\n        }\n\n        if (_debt <= _targetBorrow) {\n            if (_assetToFree > DUST_THRESHOLD) {\n                _repayWithdraw(0, _assetToFree, false);\n            }\n            return;\n        }\n\n        uint256 _repaymentAmount;\n        unchecked {\n            _repaymentAmount = _debt - _targetBorrow;\n        }\n\n        if (_targetBorrow < _minLoanSize(-int256(_repaymentAmount))) {\n            _targetBorrow = 0;\n            _repaymentAmount = _debt;\n        }\n\n        bool _closePosition = _repaymentAmount == _debt &&\n            (_assetToFree == 0 ||\n                _assetToFree == _supply ||\n                _assetToFree >= _deployedAssets);\n\n        _swapAndLeverDown(\n            _repaymentAmount,\n            _assetToFree,\n            _closePosition,\n            _assetPerWeth,\n            _collateral\n        );\n    }\n\n    /**************************************************\n     *               UNISWAP FUNCTIONS                *\n     **************************************************/\n\n    function _swapAndLeverUp(uint256 _borrowAmount, uint256 _assetPerWeth)\n        private\n    {\n        bool zeroForOne = !uniswapAsset0Weth1;\n\n        bytes memory _data = abi.encode(\n            LeverData(\n                LeverAction.LeverUp,\n                uint256(0),\n                _assetPerWeth,\n                uint256(0)\n            )\n        );\n\n        /* (int256 amount0, int256 amount1) = */\n        uniswapPool.swap(\n            address(this),\n            zeroForOne,\n            int256(_borrowAmount),\n            (\n                zeroForOne\n                    ? UNISWAP_MIN_SQRT_RATIO + 1\n                    : UNISWAP_MAX_SQRT_RATIO - 1\n            ),\n            _data\n        );\n    }\n\n    function _swapAndLeverDown(\n        uint256 _repaymentAmount,\n        uint256 _assetToLoose,\n        bool _close,\n        uint256 _assetPerWeth,\n        uint256 _totalCollateral\n    ) private {\n        bool zeroForOne = uniswapAsset0Weth1;\n\n        bytes memory _data = abi.encode(\n            LeverData(\n                _close ? LeverAction.ClosePosition : LeverAction.LeverDown,\n                _assetToLoose,\n                _assetPerWeth,\n                _totalCollateral\n            )\n        );\n\n        (int256 amount0Delta, int256 amount1Delta) = uniswapPool.swap(\n            address(this),\n            zeroForOne,\n            -int256(_repaymentAmount),\n            (\n                zeroForOne\n                    ? UNISWAP_MIN_SQRT_RATIO + 1\n                    : UNISWAP_MAX_SQRT_RATIO - 1\n            ),\n            _data\n        );\n\n        uint256 _wethOut = uint256(zeroForOne ? -amount1Delta : -amount0Delta);\n\n        // it's technically possible to not receive the full output amount\n        // require this possibility away\n        require(_wethOut == _repaymentAmount); // dev: wethOut != _repaymentAmount\n    }\n\n    /// @inheritdoc IUniswapV3SwapCallback\n    function uniswapV3SwapCallback(\n        int256 _amount0Delta,\n        int256 _amount1Delta,\n        bytes calldata _data\n    ) external {\n        require(msg.sender == address(uniswapPool)); // dev: callback only called by pool\n        require(_amount0Delta > 0 || _amount1Delta > 0); // dev: swaps entirely within 0-liquidity regions are not supported\n\n        (\n            bool _isExactInput,\n            uint256 _amountToPay,\n            uint256 _amountReceived\n        ) = _amount0Delta > 0\n                ? (\n                    !uniswapAsset0Weth1,\n                    uint256(_amount0Delta),\n                    uint256(-_amount1Delta)\n                )\n                : (\n                    uniswapAsset0Weth1,\n                    uint256(_amount1Delta),\n                    uint256(-_amount0Delta)\n                );\n\n        LeverData memory _leverData = abi.decode(_data, (LeverData));\n\n        if (_leverData.action == LeverAction.LeverUp) {\n            require(_isExactInput); // dev: WTF\n\n            uint256 _leastAssetReceived = (((_amountToPay *\n                (MAX_BPS - slippageAllowedBps)) / MAX_BPS) *\n                _leverData.assetPerWeth) / ONE_WAD;\n            require(_amountReceived >= _leastAssetReceived, \"!slippage\"); // dev: too much slippage\n\n            uint256 _collateralToAdd = _looseAssets();\n            if (!positionOpen) {\n                positionOpen = true;\n                _openPosition(_amountToPay, _collateralToAdd, ONE_WAD);\n            } else {\n                _depositAndDraw(_amountToPay, _collateralToAdd, ONE_WAD, false);\n            }\n\n            ERC20(WETH).transfer(msg.sender, _amountToPay);\n        } else if (\n            _leverData.action == LeverAction.LeverDown ||\n            _leverData.action == LeverAction.ClosePosition\n        ) {\n            require(!_isExactInput); // dev: WTF\n            uint256 _expectedAssetToPay = (_amountReceived *\n                _leverData.assetPerWeth) / ONE_WAD;\n            uint256 _mostAssetToPay = (_expectedAssetToPay *\n                (MAX_BPS + slippageAllowedBps)) / MAX_BPS;\n\n            require(_amountToPay <= _mostAssetToPay, \"!slippage\"); // dev: too much slippage\n\n            if (_amountToPay > _expectedAssetToPay) {\n                // pass slippage onto the asset to free amount\n                uint256 _slippage = _amountToPay - _expectedAssetToPay;\n                if (_leverData.assetToFree > _slippage) {\n                    _leverData.assetToFree -= _slippage;\n                } else {\n                    _leverData.assetToFree = 0;\n                }\n            }\n\n            if (_leverData.action == LeverAction.LeverDown) {\n                _repayWithdraw(\n                    _amountReceived,\n                    Math.min(\n                        _amountToPay + _leverData.assetToFree,\n                        _leverData.totalCollateral\n                    ),\n                    false\n                );\n            } else if (_leverData.action == LeverAction.ClosePosition) {\n                positionOpen = false;\n                _repayAndClose(_amountReceived);\n            }\n            asset.transfer(msg.sender, _amountToPay);\n        } else if (_leverData.action == LeverAction.ManualSwap) {\n            //require(_isExactInput, \"!wtf\"); // dev: WTF\n\n            if (\n                (_amount0Delta > 0 && uniswapAsset0Weth1) ||\n                (_amount1Delta > 0 && !uniswapAsset0Weth1)\n            ) {\n                asset.transfer(msg.sender, _amountToPay);\n            } else {\n                ERC20(WETH).transfer(msg.sender, _amountToPay);\n            }\n        }\n    }\n\n    /**************************************************\n     *               INTERNAL VIEWS                   *\n     **************************************************/\n\n    /**\n     *  @notice Returns the strategy assets which are held as loose asset\n     *  @return . The strategy's loose asset\n     */\n    function _looseAssets() internal view returns (uint256) {\n        return asset.balanceOf(address(this));\n    }\n\n    /**\n     *  @notice Returns the strategy assets which are not idle\n     *  @return . The strategy's total debt\n     */\n    function _deployedAssets() internal view returns (uint256) {\n        return _deployedAssets(TokenizedStrategy.totalAssets());\n    }\n\n    /**\n     *  @notice Returns the strategy assets which are not idle\n     *  @return . The strategy's total debt\n     */\n    function _deployedAssets(uint256 _totalAssets)\n        internal\n        view\n        returns (uint256)\n    {\n        uint256 _idle = _looseAssets();\n        if (_idle >= _totalAssets) return 0;\n        return _totalAssets - _idle;\n    }\n\n    /**\n     *  @notice Retrieves info related to our debt position\n     *  @return _debt             Current debt owed (`WAD`).\n     *  @return _collateral       Pledged collateral, including encumbered (`WAD`).\n     *  @return _t0Np             `Neutral price` (`WAD`).\n     *  @return _thresholdPrice   Borrower's `Threshold Price` (`WAD`).\n     */\n    function _positionInfo()\n        internal\n        view\n        returns (\n            uint256 _debt,\n            uint256 _collateral,\n            uint256 _t0Np,\n            uint256 _thresholdPrice\n        )\n    {\n        IERC20Pool _ajnaPool = ajnaPool;\n\n        // copied from BUSL, am i going to open source jail?\n        (uint256 inflator, uint256 lastInflatorUpdate) = _ajnaPool\n            .inflatorInfo();\n\n        (uint256 interestRate, ) = _ajnaPool.interestRateInfo();\n\n        uint256 pendingInflator = PoolCommons.pendingInflator(\n            inflator,\n            lastInflatorUpdate,\n            interestRate\n        );\n\n        uint256 t0Debt;\n        uint256 npTpRatio;\n        (t0Debt, _collateral, npTpRatio) = _ajnaPool.borrowerInfo(\n            address(summerfiAccount)\n        );\n\n        _t0Np = _collateral == 0\n            ? 0\n            : Math.mulDiv(\n                Maths.wmul(t0Debt, COLLATERALIZATION_FACTOR),\n                npTpRatio,\n                _collateral\n            );\n        _debt = Maths.ceilWmul(t0Debt, pendingInflator);\n        _thresholdPrice = _collateral == 0\n            ? 0\n            : Maths.wmul(\n                Maths.wdiv(_debt, _collateral),\n                COLLATERALIZATION_FACTOR\n            );\n    }\n\n    /**\n     *  @notice Returns the amount of quote token available for borrowing or removing from pool.\n     *  @dev    Calculated as the difference between pool balance and escrowed amounts locked in\n     *  pool (auction bons + unclaimed reserves).\n     *  @return _amount   The total quote token amount available to borrow or to be removed from pool, in `WAD` units.\n     */\n    function _availableWethBorrow() internal view returns (uint256 _amount) {\n        IERC20Pool _ajnaPool = ajnaPool;\n\n        // copied from BUSL, am i going to open source jail?\n        (uint256 bondEscrowed, uint256 unclaimedReserve, , , ) = _ajnaPool\n            .reservesInfo();\n        uint256 escrowedAmounts = bondEscrowed + unclaimedReserve;\n\n        uint256 poolBalance = ERC20(WETH).balanceOf(address(_ajnaPool)) *\n            _ajnaPool.quoteTokenScale();\n\n        if (poolBalance > escrowedAmounts)\n            _amount = poolBalance - escrowedAmounts;\n    }\n\n    /**\n     *  @notice Retrieves the oracle rate asset/quoteToken\n     *  @return Conversion rate\n     */\n    function _getAssetPerWeth() internal view returns (uint256) {\n        uint256 _answer = (ONE_WAD**2) /\n            uint256(chainlinkOracle.latestAnswer());\n        if (oracleWrapped) {\n            return _answer;\n        }\n        return _unwrappedToWrappedAsset(_answer);\n    }\n\n    /**************************************************\n     *               INTERNAL SETTERS                 *\n     **************************************************/\n\n    function _setUniswapFee(uint24 _fee) internal {\n        IUniswapV3Pool _uniswapPool = IUniswapV3Pool(\n            UNISWAP_FACTORY.getPool(address(asset), WETH, _fee)\n        );\n        require(\n            _uniswapPool.token0() == address(asset) ||\n                _uniswapPool.token1() == address(asset)\n        ); // dev: pool must contain asset\n        require(\n            _uniswapPool.token0() == address(WETH) ||\n                _uniswapPool.token1() == address(WETH)\n        ); // dev: pool must contain weth\n        uniswapPool = _uniswapPool;\n    }\n\n    /**************************************************\n     *          POSITION HELPER FUNCTIONS             *\n     **************************************************/\n\n    /**\n     *  @notice Open position via account proxy\n     *  @param  _debtAmount     Amount of debt to borrow\n     *  @param  _collateralAmount Amount of collateral to deposit\n     *  @param  _price          Price of the bucket\n     */\n    function _openPosition(\n        uint256 _debtAmount,\n        uint256 _collateralAmount,\n        uint256 _price\n    ) internal {\n        summerfiAccount.execute(\n            address(SUMMERFI_AJNA_PROXY_ACTIONS),\n            abi.encodeCall(\n                SUMMERFI_AJNA_PROXY_ACTIONS.openPosition,\n                (ajnaPool, _debtAmount, _collateralAmount, _price)\n            )\n        );\n        IWETH(WETH).deposit{value: address(this).balance}(); // summer contracts use Ether not WETH\n    }\n\n    /**\n     *  @notice Deposit collateral and draw debt via account proxy\n     *  @param  _debtAmount     Amount of debt to borrow\n     *  @param  _collateralAmount Amount of collateral to deposit\n     *  @param  _price          Price of the bucket\n     *  @param  _stamp      Whether to stamp the loan or not\n     */\n    function _depositAndDraw(\n        uint256 _debtAmount,\n        uint256 _collateralAmount,\n        uint256 _price,\n        bool _stamp\n    ) internal {\n        summerfiAccount.execute(\n            address(SUMMERFI_AJNA_PROXY_ACTIONS),\n            abi.encodeCall(\n                SUMMERFI_AJNA_PROXY_ACTIONS.depositAndDraw,\n                (ajnaPool, _debtAmount, _collateralAmount, _price, _stamp)\n            )\n        );\n        IWETH(WETH).deposit{value: address(this).balance}(); // summer contracts use Ether not WETH\n    }\n\n    /**\n     *  @notice Repay debt and withdraw collateral via account proxy\n     *  @param  _debtAmount     Amount of debt to repay\n     *  @param  _collateralAmount Amount of collateral to withdraw\n     *  @param  _stamp      Whether to stamp the loan or not\n     */\n    function _repayWithdraw(\n        uint256 _debtAmount,\n        uint256 _collateralAmount,\n        bool _stamp\n    ) internal {\n        if (_debtAmount != 0) {\n            IWETH(WETH).withdraw(_debtAmount); // summer contracts use Ether not WETH\n        }\n        summerfiAccount.execute{value: _debtAmount}(\n            address(SUMMERFI_AJNA_PROXY_ACTIONS),\n            abi.encodeCall(\n                SUMMERFI_AJNA_PROXY_ACTIONS.repayWithdraw,\n                (ajnaPool, _debtAmount, _collateralAmount, _stamp)\n            )\n        );\n    }\n\n    /**\n     *  @notice Repay debt and close position via account proxy\n     */\n    function _repayAndClose(uint256 _debtAmount) internal {\n        if (_debtAmount != 0) {\n            IWETH(WETH).withdraw(_debtAmount); // summer contracts use Ether not WETH\n        }\n        summerfiAccount.execute{value: _debtAmount}(\n            address(SUMMERFI_AJNA_PROXY_ACTIONS),\n            abi.encodeCall(\n                SUMMERFI_AJNA_PROXY_ACTIONS.repayAndClose,\n                (ajnaPool)\n            )\n        );\n        uint256 _balance = address(this).balance;\n        if (_balance != 0) {\n            IWETH(WETH).deposit{value: _balance}();\n        }\n    }\n\n    function _unwrappedToWrappedAsset(uint256 _amount)\n        internal\n        view\n        returns (uint256)\n    {\n        (bool success, bytes memory data) = address(asset).staticcall(\n            abi.encodeWithSelector(unwrappedToWrappedSelector, _amount)\n        );\n        require(success, \"!success\"); // dev: static call failed\n        return abi.decode(data, (uint256));\n    }\n\n    function _minLoanSize() internal view returns (uint256) {\n        return _minLoanSize(0);\n    }\n\n    function _minLoanSize(int256 _debtDelta)\n        internal\n        view\n        returns (uint256 _minDebtAmount)\n    {\n        IERC20Pool _ajnaPool = ajnaPool;\n        (uint256 _poolDebt, , , ) = _ajnaPool.debtInfo();\n        (, , uint256 _noOfLoans) = _ajnaPool.loansInfo();\n\n        if (_noOfLoans >= 10) {\n            // minimum debt is 10% of the average loan size\n            _minDebtAmount =\n                (uint256(int256(_poolDebt) + _debtDelta) / _noOfLoans) /\n                10;\n        }\n    }\n\n    /************************************************************************\n     *                      Position Math Functions                         *\n     ************************************************************************/\n\n    function _getBorrowFromSupply(\n        uint256 _supply,\n        uint256 _collatRatio,\n        uint256 _assetPerWeth\n    ) internal pure returns (uint256) {\n        if (_collatRatio == 0) {\n            return 0;\n        }\n        return\n            (((_supply * _collatRatio) / (ONE_WAD - _collatRatio)) * ONE_WAD) /\n            _assetPerWeth;\n    }\n\n    function _calculateLTV(\n        uint256 _debt,\n        uint256 _collateral,\n        uint256 _assetPerWeth\n    ) internal pure returns (uint256) {\n        if (_debt == 0 || _collateral == 0) {\n            return 0;\n        }\n        return (_debt * _assetPerWeth) / _collateral;\n    }\n\n    function _calculateNetPositionWithMaxSlippage(\n        uint256 _debt,\n        uint256 _collateral,\n        uint256 _assetPerWeth\n    ) internal view returns (uint256) {\n        // inflate debt by max slippage value\n        _debt = (_debt * (MAX_BPS + slippageAllowedBps)) / MAX_BPS;\n        return _calculateNetPosition(_debt, _collateral, _assetPerWeth);\n    }\n\n    function _calculateNetPosition(\n        uint256 _debt,\n        uint256 _collateral,\n        uint256 _assetPerWeth\n    ) internal pure returns (uint256) {\n        _debt = (_debt * _assetPerWeth) / ONE_WAD;\n        if (_debt >= _collateral || _collateral == 0) {\n            return 0;\n        }\n        unchecked {\n            return _collateral - _debt;\n        }\n    }\n\n    // Needed to receive ETH\n    receive() external payable {}\n}\n"
      },
      "lib/tokenized-strategy/src/BaseStrategy.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\n// TokenizedStrategy interface used for internal view delegateCalls.\nimport {ITokenizedStrategy} from \"./interfaces/ITokenizedStrategy.sol\";\n\n/**\n * @title YearnV3 Base Strategy\n * @author yearn.finance\n * @notice\n *  BaseStrategy implements all of the required functionality to\n *  seamlessly integrate with the `TokenizedStrategy` implementation contract\n *  allowing anyone to easily build a fully permissionless ERC-4626 compliant\n *  Vault by inheriting this contract and overriding three simple functions.\n\n *  It utilizes an immutable proxy pattern that allows the BaseStrategy\n *  to remain simple and small. All standard logic is held within the\n *  `TokenizedStrategy` and is reused over any n strategies all using the\n *  `fallback` function to delegatecall the implementation so that strategists\n *  can only be concerned with writing their strategy specific code.\n *\n *  This contract should be inherited and the three main abstract methods\n *  `_deployFunds`, `_freeFunds` and `_harvestAndReport` implemented to adapt\n *  the Strategy to the particular needs it has to generate yield. There are\n *  other optional methods that can be implemented to further customize\n *  the strategy if desired.\n *\n *  All default storage for the strategy is controlled and updated by the\n *  `TokenizedStrategy`. The implementation holds a storage struct that\n *  contains all needed global variables in a manual storage slot. This\n *  means strategists can feel free to implement their own custom storage\n *  variables as they need with no concern of collisions. All global variables\n *  can be viewed within the Strategy by a simple call using the\n *  `TokenizedStrategy` variable. IE: TokenizedStrategy.globalVariable();.\n */\nabstract contract BaseStrategy {\n    /*//////////////////////////////////////////////////////////////\n                            MODIFIERS\n    //////////////////////////////////////////////////////////////*/\n    /**\n     * @dev Used on TokenizedStrategy callback functions to make sure it is post\n     * a delegateCall from this address to the TokenizedStrategy.\n     */\n    modifier onlySelf() {\n        _onlySelf();\n        _;\n    }\n\n    /**\n     * @dev Use to assure that the call is coming from the strategies management.\n     */\n    modifier onlyManagement() {\n        TokenizedStrategy.requireManagement(msg.sender);\n        _;\n    }\n\n    /**\n     * @dev Use to assure that the call is coming from either the strategies\n     * management or the keeper.\n     */\n    modifier onlyKeepers() {\n        TokenizedStrategy.requireKeeperOrManagement(msg.sender);\n        _;\n    }\n\n    /**\n     * @dev Use to assure that the call is coming from either the strategies\n     * management or the emergency admin.\n     */\n    modifier onlyEmergencyAuthorized() {\n        TokenizedStrategy.requireEmergencyAuthorized(msg.sender);\n        _;\n    }\n\n    /**\n     * @dev Require that the msg.sender is this address.\n     */\n    function _onlySelf() internal view {\n        require(msg.sender == address(this), \"!self\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            CONSTANTS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev This is the address of the TokenizedStrategy implementation\n     * contract that will be used by all strategies to handle the\n     * accounting, logic, storage etc.\n     *\n     * Any external calls to the that don't hit one of the functions\n     * defined in this base or the strategy will end up being forwarded\n     * through the fallback function, which will delegateCall this address.\n     *\n     * This address should be the same for every strategy, never be adjusted\n     * and always be checked before any integration with the Strategy.\n     */\n    address public constant tokenizedStrategyAddress =\n        0xBB51273D6c746910C7C06fe718f30c936170feD0;\n\n    /*//////////////////////////////////////////////////////////////\n                            IMMUTABLES\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev Underlying asset the Strategy is earning yield on.\n     * Stored here for cheap retrievals within the strategy.\n     */\n    ERC20 internal immutable asset;\n\n    /**\n     * @dev This variable is set to address(this) during initialization of each strategy.\n     *\n     * This can be used to retrieve storage data within the strategy\n     * contract as if it were a linked library.\n     *\n     *       i.e. uint256 totalAssets = TokenizedStrategy.totalAssets()\n     *\n     * Using address(this) will mean any calls using this variable will lead\n     * to a call to itself. Which will hit the fallback function and\n     * delegateCall that to the actual TokenizedStrategy.\n     */\n    ITokenizedStrategy internal immutable TokenizedStrategy;\n\n    /**\n     * @notice Used to initialize the strategy on deployment.\n     *\n     * This will set the `TokenizedStrategy` variable for easy\n     * internal view calls to the implementation. As well as\n     * initializing the default storage variables based on the\n     * parameters and using the deployer for the permissioned roles.\n     *\n     * @param _asset Address of the underlying asset.\n     * @param _name Name the strategy will use.\n     */\n    constructor(address _asset, string memory _name) {\n        asset = ERC20(_asset);\n\n        // Set instance of the implementation for internal use.\n        TokenizedStrategy = ITokenizedStrategy(address(this));\n\n        // Initialize the strategy's storage variables.\n        _delegateCall(\n            abi.encodeCall(\n                ITokenizedStrategy.initialize,\n                (_asset, _name, msg.sender, msg.sender, msg.sender)\n            )\n        );\n\n        // Store the tokenizedStrategyAddress at the standard implementation\n        // address storage slot so etherscan picks up the interface. This gets\n        // stored on initialization and never updated.\n        assembly {\n            sstore(\n                // keccak256('eip1967.proxy.implementation' - 1)\n                0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,\n                tokenizedStrategyAddress\n            )\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                NEEDED TO BE OVERRIDDEN BY STRATEGIST\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev Can deploy up to '_amount' of 'asset' in the yield source.\n     *\n     * This function is called at the end of a {deposit} or {mint}\n     * call. Meaning that unless a whitelist is implemented it will\n     * be entirely permissionless and thus can be sandwiched or otherwise\n     * manipulated.\n     *\n     * @param _amount The amount of 'asset' that the strategy can attempt\n     * to deposit in the yield source.\n     */\n    function _deployFunds(uint256 _amount) internal virtual;\n\n    /**\n     * @dev Should attempt to free the '_amount' of 'asset'.\n     *\n     * NOTE: The amount of 'asset' that is already loose has already\n     * been accounted for.\n     *\n     * This function is called during {withdraw} and {redeem} calls.\n     * Meaning that unless a whitelist is implemented it will be\n     * entirely permissionless and thus can be sandwiched or otherwise\n     * manipulated.\n     *\n     * Should not rely on asset.balanceOf(address(this)) calls other than\n     * for diff accounting purposes.\n     *\n     * Any difference between `_amount` and what is actually freed will be\n     * counted as a loss and passed on to the withdrawer. This means\n     * care should be taken in times of illiquidity. It may be better to revert\n     * if withdraws are simply illiquid so not to realize incorrect losses.\n     *\n     * @param _amount, The amount of 'asset' to be freed.\n     */\n    function _freeFunds(uint256 _amount) internal virtual;\n\n    /**\n     * @dev Internal function to harvest all rewards, redeploy any idle\n     * funds and return an accurate accounting of all funds currently\n     * held by the Strategy.\n     *\n     * This should do any needed harvesting, rewards selling, accrual,\n     * redepositing etc. to get the most accurate view of current assets.\n     *\n     * NOTE: All applicable assets including loose assets should be\n     * accounted for in this function.\n     *\n     * Care should be taken when relying on oracles or swap values rather\n     * than actual amounts as all Strategy profit/loss accounting will\n     * be done based on this returned value.\n     *\n     * This can still be called post a shutdown, a strategist can check\n     * `TokenizedStrategy.isShutdown()` to decide if funds should be\n     * redeployed or simply realize any profits/losses.\n     *\n     * @return _totalAssets A trusted and accurate account for the total\n     * amount of 'asset' the strategy currently holds including idle funds.\n     */\n    function _harvestAndReport()\n        internal\n        virtual\n        returns (uint256 _totalAssets);\n\n    /*//////////////////////////////////////////////////////////////\n                    OPTIONAL TO OVERRIDE BY STRATEGIST\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev Optional function for strategist to override that can\n     *  be called in between reports.\n     *\n     * If '_tend' is used tendTrigger() will also need to be overridden.\n     *\n     * This call can only be called by a permissioned role so may be\n     * through protected relays.\n     *\n     * This can be used to harvest and compound rewards, deposit idle funds,\n     * perform needed position maintenance or anything else that doesn't need\n     * a full report for.\n     *\n     *   EX: A strategy that can not deposit funds without getting\n     *       sandwiched can use the tend when a certain threshold\n     *       of idle to totalAssets has been reached.\n     *\n     * This will have no effect on PPS of the strategy till report() is called.\n     *\n     * @param _totalIdle The current amount of idle funds that are available to deploy.\n     */\n    function _tend(uint256 _totalIdle) internal virtual {}\n\n    /**\n     * @dev Optional trigger to override if tend() will be used by the strategy.\n     * This must be implemented if the strategy hopes to invoke _tend().\n     *\n     * @return . Should return true if tend() should be called by keeper or false if not.\n     */\n    function _tendTrigger() internal view virtual returns (bool) {\n        return false;\n    }\n\n    /**\n     * @notice Returns if tend() should be called by a keeper.\n     *\n     * @return . Should return true if tend() should be called by keeper or false if not.\n     * @return . Calldata for the tend call.\n     */\n    function tendTrigger() external view virtual returns (bool, bytes memory) {\n        return (\n            // Return the status of the tend trigger.\n            _tendTrigger(),\n            // And the needed calldata either way.\n            abi.encodeWithSelector(ITokenizedStrategy.tend.selector)\n        );\n    }\n\n    /**\n     * @notice Gets the max amount of `asset` that an address can deposit.\n     * @dev Defaults to an unlimited amount for any address. But can\n     * be overridden by strategists.\n     *\n     * This function will be called before any deposit or mints to enforce\n     * any limits desired by the strategist. This can be used for either a\n     * traditional deposit limit or for implementing a whitelist etc.\n     *\n     *   EX:\n     *      if(isAllowed[_owner]) return super.availableDepositLimit(_owner);\n     *\n     * This does not need to take into account any conversion rates\n     * from shares to assets. But should know that any non max uint256\n     * amounts may be converted to shares. So it is recommended to keep\n     * custom amounts low enough as not to cause overflow when multiplied\n     * by `totalSupply`.\n     *\n     * @param . The address that is depositing into the strategy.\n     * @return . The available amount the `_owner` can deposit in terms of `asset`\n     */\n    function availableDepositLimit(\n        address /*_owner*/\n    ) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n     * @notice Gets the max amount of `asset` that can be withdrawn.\n     * @dev Defaults to an unlimited amount for any address. But can\n     * be overridden by strategists.\n     *\n     * This function will be called before any withdraw or redeem to enforce\n     * any limits desired by the strategist. This can be used for illiquid\n     * or sandwichable strategies. It should never be lower than `totalIdle`.\n     *\n     *   EX:\n     *       return TokenIzedStrategy.totalIdle();\n     *\n     * This does not need to take into account the `_owner`'s share balance\n     * or conversion rates from shares to assets.\n     *\n     * @param . The address that is withdrawing from the strategy.\n     * @return . The available amount that can be withdrawn in terms of `asset`\n     */\n    function availableWithdrawLimit(\n        address /*_owner*/\n    ) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n     * @dev Optional function for a strategist to override that will\n     * allow management to manually withdraw deployed funds from the\n     * yield source if a strategy is shutdown.\n     *\n     * This should attempt to free `_amount`, noting that `_amount` may\n     * be more than is currently deployed.\n     *\n     * NOTE: This will not realize any profits or losses. A separate\n     * {report} will be needed in order to record any profit/loss. If\n     * a report may need to be called after a shutdown it is important\n     * to check if the strategy is shutdown during {_harvestAndReport}\n     * so that it does not simply re-deploy all funds that had been freed.\n     *\n     * EX:\n     *   if(freeAsset > 0 && !TokenizedStrategy.isShutdown()) {\n     *       depositFunds...\n     *    }\n     *\n     * @param _amount The amount of asset to attempt to free.\n     */\n    function _emergencyWithdraw(uint256 _amount) internal virtual {}\n\n    /*//////////////////////////////////////////////////////////////\n                        TokenizedStrategy HOOKS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Can deploy up to '_amount' of 'asset' in yield source.\n     * @dev Callback for the TokenizedStrategy to call during a {deposit}\n     * or {mint} to tell the strategy it can deploy funds.\n     *\n     * Since this can only be called after a {deposit} or {mint}\n     * delegateCall to the TokenizedStrategy msg.sender == address(this).\n     *\n     * Unless a whitelist is implemented this will be entirely permissionless\n     * and thus can be sandwiched or otherwise manipulated.\n     *\n     * @param _amount The amount of 'asset' that the strategy can\n     * attempt to deposit in the yield source.\n     */\n    function deployFunds(uint256 _amount) external virtual onlySelf {\n        _deployFunds(_amount);\n    }\n\n    /**\n     * @notice Should attempt to free the '_amount' of 'asset'.\n     * @dev Callback for the TokenizedStrategy to call during a withdraw\n     * or redeem to free the needed funds to service the withdraw.\n     *\n     * This can only be called after a 'withdraw' or 'redeem' delegateCall\n     * to the TokenizedStrategy so msg.sender == address(this).\n     *\n     * @param _amount The amount of 'asset' that the strategy should attempt to free up.\n     */\n    function freeFunds(uint256 _amount) external virtual onlySelf {\n        _freeFunds(_amount);\n    }\n\n    /**\n     * @notice Returns the accurate amount of all funds currently\n     * held by the Strategy.\n     * @dev Callback for the TokenizedStrategy to call during a report to\n     * get an accurate accounting of assets the strategy controls.\n     *\n     * This can only be called after a report() delegateCall to the\n     * TokenizedStrategy so msg.sender == address(this).\n     *\n     * @return . A trusted and accurate account for the total amount\n     * of 'asset' the strategy currently holds including idle funds.\n     */\n    function harvestAndReport() external virtual onlySelf returns (uint256) {\n        return _harvestAndReport();\n    }\n\n    /**\n     * @notice Will call the internal '_tend' when a keeper tends the strategy.\n     * @dev Callback for the TokenizedStrategy to initiate a _tend call in the strategy.\n     *\n     * This can only be called after a tend() delegateCall to the TokenizedStrategy\n     * so msg.sender == address(this).\n     *\n     * We name the function `tendThis` so that `tend` calls are forwarded to\n     * the TokenizedStrategy.\n\n     * @param _totalIdle The amount of current idle funds that can be\n     * deployed during the tend\n     */\n    function tendThis(uint256 _totalIdle) external virtual onlySelf {\n        _tend(_totalIdle);\n    }\n\n    /**\n     * @notice Will call the internal '_emergencyWithdraw' function.\n     * @dev Callback for the TokenizedStrategy during an emergency withdraw.\n     *\n     * This can only be called after a emergencyWithdraw() delegateCall to\n     * the TokenizedStrategy so msg.sender == address(this).\n     *\n     * We name the function `shutdownWithdraw` so that `emergencyWithdraw`\n     * calls are forwarded to the TokenizedStrategy.\n     *\n     * @param _amount The amount of asset to attempt to free.\n     */\n    function shutdownWithdraw(uint256 _amount) external virtual onlySelf {\n        _emergencyWithdraw(_amount);\n    }\n\n    /**\n     * @dev Function used to delegate call the TokenizedStrategy with\n     * certain `_calldata` and return any return values.\n     *\n     * This is used to setup the initial storage of the strategy, and\n     * can be used by strategist to forward any other call to the\n     * TokenizedStrategy implementation.\n     *\n     * @param _calldata The abi encoded calldata to use in delegatecall.\n     * @return . The return value if the call was successful in bytes.\n     */\n    function _delegateCall(\n        bytes memory _calldata\n    ) internal returns (bytes memory) {\n        // Delegate call the tokenized strategy with provided calldata.\n        (bool success, bytes memory result) = tokenizedStrategyAddress\n            .delegatecall(_calldata);\n\n        // If the call reverted. Return the error.\n        if (!success) {\n            assembly {\n                let ptr := mload(0x40)\n                let size := returndatasize()\n                returndatacopy(ptr, 0, size)\n                revert(ptr, size)\n            }\n        }\n\n        // Return the result.\n        return result;\n    }\n\n    /**\n     * @dev Execute a function on the TokenizedStrategy and return any value.\n     *\n     * This fallback function will be executed when any of the standard functions\n     * defined in the TokenizedStrategy are called since they wont be defined in\n     * this contract.\n     *\n     * It will delegatecall the TokenizedStrategy implementation with the exact\n     * calldata and return any relevant values.\n     *\n     */\n    fallback() external {\n        // load our target address\n        address _tokenizedStrategyAddress = tokenizedStrategyAddress;\n        // Execute external function using delegatecall and return any value.\n        assembly {\n            // Copy function selector and any arguments.\n            calldatacopy(0, 0, calldatasize())\n            // Execute function delegatecall.\n            let result := delegatecall(\n                gas(),\n                _tokenizedStrategyAddress,\n                0,\n                calldatasize(),\n                0,\n                0\n            )\n            // Get any return value\n            returndatacopy(0, 0, returndatasize())\n            // Return any return value or error back to the caller\n            switch result\n            case 0 {\n                revert(0, returndatasize())\n            }\n            default {\n                return(0, returndatasize())\n            }\n        }\n    }\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/Bases/HealthCheck/BaseHealthCheck.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {BaseStrategy, ERC20} from \"@tokenized-strategy/BaseStrategy.sol\";\n\n/**\n *   @title Base Health Check\n *   @author Yearn.finance\n *   @notice This contract can be inherited by any Yearn\n *   V3 strategy wishing to implement a health check during\n *   the `report` function in order to prevent any unexpected\n *   behavior from being permanently recorded as well as the\n *   `checkHealth` modifier.\n *\n *   A strategist simply needs to inherit this contract. Set\n *   the limit ratios to the desired amounts and then\n *   override `_harvestAndReport()` just as they otherwise\n *  would. If the profit or loss that would be recorded is\n *   outside the acceptable bounds the tx will revert.\n *\n *   The healthcheck does not prevent a strategy from reporting\n *   losses, but rather can make sure manual intervention is\n *   needed before reporting an unexpected loss or profit.\n */\nabstract contract BaseHealthCheck is BaseStrategy {\n    // Can be used to determine if a healthcheck should be called.\n    // Defaults to true;\n    bool public doHealthCheck = true;\n\n    uint256 internal constant MAX_BPS = 10_000;\n\n    // Default profit limit to 100%.\n    uint16 private _profitLimitRatio = uint16(MAX_BPS);\n\n    // Defaults loss limit to 0.\n    uint16 private _lossLimitRatio;\n\n    constructor(\n        address _asset,\n        string memory _name\n    ) BaseStrategy(_asset, _name) {}\n\n    /**\n     * @notice Returns the current profit limit ratio.\n     * @dev Use a getter function to keep the variable private.\n     * @return . The current profit limit ratio.\n     */\n    function profitLimitRatio() public view returns (uint256) {\n        return _profitLimitRatio;\n    }\n\n    /**\n     * @notice Returns the current loss limit ratio.\n     * @dev Use a getter function to keep the variable private.\n     * @return . The current loss limit ratio.\n     */\n    function lossLimitRatio() public view returns (uint256) {\n        return _lossLimitRatio;\n    }\n\n    /**\n     * @notice Set the `profitLimitRatio`.\n     * @dev Denominated in basis points. I.E. 1_000 == 10%.\n     * @param _newProfitLimitRatio The mew profit limit ratio.\n     */\n    function setProfitLimitRatio(\n        uint256 _newProfitLimitRatio\n    ) external onlyManagement {\n        _setProfitLimitRatio(_newProfitLimitRatio);\n    }\n\n    /**\n     * @dev Internally set the profit limit ratio. Denominated\n     * in basis points. I.E. 1_000 == 10%.\n     * @param _newProfitLimitRatio The mew profit limit ratio.\n     */\n    function _setProfitLimitRatio(uint256 _newProfitLimitRatio) internal {\n        require(_newProfitLimitRatio > 0, \"!zero profit\");\n        require(_newProfitLimitRatio <= type(uint16).max, \"!too high\");\n        _profitLimitRatio = uint16(_newProfitLimitRatio);\n    }\n\n    /**\n     * @notice Set the `lossLimitRatio`.\n     * @dev Denominated in basis points. I.E. 1_000 == 10%.\n     * @param _newLossLimitRatio The new loss limit ratio.\n     */\n    function setLossLimitRatio(\n        uint256 _newLossLimitRatio\n    ) external onlyManagement {\n        _setLossLimitRatio(_newLossLimitRatio);\n    }\n\n    /**\n     * @dev Internally set the loss limit ratio. Denominated\n     * in basis points. I.E. 1_000 == 10%.\n     * @param _newLossLimitRatio The new loss limit ratio.\n     */\n    function _setLossLimitRatio(uint256 _newLossLimitRatio) internal {\n        require(_newLossLimitRatio < MAX_BPS, \"!loss limit\");\n        _lossLimitRatio = uint16(_newLossLimitRatio);\n    }\n\n    /**\n     * @notice Turns the healthcheck on and off.\n     * @dev If turned off the next report will auto turn it back on.\n     * @param _doHealthCheck Bool if healthCheck should be done.\n     */\n    function setDoHealthCheck(bool _doHealthCheck) public onlyManagement {\n        doHealthCheck = _doHealthCheck;\n    }\n\n    /**\n     * @notice OVerrides the default {harvestAndReport} to include a healthcheck.\n     * @return _totalAssets New totalAssets post report.\n     */\n    function harvestAndReport()\n        external\n        override\n        onlySelf\n        returns (uint256 _totalAssets)\n    {\n        // Let the strategy report.\n        _totalAssets = _harvestAndReport();\n\n        // Run the healthcheck on the amount returned.\n        _executeHealthCheck(_totalAssets);\n    }\n\n    /**\n     * @dev To be called during a report to make sure the profit\n     * or loss being recorded is within the acceptable bound.\n     *\n     * @param _newTotalAssets The amount that will be reported.\n     */\n    function _executeHealthCheck(uint256 _newTotalAssets) internal virtual {\n        if (!doHealthCheck) {\n            doHealthCheck = true;\n            return;\n        }\n\n        // Get the current total assets from the implementation.\n        uint256 currentTotalAssets = TokenizedStrategy.totalAssets();\n\n        if (_newTotalAssets > currentTotalAssets) {\n            require(\n                ((_newTotalAssets - currentTotalAssets) <=\n                    (currentTotalAssets * uint256(_profitLimitRatio)) /\n                        MAX_BPS),\n                \"healthCheck\"\n            );\n        } else if (currentTotalAssets > _newTotalAssets) {\n            require(\n                (currentTotalAssets - _newTotalAssets <=\n                    ((currentTotalAssets * uint256(_lossLimitRatio)) /\n                        MAX_BPS)),\n                \"healthCheck\"\n            );\n        }\n    }\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/swappers/AuctionSwapper.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {AuctionFactory, Auction} from \"../Auctions/AuctionFactory.sol\";\n\n/**\n *   @title AuctionSwapper\n *   @author yearn.fi\n *   @dev Helper contract for a strategy to use dutch auctions for token sales.\n *\n *   This contract is meant to be inherited by a V3 strategy in order\n *   to easily integrate dutch auctions into a contract for token swaps.\n *\n *   The strategist will need to implement a way to call `_enableAuction`\n *   for an token pair they want to use, or a setter to manually set the\n *   `auction` contract.\n *\n *   The contract comes with all of the needed function to act as a `hook`\n *   contract for the specific auction contract with the ability to override\n *   any of the functions to implement custom hooks.\n *\n *   NOTE: If any hooks are not desired, the strategist should also\n *   implement a way to call the {setHookFlags} on the auction contract\n *   to avoid unnecessary gas for unused functions.\n */\ncontract AuctionSwapper {\n    using SafeERC20 for ERC20;\n\n    modifier onlyAuction() {\n        _isAuction();\n        _;\n    }\n\n    /**\n     * @dev Check the caller is the auction contract for hooks.\n     */\n    function _isAuction() internal view virtual {\n        require(msg.sender == auction, \"!auction\");\n    }\n\n    /// @notice The pre-deployed Auction factory for cloning.\n    address public constant auctionFactory =\n        0xE6aB098E8582178A76DC80d55ca304d1Dec11AD8;\n\n    /// @notice Address of the specific Auction this strategy uses.\n    address public auction;\n\n    /*//////////////////////////////////////////////////////////////\n                    AUCTION STARTING AND STOPPING\n    //////////////////////////////////////////////////////////////*/\n\n    function _enableAuction(\n        address _from,\n        address _want\n    ) internal virtual returns (bytes32) {\n        return _enableAuction(_from, _want, 1 days, 3 days, 1e6);\n    }\n\n    /**\n     * @dev Used to enable a new Auction to sell `_from` to `_want`.\n     *   If this is the first auction enabled it will deploy a new `auction`\n     *   contract to use from the factory.\n     *\n     * NOTE: This only supports one `_want` token per strategy.\n     *\n     * @param _from Token to sell\n     * @param _want Token to buy.\n     * @return .The auction ID.\n     */\n    function _enableAuction(\n        address _from,\n        address _want,\n        uint256 _auctionLength,\n        uint256 _auctionCooldown,\n        uint256 _startingPrice\n    ) internal virtual returns (bytes32) {\n        address _auction = auction;\n\n        // If this is the first auction.\n        if (_auction == address(0)) {\n            // Deploy a new auction\n            _auction = AuctionFactory(auctionFactory).createNewAuction(\n                _want,\n                address(this),\n                address(this),\n                _auctionLength,\n                _auctionCooldown,\n                _startingPrice\n            );\n            // Store it for future use.\n            auction = _auction;\n        } else {\n            // Can only use one `want` per auction contract.\n            require(Auction(_auction).want() == _want, \"wrong want\");\n        }\n\n        // Enable new auction for `_from` token.\n        return Auction(_auction).enable(_from);\n    }\n\n    /**\n     * @dev Disable an auction for a given token.\n     * @param _from The token that was being sold.\n     */\n    function _disableAuction(address _from) internal virtual {\n        Auction(auction).disable(_from);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        OPTIONAL AUCTION HOOKS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Return how much `_token` could currently be kicked into auction.\n     * @dev This can be overridden by a strategist to implement custom logic.\n     * @param _token Address of the `_from` token.\n     * @return . The amount of `_token` ready to be auctioned off.\n     */\n    function kickable(address _token) public view virtual returns (uint256) {\n        return ERC20(_token).balanceOf(address(this));\n    }\n\n    /**\n     * @dev To override if something other than just sending the loose balance\n     *  of `_token` to the auction is desired, such as accruing and and claiming rewards.\n     *\n     * @param _token Address of the token being auctioned off\n     */\n    function _auctionKicked(address _token) internal virtual returns (uint256) {\n        // Send any loose balance to the auction.\n        uint256 balance = ERC20(_token).balanceOf(address(this));\n        if (balance != 0) ERC20(_token).safeTransfer(auction, balance);\n        return ERC20(_token).balanceOf(auction);\n    }\n\n    /**\n     * @dev To override if something needs to be done before a take is completed.\n     *   This can be used if the auctioned token only will be freed up when a `take`\n     *   occurs.\n     * @param _token Address of the token being taken.\n     * @param _amountToTake Amount of `_token` needed.\n     * @param _amountToPay Amount of `want` that will be payed.\n     */\n    function _preTake(\n        address _token,\n        uint256 _amountToTake,\n        uint256 _amountToPay\n    ) internal virtual {}\n\n    /**\n     * @dev To override if a post take action is desired.\n     *\n     * This could be used to re-deploy the bought token back into the yield source,\n     * or in conjunction with {_preTake} to check that the price sold at was within\n     * some allowed range.\n     *\n     * @param _token Address of the token that the strategy was sent.\n     * @param _amountTaken Amount of the from token taken.\n     * @param _amountPayed Amount of `_token` that was sent to the strategy.\n     */\n    function _postTake(\n        address _token,\n        uint256 _amountTaken,\n        uint256 _amountPayed\n    ) internal virtual {}\n\n    /*//////////////////////////////////////////////////////////////\n                            AUCTION HOOKS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice External hook for the auction to call during a `kick`.\n     * @dev Will call the internal version for the strategist to override.\n     * @param _token Token being kicked into auction.\n     * @return . The amount of `_token` to be auctioned off.\n     */\n    function auctionKicked(\n        address _token\n    ) external virtual onlyAuction returns (uint256) {\n        return _auctionKicked(_token);\n    }\n\n    /**\n     * @notice External hook for the auction to call before a `take`.\n     * @dev Will call the internal version for the strategist to override.\n     * @param _token Token being taken in the auction.\n     * @param _amountToTake The amount of `_token` to be sent to the taker.\n     * @param _amountToPay Amount of `want` that will be payed.\n     */\n    function preTake(\n        address _token,\n        uint256 _amountToTake,\n        uint256 _amountToPay\n    ) external virtual onlyAuction {\n        _preTake(_token, _amountToTake, _amountToPay);\n    }\n\n    /**\n     * @notice External hook for the auction to call after a `take` completed.\n     * @dev Will call the internal version for the strategist to override.\n     * @param _token The `want` token that was sent to the strategy.\n     * @param _amountTaken Amount of the from token taken.\n     * @param _amountPayed Amount of `_token` that was sent to the strategy.\n     */\n    function postTake(\n        address _token,\n        uint256 _amountTaken,\n        uint256 _amountPayed\n    ) external virtual onlyAuction {\n        _postTake(_token, _amountTaken, _amountPayed);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/ajna-core/src/interfaces/pool/erc20/IERC20Pool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\nimport { IPool }                     from '../IPool.sol';\nimport { IERC20PoolBorrowerActions } from './IERC20PoolBorrowerActions.sol';\nimport { IERC20PoolLenderActions }   from './IERC20PoolLenderActions.sol';\nimport { IERC20PoolImmutables }      from './IERC20PoolImmutables.sol';\nimport { IERC20PoolEvents }          from './IERC20PoolEvents.sol';\n\n/**\n * @title ERC20 Pool\n */\ninterface IERC20Pool is\n    IPool,\n    IERC20PoolLenderActions,\n    IERC20PoolBorrowerActions,\n    IERC20PoolImmutables,\n    IERC20PoolEvents\n{\n\n    /**\n     *  @notice Initializes a new pool, setting initial state variables.\n     *  @param  rate_ Initial interest rate of the pool (min accepted value 1%, max accepted value 10%).\n     */\n    function initialize(uint256 rate_) external;\n\n    /**\n     *  @notice Returns the minimum amount of collateral an actor may have in a bucket.\n     *  @param  bucketIndex_ The bucket index for which the dust limit is desired, or `0` for pledged collateral.\n     *  @return The dust limit for `bucketIndex_`.\n     */\n    function bucketCollateralDust(\n        uint256 bucketIndex_\n    ) external pure returns (uint256);\n\n}\n"
      },
      "lib/ajna-core/src/libraries/helpers/PoolHelper.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.18;\n\nimport { PRBMathSD59x18 } from \"@prb-math/contracts/PRBMathSD59x18.sol\";\nimport { Math }           from '@openzeppelin/contracts/utils/math/Math.sol';\nimport { SafeCast }       from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { PoolType }                 from '../../interfaces/pool/IPool.sol';\nimport { InflatorState, PoolState } from '../../interfaces/pool/commons/IPoolState.sol';\n\nimport { Buckets } from '../internal/Buckets.sol';\nimport { Maths }   from '../internal/Maths.sol';\n\n    error BucketIndexOutOfBounds();\n    error BucketPriceOutOfBounds();\n\n    /*************************/\n    /*** Price Conversions ***/\n    /*************************/\n\n    /// @dev constant price indices defining the min and max of the potential price range\n    int256  constant MAX_BUCKET_INDEX  =  4_156;\n    int256  constant MIN_BUCKET_INDEX  = -3_232;\n    uint256 constant MAX_FENWICK_INDEX =  7_388;\n\n    uint256 constant MIN_PRICE = 99_836_282_890;\n    uint256 constant MAX_PRICE = 1_004_968_987.606512354182109771 * 1e18;\n\n    uint256 constant MAX_INFLATED_PRICE = 50_248_449_380.325617709105488550 * 1e18; // 50 * MAX_PRICE\n\n    /// @dev deposit buffer (extra margin) used for calculating reserves\n    uint256 constant DEPOSIT_BUFFER = 1.000000001 * 1e18;\n\n    /// @dev step amounts in basis points. This is a constant across pools at `0.005`, achieved by dividing `WAD` by `10,000`\n    int256 constant FLOAT_STEP_INT = 1.005 * 1e18;\n\n    /// @dev collateralization factor used to calculate borrrower HTP/TP/collateralization.\n    uint256 constant COLLATERALIZATION_FACTOR = 1.04 * 1e18;\n\n    /**\n     *  @notice Calculates the price (`WAD` precision) for a given `Fenwick` index.\n     *  @dev    Reverts with `BucketIndexOutOfBounds` if index exceeds maximum constant.\n     *  @dev    Uses fixed-point math to get around lack of floating point numbers in `EVM`.\n     *  @dev    Fenwick index is converted to bucket index.\n     *  @dev    Fenwick index to bucket index conversion:\n     *  @dev      `1.00`      : bucket index `0`,     fenwick index `4156`: `7388-4156-3232=0`.\n     *  @dev      `MAX_PRICE` : bucket index `4156`,  fenwick index `0`:    `7388-0-3232=4156`.\n     *  @dev      `MIN_PRICE` : bucket index - `3232`, fenwick index `7388`: `7388-7388-3232=-3232`.\n     *  @dev    `V1`: `price = MIN_PRICE + (FLOAT_STEP * index)`\n     *  @dev    `V2`: `price = MAX_PRICE * (FLOAT_STEP ** (abs(int256(index - MAX_PRICE_INDEX))));`\n     *  @dev    `V3 (final)`: `x^y = 2^(y*log_2(x))`\n     */\n    function _priceAt(\n        uint256 index_\n    ) pure returns (uint256) {\n        // Lowest Fenwick index is highest price, so invert the index and offset by highest bucket index.\n        int256 bucketIndex = MAX_BUCKET_INDEX - int256(index_);\n        if (bucketIndex < MIN_BUCKET_INDEX || bucketIndex > MAX_BUCKET_INDEX) revert BucketIndexOutOfBounds();\n\n        return uint256(\n            PRBMathSD59x18.exp2(\n                PRBMathSD59x18.mul(\n                    PRBMathSD59x18.fromInt(bucketIndex),\n                    PRBMathSD59x18.log2(FLOAT_STEP_INT)\n                )\n            )\n        );\n    }\n\n    /**\n     *  @notice Calculates the  Fenwick  index for a given price.\n     *  @dev    Reverts with `BucketPriceOutOfBounds` if price exceeds maximum constant.\n     *  @dev    Price expected to be inputted as a `WAD` (`18` decimal).\n     *  @dev    `V1`: `bucket index = (price - MIN_PRICE) / FLOAT_STEP`\n     *  @dev    `V2`: `bucket index = (log(FLOAT_STEP) * price) /  MAX_PRICE`\n     *  @dev    `V3 (final)`: `bucket index =  log_2(price) / log_2(FLOAT_STEP)`\n     *  @dev    `Fenwick index = 7388 - bucket index + 3232`\n     */\n    function _indexOf(\n        uint256 price_\n    ) pure returns (uint256) {\n        if (price_ < MIN_PRICE || price_ > MAX_PRICE) revert BucketPriceOutOfBounds();\n\n        int256 index = PRBMathSD59x18.div(\n            PRBMathSD59x18.log2(int256(price_)),\n            PRBMathSD59x18.log2(FLOAT_STEP_INT)\n        );\n\n        int256 ceilIndex = PRBMathSD59x18.ceil(index);\n        if (index < 0 && ceilIndex - index > 0.5 * 1e18) {\n            return uint256(4157 - PRBMathSD59x18.toInt(ceilIndex));\n        }\n        return uint256(4156 - PRBMathSD59x18.toInt(ceilIndex));\n    }\n\n    /**********************/\n    /*** Pool Utilities ***/\n    /**********************/\n\n    /**\n     *  @notice Calculates the minimum debt amount that can be borrowed or can remain in a loan in pool.\n     *  @param  debt_          The debt amount to calculate minimum debt amount for.\n     *  @param  loansCount_    The number of loans in pool.\n     *  @return minDebtAmount_ Minimum debt amount value of the pool.\n     */\n    function _minDebtAmount(\n        uint256 debt_,\n        uint256 loansCount_\n    ) pure returns (uint256 minDebtAmount_) {\n        if (loansCount_ != 0) {\n            minDebtAmount_ = Maths.wdiv(Maths.wdiv(debt_, Maths.wad(loansCount_)), 10**19);\n        }\n    }\n\n    /**\n     *  @notice Calculates origination fee for a given interest rate.\n     *  @notice Calculated as greater of the current annualized interest rate divided by `52` (one week of interest) or `5` bps.\n     *  @param  interestRate_ The current interest rate.\n     *  @return Fee rate based upon the given interest rate.\n     */\n    function _borrowFeeRate(\n        uint256 interestRate_\n    ) pure returns (uint256) {\n        // greater of the current annualized interest rate divided by 52 (one week of interest) or 5 bps\n        return Maths.max(Maths.wdiv(interestRate_, 52 * 1e18), 0.0005 * 1e18);\n    }\n\n    /**\n     * @notice Calculates the unutilized deposit fee, charged to lenders who deposit below the `LUP`.\n     * @param  interestRate_ The current interest rate.\n     * @return Fee rate based upon the given interest rate\n     */\n    function _depositFeeRate(\n        uint256 interestRate_\n    ) pure returns (uint256) {\n        // current annualized rate divided by 365 * 3 (8 hours of interest)\n        return Maths.wdiv(interestRate_, 365 * 3e18);\n    }\n\n    /**\n     * @notice Determines how the inflator state should be updated\n     * @param  poolState_     State of the pool after updateInterestState was called.\n     * @param  inflatorState_ Old inflator state.\n     * @return newInflator_     New inflator value.\n     * @return updateTimestamp_ `True` if timestamp of last update should be updated.\n     */\n    function _determineInflatorState(\n        PoolState memory poolState_,\n        InflatorState memory inflatorState_\n    ) view returns (uint208 newInflator_, bool updateTimestamp_) {\n        newInflator_ = inflatorState_.inflator;\n\n        // update pool inflator\n        if (poolState_.isNewInterestAccrued) {\n            newInflator_     = SafeCast.toUint208(poolState_.inflator);\n            updateTimestamp_ = true;\n        // if the debt in the current pool state is 0, also update the inflator and inflatorUpdate fields in inflatorState\n        // slither-disable-next-line incorrect-equality\n        } else if (poolState_.debt == 0) {\n            newInflator_     = SafeCast.toUint208(Maths.WAD);\n            updateTimestamp_ = true;\n        // if the first loan has just been drawn, update the inflator timestamp\n        // slither-disable-next-line incorrect-equality\n        } else if (inflatorState_.inflator == Maths.WAD && inflatorState_.inflatorUpdate != block.timestamp){\n            updateTimestamp_ = true;\n        }\n    }\n\n    /**\n     *  @notice Calculates `HTP` price.\n     *  @param  maxT0DebtToCollateral_ Max t0 debt to collateral in pool.\n     *  @param  inflator_              Pool's inflator.\n     */\n    function _htp(\n        uint256 maxT0DebtToCollateral_,\n        uint256 inflator_\n    ) pure returns (uint256) {\n        return Maths.wmul(\n            Maths.wmul(maxT0DebtToCollateral_, inflator_),\n            COLLATERALIZATION_FACTOR\n        );\n    }\n\n    /**\n     *  @notice Calculates debt-weighted average threshold price.\n     *  @param  t0Debt_              Pool debt owed by borrowers in `t0` terms.\n     *  @param  inflator_            Pool's borrower inflator.\n     *  @param  t0Debt2ToCollateral_ `t0-debt-squared-to-collateral` accumulator. \n     */\n    function _dwatp(\n        uint256 t0Debt_,\n        uint256 inflator_,\n        uint256 t0Debt2ToCollateral_\n    ) pure returns (uint256) {\n        return t0Debt_ == 0 ? 0 : Maths.wdiv(\n            Maths.wmul(\n                Maths.wmul(inflator_, t0Debt2ToCollateral_),\n                COLLATERALIZATION_FACTOR\n            ),\n            t0Debt_\n        );\n    }\n\n    /**\n     *  @notice Collateralization calculation.\n     *  @param debt_       Debt to calculate collateralization for.\n     *  @param collateral_ Collateral to calculate collateralization for.\n     *  @param price_      Price to calculate collateralization for.\n     *  @param type_       Type of the pool.\n     *  @return `True` if value of collateral exceeds or equals debt.\n     */\n    function _isCollateralized(\n        uint256 debt_,\n        uint256 collateral_,\n        uint256 price_,\n        uint8 type_\n    ) pure returns (bool) {\n        // `False` if LUP = MIN_PRICE unless there is no debt\n        if (price_ == MIN_PRICE && debt_ != 0) return false;\n\n        // Use collateral floor for NFT pools\n        if (type_ == uint8(PoolType.ERC721)) {\n            //slither-disable-next-line divide-before-multiply\n            collateral_ = (collateral_ / Maths.WAD) * Maths.WAD; // use collateral floor\n        }\n        \n        return Maths.wmul(collateral_, price_) >= Maths.wmul(COLLATERALIZATION_FACTOR, debt_);\n    }\n\n    /**\n     *  @notice Price precision adjustment used in calculating collateral dust for a bucket.\n     *          To ensure the accuracy of the exchange rate calculation, buckets with smaller prices require\n     *          larger minimum amounts of collateral.  This formula imposes a lower bound independent of token scale.\n     *  @param  bucketIndex_              Index of the bucket, or `0` for encumbered collateral with no bucket affinity.\n     *  @return pricePrecisionAdjustment_ Unscaled integer of the minimum number of decimal places the dust limit requires.\n     */\n    function _getCollateralDustPricePrecisionAdjustment(\n        uint256 bucketIndex_\n    ) pure returns (uint256 pricePrecisionAdjustment_) {\n        // conditional is a gas optimization\n        if (bucketIndex_ > 3900) {\n            int256 bucketOffset = int256(bucketIndex_ - 3900);\n            int256 result = PRBMathSD59x18.sqrt(PRBMathSD59x18.div(bucketOffset * 1e18, int256(36 * 1e18)));\n            pricePrecisionAdjustment_ = uint256(result / 1e18);\n        }\n    }\n\n    /**\n     *  @notice Returns the amount of collateral calculated for the given amount of `LP`.\n     *  @dev    The value returned is capped at collateral amount available in bucket.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  lenderLPBalance_  The amount of `LP` to calculate collateral for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @return collateralAmount_ Amount of collateral calculated for the given `LP `amount.\n     */\n    function _lpToCollateral(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 deposit_,\n        uint256 lenderLPBalance_,\n        uint256 bucketPrice_\n    ) pure returns (uint256 collateralAmount_) {\n        collateralAmount_ = Buckets.lpToCollateral(\n            bucketCollateral_,\n            bucketLP_,\n            deposit_,\n            lenderLPBalance_,\n            bucketPrice_,\n            Math.Rounding.Down\n        );\n\n        if (collateralAmount_ > bucketCollateral_) {\n            // user is owed more collateral than is available in the bucket\n            collateralAmount_ = bucketCollateral_;\n        }\n    }\n\n    /**\n     *  @notice Returns the amount of quote tokens calculated for the given amount of `LP`.\n     *  @dev    The value returned is capped at available bucket deposit.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  lenderLPBalance_  The amount of `LP` to calculate quote token amount for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @return quoteTokenAmount_ Amount of quote tokens calculated for the given `LP` amount, capped at available bucket deposit.\n     */\n    function _lpToQuoteToken(\n        uint256 bucketLP_,\n        uint256 bucketCollateral_,\n        uint256 deposit_,\n        uint256 lenderLPBalance_,\n        uint256 bucketPrice_\n    ) pure returns (uint256 quoteTokenAmount_) {\n        quoteTokenAmount_ = Buckets.lpToQuoteTokens(\n            bucketCollateral_,\n            bucketLP_,\n            deposit_,\n            lenderLPBalance_,\n            bucketPrice_,\n            Math.Rounding.Down\n        );\n\n        if (quoteTokenAmount_ > deposit_) quoteTokenAmount_ = deposit_;\n    }\n\n    /**\n     *  @notice Rounds a token amount down to the minimum amount permissible by the token scale.\n     *  @param  amount_       Value to be rounded.\n     *  @param  tokenScale_   Scale of the token, presented as a power of `10`.\n     *  @return scaledAmount_ Rounded value.\n     */\n    function _roundToScale(\n        uint256 amount_,\n        uint256 tokenScale_\n    ) pure returns (uint256 scaledAmount_) {\n        scaledAmount_ = (amount_ / tokenScale_) * tokenScale_;\n    }\n\n    /**\n     *  @notice Rounds a token amount up to the next amount permissible by the token scale.\n     *  @param  amount_       Value to be rounded.\n     *  @param  tokenScale_   Scale of the token, presented as a power of `10`.\n     *  @return scaledAmount_ Rounded value.\n     */\n    function _roundUpToScale(\n        uint256 amount_,\n        uint256 tokenScale_\n    ) pure returns (uint256 scaledAmount_) {\n        if (amount_ % tokenScale_ == 0)\n            scaledAmount_ = amount_;\n        else\n            scaledAmount_ = _roundToScale(amount_, tokenScale_) + tokenScale_;\n    }\n\n    /*********************************/\n    /*** Reserve Auction Utilities ***/\n    /*********************************/\n\n    uint256 constant MINUTE_HALF_LIFE    = 0.988514020352896135_356867505 * 1e27;  // 0.5^(1/60)\n\n    /**\n     *  @notice Calculates claimable reserves within the pool.\n     *  @dev    Claimable reserve auctions and escrowed auction bonds are guaranteed by the pool.\n     *  @param  debt_                    Pool's debt.\n     *  @param  poolSize_                Pool's deposit size.\n     *  @param  totalBondEscrowed_       Total bond escrowed.\n     *  @param  reserveAuctionUnclaimed_ Pool's unclaimed reserve auction.\n     *  @param  quoteTokenBalance_       Pool's quote token balance.\n     *  @return claimable_               Calculated pool reserves.\n     */  \n    function _claimableReserves(\n        uint256 debt_,\n        uint256 poolSize_,\n        uint256 totalBondEscrowed_,\n        uint256 reserveAuctionUnclaimed_,\n        uint256 quoteTokenBalance_\n    ) pure returns (uint256 claimable_) {\n        uint256 guaranteedFunds = totalBondEscrowed_ + reserveAuctionUnclaimed_;\n\n        // calculate claimable reserves if there's quote token excess\n        if (quoteTokenBalance_ > guaranteedFunds) {\n            claimable_ = debt_ + quoteTokenBalance_;\n\n            claimable_ -= Maths.min(\n                claimable_,\n                // require 1.0 + 1e-9 deposit buffer (extra margin) for deposits\n                Maths.wmul(DEPOSIT_BUFFER, poolSize_) + guaranteedFunds\n            );\n\n            // incremental claimable reserve should not exceed excess quote in pool\n            claimable_ = Maths.min(\n                claimable_,\n                quoteTokenBalance_ - guaranteedFunds\n            );\n        }\n    }\n\n    /**\n     *  @notice Calculates reserves auction price.\n     *  @param  reserveAuctionKicked_ Time when reserve auction was started (kicked).\n     *  @param  lastKickedReserves_   Reserves to be auctioned when started (kicked).\n     *  @return price_                Calculated auction price.\n     */     \n    function _reserveAuctionPrice(\n        uint256 reserveAuctionKicked_,\n        uint256 lastKickedReserves_\n    ) view returns (uint256 price_) {\n        if (reserveAuctionKicked_ != 0) {\n            uint256 secondsElapsed   = block.timestamp - reserveAuctionKicked_;\n            uint256 hoursComponent   = 1e27 >> secondsElapsed / 3600;\n            uint256 minutesComponent = Maths.rpow(MINUTE_HALF_LIFE, secondsElapsed % 3600 / 60);\n            uint256 initialPrice     = lastKickedReserves_ == 0 ? 0 : Maths.wdiv(1_000_000_000 * 1e18, lastKickedReserves_);\n\n            price_ = initialPrice * Maths.rmul(hoursComponent, minutesComponent) / 1e27;\n        }\n    }\n\n    /*************************/\n    /*** Auction Utilities ***/\n    /*************************/\n\n    /// @dev min bond factor.\n    uint256 constant MIN_BOND_FACTOR = 0.005 * 1e18;\n    /// @dev max bond factor.\n    uint256 constant MAX_BOND_FACTOR = 0.03 * 1e18;\n\n    /**\n     *  @notice Calculates auction price.\n     *  @param  referencePrice_ Recorded at kick, used to calculate start price.\n     *  @param  kickTime_       Time when auction was kicked.\n     *  @return price_          Calculated auction price.\n     */\n    function _auctionPrice(\n        uint256 referencePrice_,\n        uint256 kickTime_\n    ) view returns (uint256 price_) {\n        uint256 elapsedMinutes = Maths.wdiv((block.timestamp - kickTime_) * 1e18, 1 minutes * 1e18);\n\n        int256 timeAdjustment;\n        if (elapsedMinutes < 120 * 1e18) {\n            timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256(elapsedMinutes / 20));\n            price_ = 256 * Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment)));\n        } else if (elapsedMinutes < 840 * 1e18) {\n            timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256((elapsedMinutes - 120 * 1e18) / 120));\n            price_ = 4 * Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment)));\n        } else {\n            timeAdjustment = PRBMathSD59x18.mul(-1 * 1e18, int256((elapsedMinutes - 840 * 1e18) / 60));\n            price_ = Maths.wmul(referencePrice_, uint256(PRBMathSD59x18.exp2(timeAdjustment))) / 16;\n        }\n    }\n\n    /**\n     *  @notice Calculates bond penalty factor.\n     *  @dev    Called in kick and take.\n     *  @param debtToCollateral_ Borrower debt to collateral at time of kick.\n     *  @param neutralPrice_     `NP` of auction.\n     *  @param bondFactor_       Factor used to determine bondSize.\n     *  @param auctionPrice_     Auction price at the time of call or, for bucket takes, bucket price.\n     *  @return bpf_             Factor used in determining bond `reward` (positive) or `penalty` (negative).\n     */\n    function _bpf(\n        uint256 debtToCollateral_,\n        uint256 neutralPrice_,\n        uint256 bondFactor_,\n        uint256 auctionPrice_\n    ) pure returns (int256) {\n        int256 sign;\n        if (debtToCollateral_ < neutralPrice_) {\n            // BPF = BondFactor * min(1, max(-1, (neutralPrice - price) / (neutralPrice - debtToCollateral)))\n            sign = Maths.minInt(\n                1e18,\n                Maths.maxInt(\n                    -1 * 1e18,\n                    PRBMathSD59x18.div(\n                        int256(neutralPrice_) - int256(auctionPrice_),\n                        int256(neutralPrice_) - int256(debtToCollateral_)\n                    )\n                )\n            );\n        } else {\n            int256 val = int256(neutralPrice_) - int256(auctionPrice_);\n            if (val < 0 )      sign = -1e18;\n            else if (val != 0) sign = 1e18;\n        }\n\n        return PRBMathSD59x18.mul(int256(bondFactor_), sign);\n    }\n\n    /**\n     *  @notice Calculates bond parameters of an auction.\n     *  @param  borrowerDebt_   Borrower's debt before entering in liquidation.\n     *  @param  npTpRatio_      Borrower's Np to Tp ratio\n     */\n    function _bondParams(\n        uint256 borrowerDebt_,\n        uint256 npTpRatio_\n    ) pure returns (uint256 bondFactor_, uint256 bondSize_) {\n        // bondFactor = max(min(MAX_BOND_FACTOR, (NP/TP_ratio - 1) / 10), MIN_BOND_FACTOR)\n        bondFactor_ = Maths.max(\n            Maths.min(\n                MAX_BOND_FACTOR,\n                (npTpRatio_ - 1e18) / 10\n            ),\n            MIN_BOND_FACTOR\n        );\n\n        bondSize_ = Maths.wmul(bondFactor_,  borrowerDebt_);\n    }\n"
      },
      "lib/ajna-core/src/libraries/internal/Maths.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\npragma solidity 0.8.18;\n\n/**\n    @title  Maths library\n    @notice Internal library containing common maths.\n */\nlibrary Maths {\n\n    uint256 internal constant WAD = 1e18;\n    uint256 internal constant RAY = 1e27;\n\n    function wmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + WAD / 2) / WAD;\n    }\n\n    function floorWmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y) / WAD;\n    }\n\n    function ceilWmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + WAD - 1) / WAD;\n    }\n\n    function wdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD + y / 2) / y;\n    }\n\n    function floorWdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD) / y;\n    }\n\n    function ceilWdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD + y - 1) / y;\n    }\n\n    function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x + y - 1) / y;\n    }\n\n    function max(uint256 x, uint256 y) internal pure returns (uint256) {\n        return x >= y ? x : y;\n    }\n\n    function min(uint256 x, uint256 y) internal pure returns (uint256) {\n        return x <= y ? x : y;\n    }\n\n    function wad(uint256 x) internal pure returns (uint256) {\n        return x * WAD;\n    }\n\n    function rmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + RAY / 2) / RAY;\n    }\n\n    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {\n        z = n % 2 != 0 ? x : RAY;\n\n        for (n /= 2; n != 0; n /= 2) {\n            x = rmul(x, x);\n\n            if (n % 2 != 0) {\n                z = rmul(z, x);\n            }\n        }\n    }\n\n    /*************************/\n    /*** Integer Functions ***/\n    /*************************/\n\n    function maxInt(int256 x, int256 y) internal pure returns (int256) {\n        return x >= y ? x : y;\n    }\n\n    function minInt(int256 x, int256 y) internal pure returns (int256) {\n        return x <= y ? x : y;\n    }\n\n}\n"
      },
      "lib/ajna-core/src/libraries/external/PoolCommons.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.18;\n\nimport { PRBMathSD59x18 } from \"@prb-math/contracts/PRBMathSD59x18.sol\";\nimport { PRBMathUD60x18 } from \"@prb-math/contracts/PRBMathUD60x18.sol\";\n\nimport { IERC20 }    from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\n\nimport { \n    DepositsState, \n    EmaState, \n    InflatorState,\n    InterestState, \n    PoolBalancesState, \n    PoolState \n} from '../../interfaces/pool/commons/IPoolState.sol';\nimport { IERC3156FlashBorrower }                             from '../../interfaces/pool/IERC3156FlashBorrower.sol';\n\nimport { \n    _dwatp,\n    _htp,\n    _indexOf,\n    MAX_FENWICK_INDEX,\n    MIN_PRICE, MAX_PRICE\n} from '../helpers/PoolHelper.sol';\n\nimport { Deposits } from '../internal/Deposits.sol';\nimport { Buckets }  from '../internal/Buckets.sol';\nimport { Loans }    from '../internal/Loans.sol';\nimport { Maths }    from '../internal/Maths.sol';\n\n/**\n    @title  PoolCommons library\n    @notice External library containing logic for common pool functionality:\n            - interest rate accrual and interest rate params update\n            - pool utilization\n */\nlibrary PoolCommons {\n    using SafeERC20 for IERC20;\n\n\n    /*****************/\n    /*** Constants ***/\n    /*****************/\n\n    uint256 internal constant CUBIC_ROOT_1000000 = 100 * 1e18;\n    uint256 internal constant ONE_THIRD          = 0.333333333333333334 * 1e18;\n\n    uint256 internal constant INCREASE_COEFFICIENT = 1.1 * 1e18;\n    uint256 internal constant DECREASE_COEFFICIENT = 0.9 * 1e18;\n    int256  internal constant PERCENT_102          = 1.02 * 1e18;\n    int256  internal constant NEG_H_MAU_HOURS      = -0.057762265046662105 * 1e18; // -ln(2)/12\n    int256  internal constant NEG_H_TU_HOURS       = -0.008251752149523158 * 1e18; // -ln(2)/84\n\n    /**************/\n    /*** Events ***/\n    /**************/\n\n    // See `IPoolEvents` for descriptions\n    event Flashloan(address indexed receiver, address indexed token, uint256 amount);\n    event ResetInterestRate(uint256 oldRate, uint256 newRate);\n    event UpdateInterestRate(uint256 oldRate, uint256 newRate);\n\n    /**************/\n    /*** Errors ***/\n    /**************/\n\n    // See `IPoolErrors` for descriptions\n    error FlashloanCallbackFailed();\n    error FlashloanIncorrectBalance();\n\n    /*************************/\n    /*** Local Var Structs ***/\n    /*************************/\n\n    /// @dev Struct used for `updateInterestState` function local vars.\n    struct UpdateInterestLocalVars {\n        uint256 debtEma;\n        uint256 depositEma;\n        uint256 debtColEma;\n        uint256 lupt0DebtEma;\n        uint256 t0Debt2ToCollateral;\n        uint256 newMeaningfulDeposit;\n        uint256 newDebt;\n        uint256 newDebtCol;\n        uint256 newLupt0Debt;\n        uint256 lastEmaUpdate;\n        int256 elapsed;\n        int256 weightMau;\n        int256 weightTu;\n        uint256 newInterestRate;\n        uint256 nonAuctionedT0Debt;\n    }\n\n    /**************************/\n    /*** External Functions ***/\n    /**************************/\n\n    /**\n     *  @notice Calculates EMAs, caches values required for calculating interest rate, and saves new values in storage.\n     *  @notice Calculates new pool interest rate (Never called more than once every 12 hours) and saves new values in storage.\n     *  @dev    === Write state ===\n     *  @dev    `EMA`s state\n     *  @dev    interest rate accumulator and `interestRateUpdate` state\n     *  @dev    === Emit events ===\n     *  @dev    - `UpdateInterestRate` / `ResetInterestRate`\n     */\n    function updateInterestState(\n        InterestState storage interestParams_,\n        EmaState      storage emaParams_,\n        DepositsState storage deposits_,\n        PoolState memory poolState_,\n        uint256 lup_\n    ) external {\n        UpdateInterestLocalVars memory vars;\n        // load existing EMA values\n        vars.debtEma       = emaParams_.debtEma;\n        vars.depositEma    = emaParams_.depositEma;\n        vars.debtColEma    = emaParams_.debtColEma;\n        vars.lupt0DebtEma  = emaParams_.lupt0DebtEma;\n        vars.lastEmaUpdate = emaParams_.emaUpdate;\n\n        vars.t0Debt2ToCollateral = interestParams_.t0Debt2ToCollateral;\n\n        // calculate new interest params\n        vars.nonAuctionedT0Debt = poolState_.t0Debt - poolState_.t0DebtInAuction;\n        vars.newDebt = Maths.wmul(vars.nonAuctionedT0Debt, poolState_.inflator);\n        // new meaningful deposit cannot be less than pool's debt\n        vars.newMeaningfulDeposit = Maths.max(\n            _meaningfulDeposit(\n                deposits_,\n                poolState_.t0DebtInAuction,\n                vars.nonAuctionedT0Debt,\n                poolState_.inflator,\n                vars.t0Debt2ToCollateral\n            ),\n            vars.newDebt\n        );\n        vars.newDebtCol   = Maths.wmul(poolState_.inflator, vars.t0Debt2ToCollateral);\n        vars.newLupt0Debt = Maths.wmul(lup_, vars.nonAuctionedT0Debt);\n\n        // update EMAs only once per block\n        if (vars.lastEmaUpdate != block.timestamp) {\n\n            // first time EMAs are updated, initialize EMAs\n            if (vars.lastEmaUpdate == 0) {\n                vars.debtEma      = vars.newDebt;\n                vars.depositEma   = vars.newMeaningfulDeposit;\n                vars.debtColEma   = vars.newDebtCol;\n                vars.lupt0DebtEma = vars.newLupt0Debt;\n            } else {\n                vars.elapsed   = int256(Maths.wdiv(block.timestamp - vars.lastEmaUpdate, 1 hours));\n                vars.weightMau = PRBMathSD59x18.exp(PRBMathSD59x18.mul(NEG_H_MAU_HOURS, vars.elapsed));\n                vars.weightTu  = PRBMathSD59x18.exp(PRBMathSD59x18.mul(NEG_H_TU_HOURS,  vars.elapsed));\n\n                // calculate the t0 debt EMA, used for MAU\n                vars.debtEma = uint256(\n                    PRBMathSD59x18.mul(vars.weightMau, int256(vars.debtEma)) +\n                    PRBMathSD59x18.mul(1e18 - vars.weightMau, int256(interestParams_.debt))\n                );\n\n                // update the meaningful deposit EMA, used for MAU\n                vars.depositEma = uint256(\n                    PRBMathSD59x18.mul(vars.weightMau, int256(vars.depositEma)) +\n                    PRBMathSD59x18.mul(1e18 - vars.weightMau, int256(interestParams_.meaningfulDeposit))\n                );\n\n                // calculate the debt squared to collateral EMA, used for TU\n                vars.debtColEma = uint256(\n                    PRBMathSD59x18.mul(vars.weightTu, int256(vars.debtColEma)) +\n                    PRBMathSD59x18.mul(1e18 - vars.weightTu, int256(interestParams_.debtCol))\n                );\n\n                // calculate the EMA of LUP * t0 debt\n                vars.lupt0DebtEma = uint256(\n                    PRBMathSD59x18.mul(vars.weightTu, int256(vars.lupt0DebtEma)) +\n                    PRBMathSD59x18.mul(1e18 - vars.weightTu, int256(interestParams_.lupt0Debt))\n                );\n            }\n\n            // save EMAs in storage\n            emaParams_.debtEma      = vars.debtEma;\n            emaParams_.depositEma   = vars.depositEma;\n            emaParams_.debtColEma   = vars.debtColEma;\n            emaParams_.lupt0DebtEma = vars.lupt0DebtEma;\n\n            // save last EMA update time\n            emaParams_.emaUpdate = block.timestamp;\n        }\n\n        // reset interest rate if pool rate > 10% and debtEma < 5% of depositEma\n        if (\n            poolState_.rate > 0.1 * 1e18\n            &&\n            vars.debtEma < Maths.wmul(vars.depositEma, 0.05 * 1e18)\n        ) {\n            interestParams_.interestRate       = uint208(0.1 * 1e18);\n            interestParams_.interestRateUpdate = uint48(block.timestamp);\n\n            emit ResetInterestRate(\n                poolState_.rate,\n                0.1 * 1e18\n            );\n        }\n        // otherwise calculate and update interest rate if it has been more than 12 hours since the last update\n        else if (block.timestamp - interestParams_.interestRateUpdate > 12 hours) {\n            vars.newInterestRate = _calculateInterestRate(\n                poolState_,\n                vars.debtEma,\n                vars.depositEma,\n                vars.debtColEma,\n                vars.lupt0DebtEma\n            );\n\n            if (poolState_.rate != vars.newInterestRate) {\n                interestParams_.interestRate       = uint208(vars.newInterestRate);\n                interestParams_.interestRateUpdate = uint48(block.timestamp);\n\n                emit UpdateInterestRate(\n                    poolState_.rate,\n                    vars.newInterestRate\n                );\n            }\n        }\n\n        // save new interest rate params to storage\n        interestParams_.debt              = vars.newDebt;\n        interestParams_.meaningfulDeposit = vars.newMeaningfulDeposit;\n        interestParams_.debtCol           = vars.newDebtCol;\n        interestParams_.lupt0Debt         = vars.newLupt0Debt;\n    }\n\n    /**\n     *  @notice Calculates new pool interest and scale the fenwick tree to update amount of debt owed to lenders (saved in storage).\n     *  @dev    === Write state ===\n     *  @dev    - `Deposits.mult` (scale `Fenwick` tree with new interest accrued):\n     *  @dev      update `scaling` array state\n     *  @param  emaParams_             Struct for pool `EMA`s state.\n     *  @param  deposits_              Struct for pool deposits state.\n     *  @param  poolState_             Current state of the pool.\n     *  @param  maxT0DebtToCollateral_ Max t0 debt to collateral in Pool.\n     *  @param  elapsed_               Time elapsed since last inflator update.\n     *  @return newInflator_           The new value of pool inflator.\n     *  @return newInterest_           The new interest accrued.\n     */\n    function accrueInterest(\n        EmaState      storage emaParams_,\n        DepositsState storage deposits_,\n        PoolState calldata poolState_,\n        uint256 maxT0DebtToCollateral_,\n        uint256 elapsed_\n    ) external returns (uint256 newInflator_, uint256 newInterest_) {\n        // Scale the borrower inflator to update amount of interest owed by borrowers\n        uint256 pendingFactor = PRBMathUD60x18.exp((poolState_.rate * elapsed_) / 365 days);\n\n        // calculate the highest threshold price\n        newInflator_ = Maths.wmul(poolState_.inflator, pendingFactor);\n        uint256 htp  = _htp(maxT0DebtToCollateral_, poolState_.inflator);\n\n        uint256 accrualIndex;\n        if (htp > MAX_PRICE)      accrualIndex = 1;                 // if HTP is over the highest price bucket then no buckets earn interest\n        else if (htp < MIN_PRICE) accrualIndex = MAX_FENWICK_INDEX; // if HTP is under the lowest price bucket then all buckets earn interest\n        else                      accrualIndex = _indexOf(htp);     // else HTP bucket earn interest\n\n        uint256 lupIndex = Deposits.findIndexOfSum(deposits_, poolState_.debt);\n        // accrual price is less of lup and htp, and prices decrease as index increases\n        if (lupIndex > accrualIndex) accrualIndex = lupIndex;\n\n        uint256 interestEarningDeposit = Deposits.prefixSum(deposits_, accrualIndex);\n\n        if (interestEarningDeposit != 0) {\n            newInterest_ = Maths.wmul(\n                _lenderInterestMargin(_utilization(emaParams_.debtEma, emaParams_.depositEma)),\n                Maths.wmul(pendingFactor - Maths.WAD, poolState_.debt)\n            );\n\n            // lender factor computation, capped at 10x the interest factor for borrowers\n            uint256 lenderFactor = Maths.min(\n                Maths.floorWdiv(newInterest_, interestEarningDeposit),\n                Maths.wmul(pendingFactor - Maths.WAD, Maths.wad(10))\n            ) + Maths.WAD;\n\n            // Scale the fenwick tree to update amount of debt owed to lenders\n            Deposits.mult(deposits_, accrualIndex, lenderFactor);\n        }\n    }\n\n    /**\n     *  @notice Executes a flashloan from current pool.\n     *  @dev    === Reverts on ===\n     *  @dev    - `FlashloanCallbackFailed()` if receiver is not an `ERC3156FlashBorrower`\n     *  @dev    - `FlashloanIncorrectBalance()` if pool balance after flashloan is different than initial balance\n     *  @param  receiver_ Address of the contract which implements the appropriate interface to receive tokens.\n     *  @param  token_    Address of the `ERC20` token caller wants to borrow.\n     *  @param  amount_   The denormalized amount (dependent upon token precision) of tokens to borrow.\n     *  @param  data_     User-defined calldata passed to the receiver.\n     */\n    function flashLoan(\n        IERC3156FlashBorrower receiver_,\n        address token_, \n        uint256 amount_,\n        bytes calldata data_\n    ) external {\n        IERC20 tokenContract = IERC20(token_);\n\n        uint256 initialBalance = tokenContract.balanceOf(address(this));\n\n        tokenContract.safeTransfer(\n            address(receiver_),\n            amount_\n        );\n\n        if (receiver_.onFlashLoan(msg.sender, token_, amount_, 0, data_) != \n            keccak256(\"ERC3156FlashBorrower.onFlashLoan\")) revert FlashloanCallbackFailed();\n\n        tokenContract.safeTransferFrom(\n            address(receiver_),\n            address(this),\n            amount_\n        );\n\n        if (tokenContract.balanceOf(address(this)) != initialBalance) revert FlashloanIncorrectBalance();\n\n        emit Flashloan(address(receiver_), token_, amount_);\n    }\n\n    /**************************/\n    /*** Internal Functions ***/\n    /**************************/\n\n    /**\n     *  @notice Calculates new pool interest rate.\n     */\n    function _calculateInterestRate(\n        PoolState memory poolState_,\n        uint256 debtEma_,\n        uint256 depositEma_,\n        uint256 debtColEma_,\n        uint256 lupt0DebtEma_\n    ) internal pure returns (uint256 newInterestRate_)  {\n        // meaningful actual utilization\n        int256 mau;\n        // meaningful actual utilization * 1.02\n        int256 mau102;\n\n        if (poolState_.debt != 0) {\n            // calculate meaningful actual utilization for interest rate update\n            mau    = int256(_utilization(debtEma_, depositEma_));\n            mau102 = (mau * PERCENT_102) / 1e18;\n        }\n\n        // calculate target utilization\n        int256 tu = (lupt0DebtEma_ != 0) ? \n            int256(Maths.wdiv(debtColEma_, lupt0DebtEma_)) : int(Maths.WAD);\n\n        newInterestRate_ = poolState_.rate;\n\n        // raise rates if 4*(tu-1.02*mau) < (tu+1.02*mau-1)^2-1\n        if (4 * (tu - mau102) < (((tu + mau102 - 1e18) / 1e9) ** 2) - 1e18) {\n            newInterestRate_ = Maths.wmul(poolState_.rate, INCREASE_COEFFICIENT);\n        // decrease rates if 4*(tu-mau) > 1-(tu+mau-1)^2\n        } else if (4 * (tu - mau) > 1e18 - ((tu + mau - 1e18) / 1e9) ** 2) {\n            newInterestRate_ = Maths.wmul(poolState_.rate, DECREASE_COEFFICIENT);\n        }\n\n        // bound rates between 10 bps and 400%\n        newInterestRate_ = Maths.min(4 * 1e18, Maths.max(0.001 * 1e18, newInterestRate_));\n    }\n\n    /**\n     *  @notice Calculates pool meaningful actual utilization.\n     *  @param  debtEma_     `EMA` of pool debt.\n     *  @param  depositEma_  `EMA` of meaningful pool deposit.\n     *  @return utilization_ Pool meaningful actual utilization value.\n     */\n    function _utilization(\n        uint256 debtEma_,\n        uint256 depositEma_\n    ) internal pure returns (uint256 utilization_) {\n        if (depositEma_ != 0) utilization_ = Maths.wdiv(debtEma_, depositEma_);\n    }\n\n    /**\n     *  @notice Calculates lender interest margin.\n     *  @param  mau_ Meaningful actual utilization.\n     *  @return The lender interest margin value.\n     */\n    function _lenderInterestMargin(\n        uint256 mau_\n    ) internal pure returns (uint256) {\n        // Net Interest Margin = ((1 - MAU1)^(1/3) * 0.15)\n        // Where MAU1 is MAU capped at 100% (min(MAU,1))\n        // Lender Interest Margin = 1 - Net Interest Margin\n\n        // PRBMath library forbids raising a number < 1e18 to a power.  Using the product and quotient rules of \n        // exponents, rewrite the equation with a coefficient s which provides sufficient precision:\n        // Net Interest Margin = ((1 - MAU1) * s)^(1/3) / s^(1/3) * 0.15\n\n        uint256 base = 1_000_000 * 1e18 - Maths.min(mau_, 1e18) * 1_000_000;\n        // If unutilized deposit is infinitessimal, lenders get 100% of interest.\n        if (base < 1e18) {\n            return 1e18;\n        } else {\n            // cubic root of the percentage of meaningful unutilized deposit\n            uint256 crpud = PRBMathUD60x18.pow(base, ONE_THIRD);\n            // finish calculating Net Interest Margin, and then convert to Lender Interest Margin\n            return 1e18 - Maths.wdiv(Maths.wmul(crpud, 0.15 * 1e18), CUBIC_ROOT_1000000);\n        }\n    }\n\n    /**\n     *  @notice Calculates pool's meaningful deposit.\n     *  @param  deposits_            Struct for pool deposits state.\n     *  @param  t0DebtInAuction_     Value of pool's t0 debt currently in auction.\n     *  @param  nonAuctionedT0Debt_  Value of pool's t0 debt that is not in auction.\n     *  @param  inflator_            Pool's current inflator.\n     *  @param  t0Debt2ToCollateral_ `t0Debt2ToCollateral` ratio.\n     *  @return meaningfulDeposit_   Pool's meaningful deposit.\n     */\n    function _meaningfulDeposit(\n        DepositsState storage deposits_,\n        uint256 t0DebtInAuction_,\n        uint256 nonAuctionedT0Debt_,\n        uint256 inflator_,\n        uint256 t0Debt2ToCollateral_\n    ) internal view returns (uint256 meaningfulDeposit_) {\n        uint256 dwatp = _dwatp(nonAuctionedT0Debt_, inflator_, t0Debt2ToCollateral_);\n        if (dwatp == 0) {\n            meaningfulDeposit_ = Deposits.treeSum(deposits_);\n        } else {\n            if      (dwatp >= MAX_PRICE) meaningfulDeposit_ = 0;\n            else if (dwatp >= MIN_PRICE) meaningfulDeposit_ = Deposits.prefixSum(deposits_, _indexOf(dwatp));\n            else                         meaningfulDeposit_ = Deposits.treeSum(deposits_);\n        }\n        meaningfulDeposit_ -= Maths.min(\n            meaningfulDeposit_,\n            Maths.wmul(t0DebtInAuction_, inflator_)\n        );\n    }\n\n    /**********************/\n    /*** View Functions ***/\n    /**********************/\n\n    /**\n     *  @notice Calculates pool related debt values.\n     *  @param poolBalances_  Pool debt\n     *  @param inflatorState_ Interest inflator and last update time\n     *  @param interestState_ Interest rate and t0Debt2ToCollateral accumulator\n     *  @return Current amount of debt owed by borrowers in pool.\n     *  @return Debt owed by borrowers based on last inflator snapshot.\n     *  @return Total amount of debt in auction.\n     *  @return t0debt accross all borrowers divided by their collateral, used in determining a collateralization weighted debt.  \n     */\n    function debtInfo(\n        PoolBalancesState memory poolBalances_,\n        InflatorState     memory inflatorState_,\n        InterestState     memory interestState_\n    ) external view returns (uint256, uint256, uint256, uint256) {\n        uint256 t0Debt   = poolBalances_.t0Debt;\n        uint256 inflator = inflatorState_.inflator;\n\n        return (\n            Maths.ceilWmul(\n                t0Debt,\n                pendingInflator(inflator, inflatorState_.inflatorUpdate, interestState_.interestRate)\n            ),\n            Maths.ceilWmul(t0Debt, inflator),\n            Maths.ceilWmul(poolBalances_.t0DebtInAuction, inflator),\n            interestState_.t0Debt2ToCollateral\n        );\n    }\n\n    /**\n     *  @notice Calculates pool interest factor for a given interest rate and time elapsed since last inflator update.\n     *  @param  interestRate_   Current pool interest rate.\n     *  @param  elapsed_        Time elapsed since last inflator update.\n     *  @return The value of pool interest factor.\n     */\n    function pendingInterestFactor(\n        uint256 interestRate_,\n        uint256 elapsed_\n    ) external pure returns (uint256) {\n        return PRBMathUD60x18.exp((interestRate_ * elapsed_) / 365 days);\n    }\n\n    /**\n     *  @notice Calculates pool pending inflator given the current inflator, time of last update and current interest rate.\n     *  @param  inflator_      Current pool inflator.\n     *  @param  inflatorUpdate Timestamp when inflator was updated.\n     *  @param  interestRate_  The interest rate of the pool.\n     *  @return The pending value of pool inflator.\n     */\n    function pendingInflator(\n        uint256 inflator_,\n        uint256 inflatorUpdate,\n        uint256 interestRate_\n    ) public view returns (uint256) {\n        return Maths.wmul(\n            inflator_,\n            PRBMathUD60x18.exp((interestRate_ * (block.timestamp - inflatorUpdate)) / 365 days)\n        );\n    }\n\n    /**\n     *  @notice Calculates lender interest margin for a given meaningful actual utilization.\n     *  @dev Wrapper of the internal function.\n     */\n    function lenderInterestMargin(\n        uint256 mau_\n    ) external pure returns (uint256) {\n        return _lenderInterestMargin(mau_);\n    }\n\n    /**\n     *  @notice Calculates pool meaningful actual utilization.\n     *  @dev Wrapper of the internal function.\n     */\n    function utilization(\n        EmaState storage emaParams_\n    ) external view returns (uint256 utilization_) {\n        return _utilization(emaParams_.debtEma, emaParams_.depositEma);\n    }\n}\n"
      },
      "lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';\nimport {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';\nimport {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';\nimport {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';\nimport {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';\nimport {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';\nimport {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n    IUniswapV3PoolImmutables,\n    IUniswapV3PoolState,\n    IUniswapV3PoolDerivedState,\n    IUniswapV3PoolActions,\n    IUniswapV3PoolOwnerActions,\n    IUniswapV3PoolErrors,\n    IUniswapV3PoolEvents\n{\n\n}\n"
      },
      "lib/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n    /// @dev In the implementation you must pay the pool tokens owed for the swap.\n    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n    function uniswapV3SwapCallback(\n        int256 amount0Delta,\n        int256 amount1Delta,\n        bytes calldata data\n    ) external;\n}\n"
      },
      "lib/v3-core/contracts/interfaces/IUniswapV3Factory.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n    /// @notice Emitted when the owner of the factory is changed\n    /// @param oldOwner The owner before the owner was changed\n    /// @param newOwner The owner after the owner was changed\n    event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n    /// @notice Emitted when a pool is created\n    /// @param token0 The first token of the pool by address sort order\n    /// @param token1 The second token of the pool by address sort order\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks\n    /// @param pool The address of the created pool\n    event PoolCreated(\n        address indexed token0,\n        address indexed token1,\n        uint24 indexed fee,\n        int24 tickSpacing,\n        address pool\n    );\n\n    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n    /// @param fee The enabled fee, denominated in hundredths of a bip\n    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n    /// @notice Returns the current owner of the factory\n    /// @dev Can be changed by the current owner via setOwner\n    /// @return The address of the factory owner\n    function owner() external view returns (address);\n\n    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n    /// @return The tick spacing\n    function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n    /// @param tokenA The contract address of either token0 or token1\n    /// @param tokenB The contract address of the other token\n    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n    /// @return pool The pool address\n    function getPool(\n        address tokenA,\n        address tokenB,\n        uint24 fee\n    ) external view returns (address pool);\n\n    /// @notice Creates a pool for the given two tokens and fee\n    /// @param tokenA One of the two tokens in the desired pool\n    /// @param tokenB The other of the two tokens in the desired pool\n    /// @param fee The desired fee for the pool\n    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n    /// are invalid.\n    /// @return pool The address of the newly created pool\n    function createPool(\n        address tokenA,\n        address tokenB,\n        uint24 fee\n    ) external returns (address pool);\n\n    /// @notice Updates the owner of the factory\n    /// @dev Must be called by the current owner\n    /// @param _owner The new owner of the factory\n    function setOwner(address _owner) external;\n\n    /// @notice Enables a fee amount with the given tickSpacing\n    /// @dev Fee amounts may never be removed once enabled\n    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n"
      },
      "src/interfaces/IWeth.sol": {
        "content": "pragma solidity ^0.8.18;\n\ninterface IWETH {\n    function deposit() external payable;\n\n    function transfer(address to, uint256 value) external returns (bool);\n\n    function withdraw(uint256) external;\n}\n"
      },
      "src/interfaces/summerfi/IAccount.sol": {
        "content": "pragma solidity ^0.8.18;\n\ninterface IAccount {\n    function send(address _target, bytes calldata _data) external payable;\n\n    function execute(address _target, bytes memory _data)\n        external\n        payable\n        returns (bytes32);\n}\n"
      },
      "src/interfaces/summerfi/IAccountFactory.sol": {
        "content": "pragma solidity ^0.8.18;\n\ninterface IAccountFactory {\n    function createAccount() external returns (address);\n\n    function createAccount(address _user) external returns (address);\n}\n"
      },
      "src/interfaces/summerfi/AjnaProxyActions.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity ^0.8.18;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC721} from \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {IERC20Pool} from \"@ajna-core/interfaces/pool/erc20/IERC20Pool.sol\";\nimport {IWETH} from \"../IWETH.sol\";\n\ninterface IAjnaPoolUtilsInfo {\n    function priceToIndex(uint256 price_) external pure returns (uint256);\n\n    function borrowerInfo(address pool_, address borrower_)\n        external\n        view\n        returns (\n            uint256 debt_,\n            uint256 collateral_,\n            uint256 index_\n        );\n\n    function poolPricesInfo(address ajnaPool_)\n        external\n        view\n        returns (\n            uint256 hpb_,\n            uint256 hpbIndex_,\n            uint256 htp_,\n            uint256 htpIndex_,\n            uint256 lup_,\n            uint256 lupIndex_\n        );\n\n    function lpToQuoteTokens(\n        address ajnaPool_,\n        uint256 lp_,\n        uint256 index_\n    ) external view returns (uint256 quoteAmount_);\n\n    function bucketInfo(address ajnaPool_, uint256 index_)\n        external\n        view\n        returns (\n            uint256 price_,\n            uint256 quoteTokens_,\n            uint256 collateral_,\n            uint256 bucketLP_,\n            uint256 scale_,\n            uint256 exchangeRate_\n        );\n}\n\ninterface IAccountGuard {\n    function owners(address) external view returns (address);\n\n    function owner() external view returns (address);\n\n    function setWhitelist(address target, bool status) external;\n\n    function canCall(address proxy, address operator)\n        external\n        view\n        returns (bool);\n\n    function permit(\n        address caller,\n        address target,\n        bool allowance\n    ) external;\n\n    function isWhitelisted(address target) external view returns (bool);\n\n    function isWhitelistedSend(address target) external view returns (bool);\n}\n\ncontract AjnaProxyActions {\n    IAjnaPoolUtilsInfo public immutable poolInfoUtils;\n    IERC20 public immutable ajnaToken;\n    address public immutable WETH;\n    address public immutable GUARD;\n    address public immutable deployer;\n    /* \n  This configuration is applicable across all Layer 2 (L2) networks. However, on the Ethereum mainnet, \n  we continue to use 'Ajna_rc13'. Due to the nature of 'string' data type in Solidity, it cannot be \n  declared as 'immutable' and initialized within the constructor. \n  */\n    string public constant ajnaVersion = \"Ajna_rc14\";\n\n    using SafeERC20 for IERC20;\n\n    constructor(\n        IAjnaPoolUtilsInfo _poolInfoUtils,\n        IERC20 _ajnaToken,\n        address _WETH,\n        address _GUARD\n    ) {\n        require(\n            address(_poolInfoUtils) != address(0),\n            \"apa/pool-info-utils-zero-address\"\n        );\n        require(\n            address(_ajnaToken) != address(0) || block.chainid != 1,\n            \"apa/ajna-token-zero-address\"\n        );\n        require(_WETH != address(0), \"apa/weth-zero-address\");\n        require(_GUARD != address(0), \"apa/guard-zero-address\");\n        poolInfoUtils = _poolInfoUtils;\n        ajnaToken = _ajnaToken;\n        WETH = _WETH;\n        GUARD = _GUARD;\n        deployer = msg.sender;\n    }\n\n    /**\n     * @dev Emitted once an Operation has completed execution\n     * @param name Name of the operation\n     **/\n    event ProxyActionsOperation(bytes32 indexed name);\n\n    /**\n     * @dev Emitted when a new position is created\n     * @param proxyAddress The address of the newly created position proxy contract\n     * @param protocol The name of the protocol associated with the position\n     * @param positionType The type of position being created (e.g. borrow or earn)\n     * @param collateralToken The address of the collateral token being used for the position\n     * @param debtToken The address of the debt token being used for the position\n     **/\n    event CreatePosition(\n        address indexed proxyAddress,\n        string protocol,\n        string positionType,\n        address collateralToken,\n        address debtToken\n    );\n\n    function _send(address token, uint256 amount) internal {\n        if (token == WETH) {\n            IWETH(WETH).withdraw(amount);\n            payable(msg.sender).transfer(amount);\n        } else {\n            IERC20(token).safeTransfer(msg.sender, amount);\n        }\n    }\n\n    function _pull(address token, uint256 amount) internal {\n        if (token == WETH) {\n            IWETH(WETH).deposit{value: amount}();\n        } else {\n            IERC20(token).safeTransferFrom(msg.sender, address(this), amount);\n        }\n    }\n\n    function _stampLoan(IERC20Pool pool, bool stamploanEnabled) internal {\n        if (stamploanEnabled) {\n            pool.stampLoan();\n        }\n    }\n\n    /**\n     *  @notice Called internally to add an amount of credit at a specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  amount       The maximum amount of quote token to be moved by a lender.\n     *  @param  price        The price the bucket to which the quote tokens will be added.\n     *  @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance\n     *  @dev 1WBTC = 16,990.23 USDC   translates to: 16990230\n     */\n    function _supplyQuote(\n        IERC20Pool pool,\n        uint256 amount,\n        uint256 price\n    ) internal returns (uint256 bucketLP, uint256 addedAmount) {\n        address debtToken = pool.quoteTokenAddress();\n        _pull(debtToken, amount);\n        uint256 index = convertPriceToIndex(price);\n        IERC20(debtToken).approve(address(pool), amount);\n        (bucketLP, addedAmount) = pool.addQuoteToken(\n            amount * pool.quoteTokenScale(),\n            index,\n            block.timestamp + 1\n        );\n    }\n\n    /**\n     *  @notice Called internally to move max amount of credit from a specified price bucket to another specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  oldPrice        The price of the bucket  from which the quote tokens will be removed.\n     *  @param  newPrice     The price of the bucket to which the quote tokens will be added.\n     */\n    function _moveQuote(\n        IERC20Pool pool,\n        uint256 oldPrice,\n        uint256 newPrice\n    ) internal {\n        uint256 oldIndex = convertPriceToIndex(oldPrice);\n        pool.moveQuoteToken(\n            type(uint256).max,\n            oldIndex,\n            convertPriceToIndex(newPrice),\n            block.timestamp + 1\n        );\n    }\n\n    /**\n     *  @notice Called internally to remove an amount of credit at a specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  amount       The maximum amount of quote token to be moved by a lender.\n     *  @param  price        The price the bucket to which the quote tokens will be added.\n     *  @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance\n     *  @dev 1WBTC = 16,990.23 USDC   translates to: 16990230\n     */\n    function _withdrawQuote(\n        IERC20Pool pool,\n        uint256 amount,\n        uint256 price\n    ) internal {\n        address debtToken = pool.quoteTokenAddress();\n        uint256 index = convertPriceToIndex(price);\n        uint256 withdrawnBalanceWAD;\n        if (amount == type(uint256).max) {\n            (withdrawnBalanceWAD, ) = pool.removeQuoteToken(\n                type(uint256).max,\n                index\n            );\n        } else {\n            (withdrawnBalanceWAD, ) = pool.removeQuoteToken(\n                (amount * pool.quoteTokenScale()),\n                index\n            );\n        }\n        uint256 withdrawnBalance = _roundToScale(\n            withdrawnBalanceWAD,\n            pool.quoteTokenScale()\n        ) / pool.quoteTokenScale();\n        _send(debtToken, withdrawnBalance);\n    }\n\n    /**\n     * @notice Reclaims collateral from liquidated bucket\n     * @param  pool         Address of the Ajna Pool.\n     * @param  price        Price of the bucket to redeem.\n     */\n    function _removeCollateral(IERC20Pool pool, uint256 price)\n        internal\n        returns (uint256 withdrawnBalance)\n    {\n        address collateralToken = pool.collateralAddress();\n        uint256 index = convertPriceToIndex(price);\n        (uint256 withdrawnBalanceWAD, ) = pool.removeCollateral(\n            type(uint256).max,\n            index\n        );\n        withdrawnBalance =\n            _roundToScale(withdrawnBalanceWAD, pool.collateralScale()) /\n            pool.collateralScale();\n        _send(collateralToken, withdrawnBalance);\n    }\n\n    // BORROWER ACTIONS\n\n    /**\n     *  @notice Deposit collateral\n     *  @param  pool           Pool address\n     *  @param  collateralAmount Amount of collateral to deposit\n     *  @param  price          Price of the bucket\n     *  @param stamploanEnabled      Whether to stamp the loan or not\n     */\n    function depositCollateral(\n        IERC20Pool pool,\n        uint256 collateralAmount,\n        uint256 price,\n        bool stamploanEnabled\n    ) public payable {\n        address collateralToken = pool.collateralAddress();\n        _pull(collateralToken, collateralAmount);\n\n        uint256 index = convertPriceToIndex(price);\n        IERC20(collateralToken).approve(address(pool), collateralAmount);\n        pool.drawDebt(\n            address(this),\n            0,\n            index,\n            collateralAmount * pool.collateralScale()\n        );\n        _stampLoan(pool, stamploanEnabled);\n        emit ProxyActionsOperation(\"AjnaDeposit\");\n    }\n\n    /**\n     *  @notice Draw debt\n     *  @param  pool           Pool address\n     *  @param  debtAmount     Amount of debt to draw\n     *  @param  price          Price of the bucket\n     */\n    function drawDebt(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 price\n    ) public {\n        address debtToken = pool.quoteTokenAddress();\n        uint256 index = convertPriceToIndex(price);\n\n        pool.drawDebt(\n            address(this),\n            debtAmount * pool.quoteTokenScale(),\n            index,\n            0\n        );\n        _send(debtToken, debtAmount);\n        emit ProxyActionsOperation(\"AjnaBorrow\");\n    }\n\n    /**\n     *  @notice Deposit collateral and draw debt\n     *  @param  pool           Pool address\n     *  @param  debtAmount     Amount of debt to draw\n     *  @param  collateralAmount Amount of collateral to deposit\n     *  @param  price          Price of the bucket\n     */\n    function depositCollateralAndDrawDebt(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 collateralAmount,\n        uint256 price\n    ) public {\n        address debtToken = pool.quoteTokenAddress();\n        address collateralToken = pool.collateralAddress();\n        uint256 index = convertPriceToIndex(price);\n        _pull(collateralToken, collateralAmount);\n        IERC20(collateralToken).approve(address(pool), collateralAmount);\n        pool.drawDebt(\n            address(this),\n            debtAmount * pool.quoteTokenScale(),\n            index,\n            collateralAmount * pool.collateralScale()\n        );\n        _send(debtToken, debtAmount);\n        emit ProxyActionsOperation(\"AjnaDepositBorrow\");\n    }\n\n    /**\n     *  @notice Deposit collateral and draw debt\n     *  @param  pool           Pool address\n     *  @param  debtAmount     Amount of debt to borrow\n     *  @param  collateralAmount Amount of collateral to deposit\n     *  @param  price          Price of the bucket\n     *  @param stamploanEnabled      Whether to stamp the loan or not\n     */\n    function depositAndDraw(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 collateralAmount,\n        uint256 price,\n        bool stamploanEnabled\n    ) public payable {\n        if (debtAmount > 0 && collateralAmount > 0) {\n            depositCollateralAndDrawDebt(\n                pool,\n                debtAmount,\n                collateralAmount,\n                price\n            );\n        } else if (debtAmount > 0) {\n            drawDebt(pool, debtAmount, price);\n        } else if (collateralAmount > 0) {\n            depositCollateral(pool, collateralAmount, price, stamploanEnabled);\n        }\n    }\n\n    /**\n     *  @notice Repay debt\n     *  @param  pool           Pool address\n     *  @param  amount         Amount of debt to repay\n     *  @param stamploanEnabled      Whether to stamp the loan or not\n     */\n    function repayDebt(\n        IERC20Pool pool,\n        uint256 amount,\n        bool stamploanEnabled\n    ) public payable {\n        address debtToken = pool.quoteTokenAddress();\n        _pull(debtToken, amount);\n        IERC20(debtToken).approve(address(pool), amount);\n        (, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(\n            address(pool)\n        );\n        uint256 repaidAmountWAD = pool.repayDebt(\n            address(this),\n            amount * pool.quoteTokenScale(),\n            0,\n            address(this),\n            lupIndex_\n        );\n        _stampLoan(pool, stamploanEnabled);\n        uint256 repaidAmount = _roundUpToScale(\n            repaidAmountWAD,\n            pool.quoteTokenScale()\n        ) / pool.quoteTokenScale();\n        uint256 leftoverBalance = amount - repaidAmount;\n        if (leftoverBalance > 0) {\n            _send(debtToken, leftoverBalance);\n        }\n        IERC20(debtToken).safeApprove(address(pool), 0);\n        emit ProxyActionsOperation(\"AjnaRepay\");\n    }\n\n    /**\n     *  @notice Withdraw collateral\n     *  @param  pool           Pool address\n     *  @param  amount         Amount of collateral to withdraw\n     */\n    function withdrawCollateral(IERC20Pool pool, uint256 amount) public {\n        address collateralToken = pool.collateralAddress();\n        (, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(\n            address(pool)\n        );\n        pool.repayDebt(\n            address(this),\n            0,\n            amount * pool.collateralScale(),\n            address(this),\n            lupIndex_\n        );\n        _send(collateralToken, amount);\n        emit ProxyActionsOperation(\"AjnaWithdraw\");\n    }\n\n    /**\n     *  @notice Repay debt and withdraw collateral\n     *  @param  pool           Pool address\n     *  @param  debtAmount         Amount of debt to repay\n     *  @param  collateralAmount         Amount of collateral to withdraw\n     */\n    function repayDebtAndWithdrawCollateral(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 collateralAmount\n    ) public {\n        address debtToken = pool.quoteTokenAddress();\n        address collateralToken = pool.collateralAddress();\n        _pull(debtToken, debtAmount);\n        IERC20(debtToken).approve(address(pool), debtAmount);\n        (, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(\n            address(pool)\n        );\n        uint256 repaidAmountWAD = pool.repayDebt(\n            address(this),\n            debtAmount * pool.quoteTokenScale(),\n            collateralAmount * pool.collateralScale(),\n            address(this),\n            lupIndex_\n        );\n        _send(collateralToken, collateralAmount);\n        uint256 repaidAmount = _roundUpToScale(\n            repaidAmountWAD,\n            pool.quoteTokenScale()\n        ) / pool.quoteTokenScale();\n        uint256 quoteLeftoverBalance = debtAmount - repaidAmount;\n        if (quoteLeftoverBalance > 0) {\n            _send(debtToken, quoteLeftoverBalance);\n        }\n        IERC20(debtToken).safeApprove(address(pool), 0);\n        emit ProxyActionsOperation(\"AjnaRepayWithdraw\");\n    }\n\n    /**\n     *  @notice Repay debt and withdraw collateral for msg.sender\n     *  @param  pool           Pool address\n     *  @param  debtAmount     Amount of debt to repay\n     *  @param  collateralAmount Amount of collateral to withdraw\n     *  @param stamploanEnabled      Whether to stamp the loan or not\n     */\n    function repayWithdraw(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 collateralAmount,\n        bool stamploanEnabled\n    ) external payable {\n        if (debtAmount > 0 && collateralAmount > 0) {\n            repayDebtAndWithdrawCollateral(pool, debtAmount, collateralAmount);\n        } else if (debtAmount > 0) {\n            repayDebt(pool, debtAmount, stamploanEnabled);\n        } else if (collateralAmount > 0) {\n            withdrawCollateral(pool, collateralAmount);\n        }\n    }\n\n    /**\n     *  @notice Repay debt and close position for msg.sender\n     *  @param  pool           Pool address\n     */\n    function repayAndClose(IERC20Pool pool) public payable {\n        address collateralToken = pool.collateralAddress();\n        address debtToken = pool.quoteTokenAddress();\n\n        (uint256 debt, uint256 collateral, ) = poolInfoUtils.borrowerInfo(\n            address(pool),\n            address(this)\n        );\n        uint256 debtPlusBuffer = _roundUpToScale(debt, pool.quoteTokenScale());\n        uint256 amountDebt = debtPlusBuffer / pool.quoteTokenScale();\n        _pull(debtToken, amountDebt);\n\n        IERC20(debtToken).approve(address(pool), amountDebt);\n        (, , , , , uint256 lupIndex_) = poolInfoUtils.poolPricesInfo(\n            address(pool)\n        );\n        pool.repayDebt(\n            address(this),\n            debtPlusBuffer,\n            collateral,\n            address(this),\n            lupIndex_\n        );\n\n        uint256 amountCollateral = collateral / pool.collateralScale();\n        _send(collateralToken, amountCollateral);\n        IERC20(debtToken).safeApprove(address(pool), 0);\n        emit ProxyActionsOperation(\"AjnaRepayAndClose\");\n    }\n\n    /**\n     *  @notice Open position for msg.sender\n     *  @param  pool           Pool address\n     *  @param  debtAmount     Amount of debt to borrow\n     *  @param  collateralAmount Amount of collateral to deposit\n     *  @param  price          Price of the bucket\n     */\n    function openPosition(\n        IERC20Pool pool,\n        uint256 debtAmount,\n        uint256 collateralAmount,\n        uint256 price\n    ) public payable {\n        emit CreatePosition(\n            address(this),\n            ajnaVersion,\n            \"Borrow\",\n            pool.collateralAddress(),\n            pool.quoteTokenAddress()\n        );\n        depositAndDraw(pool, debtAmount, collateralAmount, price, false);\n    }\n\n    /**\n     *  @notice Open Earn position for msg.sender\n     *  @param  pool           Pool address\n     *  @param  depositAmount     Amount of debt to borrow\n     *  @param  price          Price of the bucket\n     */\n    function openEarnPosition(\n        IERC20Pool pool,\n        uint256 depositAmount,\n        uint256 price\n    ) public payable {\n        emit CreatePosition(\n            address(this),\n            ajnaVersion,\n            \"Earn\",\n            pool.collateralAddress(),\n            pool.quoteTokenAddress()\n        );\n        _validateBucketState(pool, convertPriceToIndex(price));\n        _supplyQuote(pool, depositAmount, price);\n        emit ProxyActionsOperation(\"AjnaSupplyQuote\");\n    }\n\n    /**\n     *  @notice Called by lenders to add an amount of credit at a specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  amount       The maximum amount of quote token to be moved by a lender.\n     *  @param  price        The price the bucket to which the quote tokens will be added.\n\n     *  @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance\n     *  @dev 1WBTC = 16,990.23 USDC   translates to: 16990230\n     */\n    function supplyQuote(\n        IERC20Pool pool,\n        uint256 amount,\n        uint256 price\n    ) public payable {\n        _validateBucketState(pool, convertPriceToIndex(price));\n        _supplyQuote(pool, amount, price);\n        emit ProxyActionsOperation(\"AjnaSupplyQuote\");\n    }\n\n    /**\n     *  @notice Called by lenders to remove an amount of credit at a specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  amount       The maximum amount of quote token to be moved by a lender.\n     *  @param  price        The price the bucket to which the quote tokens will be added.\n     *  @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 3 decimal points for instance\n     *  @dev 1WBTC = 16,990.23 USDC   translates to: 16990230\n     */\n    function withdrawQuote(\n        IERC20Pool pool,\n        uint256 amount,\n        uint256 price\n    ) public {\n        _withdrawQuote(pool, amount, price);\n        emit ProxyActionsOperation(\"AjnaWithdrawQuote\");\n    }\n\n    /**\n     *  @notice Called by lenders to move max amount of credit from a specified price bucket to another specified price bucket.\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  oldPrice        The price of the bucket  from which the quote tokens will be removed.\n     *  @param  newPrice     The price of the bucket to which the quote tokens will be added.\n\n     */\n    function moveQuote(\n        IERC20Pool pool,\n        uint256 oldPrice,\n        uint256 newPrice\n    ) public {\n        _validateBucketState(pool, convertPriceToIndex(newPrice));\n        _moveQuote(pool, oldPrice, newPrice);\n        emit ProxyActionsOperation(\"AjnaMoveQuote\");\n    }\n\n    /**\n     *  @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket,\n     *  @notice whilst adding additional amount.\n     *  @param  pool            Address of the Ajna Pool.\n     *  @param  amountToAdd     The maximum amount of quote token to be moved by a lender.\n     *  @param  oldPrice        The price of the bucket  from which the quote tokens will be removed.\n     *  @param  newPrice        The price of the bucket to which the quote tokens will be added.\n\n     */\n    function supplyAndMoveQuote(\n        IERC20Pool pool,\n        uint256 amountToAdd,\n        uint256 oldPrice,\n        uint256 newPrice\n    ) public payable {\n        uint256 newIndex = convertPriceToIndex(newPrice);\n        _validateBucketState(pool, newIndex);\n        _supplyQuote(pool, amountToAdd, newPrice);\n        _validateBucketState(pool, newIndex);\n        _moveQuote(pool, oldPrice, newPrice);\n        emit ProxyActionsOperation(\"AjnaSupplyAndMoveQuote\");\n    }\n\n    /**\n     *  @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket,\n     *  @notice whilst withdrawing additional amount.\n     *  @param  pool            Address of the Ajna Pool.\n     *  @param  amountToWithdraw     Amount of quote token to be withdrawn by a lender.\n     *  @param  oldPrice        The price of the bucket  from which the quote tokens will be removed.\n     *  @param  newPrice        The price of the bucket to which the quote tokens will be added.\n\n     */\n    function withdrawAndMoveQuote(\n        IERC20Pool pool,\n        uint256 amountToWithdraw,\n        uint256 oldPrice,\n        uint256 newPrice\n    ) public {\n        _withdrawQuote(pool, amountToWithdraw, oldPrice);\n        _validateBucketState(pool, convertPriceToIndex(newPrice));\n        _moveQuote(pool, oldPrice, newPrice);\n        emit ProxyActionsOperation(\"AjnaWithdrawAndMoveQuote\");\n    }\n\n    /**\n     * @notice Reclaims collateral from liquidated bucket\n     * @param  pool         Address of the Ajna Pool.\n     * @param  price        Price of the bucket to redeem.\n     */\n    function removeCollateral(IERC20Pool pool, uint256 price) public {\n        _removeCollateral(pool, price);\n        emit ProxyActionsOperation(\"AjnaRemoveCollateral\");\n    }\n\n    // VIEW FUNCTIONS\n    /**\n     * @notice  Converts price to index\n     * @param   price   price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance\n     * @return index   index of the bucket\n     * @dev     price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance\n     * @dev     1WBTC = 16,990.23 USDC   translates to: 16990230000000000000000\n     */\n    function convertPriceToIndex(uint256 price) public view returns (uint256) {\n        return poolInfoUtils.priceToIndex(price);\n    }\n\n    /**\n     * @dev Validates the state of a bucket in an IERC20Pool contract.\n     * @param pool The IERC20Pool contract address.\n     * @param bucket The index of the bucket to validate.\n     */\n    function _validateBucketState(IERC20Pool pool, uint256 bucket) public view {\n        (, , , uint256 bucketLP_, , ) = poolInfoUtils.bucketInfo(\n            address(pool),\n            bucket\n        );\n        require(\n            bucketLP_ == 0 || bucketLP_ > 1_000_000,\n            \"apa/bucket-lps-invalid\"\n        );\n    }\n\n    /**\n     *  @notice Get the amount of quote token deposited to a specific bucket\n     *  @param  pool         Address of the Ajna Pool.\n     *  @param  price        Price of the bucket to query\n     *  @return  quoteAmount Amount of quote token deposited to dpecific bucket\n     *  @dev price of uint (10**decimals) collateral token in debt token (10**decimals) with 18 decimal points for instance\n     *  @dev     1WBTC = 16,990.23 USDC   translates to: 16990230000000000000000\n     */\n    function getQuoteAmount(IERC20Pool pool, uint256 price)\n        public\n        view\n        returns (uint256 quoteAmount)\n    {\n        uint256 index = convertPriceToIndex(price);\n\n        (uint256 lpCount, ) = pool.lenderInfo(index, address(this));\n        quoteAmount = poolInfoUtils.lpToQuoteTokens(\n            address(pool),\n            lpCount,\n            index\n        );\n    }\n\n    /**\n     *  @notice Rounds a token amount down to the minimum amount permissible by the token scale.\n     *  @param  amount_       Value to be rounded.\n     *  @param  tokenScale_   Scale of the token, presented as a power of `10`.\n     *  @return scaledAmount_ Rounded value.\n     */\n    function _roundToScale(uint256 amount_, uint256 tokenScale_)\n        internal\n        pure\n        returns (uint256 scaledAmount_)\n    {\n        scaledAmount_ = (amount_ / tokenScale_) * tokenScale_;\n    }\n\n    /**\n     *  @notice Rounds a token amount up to the next amount permissible by the token scale.\n     *  @param  amount_       Value to be rounded.\n     *  @param  tokenScale_   Scale of the token, presented as a power of `10`.\n     *  @return scaledAmount_ Rounded value.\n     */\n    function _roundUpToScale(uint256 amount_, uint256 tokenScale_)\n        internal\n        pure\n        returns (uint256 scaledAmount_)\n    {\n        if (amount_ % tokenScale_ == 0) scaledAmount_ = amount_;\n        else scaledAmount_ = _roundToScale(amount_, tokenScale_) + tokenScale_;\n    }\n}\n"
      },
      "src/interfaces/summerfi/IAjnaRedeemer.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.18;\n\n/**\n * @title AjnaRedeemer\n * @notice A contract that allows users to redeem their Ajna tokens for rewards. Pulls Ajan tokens from the Ajna Dripper contract.\n *\n * ROLES:\n * - `OPERATOR_ROLE`: Can add weekly reward snapshot merkle tree roots.\n * - `EMERGENCY_ROLE`: Can withdraw all the Ajna tokens to AjnaDripper contract in case of emergency.\n */\ninterface IAjnaRedeemer {\n    function deploymentWeek() external returns (uint256);\n\n    /**\n     * @dev Gets the current week number since the UNIX epoch.\n     *\n     * The week is defined as a 7 day period starting from Thursday at 00:00:00 UTC. This means that\n     * the week number changes on Thursdays, and that Thursday is always considered part of the current week.\n     *\n     * Effects:\n     * - Calculates the current week by dividing the block timestamp by 1 week.\n     *\n     * @return The current week number since the UNIX epoch as a uint256 value.\n     */\n    function getCurrentWeek() external view returns (uint256);\n\n    /**\n     * @dev Adds a Merkle root for a given week.\n     *\n     * Requirements:\n     * - The caller must have the OPERATOR_ROLE.\n     * - The provided week number must be greater than or equal to the deployment week.\n     * - The provided week number must not be greater than the current week number.\n     * - The provided week must not already have a root set.\n     * - The drip call from the Ajna Dripper contract must succeed.\n     *\n     * Effects:\n     * - Sets the provided Merkle root for the given week.\n     *\n     * @param week The week number for which to add the Merkle root.\n     * @param root The Merkle root to be added for the specified week.\n     */\n    function addRoot(uint256 week, bytes32 root) external;\n\n    /**\n     * @dev Retrieves the Merkle root for a given week.\n     *\n     * Requirements:\n     * - The provided week must have a root set.\n     *\n     * Effects:\n     * - None.\n     *\n     * @param week The week number for which to retrieve the Merkle root.\n     * @return The Merkle root associated with the specified week.\n     *\n     * @notice returns bytes32(0) if the provided week does not have a root set.\n     */\n    function getRoot(uint256 week) external view returns (bytes32);\n\n    /**\n     * @dev Claims multiple rewards using Merkle proofs.\n     *\n     * Requirements:\n     * - The number of weeks, amounts, and proofs given must all match.\n     * - The caller must not have already claimed any of the specified weeks' rewards.\n     * - The provided proofs must be valid and eligible to claim a reward for their corresponding weeks and amounts.\n     *\n     * Effects:\n     * - Rewards will be transferred to the caller's account if the claims are successful.\n     * - Logs an event with the details of each successful claim.\n     *\n     * @param _weeks An array of week numbers for which to claim rewards.\n     * @param amounts An array of reward amounts to claim.\n     * @param proofs An array of Merkle proofs, one for each corresponding week and amount given.\n     *\n     * @notice This function throws an exception if the provided parameters are invalid or the caller has already claimed rewards for one or more of the specified weeks. Additionally, it transfers rewards to the caller if all claims are successful.\n     */\n    function claimMultiple(\n        uint256[] calldata _weeks,\n        uint256[] calldata amounts,\n        bytes32[][] calldata proofs\n    ) external;\n\n    /**\n     * @dev Determines if the caller is eligible to claim a reward for a specified week and amount using a Merkle proof.\n     *\n     * Requirements:\n     * - The provided Merkle proof must be valid for the given week and amount.\n     *\n     * @param proof A Merkle proof, which should be generated from the root of the Merkle tree for the corresponding week.\n     * @param week The number of the week for which to check eligibility.\n     * @param amount The amount of rewards to claim.\n     *\n     * @return A boolean indicating whether or not the caller is eligible to claim rewards for the given week and amount using the provided Merkle proof.\n     *\n     * @notice This function does not modify any state.\n     */\n    function canClaim(\n        bytes32[] memory proof,\n        uint256 week,\n        uint256 amount\n    ) external view returns (bool);\n\n    /**\n     * @dev Allows a user with the EMERGENCY_ROLE to withdraw all AjnaToken tokens held by this contract.\n     *\n     * Requirements:\n     * - The caller must have the EMERGENCY_ROLE.\n     * - The contract must hold a non-zero balance of AjnaToken tokens.\n     *\n     * Effects:\n     * - Transfers the entire balance of AjnaToken tokens held by this contract to the designated \"drip\" address.\n     *\n     * @notice This function should only be used in emergency situations and may result in significant loss of funds if used improperly.\n     */\n\n    function emergencyWithdraw() external;\n}\n"
      },
      "src/interfaces/chainlink/IChainlinkAggregator.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.12;\n\ninterface IChainlinkAggregator {\n    function latestAnswer() external view returns (int256);\n\n    function latestTimestamp() external view returns (uint256);\n\n    function latestRound() external view returns (uint256);\n\n    function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);\n\n    function getAnswer(uint256 roundId) external view returns (int256);\n\n    function getTimestamp(uint256 roundId) external view returns (uint256);\n\n    event AnswerUpdated(\n        int256 indexed current,\n        uint256 indexed roundId,\n        uint256 updatedAt\n    );\n\n    event NewRound(\n        uint256 indexed roundId,\n        address indexed startedBy,\n        uint256 startedAt\n    );\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20 is Context, IERC20, IERC20Metadata {\n    mapping(address => uint256) private _balances;\n\n    mapping(address => mapping(address => uint256)) private _allowances;\n\n    uint256 private _totalSupply;\n\n    string private _name;\n    string private _symbol;\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * All two of these values are immutable: they can only be set once during\n     * construction.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual override returns (string memory) {\n        return _name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual override returns (string memory) {\n        return _symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual override returns (uint8) {\n        return 18;\n    }\n\n    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual override returns (uint256) {\n        return _totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\n    function balanceOf(address account) public view virtual override returns (uint256) {\n        return _balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `amount`.\n     */\n    function transfer(address to, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-allowance}.\n     */\n    function allowance(address owner, address spender) public view virtual override returns (uint256) {\n        return _allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 amount) public virtual override returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, amount);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Emits an {Approval} event indicating the updated allowance. This is not\n     * required by the EIP. See the note at the beginning of {ERC20}.\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `amount`.\n     */\n    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, amount);\n        _transfer(from, to, amount);\n        return true;\n    }\n\n    /**\n     * @dev Atomically increases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, allowance(owner, spender) + addedValue);\n        return true;\n    }\n\n    /**\n     * @dev Atomically decreases the allowance granted to `spender` by the caller.\n     *\n     * This is an alternative to {approve} that can be used as a mitigation for\n     * problems described in {IERC20-approve}.\n     *\n     * Emits an {Approval} event indicating the updated allowance.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `spender` must have allowance for the caller of at least\n     * `subtractedValue`.\n     */\n    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n        address owner = _msgSender();\n        uint256 currentAllowance = allowance(owner, spender);\n        require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n        unchecked {\n            _approve(owner, spender, currentAllowance - subtractedValue);\n        }\n\n        return true;\n    }\n\n    /**\n     * @dev Moves `amount` of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `from` must have a balance of at least `amount`.\n     */\n    function _transfer(address from, address to, uint256 amount) internal virtual {\n        require(from != address(0), \"ERC20: transfer from the zero address\");\n        require(to != address(0), \"ERC20: transfer to the zero address\");\n\n        _beforeTokenTransfer(from, to, amount);\n\n        uint256 fromBalance = _balances[from];\n        require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n        unchecked {\n            _balances[from] = fromBalance - amount;\n            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n            // decrementing then incrementing.\n            _balances[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        _afterTokenTransfer(from, to, amount);\n    }\n\n    /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n     * the total supply.\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     */\n    function _mint(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: mint to the zero address\");\n\n        _beforeTokenTransfer(address(0), account, amount);\n\n        _totalSupply += amount;\n        unchecked {\n            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n            _balances[account] += amount;\n        }\n        emit Transfer(address(0), account, amount);\n\n        _afterTokenTransfer(address(0), account, amount);\n    }\n\n    /**\n     * @dev Destroys `amount` tokens from `account`, reducing the\n     * total supply.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * Requirements:\n     *\n     * - `account` cannot be the zero address.\n     * - `account` must have at least `amount` tokens.\n     */\n    function _burn(address account, uint256 amount) internal virtual {\n        require(account != address(0), \"ERC20: burn from the zero address\");\n\n        _beforeTokenTransfer(account, address(0), amount);\n\n        uint256 accountBalance = _balances[account];\n        require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n        unchecked {\n            _balances[account] = accountBalance - amount;\n            // Overflow not possible: amount <= accountBalance <= totalSupply.\n            _totalSupply -= amount;\n        }\n\n        emit Transfer(account, address(0), amount);\n\n        _afterTokenTransfer(account, address(0), amount);\n    }\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     */\n    function _approve(address owner, address spender, uint256 amount) internal virtual {\n        require(owner != address(0), \"ERC20: approve from the zero address\");\n        require(spender != address(0), \"ERC20: approve to the zero address\");\n\n        _allowances[owner][spender] = amount;\n        emit Approval(owner, spender, amount);\n    }\n\n    /**\n     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n     *\n     * Does not update the allowance amount in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Might emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance != type(uint256).max) {\n            require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n            unchecked {\n                _approve(owner, spender, currentAllowance - amount);\n            }\n        }\n    }\n\n    /**\n     * @dev Hook that is called before any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * will be transferred to `to`.\n     * - when `from` is zero, `amount` tokens will be minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n\n    /**\n     * @dev Hook that is called after any transfer of tokens. This includes\n     * minting and burning.\n     *\n     * Calling conditions:\n     *\n     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n     * has been transferred to `to`.\n     * - when `from` is zero, `amount` tokens have been minted for `to`.\n     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n     * - `from` and `to` are never both zero.\n     *\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n     */\n    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}\n}\n"
      },
      "lib/tokenized-strategy/src/interfaces/ITokenizedStrategy.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {IERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\";\n\n// Interface that implements the 4626 standard and the implementation functions\ninterface ITokenizedStrategy is IERC4626, IERC20Permit {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event StrategyShutdown();\n\n    event NewTokenizedStrategy(\n        address indexed strategy,\n        address indexed asset,\n        string apiVersion\n    );\n\n    event Reported(\n        uint256 profit,\n        uint256 loss,\n        uint256 protocolFees,\n        uint256 performanceFees\n    );\n\n    event UpdatePerformanceFeeRecipient(\n        address indexed newPerformanceFeeRecipient\n    );\n\n    event UpdateKeeper(address indexed newKeeper);\n\n    event UpdatePerformanceFee(uint16 newPerformanceFee);\n\n    event UpdateManagement(address indexed newManagement);\n\n    event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);\n\n    event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime);\n\n    event UpdatePendingManagement(address indexed newPendingManagement);\n\n    /*//////////////////////////////////////////////////////////////\n                           INITIALIZATION\n    //////////////////////////////////////////////////////////////*/\n\n    function initialize(\n        address _asset,\n        string memory _name,\n        address _management,\n        address _performanceFeeRecipient,\n        address _keeper\n    ) external;\n\n    /*//////////////////////////////////////////////////////////////\n                    NON-STANDARD 4626 OPTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function withdraw(\n        uint256 assets,\n        address receiver,\n        address owner,\n        uint256 maxLoss\n    ) external returns (uint256);\n\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address owner,\n        uint256 maxLoss\n    ) external returns (uint256);\n\n    /*//////////////////////////////////////////////////////////////\n                        MODIFIER HELPERS\n    //////////////////////////////////////////////////////////////*/\n\n    function requireManagement(address _sender) external view;\n\n    function requireKeeperOrManagement(address _sender) external view;\n\n    function requireEmergencyAuthorized(address _sender) external view;\n\n    /*//////////////////////////////////////////////////////////////\n                        KEEPERS FUNCTIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function tend() external;\n\n    function report() external returns (uint256 _profit, uint256 _loss);\n\n    /*//////////////////////////////////////////////////////////////\n                        CONSTANTS\n    //////////////////////////////////////////////////////////////*/\n\n    function MAX_FEE() external view returns (uint16);\n\n    function FACTORY() external view returns (address);\n\n    /*//////////////////////////////////////////////////////////////\n                            GETTERS\n    //////////////////////////////////////////////////////////////*/\n\n    function apiVersion() external view returns (string memory);\n\n    function pricePerShare() external view returns (uint256);\n\n    function management() external view returns (address);\n\n    function pendingManagement() external view returns (address);\n\n    function keeper() external view returns (address);\n\n    function emergencyAdmin() external view returns (address);\n\n    function performanceFee() external view returns (uint16);\n\n    function performanceFeeRecipient() external view returns (address);\n\n    function fullProfitUnlockDate() external view returns (uint256);\n\n    function profitUnlockingRate() external view returns (uint256);\n\n    function profitMaxUnlockTime() external view returns (uint256);\n\n    function lastReport() external view returns (uint256);\n\n    function isShutdown() external view returns (bool);\n\n    function unlockedShares() external view returns (uint256);\n\n    /*//////////////////////////////////////////////////////////////\n                            SETTERS\n    //////////////////////////////////////////////////////////////*/\n\n    function setPendingManagement(address) external;\n\n    function acceptManagement() external;\n\n    function setKeeper(address _keeper) external;\n\n    function setEmergencyAdmin(address _emergencyAdmin) external;\n\n    function setPerformanceFee(uint16 _performanceFee) external;\n\n    function setPerformanceFeeRecipient(\n        address _performanceFeeRecipient\n    ) external;\n\n    function setProfitMaxUnlockTime(uint256 _profitMaxUnlockTime) external;\n\n    function shutdownStrategy() external;\n\n    function emergencyWithdraw(uint256 _amount) external;\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/Auctions/AuctionFactory.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {Auction} from \"./Auction.sol\";\nimport {Clonable} from \"../utils/Clonable.sol\";\n\n/// @title AuctionFactory\n/// @notice Deploy a new Auction.\ncontract AuctionFactory is Clonable {\n    event DeployedNewAuction(address indexed auction, address indexed want);\n\n    /// @notice The time that each auction lasts.\n    uint256 public constant DEFAULT_AUCTION_LENGTH = 1 days;\n\n    /// @notice The minimum time to wait between auction 'kicks'.\n    uint256 public constant DEFAULT_AUCTION_COOLDOWN = 5 days;\n\n    /// @notice The amount to start the auction with.\n    uint256 public constant DEFAULT_STARTING_PRICE = 1_000_000;\n\n    /// @notice Full array of all auctions deployed through this factory.\n    address[] public auctions;\n\n    constructor() {\n        // Deploy the original\n        original = address(new Auction());\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(address _want) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                address(0),\n                msg.sender,\n                DEFAULT_AUCTION_LENGTH,\n                DEFAULT_AUCTION_COOLDOWN,\n                DEFAULT_STARTING_PRICE\n            );\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @param _hook Address of the hook contract if any.\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(\n        address _want,\n        address _hook\n    ) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                _hook,\n                msg.sender,\n                DEFAULT_AUCTION_LENGTH,\n                DEFAULT_AUCTION_COOLDOWN,\n                DEFAULT_STARTING_PRICE\n            );\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @param _hook Address of the hook contract if any.\n     * @param _governance Address allowed to enable and disable auctions.\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(\n        address _want,\n        address _hook,\n        address _governance\n    ) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                _hook,\n                _governance,\n                DEFAULT_AUCTION_LENGTH,\n                DEFAULT_AUCTION_COOLDOWN,\n                DEFAULT_STARTING_PRICE\n            );\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @param _hook Address of the hook contract if any.\n     * @param _governance Address allowed to enable and disable auctions.\n     * @param _auctionLength Length of the auction in seconds.\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(\n        address _want,\n        address _hook,\n        address _governance,\n        uint256 _auctionLength\n    ) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                _hook,\n                _governance,\n                _auctionLength,\n                DEFAULT_AUCTION_COOLDOWN,\n                DEFAULT_STARTING_PRICE\n            );\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @param _hook Address of the hook contract if any.\n     * @param _governance Address allowed to enable and disable auctions.\n     * @param _auctionLength Length of the auction in seconds.\n     * @param _auctionCooldown Minimum time period between kicks in seconds.\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(\n        address _want,\n        address _hook,\n        address _governance,\n        uint256 _auctionLength,\n        uint256 _auctionCooldown\n    ) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                _hook,\n                _governance,\n                _auctionLength,\n                _auctionCooldown,\n                DEFAULT_STARTING_PRICE\n            );\n    }\n\n    /**\n     * @notice Creates a new auction contract.\n     * @param _want Address of the token users will bid with.\n     * @param _hook Address of the hook contract if any.\n     * @param _governance Address allowed to enable and disable auctions.\n     * @param _auctionLength Length of the auction in seconds.\n     * @param _auctionCooldown Minimum time period between kicks in seconds.\n     * @param _startingPrice Starting price for the auction (no decimals).\n     *  NOTE: The starting price should be without decimals (1k == 1_000).\n     * @return _newAuction Address of the newly created auction contract.\n     */\n    function createNewAuction(\n        address _want,\n        address _hook,\n        address _governance,\n        uint256 _auctionLength,\n        uint256 _auctionCooldown,\n        uint256 _startingPrice\n    ) external returns (address) {\n        return\n            _createNewAuction(\n                _want,\n                _hook,\n                _governance,\n                _auctionLength,\n                _auctionCooldown,\n                _startingPrice\n            );\n    }\n\n    /**\n     * @dev Deploys and initializes a new Auction\n     */\n    function _createNewAuction(\n        address _want,\n        address _hook,\n        address _governance,\n        uint256 _auctionLength,\n        uint256 _auctionCooldown,\n        uint256 _startingPrice\n    ) internal returns (address _newAuction) {\n        _newAuction = _clone();\n\n        Auction(_newAuction).initialize(\n            _want,\n            _hook,\n            _governance,\n            _auctionLength,\n            _auctionCooldown,\n            _startingPrice\n        );\n\n        auctions.push(_newAuction);\n\n        emit DeployedNewAuction(_newAuction, _want);\n    }\n\n    /**\n     * @notice Get the full list of auctions deployed through this factory.\n     */\n    function getAllAuctions() external view returns (address[] memory) {\n        return auctions;\n    }\n\n    /**\n     * @notice Get the total number of auctions deployed through this factory.\n     */\n    function numberOfAuctions() external view returns (uint256) {\n        return auctions.length;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (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 *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\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     * CAUTION: See Security Considerations above.\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"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/IPool.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\nimport { IPoolBorrowerActions } from './commons/IPoolBorrowerActions.sol';\nimport { IPoolLPActions }       from './commons/IPoolLPActions.sol';\nimport { IPoolLenderActions }   from './commons/IPoolLenderActions.sol';\nimport { IPoolKickerActions }   from './commons/IPoolKickerActions.sol';\nimport { IPoolTakerActions }    from './commons/IPoolTakerActions.sol';\nimport { IPoolSettlerActions }  from './commons/IPoolSettlerActions.sol';\n\nimport { IPoolImmutables }      from './commons/IPoolImmutables.sol';\nimport { IPoolState }           from './commons/IPoolState.sol';\nimport { IPoolDerivedState }    from './commons/IPoolDerivedState.sol';\nimport { IPoolEvents }          from './commons/IPoolEvents.sol';\nimport { IPoolErrors }          from './commons/IPoolErrors.sol';\nimport { IERC3156FlashLender }  from './IERC3156FlashLender.sol';\n\n/**\n * @title Base Pool Interface\n */\ninterface IPool is\n    IPoolBorrowerActions,\n    IPoolLPActions,\n    IPoolLenderActions,\n    IPoolKickerActions,\n    IPoolTakerActions,\n    IPoolSettlerActions,\n    IPoolImmutables,\n    IPoolState,\n    IPoolDerivedState,\n    IPoolEvents,\n    IPoolErrors,\n    IERC3156FlashLender\n{\n\n}\n\n/// @dev Pool type enum - `ERC20` and `ERC721`\nenum PoolType { ERC20, ERC721 }\n\n/// @dev `ERC20` token interface.\ninterface IERC20Token {\n    function balanceOf(address account) external view returns (uint256);\n    function burn(uint256 amount) external;\n    function decimals() external view returns (uint8);\n}\n\n/// @dev `ERC721` token interface.\ninterface IERC721Token {\n    function transferFrom(\n        address from,\n        address to,\n        uint256 tokenId\n    ) external;\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/erc20/IERC20PoolBorrowerActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title ERC20 Pool Borrower Actions\n */\ninterface IERC20PoolBorrowerActions {\n\n    /**\n     *  @notice Called by borrowers to add collateral to the pool and/or borrow quote from the pool.\n     *  @dev    Can be called by borrowers with either `0` `amountToBorrow_` or `0` `collateralToPledge_`, if borrower only wants to take a single action. \n     *  @param  borrowerAddress_    The borrower to whom collateral was pledged, and/or debt was drawn for.\n     *  @param  amountToBorrow_     The amount of quote tokens to borrow (`WAD` precision).\n     *  @param  limitIndex_         Lower bound of `LUP` change (if any) that the borrower will tolerate from a creating or modifying position.\n     *  @param  collateralToPledge_ The amount of collateral to be added to the pool (`WAD` precision).\n     */\n    function drawDebt(\n        address borrowerAddress_,\n        uint256 amountToBorrow_,\n        uint256 limitIndex_,\n        uint256 collateralToPledge_\n    ) external;\n\n    /**\n     *  @notice Called by borrowers to repay borrowed quote to the pool, and/or pull collateral form the pool.\n     *  @dev    Can be called by borrowers with either `0` `maxQuoteTokenAmountToRepay_` or `0` `collateralAmountToPull_`, if borrower only wants to take a single action. \n     *  @param  borrowerAddress_            The borrower whose loan is being interacted with.\n     *  @param  maxQuoteTokenAmountToRepay_ The max amount of quote tokens to repay (`WAD` precision).\n     *  @param  collateralAmountToPull_     The max amount of collateral to be puled from the pool (`WAD` precision).\n     *  @param  recipient_                  The address to receive amount of pulled collateral.\n     *  @param  limitIndex_                 Ensures `LUP` has not moved far from state when borrower pulls collateral.\n     *  @return amountRepaid_               The amount of quote token repaid (`WAD` precision).\n     */\n    function repayDebt(\n        address borrowerAddress_,\n        uint256 maxQuoteTokenAmountToRepay_,\n        uint256 collateralAmountToPull_,\n        address recipient_,\n        uint256 limitIndex_\n    ) external returns (uint256 amountRepaid_);\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/erc20/IERC20PoolLenderActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title ERC20 Pool Lender Actions\n */\ninterface IERC20PoolLenderActions {\n\n    /**\n     *  @notice Deposit claimable collateral into a specified bucket.\n     *  @param  amountToAdd_ Amount of collateral to deposit (`WAD` precision).\n     *  @param  index_       The bucket index to which collateral will be deposited.\n     *  @param  expiry_      Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.\n     *  @return bucketLP_    The amount of `LP` awarded for the added collateral (`WAD` precision).\n     */\n    function addCollateral(\n        uint256 amountToAdd_,\n        uint256 index_,\n        uint256 expiry_\n    ) external returns (uint256 bucketLP_);\n}"
      },
      "lib/ajna-core/src/interfaces/pool/erc20/IERC20PoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title ERC20 Pool Immutables\n */\ninterface IERC20PoolImmutables {\n\n    /**\n     *  @notice Returns the `collateralScale` immutable.\n     *  @return The precision of the collateral `ERC20` token based on decimals.\n     */\n    function collateralScale() external view returns (uint256);\n\n}"
      },
      "lib/ajna-core/src/interfaces/pool/erc20/IERC20PoolEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title ERC20 Pool Events\n */\ninterface IERC20PoolEvents {\n\n    /**\n     *  @notice Emitted when actor adds claimable collateral to a bucket.\n     *  @param  actor     Recipient that added collateral.\n     *  @param  index     Index at which collateral were added.\n     *  @param  amount    Amount of collateral added to the pool (`WAD` precision).\n     *  @param  lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).\n     */\n    event AddCollateral(\n        address indexed actor,\n        uint256 indexed index,\n        uint256 amount,\n        uint256 lpAwarded\n    );\n\n    /**\n     *  @notice Emitted when borrower draws debt from the pool, or adds collateral to the pool.\n     *  @param  borrower          The borrower to whom collateral was pledged, and/or debt was drawn for.\n     *  @param  amountBorrowed    Amount of quote tokens borrowed from the pool (`WAD` precision).\n     *  @param  collateralPledged Amount of collateral locked in the pool (`WAD` precision).\n     *  @param  lup               `LUP` after borrow.\n     */\n    event DrawDebt(\n        address indexed borrower,\n        uint256 amountBorrowed,\n        uint256 collateralPledged,\n        uint256 lup\n    );\n}\n"
      },
      "lib/ajna-core/lib/prb-math/contracts/PRBMathSD59x18.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\nimport \"./PRBMath.sol\";\n\n/// @title PRBMathSD59x18\n/// @author Paul Razvan Berg\n/// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18\n/// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have\n/// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers\n/// are bound by the minimum and the maximum values permitted by the Solidity type int256.\nlibrary PRBMathSD59x18 {\n    /// @dev log2(e) as a signed 59.18-decimal fixed-point number.\n    int256 internal constant LOG2_E = 1_442695040888963407;\n\n    /// @dev Half the SCALE number.\n    int256 internal constant HALF_SCALE = 5e17;\n\n    /// @dev The maximum value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MAX_SD59x18 =\n        57896044618658097711785492504343953926634992332820282019728_792003956564819967;\n\n    /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MAX_WHOLE_SD59x18 =\n        57896044618658097711785492504343953926634992332820282019728_000000000000000000;\n\n    /// @dev The minimum value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MIN_SD59x18 =\n        -57896044618658097711785492504343953926634992332820282019728_792003956564819968;\n\n    /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have.\n    int256 internal constant MIN_WHOLE_SD59x18 =\n        -57896044618658097711785492504343953926634992332820282019728_000000000000000000;\n\n    /// @dev How many trailing decimals can be represented.\n    int256 internal constant SCALE = 1e18;\n\n    /// INTERNAL FUNCTIONS ///\n\n    /// @notice Calculate the absolute value of x.\n    ///\n    /// @dev Requirements:\n    /// - x must be greater than MIN_SD59x18.\n    ///\n    /// @param x The number to calculate the absolute value for.\n    /// @param result The absolute value of x.\n    function abs(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            if (x == MIN_SD59x18) {\n                revert PRBMathSD59x18__AbsInputTooSmall();\n            }\n            result = x < 0 ? -x : x;\n        }\n    }\n\n    /// @notice Calculates the arithmetic average of x and y, rounding down.\n    /// @param x The first operand as a signed 59.18-decimal fixed-point number.\n    /// @param y The second operand as a signed 59.18-decimal fixed-point number.\n    /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number.\n    function avg(int256 x, int256 y) internal pure returns (int256 result) {\n        // The operations can never overflow.\n        unchecked {\n            int256 sum = (x >> 1) + (y >> 1);\n            if (sum < 0) {\n                // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the\n                // right rounds down to infinity.\n                assembly {\n                    result := add(sum, and(or(x, y), 1))\n                }\n            } else {\n                // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5\n                // remainder gets truncated twice.\n                result = sum + (x & y & 1);\n            }\n        }\n    }\n\n    /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x.\n    ///\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be less than or equal to MAX_WHOLE_SD59x18.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number to ceil.\n    /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number.\n    function ceil(int256 x) internal pure returns (int256 result) {\n        if (x > MAX_WHOLE_SD59x18) {\n            revert PRBMathSD59x18__CeilOverflow(x);\n        }\n        unchecked {\n            int256 remainder = x % SCALE;\n            if (remainder == 0) {\n                result = x;\n            } else {\n                // Solidity uses C fmod style, which returns a modulus with the same sign as x.\n                result = x - remainder;\n                if (x > 0) {\n                    result += SCALE;\n                }\n            }\n        }\n    }\n\n    /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number.\n    ///\n    /// @dev Variant of \"mulDiv\" that works with signed numbers. Works by computing the signs and the absolute values separately.\n    ///\n    /// Requirements:\n    /// - All from \"PRBMath.mulDiv\".\n    /// - None of the inputs can be MIN_SD59x18.\n    /// - The denominator cannot be zero.\n    /// - The result must fit within int256.\n    ///\n    /// Caveats:\n    /// - All from \"PRBMath.mulDiv\".\n    ///\n    /// @param x The numerator as a signed 59.18-decimal fixed-point number.\n    /// @param y The denominator as a signed 59.18-decimal fixed-point number.\n    /// @param result The quotient as a signed 59.18-decimal fixed-point number.\n    function div(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == MIN_SD59x18 || y == MIN_SD59x18) {\n            revert PRBMathSD59x18__DivInputTooSmall();\n        }\n\n        // Get hold of the absolute values of x and y.\n        uint256 ax;\n        uint256 ay;\n        unchecked {\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n        }\n\n        // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256.\n        uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay);\n        if (rAbs > uint256(MAX_SD59x18)) {\n            revert PRBMathSD59x18__DivOverflow(rAbs);\n        }\n\n        // Get the signs of x and y.\n        uint256 sx;\n        uint256 sy;\n        assembly {\n            sx := sgt(x, sub(0, 1))\n            sy := sgt(y, sub(0, 1))\n        }\n\n        // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result\n        // should be positive. Otherwise, it should be negative.\n        result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);\n    }\n\n    /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number.\n    /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).\n    function e() internal pure returns (int256 result) {\n        result = 2_718281828459045235;\n    }\n\n    /// @notice Calculates the natural exponent of x.\n    ///\n    /// @dev Based on the insight that e^x = 2^(x * log2(e)).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    /// - x must be less than 133.084258667509499441.\n    ///\n    /// Caveats:\n    /// - All from \"exp2\".\n    /// - For any x less than -41.446531673892822322, the result is zero.\n    ///\n    /// @param x The exponent as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function exp(int256 x) internal pure returns (int256 result) {\n        // Without this check, the value passed to \"exp2\" would be less than -59.794705707972522261.\n        if (x < -41_446531673892822322) {\n            return 0;\n        }\n\n        // Without this check, the value passed to \"exp2\" would be greater than 192.\n        if (x >= 133_084258667509499441) {\n            revert PRBMathSD59x18__ExpInputTooBig(x);\n        }\n\n        // Do the fixed-point multiplication inline to save gas.\n        unchecked {\n            int256 doubleScaleProduct = x * LOG2_E;\n            result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n        }\n    }\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    ///\n    /// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n    ///\n    /// Requirements:\n    /// - x must be 192 or less.\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - For any x less than -59.794705707972522261, the result is zero.\n    ///\n    /// @param x The exponent as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function exp2(int256 x) internal pure returns (int256 result) {\n        // This works because 2^(-x) = 1/2^x.\n        if (x < 0) {\n            // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.\n            if (x < -59_794705707972522261) {\n                return 0;\n            }\n\n            // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.\n            unchecked {\n                result = 1e36 / exp2(-x);\n            }\n        } else {\n            // 2^192 doesn't fit within the 192.64-bit format used internally in this function.\n            if (x >= 192e18) {\n                revert PRBMathSD59x18__Exp2InputTooBig(x);\n            }\n\n            unchecked {\n                // Convert x to the 192.64-bit fixed-point format.\n                uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);\n\n                // Safe to convert the result to int256 directly because the maximum input allowed is 192.\n                result = int256(PRBMath.exp2(x192x64));\n            }\n        }\n    }\n\n    /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x.\n    ///\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be greater than or equal to MIN_WHOLE_SD59x18.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number to floor.\n    /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number.\n    function floor(int256 x) internal pure returns (int256 result) {\n        if (x < MIN_WHOLE_SD59x18) {\n            revert PRBMathSD59x18__FloorUnderflow(x);\n        }\n        unchecked {\n            int256 remainder = x % SCALE;\n            if (remainder == 0) {\n                result = x;\n            } else {\n                // Solidity uses C fmod style, which returns a modulus with the same sign as x.\n                result = x - remainder;\n                if (x < 0) {\n                    result -= SCALE;\n                }\n            }\n        }\n    }\n\n    /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right\n    /// of the radix point for negative numbers.\n    /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part\n    /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of.\n    /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number.\n    function frac(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            result = x % SCALE;\n        }\n    }\n\n    /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation.\n    ///\n    /// @dev Requirements:\n    /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE.\n    /// - x must be less than or equal to MAX_SD59x18 divided by SCALE.\n    ///\n    /// @param x The basic integer to convert.\n    /// @param result The same number in signed 59.18-decimal fixed-point representation.\n    function fromInt(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            if (x < MIN_SD59x18 / SCALE) {\n                revert PRBMathSD59x18__FromIntUnderflow(x);\n            }\n            if (x > MAX_SD59x18 / SCALE) {\n                revert PRBMathSD59x18__FromIntOverflow(x);\n            }\n            result = x * SCALE;\n        }\n    }\n\n    /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n    ///\n    /// @dev Requirements:\n    /// - x * y must fit within MAX_SD59x18, lest it overflows.\n    /// - x * y cannot be negative.\n    ///\n    /// @param x The first operand as a signed 59.18-decimal fixed-point number.\n    /// @param y The second operand as a signed 59.18-decimal fixed-point number.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function gm(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        unchecked {\n            // Checking for overflow this way is faster than letting Solidity do it.\n            int256 xy = x * y;\n            if (xy / x != y) {\n                revert PRBMathSD59x18__GmOverflow(x, y);\n            }\n\n            // The product cannot be negative.\n            if (xy < 0) {\n                revert PRBMathSD59x18__GmNegativeProduct(x, y);\n            }\n\n            // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n            // during multiplication. See the comments within the \"sqrt\" function.\n            result = int256(PRBMath.sqrt(uint256(xy)));\n        }\n    }\n\n    /// @notice Calculates 1 / x, rounding toward zero.\n    ///\n    /// @dev Requirements:\n    /// - x cannot be zero.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse.\n    /// @return result The inverse as a signed 59.18-decimal fixed-point number.\n    function inv(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            // 1e36 is SCALE * SCALE.\n            result = 1e36 / x;\n        }\n    }\n\n    /// @notice Calculates the natural logarithm of x.\n    ///\n    /// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm.\n    /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number.\n    function ln(int256 x) internal pure returns (int256 result) {\n        // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n        // can return is 195205294292027477728.\n        unchecked {\n            result = (log2(x) * SCALE) / LOG2_E;\n        }\n    }\n\n    /// @notice Calculates the common logarithm of x.\n    ///\n    /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common\n    /// logarithm based on the insight that log10(x) = log2(x) / log2(10).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm.\n    /// @return result The common logarithm as a signed 59.18-decimal fixed-point number.\n    function log10(int256 x) internal pure returns (int256 result) {\n        if (x <= 0) {\n            revert PRBMathSD59x18__LogInputTooSmall(x);\n        }\n\n        // Note that the \"mul\" in this block is the assembly mul operation, not the \"mul\" function defined in this contract.\n        // prettier-ignore\n        assembly {\n            switch x\n            case 1 { result := mul(SCALE, sub(0, 18)) }\n            case 10 { result := mul(SCALE, sub(1, 18)) }\n            case 100 { result := mul(SCALE, sub(2, 18)) }\n            case 1000 { result := mul(SCALE, sub(3, 18)) }\n            case 10000 { result := mul(SCALE, sub(4, 18)) }\n            case 100000 { result := mul(SCALE, sub(5, 18)) }\n            case 1000000 { result := mul(SCALE, sub(6, 18)) }\n            case 10000000 { result := mul(SCALE, sub(7, 18)) }\n            case 100000000 { result := mul(SCALE, sub(8, 18)) }\n            case 1000000000 { result := mul(SCALE, sub(9, 18)) }\n            case 10000000000 { result := mul(SCALE, sub(10, 18)) }\n            case 100000000000 { result := mul(SCALE, sub(11, 18)) }\n            case 1000000000000 { result := mul(SCALE, sub(12, 18)) }\n            case 10000000000000 { result := mul(SCALE, sub(13, 18)) }\n            case 100000000000000 { result := mul(SCALE, sub(14, 18)) }\n            case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }\n            case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }\n            case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }\n            case 1000000000000000000 { result := 0 }\n            case 10000000000000000000 { result := SCALE }\n            case 100000000000000000000 { result := mul(SCALE, 2) }\n            case 1000000000000000000000 { result := mul(SCALE, 3) }\n            case 10000000000000000000000 { result := mul(SCALE, 4) }\n            case 100000000000000000000000 { result := mul(SCALE, 5) }\n            case 1000000000000000000000000 { result := mul(SCALE, 6) }\n            case 10000000000000000000000000 { result := mul(SCALE, 7) }\n            case 100000000000000000000000000 { result := mul(SCALE, 8) }\n            case 1000000000000000000000000000 { result := mul(SCALE, 9) }\n            case 10000000000000000000000000000 { result := mul(SCALE, 10) }\n            case 100000000000000000000000000000 { result := mul(SCALE, 11) }\n            case 1000000000000000000000000000000 { result := mul(SCALE, 12) }\n            case 10000000000000000000000000000000 { result := mul(SCALE, 13) }\n            case 100000000000000000000000000000000 { result := mul(SCALE, 14) }\n            case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }\n            case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }\n            case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }\n            case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }\n            case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }\n            case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }\n            case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }\n            case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }\n            case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }\n            case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }\n            case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }\n            case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }\n            case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }\n            case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }\n            case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }\n            case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }\n            case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }\n            case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }\n            case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }\n            case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }\n            case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }\n            case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }\n            case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }\n            case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }\n            case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }\n            case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }\n            case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }\n            case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }\n            case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }\n            case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }\n            case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }\n            case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }\n            case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }\n            default {\n                result := MAX_SD59x18\n            }\n        }\n\n        if (result == MAX_SD59x18) {\n            // Do the fixed-point division inline to save gas. The denominator is log2(10).\n            unchecked {\n                result = (log2(x) * SCALE) / 3_321928094887362347;\n            }\n        }\n    }\n\n    /// @notice Calculates the binary logarithm of x.\n    ///\n    /// @dev Based on the iterative approximation algorithm.\n    /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation\n    ///\n    /// Requirements:\n    /// - x must be greater than zero.\n    ///\n    /// Caveats:\n    /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm.\n    /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number.\n    function log2(int256 x) internal pure returns (int256 result) {\n        if (x <= 0) {\n            revert PRBMathSD59x18__LogInputTooSmall(x);\n        }\n        unchecked {\n            // This works because log2(x) = -log2(1/x).\n            int256 sign;\n            if (x >= SCALE) {\n                sign = 1;\n            } else {\n                sign = -1;\n                // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.\n                assembly {\n                    x := div(1000000000000000000000000000000000000, x)\n                }\n            }\n\n            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n            uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));\n\n            // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow\n            // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1.\n            result = int256(n) * SCALE;\n\n            // This is y = x * 2^(-n).\n            int256 y = x >> n;\n\n            // If y = 1, the fractional part is zero.\n            if (y == SCALE) {\n                return result * sign;\n            }\n\n            // Calculate the fractional part via the iterative approximation.\n            // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n            for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {\n                y = (y * y) / SCALE;\n\n                // Is y^2 > 2 and so in the range [2,4)?\n                if (y >= 2 * SCALE) {\n                    // Add the 2^(-m) factor to the logarithm.\n                    result += delta;\n\n                    // Corresponds to z/2 on Wikipedia.\n                    y >>= 1;\n                }\n            }\n            result *= sign;\n        }\n    }\n\n    /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal\n    /// fixed-point number.\n    ///\n    /// @dev Variant of \"mulDiv\" that works with signed numbers and employs constant folding, i.e. the denominator is\n    /// always 1e18.\n    ///\n    /// Requirements:\n    /// - All from \"PRBMath.mulDivFixedPoint\".\n    /// - None of the inputs can be MIN_SD59x18\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - The body is purposely left uncommented; see the NatSpec comments in \"PRBMath.mulDiv\" to understand how this works.\n    ///\n    /// @param x The multiplicand as a signed 59.18-decimal fixed-point number.\n    /// @param y The multiplier as a signed 59.18-decimal fixed-point number.\n    /// @return result The product as a signed 59.18-decimal fixed-point number.\n    function mul(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == MIN_SD59x18 || y == MIN_SD59x18) {\n            revert PRBMathSD59x18__MulInputTooSmall();\n        }\n\n        unchecked {\n            uint256 ax;\n            uint256 ay;\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n\n            uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay);\n            if (rAbs > uint256(MAX_SD59x18)) {\n                revert PRBMathSD59x18__MulOverflow(rAbs);\n            }\n\n            uint256 sx;\n            uint256 sy;\n            assembly {\n                sx := sgt(x, sub(0, 1))\n                sy := sgt(y, sub(0, 1))\n            }\n            result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);\n        }\n    }\n\n    /// @notice Returns PI as a signed 59.18-decimal fixed-point number.\n    function pi() internal pure returns (int256 result) {\n        result = 3_141592653589793238;\n    }\n\n    /// @notice Raises x to the power of y.\n    ///\n    /// @dev Based on the insight that x^y = 2^(log2(x) * y).\n    ///\n    /// Requirements:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - z cannot be zero.\n    ///\n    /// Caveats:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number.\n    /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number.\n    /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number.\n    function pow(int256 x, int256 y) internal pure returns (int256 result) {\n        if (x == 0) {\n            result = y == 0 ? SCALE : int256(0);\n        } else {\n            result = exp2(mul(log2(x), y));\n        }\n    }\n\n    /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n    /// famous algorithm \"exponentiation by squaring\".\n    ///\n    /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n    ///\n    /// Requirements:\n    /// - All from \"abs\" and \"PRBMath.mulDivFixedPoint\".\n    /// - The result must fit within MAX_SD59x18.\n    ///\n    /// Caveats:\n    /// - All from \"PRBMath.mulDivFixedPoint\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x The base as a signed 59.18-decimal fixed-point number.\n    /// @param y The exponent as an uint256.\n    /// @return result The result as a signed 59.18-decimal fixed-point number.\n    function powu(int256 x, uint256 y) internal pure returns (int256 result) {\n        uint256 xAbs = uint256(abs(x));\n\n        // Calculate the first iteration of the loop in advance.\n        uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);\n\n        // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n        uint256 yAux = y;\n        for (yAux >>= 1; yAux > 0; yAux >>= 1) {\n            xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);\n\n            // Equivalent to \"y % 2 == 1\" but faster.\n            if (yAux & 1 > 0) {\n                rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);\n            }\n        }\n\n        // The result must fit within the 59.18-decimal fixed-point representation.\n        if (rAbs > uint256(MAX_SD59x18)) {\n            revert PRBMathSD59x18__PowuOverflow(rAbs);\n        }\n\n        // Is the base negative and the exponent an odd number?\n        bool isNegative = x < 0 && y & 1 == 1;\n        result = isNegative ? -int256(rAbs) : int256(rAbs);\n    }\n\n    /// @notice Returns 1 as a signed 59.18-decimal fixed-point number.\n    function scale() internal pure returns (int256 result) {\n        result = SCALE;\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Requirements:\n    /// - x cannot be negative.\n    /// - x must be less than MAX_SD59x18 / SCALE.\n    ///\n    /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root.\n    /// @return result The result as a signed 59.18-decimal fixed-point .\n    function sqrt(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            if (x < 0) {\n                revert PRBMathSD59x18__SqrtNegativeInput(x);\n            }\n            if (x > MAX_SD59x18 / SCALE) {\n                revert PRBMathSD59x18__SqrtOverflow(x);\n            }\n            // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed\n            // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n            result = int256(PRBMath.sqrt(uint256(x * SCALE)));\n        }\n    }\n\n    /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process.\n    /// @param x The signed 59.18-decimal fixed-point number to convert.\n    /// @return result The same number in basic integer form.\n    function toInt(int256 x) internal pure returns (int256 result) {\n        unchecked {\n            result = x / SCALE;\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolState.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool State\n */\ninterface IPoolState {\n\n    /**\n     *  @notice Returns details of an auction for a given borrower address.\n     *  @param  borrower_         Address of the borrower that is liquidated.\n     *  @return kicker_           Address of the kicker that is kicking the auction.\n     *  @return bondFactor_       The factor used for calculating bond size.\n     *  @return bondSize_         The bond amount in quote token terms.\n     *  @return kickTime_         Time the liquidation was initiated.\n     *  @return referencePrice_   Price used to determine auction start price.\n     *  @return neutralPrice_     `Neutral Price` of auction.\n     *  @return debtToCollateral_ Borrower debt to collateral, which is used in BPF for kicker's reward calculation.\n     *  @return head_             Address of the head auction.\n     *  @return next_             Address of the next auction in queue.\n     *  @return prev_             Address of the prev auction in queue.\n     */\n    function auctionInfo(address borrower_)\n        external\n        view\n        returns (\n            address kicker_,\n            uint256 bondFactor_,\n            uint256 bondSize_,\n            uint256 kickTime_,\n            uint256 referencePrice_,\n            uint256 neutralPrice_,\n            uint256 debtToCollateral_,\n            address head_,\n            address next_,\n            address prev_\n        );\n\n    /**\n     *  @notice Returns pool related debt values.\n     *  @return debt_                Current amount of debt owed by borrowers in pool.\n     *  @return accruedDebt_         Debt owed by borrowers based on last inflator snapshot.\n     *  @return debtInAuction_       Total amount of debt in auction.\n     *  @return t0Debt2ToCollateral_ t0debt accross all borrowers divided by their collateral, used in determining a collateralization weighted debt.\n     */\n    function debtInfo()\n        external\n        view\n        returns (\n            uint256 debt_,\n            uint256 accruedDebt_,\n            uint256 debtInAuction_,\n            uint256 t0Debt2ToCollateral_\n        );\n\n    /**\n     *  @notice Mapping of borrower addresses to `Borrower` structs.\n     *  @dev    NOTE: Cannot use appended underscore syntax for return params since struct is used.\n     *  @param  borrower_   Address of the borrower.\n     *  @return t0Debt_     Amount of debt borrower would have had if their loan was the first debt drawn from the pool.\n     *  @return collateral_ Amount of collateral that the borrower has deposited, in collateral token.\n     *  @return npTpRatio_  Np to Tp ratio of borrower at the time of last borrow or pull collateral.\n     */\n    function borrowerInfo(address borrower_)\n        external\n        view\n        returns (\n            uint256 t0Debt_,\n            uint256 collateral_,\n            uint256 npTpRatio_\n        );\n\n    /**\n     *  @notice Mapping of buckets indexes to `Bucket` structs.\n     *  @dev    NOTE: Cannot use appended underscore syntax for return params since struct is used.\n     *  @param  index_               Bucket index.\n     *  @return lpAccumulator_       Amount of `LP` accumulated in current bucket.\n     *  @return availableCollateral_ Amount of collateral available in current bucket.\n     *  @return bankruptcyTime_      Timestamp when bucket become insolvent, `0` if healthy.\n     *  @return bucketDeposit_       Amount of quote tokens in bucket.\n     *  @return bucketScale_         Bucket multiplier.\n     */\n    function bucketInfo(uint256 index_)\n        external\n        view\n        returns (\n            uint256 lpAccumulator_,\n            uint256 availableCollateral_,\n            uint256 bankruptcyTime_,\n            uint256 bucketDeposit_,\n            uint256 bucketScale_\n        );\n\n    /**\n     *  @notice Mapping of burnEventEpoch to `BurnEvent` structs.\n     *  @dev    Reserve auctions correspond to burn events.\n     *  @param  burnEventEpoch_  Id of the current reserve auction.\n     *  @return burnBlock_       Block in which a reserve auction started.\n     *  @return totalInterest_   Total interest as of the reserve auction.\n     *  @return totalBurned_     Total ajna tokens burned as of the reserve auction.\n     */\n    function burnInfo(uint256 burnEventEpoch_) external view returns (uint256, uint256, uint256);\n\n    /**\n     *  @notice Returns the latest `burnEventEpoch` of reserve auctions.\n     *  @dev    If a reserve auction is active, it refers to the current reserve auction. If no reserve auction is active, it refers to the last reserve auction.\n     *  @return Current `burnEventEpoch`.\n     */\n    function currentBurnEpoch() external view returns (uint256);\n\n    /**\n     *  @notice Returns information about the pool `EMA (Exponential Moving Average)` variables.\n     *  @return debtColEma_   Debt squared to collateral Exponential, numerator to `TU` calculation.\n     *  @return lupt0DebtEma_ Exponential of `LUP * t0 debt`, denominator to `TU` calculation\n     *  @return debtEma_      Exponential debt moving average.\n     *  @return depositEma_   sample of meaningful deposit Exponential, denominator to `MAU` calculation.\n     */\n    function emasInfo()\n        external\n        view\n        returns (\n            uint256 debtColEma_,\n            uint256 lupt0DebtEma_,\n            uint256 debtEma_,\n            uint256 depositEma_\n    );\n\n    /**\n     *  @notice Returns information about pool inflator.\n     *  @return inflator_   Pool inflator value.\n     *  @return lastUpdate_ The timestamp of the last `inflator` update.\n     */\n    function inflatorInfo()\n        external\n        view\n        returns (\n            uint256 inflator_,\n            uint256 lastUpdate_\n    );\n\n    /**\n     *  @notice Returns information about pool interest rate.\n     *  @return interestRate_       Current interest rate in pool.\n     *  @return interestRateUpdate_ The timestamp of the last interest rate update.\n     */\n    function interestRateInfo()\n        external\n        view\n        returns (\n            uint256 interestRate_,\n            uint256 interestRateUpdate_\n        );\n\n\n    /**\n     *  @notice Returns details about kicker balances.\n     *  @param  kicker_    The address of the kicker to retrieved info for.\n     *  @return claimable_ Amount of quote token kicker can claim / withdraw from pool at any time.\n     *  @return locked_    Amount of quote token kicker locked in auctions (as bonds).\n     */\n    function kickerInfo(address kicker_)\n        external\n        view\n        returns (\n            uint256 claimable_,\n            uint256 locked_\n        );\n\n    /**\n     *  @notice Mapping of buckets indexes and owner addresses to `Lender` structs.\n     *  @param  index_       Bucket index.\n     *  @param  lender_      Address of the liquidity provider.\n     *  @return lpBalance_   Amount of `LP` owner has in current bucket.\n     *  @return depositTime_ Time the user last deposited quote token.\n     */\n    function lenderInfo(\n        uint256 index_,\n        address lender_\n    )\n        external\n        view\n        returns (\n            uint256 lpBalance_,\n            uint256 depositTime_\n    );\n\n    /**\n     *  @notice Return the `LP` allowance a `LP` owner provided to a spender.\n     *  @param  index_     Bucket index.\n     *  @param  spender_   Address of the `LP` spender.\n     *  @param  owner_     The initial owner of the `LP`.\n     *  @return allowance_ Amount of `LP` spender can utilize.\n     */\n    function lpAllowance(\n        uint256 index_,\n        address spender_,\n        address owner_\n    ) external view returns (uint256 allowance_);\n\n    /**\n     *  @notice Returns information about a loan in the pool.\n     *  @param  loanId_             Loan's id within loan heap. Max loan is position `1`.\n     *  @return borrower_           Borrower address at the given position.\n     *  @return t0DebtToCollateral_ Borrower t0 debt to collateral.\n     */\n    function loanInfo(\n        uint256 loanId_\n    )\n        external\n        view\n        returns (\n            address borrower_,\n            uint256 t0DebtToCollateral_\n    );\n\n    /**\n     *  @notice Returns information about pool loans.\n     *  @return maxBorrower_           Borrower address with highest t0 debt to collateral.\n     *  @return maxT0DebtToCollateral_ Highest t0 debt to collateral in pool.\n     *  @return noOfLoans_             Total number of loans.\n     */\n    function loansInfo()\n        external\n        view\n        returns (\n            address maxBorrower_,\n            uint256 maxT0DebtToCollateral_,\n            uint256 noOfLoans_\n    );\n\n    /**\n     *  @notice Returns information about pool reserves.\n     *  @return liquidationBondEscrowed_ Amount of liquidation bond across all liquidators.\n     *  @return reserveAuctionUnclaimed_ Amount of claimable reserves which has not been taken in the `Claimable Reserve Auction`.\n     *  @return reserveAuctionKicked_    Time a `Claimable Reserve Auction` was last kicked.\n     *  @return lastKickedReserves_      Amount of reserves upon last kick, used to calculate price.\n     *  @return totalInterestEarned_     Total interest earned by all lenders in the pool\n     */\n    function reservesInfo()\n        external\n        view\n        returns (\n            uint256 liquidationBondEscrowed_,\n            uint256 reserveAuctionUnclaimed_,\n            uint256 reserveAuctionKicked_,\n            uint256 lastKickedReserves_,\n            uint256 totalInterestEarned_\n    );\n\n    /**\n     *  @notice Returns the `pledgedCollateral` state variable.\n     *  @return The total pledged collateral in the system, in WAD units.\n     */\n    function pledgedCollateral() external view returns (uint256);\n\n    /**\n     *  @notice Returns the total number of active auctions in pool.\n     *  @return totalAuctions_ Number of active auctions.\n     */\n    function totalAuctionsInPool() external view returns (uint256);\n\n     /**\n     *  @notice Returns the `t0Debt` state variable.\n     *  @dev    This value should be multiplied by inflator in order to calculate current debt of the pool.\n     *  @return The total `t0Debt` in the system, in `WAD` units.\n     */\n    function totalT0Debt() external view returns (uint256);\n\n    /**\n     *  @notice Returns the `t0DebtInAuction` state variable.\n     *  @dev    This value should be multiplied by inflator in order to calculate current debt in auction of the pool.\n     *  @return The total `t0DebtInAuction` in the system, in `WAD` units.\n     */\n    function totalT0DebtInAuction() external view returns (uint256);\n\n    /**\n     *  @notice Mapping of addresses that can transfer `LP` to a given lender.\n     *  @param  lender_     Lender that receives `LP`.\n     *  @param  transferor_ Transferor that transfers `LP`.\n     *  @return True if the transferor is approved by lender.\n     */\n    function approvedTransferors(\n        address lender_,\n        address transferor_\n    ) external view returns (bool);\n\n}\n\n/*********************/\n/*** State Structs ***/\n/*********************/\n\n/******************/\n/*** Pool State ***/\n/******************/\n\n/// @dev Struct holding inflator state.\nstruct InflatorState {\n    uint208 inflator;       // [WAD] pool's inflator\n    uint48  inflatorUpdate; // [SEC] last time pool's inflator was updated\n}\n\n/// @dev Struct holding pool interest state.\nstruct InterestState {\n    uint208 interestRate;        // [WAD] pool's interest rate\n    uint48  interestRateUpdate;  // [SEC] last time pool's interest rate was updated (not before 12 hours passed)\n    uint256 debt;                // [WAD] previous update's debt\n    uint256 meaningfulDeposit;   // [WAD] previous update's meaningfulDeposit\n    uint256 t0Debt2ToCollateral; // [WAD] utilization weight accumulator, tracks debt and collateral relationship accross borrowers \n    uint256 debtCol;             // [WAD] previous debt squared to collateral\n    uint256 lupt0Debt;           // [WAD] previous LUP * t0 debt\n}\n\n/// @dev Struct holding pool EMAs state.\nstruct EmaState {\n    uint256 debtEma;             // [WAD] sample of debt EMA, numerator to MAU calculation\n    uint256 depositEma;          // [WAD] sample of meaningful deposit EMA, denominator to MAU calculation\n    uint256 debtColEma;          // [WAD] debt squared to collateral EMA, numerator to TU calculation\n    uint256 lupt0DebtEma;        // [WAD] EMA of LUP * t0 debt, denominator to TU calculation\n    uint256 emaUpdate;           // [SEC] last time pool's EMAs were updated\n}\n\n/// @dev Struct holding pool balances state.\nstruct PoolBalancesState {\n    uint256 pledgedCollateral; // [WAD] total collateral pledged in pool\n    uint256 t0DebtInAuction;   // [WAD] Total debt in auction used to restrict LPB holder from withdrawing\n    uint256 t0Debt;            // [WAD] Pool debt as if the whole amount was incurred upon the first loan\n}\n\n/// @dev Struct holding pool params (in memory only).\nstruct PoolState {\n    uint8   poolType;             // pool type, can be ERC20 or ERC721\n    uint256 t0Debt;               // [WAD] t0 debt in pool\n    uint256 t0DebtInAuction;      // [WAD] t0 debt in auction within pool\n    uint256 debt;                 // [WAD] total debt in pool, accrued in current block\n    uint256 collateral;           // [WAD] total collateral pledged in pool\n    uint256 inflator;             // [WAD] current pool inflator\n    bool    isNewInterestAccrued; // true if new interest already accrued in current block\n    uint256 rate;                 // [WAD] pool's current interest rate\n    uint256 quoteTokenScale;      // [WAD] quote token scale of the pool. Same as quote token dust.\n}\n\n/*********************/\n/*** Buckets State ***/\n/*********************/\n\n/// @dev Struct holding lender state.\nstruct Lender {\n    uint256 lps;         // [WAD] Lender LP accumulator\n    uint256 depositTime; // timestamp of last deposit\n}\n\n/// @dev Struct holding bucket state.\nstruct Bucket {\n    uint256 lps;                        // [WAD] Bucket LP accumulator\n    uint256 collateral;                 // [WAD] Available collateral tokens deposited in the bucket\n    uint256 bankruptcyTime;             // Timestamp when bucket become insolvent, 0 if healthy\n    mapping(address => Lender) lenders; // lender address to Lender struct mapping\n}\n\n/**********************/\n/*** Deposits State ***/\n/**********************/\n\n/// @dev Struct holding deposits (Fenwick) values and scaling.\nstruct DepositsState {\n    uint256[8193] values;  // Array of values in the FenwickTree.\n    uint256[8193] scaling; // Array of values which scale (multiply) the FenwickTree accross indexes.\n}\n\n/*******************/\n/*** Loans State ***/\n/*******************/\n\n/// @dev Struct holding loans state.\nstruct LoansState {\n    Loan[] loans;\n    mapping (address => uint)     indices;   // borrower address => loan index mapping\n    mapping (address => Borrower) borrowers; // borrower address => Borrower struct mapping\n}\n\n/// @dev Struct holding loan state.\nstruct Loan {\n    address borrower;           // borrower address\n    uint96  t0DebtToCollateral; // [WAD] Borrower t0 debt to collateral.\n}\n\n/// @dev Struct holding borrower state.\nstruct Borrower {\n    uint256 t0Debt;                    // [WAD] Borrower debt time-adjusted as if it was incurred upon first loan of pool.\n    uint256 collateral;                // [WAD] Collateral deposited by borrower.\n    uint256 npTpRatio;                 // [WAD] Np to Tp ratio at the time of last borrow or pull collateral.\n}\n\n/**********************/\n/*** Auctions State ***/\n/**********************/\n\n/// @dev Struct holding pool auctions state.\nstruct AuctionsState {\n    uint96  noOfAuctions;                         // total number of auctions in pool\n    address head;                                 // first address in auction queue\n    address tail;                                 // last address in auction queue\n    uint256 totalBondEscrowed;                    // [WAD] total amount of quote token posted as auction kick bonds\n    mapping(address => Liquidation) liquidations; // mapping of borrower address and auction details\n    mapping(address => Kicker)      kickers;      // mapping of kicker address and kicker balances\n}\n\n/// @dev Struct holding liquidation state.\nstruct Liquidation {\n    address kicker;                // address that initiated liquidation\n    uint96  bondFactor;            // [WAD] bond factor used to start liquidation\n    uint96  kickTime;              // timestamp when liquidation was started\n    address prev;                  // previous liquidated borrower in auctions queue\n    uint96  referencePrice;        // [WAD] used to calculate auction start price\n    address next;                  // next liquidated borrower in auctions queue\n    uint160 bondSize;              // [WAD] liquidation bond size\n    uint96  neutralPrice;          // [WAD] Neutral Price when liquidation was started\n    uint256 debtToCollateral;      // [WAD] Borrower debt to collateral, which is used in BPF for kicker's reward calculation\n    uint256 t0ReserveSettleAmount; // [WAD] Amount of t0Debt that could be settled via reserves in this auction\n}\n\n/// @dev Struct holding kicker state.\nstruct Kicker {\n    uint256 claimable; // [WAD] kicker's claimable balance\n    uint256 locked;    // [WAD] kicker's balance of tokens locked in auction bonds\n}\n\n/******************************/\n/*** Reserve Auctions State ***/\n/******************************/\n\n/// @dev Struct holding reserve auction state.\nstruct ReserveAuctionState {\n    uint256 kicked;                            // Time a Claimable Reserve Auction was last kicked.\n    uint256 lastKickedReserves;                // [WAD] Amount of reserves upon last kick, used to calculate price.\n    uint256 unclaimed;                         // [WAD] Amount of claimable reserves which has not been taken in the Claimable Reserve Auction.\n    uint256 latestBurnEventEpoch;              // Latest burn event epoch.\n    uint256 totalAjnaBurned;                   // [WAD] Total ajna burned in the pool.\n    uint256 totalInterestEarned;               // [WAD] Total interest earned by all lenders in the pool.\n    mapping (uint256 => BurnEvent) burnEvents; // Mapping burnEventEpoch => BurnEvent.\n}\n\n/// @dev Struct holding burn event state.\nstruct BurnEvent {\n    uint256 timestamp;     // time at which the burn event occured\n    uint256 totalInterest; // [WAD] current pool interest accumulator `PoolCommons.accrueInterest().newInterest`\n    uint256 totalBurned;   // [WAD] burn amount accumulator\n}"
      },
      "lib/ajna-core/src/libraries/internal/Buckets.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.18;\n\nimport { Math } from '@openzeppelin/contracts/utils/math/Math.sol';\n\nimport { Bucket, Lender } from '../../interfaces/pool/commons/IPoolState.sol';\n\nimport { Maths } from './Maths.sol';\n\n/**\n    @title  Buckets library\n    @notice Internal library containing common logic for buckets management.\n */\nlibrary Buckets {\n\n    /**************/\n    /*** Events ***/\n    /**************/\n\n    // See `IPoolError` for descriptions\n    error BucketBankruptcyBlock();\n\n    /***********************************/\n    /*** Bucket Management Functions ***/\n    /***********************************/\n\n    /**\n     *  @notice Add collateral to a bucket and updates `LP` for bucket and lender with the amount coresponding to collateral amount added.\n     *  @dev    Increment `bucket.collateral` and `bucket.lps` accumulator\n     *  @dev    - `addLenderLP`:\n     *  @dev    increment `lender.lps` accumulator and `lender.depositTime` state\n     *  @param  lender_                Address of the lender.\n     *  @param  deposit_               Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  collateralAmountToAdd_ Additional collateral amount to add to bucket.\n     *  @param  bucketPrice_           Bucket price.\n     *  @return addedLP_               Amount of bucket `LP` for the collateral amount added.\n     */\n    function addCollateral(\n        Bucket storage bucket_,\n        address lender_,\n        uint256 deposit_,\n        uint256 collateralAmountToAdd_,\n        uint256 bucketPrice_\n    ) internal returns (uint256 addedLP_) {\n        // cannot deposit in the same block when bucket becomes insolvent\n        uint256 bankruptcyTime = bucket_.bankruptcyTime;\n        if (bankruptcyTime == block.timestamp) revert BucketBankruptcyBlock();\n\n        // calculate amount of LP to be added for the amount of collateral added to bucket\n        addedLP_ = collateralToLP(\n            bucket_.collateral,\n            bucket_.lps,\n            deposit_,\n            collateralAmountToAdd_,\n            bucketPrice_,\n            Math.Rounding.Down\n        );\n        // update bucket LP balance and collateral\n\n        // update bucket collateral\n        bucket_.collateral += collateralAmountToAdd_;\n        // update bucket and lender LP balance and deposit timestamp\n        bucket_.lps += addedLP_;\n\n        addLenderLP(bucket_, bankruptcyTime, lender_, addedLP_);\n    }\n\n    /**\n     *  @notice Add amount of `LP` for a given lender in a given bucket.\n     *  @dev    Increments lender lps accumulator and updates the deposit time.\n     *  @param  bucket_         Bucket to record lender `LP`.\n     *  @param  bankruptcyTime_ Time when bucket become insolvent.\n     *  @param  lender_         Lender address to add `LP` for in the given bucket.\n     *  @param  lpAmount_       Amount of `LP` to be recorded for the given lender.\n     */\n    function addLenderLP(\n        Bucket storage bucket_,\n        uint256 bankruptcyTime_,\n        address lender_,\n        uint256 lpAmount_\n    ) internal {\n        if (lpAmount_ != 0) {\n            Lender storage lender = bucket_.lenders[lender_];\n\n            if (bankruptcyTime_ >= lender.depositTime) lender.lps = lpAmount_;\n            else lender.lps += lpAmount_;\n\n            lender.depositTime = block.timestamp;\n        }\n    }\n\n    /**********************/\n    /*** View Functions ***/\n    /**********************/\n\n    /****************************/\n    /*** Assets to LP helpers ***/\n    /****************************/\n\n    /**\n     *  @notice Returns the amount of bucket `LP` calculated for the given amount of collateral.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  collateral_       The amount of collateral to calculate bucket LP for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @param  rounding_         The direction of rounding when calculating LP (down when adding, up when removing collateral from pool).\n     *  @return Amount of `LP` calculated for the amount of collateral.\n     */\n    function collateralToLP(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 deposit_,\n        uint256 collateral_,\n        uint256 bucketPrice_,\n        Math.Rounding rounding_\n    ) internal pure returns (uint256) {\n        // case when there's no deposit nor collateral in bucket\n        if (deposit_ == 0 && bucketCollateral_ == 0) return Maths.wmul(collateral_, bucketPrice_);\n\n        // case when there's deposit or collateral in bucket but no LP to cover\n        if (bucketLP_ == 0) return Maths.wmul(collateral_, bucketPrice_);\n\n        // case when there's deposit or collateral and bucket has LP balance\n        return Math.mulDiv(\n            bucketLP_,\n            collateral_ * bucketPrice_,\n            deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,\n            rounding_\n        );\n    }\n\n    /**\n     *  @notice Returns the amount of `LP` calculated for the given amount of quote tokens.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  quoteTokens_      The amount of quote tokens to calculate `LP` amount for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @param  rounding_         The direction of rounding when calculating LP (down when adding, up when removing quote tokens from pool).\n     *  @return The amount of `LP` coresponding to the given quote tokens in current bucket.\n     */\n    function quoteTokensToLP(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 deposit_,\n        uint256 quoteTokens_,\n        uint256 bucketPrice_,\n        Math.Rounding rounding_\n    ) internal pure returns (uint256) {\n        // case when there's no deposit nor collateral in bucket\n        if (deposit_ == 0 && bucketCollateral_ == 0) return quoteTokens_;\n\n        // case when there's deposit or collateral in bucket but no LP to cover\n        if (bucketLP_ == 0) return quoteTokens_;\n\n        // case when there's deposit or collateral and bucket has LP balance\n        return Math.mulDiv(\n            bucketLP_,\n            quoteTokens_ * Maths.WAD,\n            deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,\n            rounding_\n        );\n    }\n\n    /****************************/\n    /*** LP to Assets helpers ***/\n    /****************************/\n\n    /**\n     *  @notice Returns the amount of collateral calculated for the given amount of lp\n     *  @dev    The value returned is not capped at collateral amount available in bucket.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  lp_               The amount of LP to calculate collateral amount for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @return The amount of collateral coresponding to the given `LP` in current bucket.\n     */\n    function lpToCollateral(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 deposit_,\n        uint256 lp_,\n        uint256 bucketPrice_,\n        Math.Rounding rounding_\n    ) internal pure returns (uint256) {\n        // case when there's no deposit nor collateral in bucket\n        if (deposit_ == 0 && bucketCollateral_ == 0) return Maths.wdiv(lp_, bucketPrice_);\n\n        // case when there's deposit or collateral in bucket but no LP to cover\n        if (bucketLP_ == 0) return Maths.wdiv(lp_, bucketPrice_);\n\n        // case when there's deposit or collateral and bucket has LP balance\n        return Math.mulDiv(\n            deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,\n            lp_,\n            bucketLP_ * bucketPrice_,\n            rounding_\n        );\n    }\n\n    /**\n     *  @notice Returns the amount of quote token (in value) calculated for the given amount of `LP`.\n     *  @dev    The value returned is not capped at available bucket deposit.\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  deposit_          Current bucket deposit (quote tokens). Used to calculate bucket's exchange rate / `LP`.\n     *  @param  lp_               The amount of LP to calculate quote tokens amount for.\n     *  @param  bucketPrice_      Bucket's price.\n     *  @return The amount coresponding to the given quote tokens in current bucket.\n     */\n    function lpToQuoteTokens(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 deposit_,\n        uint256 lp_,\n        uint256 bucketPrice_,\n        Math.Rounding rounding_\n    ) internal pure returns (uint256) {\n        // case when there's no deposit nor collateral in bucket\n        if (deposit_ == 0 && bucketCollateral_ == 0) return lp_;\n\n        // case when there's deposit or collateral in bucket but no LP to cover\n        if (bucketLP_ == 0) return lp_;\n\n        // case when there's deposit or collateral and bucket has LP balance\n        return Math.mulDiv(\n            deposit_ * Maths.WAD + bucketCollateral_ * bucketPrice_,\n            lp_,\n            bucketLP_ * Maths.WAD,\n            rounding_\n        );\n    }\n\n    /****************************/\n    /*** Exchange Rate helper ***/\n    /****************************/\n\n    /**\n     *  @notice Returns the exchange rate for a given bucket (conversion of 1 lp to quote token).\n     *  @param  bucketCollateral_ Amount of collateral in bucket.\n     *  @param  bucketLP_         Amount of `LP` in bucket.\n     *  @param  bucketDeposit_    The amount of quote tokens deposited in the given bucket.\n     *  @param  bucketPrice_      Bucket's price.\n     */\n    function getExchangeRate(\n        uint256 bucketCollateral_,\n        uint256 bucketLP_,\n        uint256 bucketDeposit_,\n        uint256 bucketPrice_\n    ) internal pure returns (uint256) {\n        return lpToQuoteTokens(\n            bucketCollateral_,\n            bucketLP_,\n            bucketDeposit_,\n            Maths.WAD,\n            bucketPrice_,\n            Math.Rounding.Up\n        );\n    }\n}\n"
      },
      "lib/ajna-core/lib/prb-math/contracts/PRBMathUD60x18.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\nimport \"./PRBMath.sol\";\n\n/// @title PRBMathUD60x18\n/// @author Paul Razvan Berg\n/// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18\n/// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60\n/// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the\n/// maximum values permitted by the Solidity type uint256.\nlibrary PRBMathUD60x18 {\n    /// @dev Half the SCALE number.\n    uint256 internal constant HALF_SCALE = 5e17;\n\n    /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number.\n    uint256 internal constant LOG2_E = 1_442695040888963407;\n\n    /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have.\n    uint256 internal constant MAX_UD60x18 =\n        115792089237316195423570985008687907853269984665640564039457_584007913129639935;\n\n    /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have.\n    uint256 internal constant MAX_WHOLE_UD60x18 =\n        115792089237316195423570985008687907853269984665640564039457_000000000000000000;\n\n    /// @dev How many trailing decimals can be represented.\n    uint256 internal constant SCALE = 1e18;\n\n    /// @notice Calculates the arithmetic average of x and y, rounding down.\n    /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number.\n    function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        // The operations can never overflow.\n        unchecked {\n            // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need\n            // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice.\n            result = (x >> 1) + (y >> 1) + (x & y & 1);\n        }\n    }\n\n    /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x.\n    ///\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    ///\n    /// Requirements:\n    /// - x must be less than or equal to MAX_WHOLE_UD60x18.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number to ceil.\n    /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n    function ceil(uint256 x) internal pure returns (uint256 result) {\n        if (x > MAX_WHOLE_UD60x18) {\n            revert PRBMathUD60x18__CeilOverflow(x);\n        }\n        assembly {\n            // Equivalent to \"x % SCALE\" but faster.\n            let remainder := mod(x, SCALE)\n\n            // Equivalent to \"SCALE - remainder\" but faster.\n            let delta := sub(SCALE, remainder)\n\n            // Equivalent to \"x + delta * (remainder > 0 ? 1 : 0)\" but faster.\n            result := add(x, mul(delta, gt(remainder, 0)))\n        }\n    }\n\n    /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number.\n    ///\n    /// @dev Uses mulDiv to enable overflow-safe multiplication and division.\n    ///\n    /// Requirements:\n    /// - The denominator cannot be zero.\n    ///\n    /// @param x The numerator as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The denominator as an unsigned 60.18-decimal fixed-point number.\n    /// @param result The quotient as an unsigned 60.18-decimal fixed-point number.\n    function div(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        result = PRBMath.mulDiv(x, SCALE, y);\n    }\n\n    /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number.\n    /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).\n    function e() internal pure returns (uint256 result) {\n        result = 2_718281828459045235;\n    }\n\n    /// @notice Calculates the natural exponent of x.\n    ///\n    /// @dev Based on the insight that e^x = 2^(x * log2(e)).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    /// - x must be less than 133.084258667509499441.\n    ///\n    /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp(uint256 x) internal pure returns (uint256 result) {\n        // Without this check, the value passed to \"exp2\" would be greater than 192.\n        if (x >= 133_084258667509499441) {\n            revert PRBMathUD60x18__ExpInputTooBig(x);\n        }\n\n        // Do the fixed-point multiplication inline to save gas.\n        unchecked {\n            uint256 doubleScaleProduct = x * LOG2_E;\n            result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);\n        }\n    }\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    ///\n    /// @dev See https://ethereum.stackexchange.com/q/79903/24693.\n    ///\n    /// Requirements:\n    /// - x must be 192 or less.\n    /// - The result must fit within MAX_UD60x18.\n    ///\n    /// @param x The exponent as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp2(uint256 x) internal pure returns (uint256 result) {\n        // 2^192 doesn't fit within the 192.64-bit format used internally in this function.\n        if (x >= 192e18) {\n            revert PRBMathUD60x18__Exp2InputTooBig(x);\n        }\n\n        unchecked {\n            // Convert x to the 192.64-bit fixed-point format.\n            uint256 x192x64 = (x << 64) / SCALE;\n\n            // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation.\n            result = PRBMath.exp2(x192x64);\n        }\n    }\n\n    /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x.\n    /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.\n    /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.\n    /// @param x The unsigned 60.18-decimal fixed-point number to floor.\n    /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number.\n    function floor(uint256 x) internal pure returns (uint256 result) {\n        assembly {\n            // Equivalent to \"x % SCALE\" but faster.\n            let remainder := mod(x, SCALE)\n\n            // Equivalent to \"x - remainder * (remainder > 0 ? 1 : 0)\" but faster.\n            result := sub(x, mul(remainder, gt(remainder, 0)))\n        }\n    }\n\n    /// @notice Yields the excess beyond the floor of x.\n    /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part.\n    /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of.\n    /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number.\n    function frac(uint256 x) internal pure returns (uint256 result) {\n        assembly {\n            result := mod(x, SCALE)\n        }\n    }\n\n    /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation.\n    ///\n    /// @dev Requirements:\n    /// - x must be less than or equal to MAX_UD60x18 divided by SCALE.\n    ///\n    /// @param x The basic integer to convert.\n    /// @param result The same number in unsigned 60.18-decimal fixed-point representation.\n    function fromUint(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            if (x > MAX_UD60x18 / SCALE) {\n                revert PRBMathUD60x18__FromUintOverflow(x);\n            }\n            result = x * SCALE;\n        }\n    }\n\n    /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.\n    ///\n    /// @dev Requirements:\n    /// - x * y must fit within MAX_UD60x18, lest it overflows.\n    ///\n    /// @param x The first operand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The second operand as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        unchecked {\n            // Checking for overflow this way is faster than letting Solidity do it.\n            uint256 xy = x * y;\n            if (xy / x != y) {\n                revert PRBMathUD60x18__GmOverflow(x, y);\n            }\n\n            // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE\n            // during multiplication. See the comments within the \"sqrt\" function.\n            result = PRBMath.sqrt(xy);\n        }\n    }\n\n    /// @notice Calculates 1 / x, rounding toward zero.\n    ///\n    /// @dev Requirements:\n    /// - x cannot be zero.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse.\n    /// @return result The inverse as an unsigned 60.18-decimal fixed-point number.\n    function inv(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            // 1e36 is SCALE * SCALE.\n            result = 1e36 / x;\n        }\n    }\n\n    /// @notice Calculates the natural logarithm of x.\n    ///\n    /// @dev Based on the insight that ln(x) = log2(x) / log2(e).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm.\n    /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number.\n    function ln(uint256 x) internal pure returns (uint256 result) {\n        // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)\n        // can return is 196205294292027477728.\n        unchecked {\n            result = (log2(x) * SCALE) / LOG2_E;\n        }\n    }\n\n    /// @notice Calculates the common logarithm of x.\n    ///\n    /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common\n    /// logarithm based on the insight that log10(x) = log2(x) / log2(10).\n    ///\n    /// Requirements:\n    /// - All from \"log2\".\n    ///\n    /// Caveats:\n    /// - All from \"log2\".\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm.\n    /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number.\n    function log10(uint256 x) internal pure returns (uint256 result) {\n        if (x < SCALE) {\n            revert PRBMathUD60x18__LogInputTooSmall(x);\n        }\n\n        // Note that the \"mul\" in this block is the assembly multiplication operation, not the \"mul\" function defined\n        // in this contract.\n        // prettier-ignore\n        assembly {\n            switch x\n            case 1 { result := mul(SCALE, sub(0, 18)) }\n            case 10 { result := mul(SCALE, sub(1, 18)) }\n            case 100 { result := mul(SCALE, sub(2, 18)) }\n            case 1000 { result := mul(SCALE, sub(3, 18)) }\n            case 10000 { result := mul(SCALE, sub(4, 18)) }\n            case 100000 { result := mul(SCALE, sub(5, 18)) }\n            case 1000000 { result := mul(SCALE, sub(6, 18)) }\n            case 10000000 { result := mul(SCALE, sub(7, 18)) }\n            case 100000000 { result := mul(SCALE, sub(8, 18)) }\n            case 1000000000 { result := mul(SCALE, sub(9, 18)) }\n            case 10000000000 { result := mul(SCALE, sub(10, 18)) }\n            case 100000000000 { result := mul(SCALE, sub(11, 18)) }\n            case 1000000000000 { result := mul(SCALE, sub(12, 18)) }\n            case 10000000000000 { result := mul(SCALE, sub(13, 18)) }\n            case 100000000000000 { result := mul(SCALE, sub(14, 18)) }\n            case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }\n            case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }\n            case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }\n            case 1000000000000000000 { result := 0 }\n            case 10000000000000000000 { result := SCALE }\n            case 100000000000000000000 { result := mul(SCALE, 2) }\n            case 1000000000000000000000 { result := mul(SCALE, 3) }\n            case 10000000000000000000000 { result := mul(SCALE, 4) }\n            case 100000000000000000000000 { result := mul(SCALE, 5) }\n            case 1000000000000000000000000 { result := mul(SCALE, 6) }\n            case 10000000000000000000000000 { result := mul(SCALE, 7) }\n            case 100000000000000000000000000 { result := mul(SCALE, 8) }\n            case 1000000000000000000000000000 { result := mul(SCALE, 9) }\n            case 10000000000000000000000000000 { result := mul(SCALE, 10) }\n            case 100000000000000000000000000000 { result := mul(SCALE, 11) }\n            case 1000000000000000000000000000000 { result := mul(SCALE, 12) }\n            case 10000000000000000000000000000000 { result := mul(SCALE, 13) }\n            case 100000000000000000000000000000000 { result := mul(SCALE, 14) }\n            case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }\n            case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }\n            case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }\n            case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }\n            case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }\n            case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }\n            case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }\n            case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }\n            case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }\n            case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }\n            case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }\n            case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }\n            case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }\n            case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }\n            case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }\n            case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }\n            case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }\n            case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }\n            case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }\n            case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }\n            case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }\n            case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }\n            case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }\n            case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }\n            case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }\n            case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }\n            case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }\n            case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }\n            case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }\n            case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }\n            case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }\n            case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }\n            case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }\n            case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }\n            case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }\n            case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) }\n            default {\n                result := MAX_UD60x18\n            }\n        }\n\n        if (result == MAX_UD60x18) {\n            // Do the fixed-point division inline to save gas. The denominator is log2(10).\n            unchecked {\n                result = (log2(x) * SCALE) / 3_321928094887362347;\n            }\n        }\n    }\n\n    /// @notice Calculates the binary logarithm of x.\n    ///\n    /// @dev Based on the iterative approximation algorithm.\n    /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation\n    ///\n    /// Requirements:\n    /// - x must be greater than or equal to SCALE, otherwise the result would be negative.\n    ///\n    /// Caveats:\n    /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm.\n    /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number.\n    function log2(uint256 x) internal pure returns (uint256 result) {\n        if (x < SCALE) {\n            revert PRBMathUD60x18__LogInputTooSmall(x);\n        }\n        unchecked {\n            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).\n            uint256 n = PRBMath.mostSignificantBit(x / SCALE);\n\n            // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow\n            // because n is maximum 255 and SCALE is 1e18.\n            result = n * SCALE;\n\n            // This is y = x * 2^(-n).\n            uint256 y = x >> n;\n\n            // If y = 1, the fractional part is zero.\n            if (y == SCALE) {\n                return result;\n            }\n\n            // Calculate the fractional part via the iterative approximation.\n            // The \"delta >>= 1\" part is equivalent to \"delta /= 2\", but shifting bits is faster.\n            for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {\n                y = (y * y) / SCALE;\n\n                // Is y^2 > 2 and so in the range [2,4)?\n                if (y >= 2 * SCALE) {\n                    // Add the 2^(-m) factor to the logarithm.\n                    result += delta;\n\n                    // Corresponds to z/2 on Wikipedia.\n                    y >>= 1;\n                }\n            }\n        }\n    }\n\n    /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal\n    /// fixed-point number.\n    /// @dev See the documentation for the \"PRBMath.mulDivFixedPoint\" function.\n    /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The product as an unsigned 60.18-decimal fixed-point number.\n    function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        result = PRBMath.mulDivFixedPoint(x, y);\n    }\n\n    /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number.\n    function pi() internal pure returns (uint256 result) {\n        result = 3_141592653589793238;\n    }\n\n    /// @notice Raises x to the power of y.\n    ///\n    /// @dev Based on the insight that x^y = 2^(log2(x) * y).\n    ///\n    /// Requirements:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    ///\n    /// Caveats:\n    /// - All from \"exp2\", \"log2\" and \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number.\n    /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number.\n    /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number.\n    function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        if (x == 0) {\n            result = y == 0 ? SCALE : uint256(0);\n        } else {\n            result = exp2(mul(log2(x), y));\n        }\n    }\n\n    /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the\n    /// famous algorithm \"exponentiation by squaring\".\n    ///\n    /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring\n    ///\n    /// Requirements:\n    /// - The result must fit within MAX_UD60x18.\n    ///\n    /// Caveats:\n    /// - All from \"mul\".\n    /// - Assumes 0^0 is 1.\n    ///\n    /// @param x The base as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The exponent as an uint256.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        // Calculate the first iteration of the loop in advance.\n        result = y & 1 > 0 ? x : SCALE;\n\n        // Equivalent to \"for(y /= 2; y > 0; y /= 2)\" but faster.\n        for (y >>= 1; y > 0; y >>= 1) {\n            x = PRBMath.mulDivFixedPoint(x, x);\n\n            // Equivalent to \"y % 2 == 1\" but faster.\n            if (y & 1 > 0) {\n                result = PRBMath.mulDivFixedPoint(result, x);\n            }\n        }\n    }\n\n    /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number.\n    function scale() internal pure returns (uint256 result) {\n        result = SCALE;\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Requirements:\n    /// - x must be less than MAX_UD60x18 / SCALE.\n    ///\n    /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point .\n    function sqrt(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            if (x > MAX_UD60x18 / SCALE) {\n                revert PRBMathUD60x18__SqrtOverflow(x);\n            }\n            // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned\n            // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).\n            result = PRBMath.sqrt(x * SCALE);\n        }\n    }\n\n    /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process.\n    /// @param x The unsigned 60.18-decimal fixed-point number to convert.\n    /// @return result The same number in basic integer form.\n    function toUint(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            result = x / SCALE;\n        }\n    }\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/IERC3156FlashBorrower.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\ninterface IERC3156FlashBorrower {\n\n    /**\n     * @dev    Receive a flash loan.\n     * @param  initiator The initiator of the loan.\n     * @param  token     The loan currency.\n     * @param  amount    The amount of tokens lent (token precision).\n     * @param  fee       The additional amount of tokens to repay.\n     * @param  data      Arbitrary data structure, intended to contain user-defined parameters.\n     * @return The `keccak256` hash of `ERC3156FlashBorrower.onFlashLoan`\n     */\n    function onFlashLoan(\n        address initiator,\n        address token,\n        uint256 amount,\n        uint256 fee,\n        bytes   calldata data\n    ) external returns (bytes32);\n}"
      },
      "lib/ajna-core/src/libraries/internal/Deposits.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.18;\n\nimport { Math } from '@openzeppelin/contracts/utils/math/Math.sol';\n\nimport { DepositsState } from '../../interfaces/pool/commons/IPoolState.sol';\n\nimport { _priceAt, MAX_FENWICK_INDEX } from '../helpers/PoolHelper.sol';\n\nimport { Maths } from './Maths.sol';\n\n/**\n    @title  Deposits library\n    @notice Internal library containing common logic for deposits management.\n    @dev    Implemented as `Fenwick Tree` data structure.\n */\nlibrary Deposits {\n\n    /// @dev Max index supported in the `Fenwick` tree\n    uint256 internal constant SIZE = 8192;\n\n    /**************/\n    /*** Errors ***/\n    /**************/\n\n    // See `IPoolErrors` for descriptions\n    error InvalidAmount();\n\n    /**\n     *  @notice Increase a value in the FenwickTree at an index.\n     *  @dev    Starts at leaf/target and moved up towards root\n     *  @dev    === Reverts on ===\n     *  @dev    unscaled amount to add is 0 `InvalidAmount()`\n     *  @param  deposits_          Deposits state struct.\n     *  @param  index_             The deposit index.\n     *  @param  unscaledAddAmount_ The unscaled amount to increase deposit by.\n     */\n    function unscaledAdd(\n        DepositsState storage deposits_,\n        uint256 index_,\n        uint256 unscaledAddAmount_\n    ) internal {\n\n        // revert if 0 amount is added.\n        if (unscaledAddAmount_ == 0) revert InvalidAmount();\n\n        // price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1\n        ++index_;\n\n        // unscaledAddAmount_ is the raw amount to add directly to the value at index_, unaffected by the scale array\n        // For example, to denote an amount of deposit added to the array, we would need to call unscaledAdd with\n        // (deposit amount) / scale(index).  There are two reasons for this:\n        // 1- scale(index) is often already known in the context of where unscaledAdd(..) is called, and we want to avoid\n        //    redundant iterations through the Fenwick tree.\n        // 2- We often need to precisely change the value in the tree, avoiding the rounding that dividing by scale(index).\n        //    This is more relevant to unscaledRemove(...), where we need to ensure the value is precisely set to 0, but we\n        //    also prefer it here for consistency.\n\n        uint256 value;\n        uint256 scaling;\n        uint256 newValue;\n\n        while (index_ <= SIZE) {\n            value    = deposits_.values[index_];\n            scaling  = deposits_.scaling[index_];\n\n            // Compute the new value to be put in location index_\n            newValue = value + unscaledAddAmount_;\n\n            // Update unscaledAddAmount to propogate up the Fenwick tree\n            // Note: we can't just multiply addAmount_ by scaling[i_] due to rounding\n            // We need to track the precice change in values[i_] in order to ensure\n            // obliterated indices remain zero after subsequent adding to related indices\n            // if scaling==0, the actual scale value is 1, otherwise it is scaling\n            if (scaling != 0) unscaledAddAmount_ = Maths.wmul(newValue, scaling) - Maths.wmul(value, scaling);\n\n            deposits_.values[index_] = newValue;\n\n            // traverse upwards through tree via \"update\" route\n            index_ += lsb(index_);\n        }\n    }\n\n    /**\n     *  @notice Finds index and sum of first bucket that EXCEEDS the given sum\n     *  @dev    Used in `LUP` calculation\n     *  @param  deposits_      Struct for deposits state.\n     *  @param  targetSum_     The sum to find index for.\n     *  @return sumIndex_      Smallest index where prefixsum greater than the sum.\n     *  @return sumIndexSum_   Sum at index PRECEDING `sumIndex_`.\n     *  @return sumIndexScale_ Scale of bucket PRECEDING `sumIndex_`.\n     */\n    function findIndexAndSumOfSum(\n        DepositsState storage deposits_,\n        uint256 targetSum_\n    ) internal view returns (uint256 sumIndex_, uint256 sumIndexSum_, uint256 sumIndexScale_) {\n        // i iterates over bits from MSB to LSB.  We check at each stage if the target sum is to the left or right of sumIndex_+i\n        uint256 i  = 4096; // 1 << (_numBits - 1) = 1 << (13 - 1) = 4096\n        uint256 runningScale = Maths.WAD;\n\n        // We construct the target sumIndex_ bit by bit, from MSB to LSB.  lowerIndexSum_ always maintains the sum\n        // up to the current value of sumIndex_\n        uint256 lowerIndexSum;\n        uint256 curIndex;\n        uint256 value;\n        uint256 scaling;\n        uint256 scaledValue;\n\n        while (i > 0) {\n            // Consider if the target index is less than or greater than sumIndex_ + i\n            curIndex = sumIndex_ + i;\n            value    = deposits_.values[curIndex];\n            scaling  = deposits_.scaling[curIndex];\n\n            // Compute sum up to sumIndex_ + i\n            scaledValue =\n                lowerIndexSum +\n                (\n                    scaling != 0 ? Math.mulDiv(\n                        runningScale * scaling,\n                        value,\n                        1e36\n                    ) : Maths.wmul(runningScale, value)\n                );\n\n            if (scaledValue  < targetSum_) {\n                // Target value is too small, need to consider increasing sumIndex_ still\n                if (curIndex <= MAX_FENWICK_INDEX) {\n                    // sumIndex_+i is in range of Fenwick prices.  Target index has this bit set to 1.  \n                    sumIndex_ = curIndex;\n                    lowerIndexSum = scaledValue;\n                }\n            } else {\n                // Target index has this bit set to 0\n                // scaling == 0 means scale factor == 1, otherwise scale factor == scaling\n                if (scaling != 0) runningScale = Maths.floorWmul(runningScale, scaling);\n\n                // Current scaledValue is <= targetSum_, it's a candidate value for sumIndexSum_\n                sumIndexSum_   = scaledValue;\n                sumIndexScale_ = runningScale;\n            }\n            // Shift i to next less significant bit\n            i = i >> 1;\n        }\n    }\n\n    /**\n     *  @notice Finds index of passed sum. Helper function for `findIndexAndSumOfSum`.\n     *  @dev    Used in `LUP` calculation\n     *  @param  deposits_ Deposits state struct.\n     *  @param  sum_      The sum to find index for.\n     *  @return sumIndex_ Smallest index where prefixsum greater than the sum.\n     */\n    function findIndexOfSum(\n        DepositsState storage deposits_,\n        uint256 sum_\n    ) internal view returns (uint256 sumIndex_) {\n        (sumIndex_,,) = findIndexAndSumOfSum(deposits_, sum_);\n    }\n\n    /**\n     *  @notice Get least significant bit (`LSB`) of integer `i_`.\n     *  @dev    Used primarily to decrement the binary index in loops, iterating over range parents.\n     *  @param  i_  The integer with which to return the `LSB`.\n     */\n    function lsb(\n        uint256 i_\n    ) internal pure returns (uint256 lsb_) {\n        if (i_ != 0) {\n            // \"i & (-i)\"\n            lsb_ = i_ & ((i_ ^ 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) + 1);\n        }\n    }\n\n    /**\n     *  @notice Scale values in the tree from the index provided, upwards.\n     *  @dev    Starts at passed in node and increments through range parent nodes, and ends at `8192`.\n     *  @param  deposits_ Deposits state struct.\n     *  @param  index_    The index to start scaling from.\n     *  @param  factor_   The factor to scale the values by.\n     */\n    function mult(\n        DepositsState storage deposits_,\n        uint256 index_,\n        uint256 factor_\n    ) internal {\n        // price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1\n        ++index_;\n\n        uint256 sum;\n        uint256 value;\n        uint256 scaling;\n        uint256 bit = lsb(index_);\n\n        // Starting with the LSB of index, we iteratively move up towards the MSB of SIZE\n        // Case 1:     the bit of index_ is set to 1.  In this case, the entire subtree below index_\n        //             is scaled.  So, we include factor_ into scaling[index_], and remember in sum how much\n        //             we increased the subtree by, so that we can use it in case we encounter 0 bits (below).\n        // Case 2:     The bit of index_ is set to 0.  In this case, consider the subtree below the node\n        //             index_+bit. The subtree below that is not entirely scaled, but it does contain the\n        //             subtree what was scaled earlier.  Therefore: we need to increment it's stored value\n        //             (in sum) which was set in a prior interation in case 1.\n        while (bit <= SIZE) {\n            if ((bit & index_) != 0) {\n                // Case 1 as described above\n                value   = deposits_.values[index_];\n                scaling = deposits_.scaling[index_];\n\n                // Calc sum, will only be stored in range parents of starting node, index_\n                if (scaling != 0) {\n                    // Note: we can't just multiply by factor_ - 1 in the following line, as rounding will\n                    // cause obliterated indices to have nonzero values.  Need to track the actual\n                    // precise delta in the value array\n                    uint256 scaledFactor = Maths.wmul(factor_, scaling);\n\n                    sum += Maths.wmul(scaledFactor, value) - Maths.wmul(scaling, value);\n\n                    // Apply scaling to all range parents less then starting node, index_\n                    deposits_.scaling[index_] = scaledFactor;\n                } else {\n                    // this node's scale factor is 1\n                    sum += Maths.wmul(factor_, value) - value;\n                    deposits_.scaling[index_] = factor_;\n                }\n                // Unset the bit in index to continue traversing up the Fenwick tree\n                index_ -= bit;\n            } else {\n                // Case 2 above.  superRangeIndex is the index of the node to consider that\n                //                contains the sub range that was already scaled in prior iteration\n                uint256 superRangeIndex = index_ + bit;\n\n                value   = (deposits_.values[superRangeIndex] += sum);\n                scaling = deposits_.scaling[superRangeIndex];\n\n                // Need to be careful due to rounding to propagate actual changes upwards in tree.\n                // sum is always equal to the actual value we changed deposits_.values[] by\n                if (scaling != 0) sum = Maths.wmul(value, scaling) - Maths.wmul(value - sum, scaling);\n            }\n            // consider next most significant bit\n            bit = bit << 1;\n        }\n    }\n\n    /**\n     *  @notice Get prefix sum of all indexes from provided index downwards.\n     *  @dev    Starts at tree root and decrements through range parent nodes summing from index `sumIndex_`'s range to index `0`.\n     *  @param  deposits_  Deposits state struct.\n     *  @param  sumIndex_  The index to receive the prefix sum.\n     *  @param  sum_       The prefix sum from current index downwards.\n     */\n    function prefixSum(\n        DepositsState storage deposits_,\n        uint256 sumIndex_\n    ) internal view returns (uint256 sum_) {\n        // price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1\n        ++sumIndex_;\n\n        uint256 runningScale = Maths.WAD; // Tracks scale(index_) as we move down Fenwick tree\n        uint256 j            = SIZE;      // bit that iterates from MSB to LSB\n        uint256 index        = 0;         // build up sumIndex bit by bit\n\n        // Used to terminate loop.  We don't need to consider final 0 bits of sumIndex_\n        uint256 indexLSB = lsb(sumIndex_);\n        uint256 curIndex;\n\n        while (j >= indexLSB) {\n            curIndex = index + j;\n\n            // Skip considering indices outside bounds of Fenwick tree\n            if (curIndex > SIZE) continue;\n\n            // We are considering whether to include node index + j in the sum or not.  Either way, we need to scaling[index + j],\n            // either to increment sum_ or to accumulate in runningScale\n            uint256 scaled = deposits_.scaling[curIndex];\n\n            if (sumIndex_ & j != 0) {\n                // node index + j of tree is included in sum\n                uint256 value = deposits_.values[curIndex];\n\n                // Accumulate in sum_, recall that scaled==0 means that the scale factor is actually 1\n                sum_  += scaled != 0 ? Math.mulDiv(\n                    runningScale * scaled,\n                    value,\n                    1e36\n                ) : Maths.wmul(runningScale, value);\n\n                // Build up index bit by bit\n                index = curIndex;\n\n                // terminate if we've already matched sumIndex_\n                if (index == sumIndex_) break;\n            } else {\n                // node is not included in sum, but its scale needs to be included for subsequent sums\n                if (scaled != 0) runningScale = Maths.floorWmul(runningScale, scaled);\n            }\n            // shift j to consider next less signficant bit\n            j = j >> 1;\n        }\n    }\n\n    /**\n     *  @notice Decrease a node in the `FenwickTree` at an index.\n     *  @dev    Starts at leaf/target and moved up towards root.\n     *  @dev    === Reverts on ===\n     *  @dev    unscaled amount to remove is 0 `InvalidAmount()`\n     *  @param  deposits_             Deposits state struct.\n     *  @param  index_                The deposit index.\n     *  @param  unscaledRemoveAmount_ Unscaled amount to decrease deposit by.\n     */\n    function unscaledRemove(\n        DepositsState storage deposits_,\n        uint256 index_,\n        uint256 unscaledRemoveAmount_\n    ) internal {\n\n        // revert if 0 amount is removed.\n        if (unscaledRemoveAmount_ == 0) revert InvalidAmount();\n\n        // price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1\n        ++index_;\n\n        // We operate with unscaledRemoveAmount_ here instead of a scaled quantity to avoid duplicate computation of scale factor\n        // (thus redundant iterations through the Fenwick tree), and ALSO so that we can set the value of a given deposit exactly\n        // to 0.\n        \n        while (index_ <= SIZE) {\n            // Decrement deposits_ at index_ for removeAmount, storing new value in value\n            uint256 value   = (deposits_.values[index_] -= unscaledRemoveAmount_);\n            uint256 scaling = deposits_.scaling[index_];\n\n            // If scale factor != 1, we need to adjust unscaledRemoveAmount by scale factor to adjust values further up in tree\n            // On the line below, it would be tempting to replace this with:\n            // unscaledRemoveAmount_ = Maths.wmul(unscaledRemoveAmount, scaling).  This will introduce nonzero values up\n            // the tree due to rounding.  It's important to compute the actual change in deposits_.values[index_]\n            // and propogate that upwards.\n            if (scaling != 0) unscaledRemoveAmount_ = Maths.wmul(value + unscaledRemoveAmount_, scaling) - Maths.wmul(value,  scaling);\n\n            // Traverse upward through the \"update\" path of the Fenwick tree\n            index_ += lsb(index_);\n        }\n    }\n\n    /**\n     *  @notice Scale tree starting from given index.\n     *  @dev    Starts at leaf/target and moved up towards root.\n     *  @param  deposits_ Deposits state struct.\n     *  @param  index_    The deposit index.\n     *  @return scaled_   Scaled value.\n     */\n    function scale(\n        DepositsState storage deposits_,\n        uint256 index_\n    ) internal view returns (uint256 scaled_) {\n        // price buckets are indexed starting at 0, Fenwick bit logic is more elegant starting at 1\n        ++index_;\n\n        // start with scaled_1 = 1\n        scaled_ = Maths.WAD;\n        while (index_ <= SIZE) {\n            // Traverse up through Fenwick tree via \"update\" path, accumulating scale factors as we go\n            uint256 scaling = deposits_.scaling[index_];\n            // scaling==0 means actual scale factor is 1\n            if (scaling != 0) scaled_ = Maths.wmul(scaled_, scaling);\n            index_ += lsb(index_);\n        }\n    }\n\n    /**\n     *  @notice Returns sum of all deposits.\n     *  @param  deposits_ Deposits state struct.\n     *  @return Sum of all deposits in tree.\n     */\n    function treeSum(\n        DepositsState storage deposits_\n    ) internal view returns (uint256) {\n        // In a scaled Fenwick tree, sum is at the root node and never scaled\n        return deposits_.values[SIZE];\n    }\n\n    /**\n     *  @notice Returns deposit value for a given deposit index.\n     *  @param  deposits_     Deposits state struct.\n     *  @param  index_        The deposit index.\n     *  @return depositValue_ Value of the deposit.\n     */\n    function valueAt(\n        DepositsState storage deposits_,\n        uint256 index_\n    ) internal view returns (uint256 depositValue_) {\n        // Get unscaled value at index and multiply by scale\n        depositValue_ = Maths.wmul(unscaledValueAt(deposits_, index_), scale(deposits_,index_));\n    }\n\n    /**\n     *  @notice Returns unscaled (deposit without interest) deposit value for a given deposit index.\n     *  @param  deposits_             Deposits state struct.\n     *  @param  index_                The deposit index.\n     *  @return unscaledDepositValue_ Value of unscaled deposit.\n     */\n    function unscaledValueAt(\n        DepositsState storage deposits_,\n        uint256 index_\n    ) internal view returns (uint256 unscaledDepositValue_) {\n        // In a scaled Fenwick tree, sum is at the root node, but needs to be scaled\n        ++index_;\n\n        uint256 j = 1;\n\n        // Returns the unscaled value at the node.  We consider the unscaled value for two reasons:\n        // 1- If we want to zero out deposit in bucket, we need to subtract the exact unscaled value\n        // 2- We may already have computed the scale factor, so we can avoid duplicate traversal\n\n        unscaledDepositValue_ = deposits_.values[index_];\n        uint256 curIndex;\n        uint256 value;\n        uint256 scaling;\n\n        while (j & index_ == 0) {\n            curIndex = index_ - j;\n\n            value   = deposits_.values[curIndex];\n            scaling = deposits_.scaling[curIndex];\n\n            unscaledDepositValue_ -= scaling != 0 ? Maths.wmul(scaling, value) : value;\n            j = j << 1;\n        }\n    }\n\n    /**\n     *  @notice Returns `LUP` for a given debt value (capped at min bucket price).\n     *  @param  deposits_ Deposits state struct.\n     *  @param  debt_     The debt amount to calculate `LUP` for.\n     *  @return `LUP` for given debt.\n     */\n    function getLup(\n        DepositsState storage deposits_,\n        uint256 debt_\n    ) internal view returns (uint256) {\n        return _priceAt(findIndexOfSum(deposits_, debt_));\n    }\n}\n"
      },
      "lib/ajna-core/src/libraries/internal/Loans.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\n\npragma solidity 0.8.18;\n\nimport { SafeCast }       from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport { PRBMathSD59x18 } from \"@prb-math/contracts/PRBMathSD59x18.sol\";\n\nimport {\n    AuctionsState,\n    Borrower,\n    DepositsState,\n    Loan,\n    LoansState\n} from '../../interfaces/pool/commons/IPoolState.sol';\n\nimport { _priceAt } from '../helpers/PoolHelper.sol';\n\nimport { Deposits } from './Deposits.sol';\nimport { Maths }    from './Maths.sol';\n\n/**\n    @title  Loans library\n    @notice Internal library containing common logic for loans management.\n    @dev    The `Loans` heap is a `Max Heap` data structure (complete binary tree), the root node is the loan with the highest t0 threshold price (`TP`)\n            at a given time. The heap is represented as an array, where the first element is a dummy element (`Loan(address(0), 0)`) and the first\n            value of the heap starts at index `1`, `ROOT_INDEX`. The t0 threshold price of a loan's parent is always greater than or equal to the\n            t0 threshold price of the loan.\n    @dev    This code was modified from the following source: https://github.com/zmitton/eth-heap/blob/master/contracts/Heap.sol\n */\nlibrary Loans {\n\n    uint256 constant ROOT_INDEX = 1;\n\n    /**************/\n    /*** Errors ***/\n    /**************/\n\n    // See `IPoolErrors` for descriptions\n    error ZeroDebtToCollateral();\n\n    /***********************/\n    /***  Initialization ***/\n    /***********************/\n\n    /**\n     *  @notice Initializes Loans Max Heap.\n     *  @dev    Organizes loans so `Highest t0 threshold price` can be retrieved easily.\n     *  @param  loans_ Holds Loan heap data.\n     */\n    function init(LoansState storage loans_) internal {\n        loans_.loans.push(Loan(address(0), 0));\n    }\n\n    /***********************************/\n    /***  Loans Management Functions ***/\n    /***********************************/\n\n    /**\n     *  @notice Updates a loan: updates heap (`upsert` if `TP` not `0`, `remove` otherwise) and borrower balance.\n     *  @dev    === Write state ===\n     *  @dev    - `_upsert`:\n     *  @dev      insert or update loan in `loans` array\n     *  @dev    - `remove`:\n     *  @dev      remove loan from `loans` array\n     *  @dev    - update borrower in `address => borrower` mapping\n     *  @param loans_           Holds loans heap data.\n     *  @param borrower_        Borrower struct with borrower details.\n     *  @param borrowerAddress_ Borrower's address to update.\n     *  @param poolRate_        Pool's current rate.\n     *  @param inAuction_       Whether the loan is in auction or not.\n     *  @param npTpRatioUpdate_ Whether the Np to Tp ratio of borrower should be updated or not.\n     */\n    function update(\n        LoansState storage loans_,\n        Borrower memory borrower_,\n        address borrowerAddress_,\n        uint256 poolRate_,\n        bool inAuction_,\n        bool npTpRatioUpdate_\n    ) internal {\n\n        bool activeBorrower = borrower_.t0Debt != 0 && borrower_.collateral != 0;\n\n        uint256 t0DebtToCollateral = activeBorrower ? Maths.wdiv(borrower_.t0Debt, borrower_.collateral) : 0;\n\n        // loan not in auction, update t0 threshold price and position in heap\n        if (!inAuction_ ) {\n            // get the loan id inside the heap\n            uint256 loanId = loans_.indices[borrowerAddress_];\n            if (activeBorrower) {\n                // revert if t0 threshold price is zero\n                if (t0DebtToCollateral == 0) revert ZeroDebtToCollateral();\n\n                // update heap, insert if a new loan, update loan if already in heap\n                _upsert(loans_, borrowerAddress_, loanId, SafeCast.toUint96(t0DebtToCollateral));\n\n            // if loan is in heap and borrwer is no longer active (no debt, no collateral) then remove loan from heap\n            } else if (loanId != 0) {\n                remove(loans_, borrowerAddress_, loanId);\n            }\n        }\n\n        // update Np to Tp ratio of borrower\n        if (npTpRatioUpdate_) {\n            borrower_.npTpRatio = 1e18 + uint256(PRBMathSD59x18.sqrt(int256(poolRate_))) / 2;\n        }\n\n        // save borrower state\n        loans_.borrowers[borrowerAddress_] = borrower_;\n    }\n\n    /**************************************/\n    /***  Loans Heap Internal Functions ***/\n    /**************************************/\n\n    /**\n     *  @notice Moves a `Loan` up the heap.\n     *  @param loans_ Holds loans heap data.\n     *  @param loan_  `Loan` to be moved.\n     *  @param index_ Index of `Loan` to be moved to.\n     */\n    function _bubbleUp(LoansState storage loans_, Loan memory loan_, uint index_) private {\n        uint256 count = loans_.loans.length;\n        if (index_ == ROOT_INDEX || loan_.t0DebtToCollateral <= loans_.loans[index_ / 2].t0DebtToCollateral){\n          _insert(loans_, loan_, index_, count);\n        } else {\n          _insert(loans_, loans_.loans[index_ / 2], index_, count);\n          _bubbleUp(loans_, loan_, index_ / 2);\n        }\n    }\n\n    /**\n     *  @notice Moves a `Loan` down the heap.\n     *  @param loans_ Holds loans heap data.\n     *  @param loan_  `Loan` to be moved.\n     *  @param index_ Index of `Loan` to be moved to.\n     */\n    function _bubbleDown(LoansState storage loans_, Loan memory loan_, uint index_) private {\n        // Left child index.\n        uint cIndex = index_ * 2;\n\n        uint256 count = loans_.loans.length;\n        if (count <= cIndex) {\n            _insert(loans_, loan_, index_, count);\n        } else {\n            Loan memory largestChild = loans_.loans[cIndex];\n\n            if (count > cIndex + 1 && loans_.loans[cIndex + 1].t0DebtToCollateral > largestChild.t0DebtToCollateral) {\n                largestChild = loans_.loans[++cIndex];\n            }\n\n            if (largestChild.t0DebtToCollateral <= loan_.t0DebtToCollateral) {\n              _insert(loans_, loan_, index_, count);\n            } else {\n              _insert(loans_, largestChild, index_, count);\n              _bubbleDown(loans_, loan_, cIndex);\n            }\n        }\n    }\n\n    /**\n     *  @notice Inserts a `Loan` in the heap.\n     *  @param loans_ Holds loans heap data.\n     *  @param loan_  `Loan` to be inserted.\n     *  @param index_ Index of `Loan` to be inserted at.\n     */\n    function _insert(LoansState storage loans_, Loan memory loan_, uint index_, uint256 count_) private {\n        if (index_ == count_) loans_.loans.push(loan_);\n        else loans_.loans[index_] = loan_;\n\n        loans_.indices[loan_.borrower] = index_;\n    }\n\n    /**\n     *  @notice Removes `Loan` from heap given borrower address.\n     *  @param loans_    Holds loans heap data.\n     *  @param borrower_ Borrower address whose `Loan` is being updated or inserted.\n     *  @param index_    Index of `Loan` to be removed.\n     */\n    function remove(LoansState storage loans_, address borrower_, uint256 index_) internal {\n        delete loans_.indices[borrower_];\n        uint256 tailIndex = loans_.loans.length - 1;\n        if (index_ == tailIndex) loans_.loans.pop(); // we're removing the tail, pop without sorting\n        else {\n            Loan memory tail = loans_.loans[tailIndex];\n            loans_.loans.pop();            // remove tail loan\n            _bubbleUp(loans_, tail, index_);\n            _bubbleDown(loans_, loans_.loans[index_], index_);\n        }\n    }\n\n    /**\n     *  @notice Performs an insert or an update dependent on borrowers existance.\n     *  @param loans_              Holds loans heap data.\n     *  @param borrower_           Borrower address that is being updated or inserted.\n     *  @param index_              Index of `Loan` to be upserted.\n     *  @param t0DebtToCollateral_ Borrower t0 debt to collateral that is updated or inserted.\n     */\n    function _upsert(\n        LoansState storage loans_,\n        address borrower_,\n        uint256 index_,\n        uint96 t0DebtToCollateral_\n    ) internal {\n        // Loan exists, update in place.\n        if (index_ != 0) {\n            Loan memory currentLoan = loans_.loans[index_];\n            if (currentLoan.t0DebtToCollateral > t0DebtToCollateral_) {\n                currentLoan.t0DebtToCollateral = t0DebtToCollateral_;\n                _bubbleDown(loans_, currentLoan, index_);\n            } else {\n                currentLoan.t0DebtToCollateral = t0DebtToCollateral_;\n                _bubbleUp(loans_, currentLoan, index_);\n            }\n\n        // New loan, insert it\n        } else {\n            _bubbleUp(loans_, Loan(borrower_, t0DebtToCollateral_), loans_.loans.length);\n        }\n    }\n\n\n    /**********************/\n    /*** View Functions ***/\n    /**********************/\n\n    /**\n     *  @notice Retreives `Loan` by index, `index_`.\n     *  @param loans_ Holds loans heap data.\n     *  @param index_ Index to retrieve `Loan`.\n     *  @return `Loan` struct retrieved by index.\n     */\n    function getByIndex(LoansState storage loans_, uint256 index_) internal view returns(Loan memory) {\n        return loans_.loans.length > index_ ? loans_.loans[index_] : Loan(address(0), 0);\n    }\n\n    /**\n     *  @notice Retreives `Loan` with the highest t0 threshold price value.\n     *  @param loans_ Holds loans heap data.\n     *  @return `Max Loan` in the heap.\n     */\n    function getMax(LoansState storage loans_) internal view returns(Loan memory) {\n        return getByIndex(loans_, ROOT_INDEX);\n    }\n\n    /**\n     *  @notice Returns number of loans in pool.\n     *  @param loans_ Holds loans heap data.\n     *  @return Number of loans in pool.\n     */\n    function noOfLoans(LoansState storage loans_) internal view returns (uint256) {\n        return loans_.loans.length - 1;\n    }\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n    /// @return The contract address\n    function factory() external view returns (address);\n\n    /// @notice The first of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token0() external view returns (address);\n\n    /// @notice The second of the two tokens of the pool, sorted by address\n    /// @return The token contract address\n    function token1() external view returns (address);\n\n    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n    /// @return The fee\n    function fee() external view returns (uint24);\n\n    /// @notice The pool tick spacing\n    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n    /// This value is an int24 to avoid casting even though it is always positive.\n    /// @return The tick spacing\n    function tickSpacing() external view returns (int24);\n\n    /// @notice The maximum amount of position liquidity that can use any tick in the range\n    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n    /// @return The max amount of liquidity per tick\n    function maxLiquidityPerTick() external view returns (uint128);\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n    /// when accessed externally.\n    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n    /// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.\n    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n    /// boundary.\n    /// @return observationIndex The index of the last oracle observation that was written,\n    /// @return observationCardinality The current maximum number of observations stored in the pool,\n    /// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n    /// @return feeProtocol The protocol fee for both tokens of the pool.\n    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n    /// unlocked Whether the pool is currently locked to reentrancy\n    function slot0()\n        external\n        view\n        returns (\n            uint160 sqrtPriceX96,\n            int24 tick,\n            uint16 observationIndex,\n            uint16 observationCardinality,\n            uint16 observationCardinalityNext,\n            uint8 feeProtocol,\n            bool unlocked\n        );\n\n    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal0X128() external view returns (uint256);\n\n    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n    /// @dev This value can overflow the uint256\n    function feeGrowthGlobal1X128() external view returns (uint256);\n\n    /// @notice The amounts of token0 and token1 that are owed to the protocol\n    /// @dev Protocol fees will never exceed uint128 max in either token\n    function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n    /// @notice The currently in range liquidity available to the pool\n    /// @dev This value has no relationship to the total liquidity across all ticks\n    /// @return The liquidity at the current price of the pool\n    function liquidity() external view returns (uint128);\n\n    /// @notice Look up information about a specific tick in the pool\n    /// @param tick The tick to look up\n    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n    /// tick upper\n    /// @return liquidityNet how much liquidity changes when the pool price crosses the tick,\n    /// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n    /// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n    /// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n    /// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n    /// @return secondsOutside the seconds spent on the other side of the tick from the current tick,\n    /// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n    /// a specific position.\n    function ticks(int24 tick)\n        external\n        view\n        returns (\n            uint128 liquidityGross,\n            int128 liquidityNet,\n            uint256 feeGrowthOutside0X128,\n            uint256 feeGrowthOutside1X128,\n            int56 tickCumulativeOutside,\n            uint160 secondsPerLiquidityOutsideX128,\n            uint32 secondsOutside,\n            bool initialized\n        );\n\n    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n    function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n    /// @notice Returns the information about a position by the position's key\n    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n    /// @return liquidity The amount of liquidity in the position,\n    /// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n    /// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n    /// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n    /// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\n    function positions(bytes32 key)\n        external\n        view\n        returns (\n            uint128 liquidity,\n            uint256 feeGrowthInside0LastX128,\n            uint256 feeGrowthInside1LastX128,\n            uint128 tokensOwed0,\n            uint128 tokensOwed1\n        );\n\n    /// @notice Returns data about a specific observation index\n    /// @param index The element of the observations array to fetch\n    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n    /// ago, rather than at a specific index in the array.\n    /// @return blockTimestamp The timestamp of the observation,\n    /// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n    /// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n    /// @return initialized whether the observation has been initialized and the values are safe to use\n    function observations(uint256 index)\n        external\n        view\n        returns (\n            uint32 blockTimestamp,\n            int56 tickCumulative,\n            uint160 secondsPerLiquidityCumulativeX128,\n            bool initialized\n        );\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n    /// you must call it with secondsAgos = [3600, 0].\n    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n    /// timestamp\n    function observe(uint32[] calldata secondsAgos)\n        external\n        view\n        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n    /// snapshot is taken and the second snapshot is taken.\n    /// @param tickLower The lower tick of the range\n    /// @param tickUpper The upper tick of the range\n    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n    /// @return secondsInside The snapshot of seconds per liquidity for the range\n    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n        external\n        view\n        returns (\n            int56 tickCumulativeInside,\n            uint160 secondsPerLiquidityInsideX128,\n            uint32 secondsInside\n        );\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n    /// @notice Sets the initial price for the pool\n    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n    function initialize(uint160 sqrtPriceX96) external;\n\n    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n    /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n    /// @param recipient The address for which the liquidity will be created\n    /// @param tickLower The lower tick of the position in which to add liquidity\n    /// @param tickUpper The upper tick of the position in which to add liquidity\n    /// @param amount The amount of liquidity to mint\n    /// @param data Any data that should be passed through to the callback\n    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n    function mint(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount,\n        bytes calldata data\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Collects tokens owed to a position\n    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n    /// @param recipient The address which should receive the fees collected\n    /// @param tickLower The lower tick of the position for which to collect fees\n    /// @param tickUpper The upper tick of the position for which to collect fees\n    /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n    /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n    /// @return amount0 The amount of fees collected in token0\n    /// @return amount1 The amount of fees collected in token1\n    function collect(\n        address recipient,\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n\n    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n    /// @dev Fees must be collected separately via a call to #collect\n    /// @param tickLower The lower tick of the position for which to burn liquidity\n    /// @param tickUpper The upper tick of the position for which to burn liquidity\n    /// @param amount How much liquidity to burn\n    /// @return amount0 The amount of token0 sent to the recipient\n    /// @return amount1 The amount of token1 sent to the recipient\n    function burn(\n        int24 tickLower,\n        int24 tickUpper,\n        uint128 amount\n    ) external returns (uint256 amount0, uint256 amount1);\n\n    /// @notice Swap token0 for token1, or token1 for token0\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n    /// @param recipient The address to receive the output of the swap\n    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n    /// @param data Any data to be passed through to the callback\n    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n    function swap(\n        address recipient,\n        bool zeroForOne,\n        int256 amountSpecified,\n        uint160 sqrtPriceLimitX96,\n        bytes calldata data\n    ) external returns (int256 amount0, int256 amount1);\n\n    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n    /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n    /// @param recipient The address which will receive the token0 and token1 amounts\n    /// @param amount0 The amount of token0 to send\n    /// @param amount1 The amount of token1 to send\n    /// @param data Any data to be passed through to the callback\n    function flash(\n        address recipient,\n        uint256 amount0,\n        uint256 amount1,\n        bytes calldata data\n    ) external;\n\n    /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n    /// the input observationCardinalityNext.\n    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n    /// @notice Set the denominator of the protocol's % share of the fees\n    /// @param feeProtocol0 new protocol fee for token0 of the pool\n    /// @param feeProtocol1 new protocol fee for token1 of the pool\n    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n    /// @notice Collect the protocol fee accrued to the pool\n    /// @param recipient The address to which collected protocol fees should be sent\n    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n    /// @return amount0 The protocol fee collected in token0\n    /// @return amount1 The protocol fee collected in token1\n    function collectProtocol(\n        address recipient,\n        uint128 amount0Requested,\n        uint128 amount1Requested\n    ) external returns (uint128 amount0, uint128 amount1);\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolErrors.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Errors emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolErrors {\n    error LOK();\n    error TLU();\n    error TLM();\n    error TUM();\n    error AI();\n    error M0();\n    error M1();\n    error AS();\n    error IIA();\n    error L();\n    error F0();\n    error F1();\n}\n"
      },
      "lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n    event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n    /// @notice Emitted when liquidity is minted for a given position\n    /// @param sender The address that minted the liquidity\n    /// @param owner The owner of the position and recipient of any minted liquidity\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity minted to the position range\n    /// @param amount0 How much token0 was required for the minted liquidity\n    /// @param amount1 How much token1 was required for the minted liquidity\n    event Mint(\n        address sender,\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted when fees are collected by the owner of a position\n    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n    /// @param owner The owner of the position for which fees are collected\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount0 The amount of token0 fees collected\n    /// @param amount1 The amount of token1 fees collected\n    event Collect(\n        address indexed owner,\n        address recipient,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount0,\n        uint128 amount1\n    );\n\n    /// @notice Emitted when a position's liquidity is removed\n    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n    /// @param owner The owner of the position for which liquidity is removed\n    /// @param tickLower The lower tick of the position\n    /// @param tickUpper The upper tick of the position\n    /// @param amount The amount of liquidity to remove\n    /// @param amount0 The amount of token0 withdrawn\n    /// @param amount1 The amount of token1 withdrawn\n    event Burn(\n        address indexed owner,\n        int24 indexed tickLower,\n        int24 indexed tickUpper,\n        uint128 amount,\n        uint256 amount0,\n        uint256 amount1\n    );\n\n    /// @notice Emitted by the pool for any swaps between token0 and token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the output of the swap\n    /// @param amount0 The delta of the token0 balance of the pool\n    /// @param amount1 The delta of the token1 balance of the pool\n    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n    /// @param liquidity The liquidity of the pool after the swap\n    /// @param tick The log base 1.0001 of price of the pool after the swap\n    event Swap(\n        address indexed sender,\n        address indexed recipient,\n        int256 amount0,\n        int256 amount1,\n        uint160 sqrtPriceX96,\n        uint128 liquidity,\n        int24 tick\n    );\n\n    /// @notice Emitted by the pool for any flashes of token0/token1\n    /// @param sender The address that initiated the swap call, and that received the callback\n    /// @param recipient The address that received the tokens from flash\n    /// @param amount0 The amount of token0 that was flashed\n    /// @param amount1 The amount of token1 that was flashed\n    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n    event Flash(\n        address indexed sender,\n        address indexed recipient,\n        uint256 amount0,\n        uint256 amount1,\n        uint256 paid0,\n        uint256 paid1\n    );\n\n    /// @notice Emitted by the pool for increases to the number of observations that can be stored\n    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n    /// just before a mint/swap/burn.\n    /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n    /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n    event IncreaseObservationCardinalityNext(\n        uint16 observationCardinalityNextOld,\n        uint16 observationCardinalityNextNew\n    );\n\n    /// @notice Emitted when the protocol fee is changed by the pool\n    /// @param feeProtocol0Old The previous value of the token0 protocol fee\n    /// @param feeProtocol1Old The previous value of the token1 protocol fee\n    /// @param feeProtocol0New The updated value of the token0 protocol fee\n    /// @param feeProtocol1New The updated value of the token1 protocol fee\n    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n    /// @param sender The address that collects the protocol fees\n    /// @param recipient The address that receives the collected protocol fees\n    /// @param amount0 The amount of token0 protocol fees that is withdrawn\n    /// @param amount0 The amount of token1 protocol fees that is withdrawn\n    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the caller.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"
      },
      "src/interfaces/IWETH.sol": {
        "content": "pragma solidity ^0.8.18;\n\ninterface IWETH {\n    function deposit() external payable;\n\n    function transfer(address to, uint256 value) external returns (bool);\n\n    function withdraw(uint256) external;\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/openzeppelin-contracts/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/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"
      },
      "lib/tokenized-strategy-periphery/src/Auctions/Auction.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\nimport {Maths} from \"../libraries/Maths.sol\";\nimport {Governance} from \"../utils/Governance.sol\";\nimport {ERC20} from \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {ReentrancyGuard} from \"@openzeppelin/contracts/security/ReentrancyGuard.sol\";\nimport {ITaker} from \"../interfaces/ITaker.sol\";\n\n/// @notice Interface that the optional `hook` contract should implement if the non-standard logic is desired.\ninterface IHook {\n    function kickable(address _fromToken) external view returns (uint256);\n\n    function auctionKicked(address _fromToken) external returns (uint256);\n\n    function preTake(\n        address _fromToken,\n        uint256 _amountToTake,\n        uint256 _amountToPay\n    ) external;\n\n    function postTake(\n        address _toToken,\n        uint256 _amountTaken,\n        uint256 _amountPayed\n    ) external;\n}\n\n/**\n *   @title Auction\n *   @author yearn.fi\n *   @notice General use dutch auction contract for token sales.\n */\ncontract Auction is Governance, ReentrancyGuard {\n    using SafeERC20 for ERC20;\n\n    /// @notice Emitted when a new auction is enabled\n    event AuctionEnabled(\n        bytes32 auctionId,\n        address indexed from,\n        address indexed to,\n        address indexed auctionAddress\n    );\n\n    /// @notice Emitted when an auction is disabled.\n    event AuctionDisabled(\n        bytes32 auctionId,\n        address indexed from,\n        address indexed to,\n        address indexed auctionAddress\n    );\n\n    /// @notice Emitted when auction has been kicked.\n    event AuctionKicked(bytes32 auctionId, uint256 available);\n\n    /// @notice Emitted when any amount of an active auction was taken.\n    event AuctionTaken(\n        bytes32 auctionId,\n        uint256 amountTaken,\n        uint256 amountLeft\n    );\n\n    /// @dev Store address and scaler in one slot.\n    struct TokenInfo {\n        address tokenAddress;\n        uint96 scaler;\n    }\n\n    /// @notice Store all the auction specific information.\n    struct AuctionInfo {\n        TokenInfo fromInfo;\n        uint96 kicked;\n        address receiver;\n        uint128 initialAvailable;\n        uint128 currentAvailable;\n    }\n\n    /// @notice Store the hook address and each flag in one slot.\n    struct Hook {\n        address hook;\n        bool kickable;\n        bool kick;\n        bool preTake;\n        bool postTake;\n    }\n\n    uint256 internal constant WAD = 1e18;\n\n    /// @notice Used for the price decay.\n    uint256 internal constant MINUTE_HALF_LIFE =\n        0.988514020352896135_356867505 * 1e27; // 0.5^(1/60)\n\n    /// @notice Struct to hold the info for `want`.\n    TokenInfo internal wantInfo;\n\n    /// @notice Contract to call during write functions.\n    Hook internal hook_;\n\n    /// @notice The amount to start the auction at.\n    uint256 public startingPrice;\n\n    /// @notice The time that each auction lasts.\n    uint256 public auctionLength;\n\n    /// @notice The minimum time to wait between auction 'kicks'.\n    uint256 public auctionCooldown;\n\n    /// @notice Mapping from an auction ID to its struct.\n    mapping(bytes32 => AuctionInfo) public auctions;\n\n    /// @notice Array of all the enabled auction for this contract.\n    bytes32[] public enabledAuctions;\n\n    constructor() Governance(msg.sender) {}\n\n    /**\n     * @notice Initializes the Auction contract with initial parameters.\n     * @param _want Address this auction is selling to.\n     * @param _hook Address of the hook contract (optional).\n     * @param _governance Address of the contract governance.\n     * @param _auctionLength Duration of each auction in seconds.\n     * @param _auctionCooldown Cooldown period between auctions in seconds.\n     * @param _startingPrice Starting price for each auction.\n     */\n    function initialize(\n        address _want,\n        address _hook,\n        address _governance,\n        uint256 _auctionLength,\n        uint256 _auctionCooldown,\n        uint256 _startingPrice\n    ) external virtual {\n        require(auctionLength == 0, \"initialized\");\n        require(_want != address(0), \"ZERO ADDRESS\");\n        require(_auctionLength != 0, \"length\");\n        require(_auctionLength < _auctionCooldown, \"cooldown\");\n        require(_startingPrice != 0, \"starting price\");\n\n        // Cannot have more than 18 decimals.\n        uint256 decimals = ERC20(_want).decimals();\n        require(decimals <= 18, \"unsupported decimals\");\n\n        // Set variables\n        wantInfo = TokenInfo({\n            tokenAddress: _want,\n            scaler: uint96(WAD / 10 ** decimals)\n        });\n\n        // If we are using a hook.\n        if (_hook != address(0)) {\n            // All flags default to true.\n            hook_ = Hook({\n                hook: _hook,\n                kickable: true,\n                kick: true,\n                preTake: true,\n                postTake: true\n            });\n        }\n\n        governance = _governance;\n        auctionLength = _auctionLength;\n        auctionCooldown = _auctionCooldown;\n        startingPrice = _startingPrice;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                         VIEW METHODS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Get the address of this auctions want token.\n     * @return . The want token.\n     */\n    function want() public view virtual returns (address) {\n        return wantInfo.tokenAddress;\n    }\n\n    /**\n     * @notice Get the address of the hook if any.\n     * @return . The hook.\n     */\n    function hook() external view virtual returns (address) {\n        return hook_.hook;\n    }\n\n    /**\n     * @notice Get the current status of which hooks are being used.\n     * @return . If the kickable hook is used.\n     * @return . If the kick hook is used.\n     * @return . If the preTake hook is used.\n     * @return . If the postTake hook is used.\n     */\n    function getHookFlags()\n        external\n        view\n        virtual\n        returns (bool, bool, bool, bool)\n    {\n        Hook memory _hook = hook_;\n        return (_hook.kickable, _hook.kick, _hook.preTake, _hook.postTake);\n    }\n\n    /**\n     * @notice Get the length of the enabled auctions array.\n     */\n    function numberOfEnabledAuctions() external view virtual returns (uint256) {\n        return enabledAuctions.length;\n    }\n\n    /**\n     * @notice Get the unique auction identifier.\n     * @param _from The address of the token to sell.\n     * @return bytes32 A unique auction identifier.\n     */\n    function getAuctionId(address _from) public view virtual returns (bytes32) {\n        return keccak256(abi.encodePacked(_from, want(), address(this)));\n    }\n\n    /**\n     * @notice Retrieves information about a specific auction.\n     * @param _auctionId The unique identifier of the auction.\n     * @return _from The address of the token to sell.\n     * @return _to The address of the token to buy.\n     * @return _kicked The timestamp of the last kick.\n     * @return _available The current available amount for the auction.\n     */\n    function auctionInfo(\n        bytes32 _auctionId\n    )\n        public\n        view\n        virtual\n        returns (\n            address _from,\n            address _to,\n            uint256 _kicked,\n            uint256 _available\n        )\n    {\n        AuctionInfo memory auction = auctions[_auctionId];\n\n        return (\n            auction.fromInfo.tokenAddress,\n            want(),\n            auction.kicked,\n            auction.kicked + auctionLength > block.timestamp\n                ? auction.currentAvailable\n                : 0\n        );\n    }\n\n    /**\n     * @notice Get the pending amount available for the next auction.\n     * @dev Defaults to the auctions balance of the from token if no hook.\n     * @param _auctionId The unique identifier of the auction.\n     * @return uint256 The amount that can be kicked into the auction.\n     */\n    function kickable(\n        bytes32 _auctionId\n    ) external view virtual returns (uint256) {\n        // If not enough time has passed then `kickable` is 0.\n        if (auctions[_auctionId].kicked + auctionCooldown > block.timestamp) {\n            return 0;\n        }\n\n        // Check if we have a hook to call.\n        Hook memory _hook = hook_;\n        if (_hook.kickable) {\n            // If so default to the hooks logic.\n            return\n                IHook(_hook.hook).kickable(\n                    auctions[_auctionId].fromInfo.tokenAddress\n                );\n        } else {\n            // Else just use the full balance of this contract.\n            return\n                ERC20(auctions[_auctionId].fromInfo.tokenAddress).balanceOf(\n                    address(this)\n                );\n        }\n    }\n\n    /**\n     * @notice Gets the amount of `want` needed to buy a specific amount of `from`.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _amountToTake The amount of `from` to take in the auction.\n     * @return . The amount of `want` needed to fulfill the take amount.\n     */\n    function getAmountNeeded(\n        bytes32 _auctionId,\n        uint256 _amountToTake\n    ) external view virtual returns (uint256) {\n        return\n            _getAmountNeeded(\n                auctions[_auctionId],\n                _amountToTake,\n                block.timestamp\n            );\n    }\n\n    /**\n     * @notice Gets the amount of `want` needed to buy a specific amount of `from` at a specific timestamp.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _amountToTake The amount `from` to take in the auction.\n     * @param _timestamp The specific timestamp for calculating the amount needed.\n     * @return . The amount of `want` needed to fulfill the take amount.\n     */\n    function getAmountNeeded(\n        bytes32 _auctionId,\n        uint256 _amountToTake,\n        uint256 _timestamp\n    ) external view virtual returns (uint256) {\n        return\n            _getAmountNeeded(auctions[_auctionId], _amountToTake, _timestamp);\n    }\n\n    /**\n     * @dev Return the amount of `want` needed to buy `_amountToTake`.\n     */\n    function _getAmountNeeded(\n        AuctionInfo memory _auction,\n        uint256 _amountToTake,\n        uint256 _timestamp\n    ) internal view virtual returns (uint256) {\n        return\n            // Scale _amountToTake to 1e18\n            (_amountToTake *\n                _auction.fromInfo.scaler *\n                // Price is always 1e18\n                _price(\n                    _auction.kicked,\n                    _auction.initialAvailable * _auction.fromInfo.scaler,\n                    _timestamp\n                )) /\n            1e18 /\n            // Scale back down to want.\n            wantInfo.scaler;\n    }\n\n    /**\n     * @notice Gets the price of the auction at the current timestamp.\n     * @param _auctionId The unique identifier of the auction.\n     * @return . The price of the auction.\n     */\n    function price(bytes32 _auctionId) external view virtual returns (uint256) {\n        return price(_auctionId, block.timestamp);\n    }\n\n    /**\n     * @notice Gets the price of the auction at a specific timestamp.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _timestamp The specific timestamp for calculating the price.\n     * @return . The price of the auction.\n     */\n    function price(\n        bytes32 _auctionId,\n        uint256 _timestamp\n    ) public view virtual returns (uint256) {\n        // Get unscaled price and scale it down.\n        return\n            _price(\n                auctions[_auctionId].kicked,\n                auctions[_auctionId].initialAvailable *\n                    auctions[_auctionId].fromInfo.scaler,\n                _timestamp\n            ) / wantInfo.scaler;\n    }\n\n    /**\n     * @dev Internal function to calculate the scaled price based on auction parameters.\n     * @param _kicked The timestamp the auction was kicked.\n     * @param _available The initial available amount scaled 1e18.\n     * @param _timestamp The specific timestamp for calculating the price.\n     * @return . The calculated price scaled to 1e18.\n     */\n    function _price(\n        uint256 _kicked,\n        uint256 _available,\n        uint256 _timestamp\n    ) internal view virtual returns (uint256) {\n        if (_available == 0) return 0;\n\n        uint256 secondsElapsed = _timestamp - _kicked;\n\n        if (secondsElapsed > auctionLength) return 0;\n\n        // Exponential decay from https://github.com/ajna-finance/ajna-core/blob/master/src/libraries/helpers/PoolHelper.sol\n        uint256 hoursComponent = 1e27 >> (secondsElapsed / 3600);\n        uint256 minutesComponent = Maths.rpow(\n            MINUTE_HALF_LIFE,\n            (secondsElapsed % 3600) / 60\n        );\n        uint256 initialPrice = Maths.wdiv(startingPrice * 1e18, _available);\n\n        return\n            (initialPrice * Maths.rmul(hoursComponent, minutesComponent)) /\n            1e27;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            SETTERS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Enables a new auction.\n     * @dev Uses governance as the receiver.\n     * @param _from The address of the token to be auctioned.\n     * @return . The unique identifier of the enabled auction.\n     */\n    function enable(address _from) external virtual returns (bytes32) {\n        return enable(_from, msg.sender);\n    }\n\n    /**\n     * @notice Enables a new auction.\n     * @param _from The address of the token to be auctioned.\n     * @param _receiver The address that will receive the funds in the auction.\n     * @return _auctionId The unique identifier of the enabled auction.\n     */\n    function enable(\n        address _from,\n        address _receiver\n    ) public virtual onlyGovernance returns (bytes32 _auctionId) {\n        address _want = want();\n        require(_from != address(0) && _from != _want, \"ZERO ADDRESS\");\n        require(\n            _receiver != address(0) && _receiver != address(this),\n            \"receiver\"\n        );\n        // Cannot have more than 18 decimals.\n        uint256 decimals = ERC20(_from).decimals();\n        require(decimals <= 18, \"unsupported decimals\");\n\n        // Calculate the id.\n        _auctionId = getAuctionId(_from);\n\n        require(\n            auctions[_auctionId].fromInfo.tokenAddress == address(0),\n            \"already enabled\"\n        );\n\n        // Store all needed info.\n        auctions[_auctionId].fromInfo = TokenInfo({\n            tokenAddress: _from,\n            scaler: uint96(WAD / 10 ** decimals)\n        });\n        auctions[_auctionId].receiver = _receiver;\n\n        // Add to the array.\n        enabledAuctions.push(_auctionId);\n\n        emit AuctionEnabled(_auctionId, _from, _want, address(this));\n    }\n\n    /**\n     * @notice Disables an existing auction.\n     * @dev Only callable by governance.\n     * @param _from The address of the token being sold.\n     */\n    function disable(address _from) external virtual {\n        disable(_from, 0);\n    }\n\n    /**\n     * @notice Disables an existing auction.\n     * @dev Only callable by governance.\n     * @param _from The address of the token being sold.\n     * @param _index The index the auctionId is at in the array.\n     */\n    function disable(\n        address _from,\n        uint256 _index\n    ) public virtual onlyGovernance {\n        bytes32 _auctionId = getAuctionId(_from);\n\n        // Make sure the auction was enabled.\n        require(\n            auctions[_auctionId].fromInfo.tokenAddress != address(0),\n            \"not enabled\"\n        );\n\n        // Remove the struct.\n        delete auctions[_auctionId];\n\n        // Remove the auction ID from the array.\n        bytes32[] memory _enabledAuctions = enabledAuctions;\n        if (_enabledAuctions[_index] != _auctionId) {\n            // If the _index given is not the id find it.\n            for (uint256 i = 0; i < _enabledAuctions.length; ++i) {\n                if (_enabledAuctions[i] == _auctionId) {\n                    _index = i;\n                    break;\n                }\n            }\n        }\n\n        // Move the id to the last spot if not there.\n        if (_index < _enabledAuctions.length - 1) {\n            _enabledAuctions[_index] = _enabledAuctions[\n                _enabledAuctions.length - 1\n            ];\n            // Update the array.\n            enabledAuctions = _enabledAuctions;\n        }\n\n        // Pop the id off the array.\n        enabledAuctions.pop();\n\n        emit AuctionDisabled(_auctionId, _from, want(), address(this));\n    }\n\n    /**\n     * @notice Set the flags to be used with hook.\n     * @param _kickable If the kickable hook should be used.\n     * @param _kick If the kick hook should be used.\n     * @param _preTake If the preTake hook should be used.\n     * @param _postTake If the postTake should be used.\n     */\n    function setHookFlags(\n        bool _kickable,\n        bool _kick,\n        bool _preTake,\n        bool _postTake\n    ) external virtual onlyGovernance {\n        address _hook = hook_.hook;\n        require(_hook != address(0), \"no hook set\");\n\n        hook_ = Hook({\n            hook: _hook,\n            kickable: _kickable,\n            kick: _kick,\n            preTake: _preTake,\n            postTake: _postTake\n        });\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                      PARTICIPATE IN AUCTION\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Kicks off an auction, updating its status and making funds available for bidding.\n     * @param _auctionId The unique identifier of the auction.\n     * @return available The available amount for bidding on in the auction.\n     */\n    function kick(\n        bytes32 _auctionId\n    ) external virtual nonReentrant returns (uint256 available) {\n        address _fromToken = auctions[_auctionId].fromInfo.tokenAddress;\n        require(_fromToken != address(0), \"not enabled\");\n        require(\n            block.timestamp > auctions[_auctionId].kicked + auctionCooldown,\n            \"too soon\"\n        );\n\n        Hook memory _hook = hook_;\n        // Use hook if defined.\n        if (_hook.kick) {\n            available = IHook(_hook.hook).auctionKicked(_fromToken);\n        } else {\n            // Else just use current balance.\n            available = ERC20(_fromToken).balanceOf(address(this));\n        }\n\n        require(available != 0, \"nothing to kick\");\n\n        // Update the auctions status.\n        auctions[_auctionId].kicked = uint96(block.timestamp);\n        auctions[_auctionId].initialAvailable = uint128(available);\n        auctions[_auctionId].currentAvailable = uint128(available);\n\n        emit AuctionKicked(_auctionId, available);\n    }\n\n    /**\n     * @notice Take the token being sold in a live auction.\n     * @dev Defaults to taking the full amount and sending to the msg sender.\n     * @param _auctionId The unique identifier of the auction.\n     * @return . The amount of fromToken taken in the auction.\n     */\n    function take(bytes32 _auctionId) external virtual returns (uint256) {\n        return _take(_auctionId, type(uint256).max, msg.sender, new bytes(0));\n    }\n\n    /**\n     * @notice Take the token being sold in a live auction with a specified maximum amount.\n     * @dev Uses the sender's address as the receiver.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _maxAmount The maximum amount of fromToken to take in the auction.\n     * @return . The amount of fromToken taken in the auction.\n     */\n    function take(\n        bytes32 _auctionId,\n        uint256 _maxAmount\n    ) external virtual returns (uint256) {\n        return _take(_auctionId, _maxAmount, msg.sender, new bytes(0));\n    }\n\n    /**\n     * @notice Take the token being sold in a live auction.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _maxAmount The maximum amount of fromToken to take in the auction.\n     * @param _receiver The address that will receive the fromToken.\n     * @return _amountTaken The amount of fromToken taken in the auction.\n     */\n    function take(\n        bytes32 _auctionId,\n        uint256 _maxAmount,\n        address _receiver\n    ) external virtual returns (uint256) {\n        return _take(_auctionId, _maxAmount, _receiver, new bytes(0));\n    }\n\n    /**\n     * @notice Take the token being sold in a live auction.\n     * @param _auctionId The unique identifier of the auction.\n     * @param _maxAmount The maximum amount of fromToken to take in the auction.\n     * @param _receiver The address that will receive the fromToken.\n     * @param _data The data signify the callback should be used and sent with it.\n     * @return _amountTaken The amount of fromToken taken in the auction.\n     */\n    function take(\n        bytes32 _auctionId,\n        uint256 _maxAmount,\n        address _receiver,\n        bytes calldata _data\n    ) external virtual returns (uint256) {\n        return _take(_auctionId, _maxAmount, _receiver, _data);\n    }\n\n    /// @dev Implements the take of the auction.\n    function _take(\n        bytes32 _auctionId,\n        uint256 _maxAmount,\n        address _receiver,\n        bytes memory _data\n    ) internal virtual nonReentrant returns (uint256 _amountTaken) {\n        AuctionInfo memory auction = auctions[_auctionId];\n        // Make sure the auction is active.\n        require(\n            auction.kicked + auctionLength >= block.timestamp,\n            \"not kicked\"\n        );\n\n        // Max amount that can be taken.\n        _amountTaken = auction.currentAvailable > _maxAmount\n            ? _maxAmount\n            : auction.currentAvailable;\n\n        // Get the amount needed\n        uint256 needed = _getAmountNeeded(\n            auction,\n            _amountTaken,\n            block.timestamp\n        );\n\n        require(needed != 0, \"zero needed\");\n\n        // How much is left in this auction.\n        uint256 left;\n        unchecked {\n            left = auction.currentAvailable - _amountTaken;\n        }\n        auctions[_auctionId].currentAvailable = uint128(left);\n\n        Hook memory _hook = hook_;\n        if (_hook.preTake) {\n            // Use hook if defined.\n            IHook(_hook.hook).preTake(\n                auction.fromInfo.tokenAddress,\n                _amountTaken,\n                needed\n            );\n        }\n\n        // Send `from`.\n        ERC20(auction.fromInfo.tokenAddress).safeTransfer(\n            _receiver,\n            _amountTaken\n        );\n\n        // If the caller has specified data.\n        if (_data.length != 0) {\n            // Do the callback.\n            ITaker(_receiver).auctionTakeCallback(\n                _auctionId,\n                msg.sender,\n                _amountTaken,\n                needed,\n                _data\n            );\n        }\n\n        // Cache the want address.\n        address _want = want();\n\n        // Pull `want`.\n        ERC20(_want).safeTransferFrom(msg.sender, auction.receiver, needed);\n\n        // Post take hook if defined.\n        if (_hook.postTake) {\n            IHook(_hook.hook).postTake(_want, _amountTaken, needed);\n        }\n\n        emit AuctionTaken(_auctionId, _amountTaken, left);\n    }\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/utils/Clonable.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\ncontract Clonable {\n    /// @notice Set to the address to auto clone from.\n    address public original;\n\n    /**\n     * @notice Clone the contracts default `original` contract.\n     * @return Address of the new Minimal Proxy clone.\n     */\n    function _clone() internal virtual returns (address) {\n        return _clone(original);\n    }\n\n    /**\n     * @notice Clone any `_original` contract.\n     * @return _newContract Address of the new Minimal Proxy clone.\n     */\n    function _clone(\n        address _original\n    ) internal virtual returns (address _newContract) {\n        // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol\n        bytes20 addressBytes = bytes20(_original);\n        assembly {\n            // EIP-1167 bytecode\n            let clone_code := mload(0x40)\n            mstore(\n                clone_code,\n                0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000\n            )\n            mstore(add(clone_code, 0x14), addressBytes)\n            mstore(\n                add(clone_code, 0x28),\n                0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000\n            )\n            _newContract := create(0, clone_code, 0x37)\n        }\n    }\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolBorrowerActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Borrower Actions\n */\ninterface IPoolBorrowerActions {\n\n    /**\n     *  @notice Called by fully collateralized borrowers to restamp the `Np to Tp ratio` of the loan (only if loan is fully collateralized and not in auction).\n     *          The reason for stamping the `Np to Tp ratio` on the loan is to provide some certainty to the borrower as to at what price they can expect to be liquidated.\n     *          This action can restamp only the loan of `msg.sender`.\n     */\n    function stampLoan() external;\n\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolLPActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool `LP` Actions\n */\ninterface IPoolLPActions {\n\n    /**\n     *  @notice Called by `LP` owners to approve transfer of an amount of `LP` to a new owner.\n     *  @dev    Intended for use by the `PositionManager` contract.\n     *  @param  spender_ The new owner of the `LP`.\n     *  @param  indexes_ Bucket indexes from where `LP` are transferred.\n     *  @param  amounts_ The amounts of `LP` approved to transfer (`WAD` precision).\n     */\n    function increaseLPAllowance(\n        address spender_,\n        uint256[] calldata indexes_,\n        uint256[] calldata amounts_\n    ) external;\n\n    /**\n     *  @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner.\n     *  @dev    Intended for use by the `PositionManager` contract.\n     *  @param  spender_ The new owner of the `LP`.\n     *  @param  indexes_ Bucket indexes from where `LP` are transferred.\n     *  @param  amounts_ The amounts of `LP` disapproved to transfer (`WAD` precision).\n     */\n    function decreaseLPAllowance(\n        address spender_,\n        uint256[] calldata indexes_,\n        uint256[] calldata amounts_\n    ) external;\n\n    /**\n     *  @notice Called by `LP` owners to decrease the amount of `LP` that can be spend by a new owner.\n     *  @param  spender_ Address that is having it's allowance revoked.\n     *  @param  indexes_ List of bucket index to remove the allowance from.\n     */\n    function revokeLPAllowance(\n        address spender_,\n        uint256[] calldata indexes_\n    ) external;\n\n    /**\n     *  @notice Called by `LP` owners to allow addresses that can transfer LP.\n     *  @dev    Intended for use by the `PositionManager` contract.\n     *  @param  transferors_ Addresses that are allowed to transfer `LP` to new owner.\n     */\n    function approveLPTransferors(\n        address[] calldata transferors_\n    ) external;\n\n    /**\n     *  @notice Called by `LP` owners to revoke addresses that can transfer `LP`.\n     *  @dev    Intended for use by the `PositionManager` contract.\n     *  @param  transferors_ Addresses that are revoked to transfer `LP` to new owner.\n     */\n    function revokeLPTransferors(\n        address[] calldata transferors_\n    ) external;\n\n    /**\n     *  @notice Called by `LP` owners to transfers their `LP` to a different address. `approveLpOwnership` needs to be run first.\n     *  @dev    Used by `PositionManager.memorializePositions()`.\n     *  @param  owner_    The original owner address of the position.\n     *  @param  newOwner_ The new owner address of the position.\n     *  @param  indexes_  Array of price buckets index at which `LP` were moved.\n     */\n    function transferLP(\n        address owner_,\n        address newOwner_,\n        uint256[] calldata indexes_\n    ) external;\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolLenderActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Lender Actions\n */\ninterface IPoolLenderActions {\n\n    /*********************************************/\n    /*** Quote/collateral management functions ***/\n    /*********************************************/\n\n    /**\n     *  @notice Called by lenders to add an amount of credit at a specified price bucket.\n     *  @param  amount_           The amount of quote token to be added by a lender (`WAD` precision).\n     *  @param  index_            The index of the bucket to which the quote tokens will be added.\n     *  @param  expiry_           Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.\n     *  @return bucketLP_         The amount of `LP` changed for the added quote tokens (`WAD` precision).\n     *  @return addedAmount_      The amount of quote token added (`WAD` precision).\n     */\n    function addQuoteToken(\n        uint256 amount_,\n        uint256 index_,\n        uint256 expiry_\n    ) external returns (uint256 bucketLP_, uint256 addedAmount_);\n\n    /**\n     *  @notice Called by lenders to move an amount of credit from a specified price bucket to another specified price bucket.\n     *  @param  maxAmount_        The maximum amount of quote token to be moved by a lender (`WAD` precision).\n     *  @param  fromIndex_        The bucket index from which the quote tokens will be removed.\n     *  @param  toIndex_          The bucket index to which the quote tokens will be added.\n     *  @param  expiry_           Timestamp after which this transaction will revert, preventing inclusion in a block with unfavorable price.\n     *  @return fromBucketLP_     The amount of `LP` moved out from bucket (`WAD` precision).\n     *  @return toBucketLP_       The amount of `LP` moved to destination bucket (`WAD` precision).\n     *  @return movedAmount_      The amount of quote token moved (`WAD` precision).\n     */\n    function moveQuoteToken(\n        uint256 maxAmount_,\n        uint256 fromIndex_,\n        uint256 toIndex_,\n        uint256 expiry_\n    ) external returns (uint256 fromBucketLP_, uint256 toBucketLP_, uint256 movedAmount_);\n\n    /**\n     *  @notice Called by lenders to claim collateral from a price bucket.\n     *  @param  maxAmount_     The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) to claim.\n     *  @param  index_         The bucket index from which collateral will be removed.\n     *  @return removedAmount_ The amount of collateral removed (`WAD` precision).\n     *  @return redeemedLP_    The amount of `LP` used for removing collateral amount (`WAD` precision).\n     */\n    function removeCollateral(\n        uint256 maxAmount_,\n        uint256 index_\n    ) external returns (uint256 removedAmount_, uint256 redeemedLP_);\n\n    /**\n     *  @notice Called by lenders to remove an amount of credit at a specified price bucket.\n     *  @param  maxAmount_     The max amount of quote token to be removed by a lender (`WAD` precision).\n     *  @param  index_         The bucket index from which quote tokens will be removed.\n     *  @return removedAmount_ The amount of quote token removed (`WAD` precision).\n     *  @return redeemedLP_    The amount of `LP` used for removing quote tokens amount (`WAD` precision).\n     */\n    function removeQuoteToken(\n        uint256 maxAmount_,\n        uint256 index_\n    ) external returns (uint256 removedAmount_, uint256 redeemedLP_);\n\n    /********************************/\n    /*** Interest update function ***/\n    /********************************/\n\n    /**\n     *  @notice Called by actors to update pool interest rate (can be updated only once in a `12` hours period of time).\n     */\n    function updateInterest() external;\n\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolKickerActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Kicker Actions\n */\ninterface IPoolKickerActions {\n\n    /********************/\n    /*** Liquidations ***/\n    /********************/\n\n    /**\n     *  @notice Called by actors to initiate a liquidation.\n     *  @param  borrower_     Identifies the loan to liquidate.\n     *  @param  npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction.\n     */\n    function kick(\n        address borrower_,\n        uint256 npLimitIndex_\n    ) external;\n\n    /**\n     *  @notice Called by lenders to liquidate the top loan.\n     *  @param  index_        The deposit index to use for kicking the top loan.\n     *  @param  npLimitIndex_ Index of the lower bound of `NP` tolerated when kicking the auction.\n     */\n    function lenderKick(\n        uint256 index_,\n        uint256 npLimitIndex_\n    ) external;\n\n    /**\n     *  @notice Called by kickers to withdraw their auction bonds (the amount of quote tokens that are not locked in active auctions).\n     *  @param  recipient_ Address to receive claimed bonds amount.\n     *  @param  maxAmount_ The max amount to withdraw from auction bonds (`WAD` precision). Constrained by claimable amounts and liquidity.\n     *  @return withdrawnAmount_ The amount withdrawn (`WAD` precision).\n     */\n    function withdrawBonds(\n        address recipient_,\n        uint256 maxAmount_\n    ) external returns (uint256 withdrawnAmount_);\n\n    /***********************/\n    /*** Reserve Auction ***/\n    /***********************/\n\n    /**\n     *  @notice Called by actor to start a `Claimable Reserve Auction` (`CRA`).\n     */\n    function kickReserveAuction() external;\n}"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolTakerActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Taker Actions\n */\ninterface IPoolTakerActions {\n\n    /**\n     *  @notice Called by actors to use quote token to arb higher-priced deposit off the book.\n     *  @param  borrowerAddress_  Address of the borower take is being called upon.\n     *  @param  depositTake_      If `true` then the take will happen at an auction price equal with bucket price. Auction price is used otherwise.\n     *  @param  index_            Index of a bucket, likely the `HPB`, in which collateral will be deposited.\n     */\n    function bucketTake(\n        address borrowerAddress_,\n        bool    depositTake_,\n        uint256 index_\n    ) external;\n\n    /**\n     *  @notice Called by actors to purchase collateral from the auction in exchange for quote token.\n     *  @param  borrowerAddress_  Address of the borower take is being called upon.\n     *  @param  maxAmount_        Max amount of collateral that will be taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).\n     *  @param  callee_           Identifies where collateral should be sent and where quote token should be obtained.\n     *  @param  data_             If provided, take will assume the callee implements `IERC*Taker`.  Take will send collateral to \n     *                            callee before passing this data to `IERC*Taker.atomicSwapCallback`.  If not provided, \n     *                            the callback function will not be invoked.\n     *  @return collateralTaken_  Amount of collateral taken from the auction (`WAD` precision for `ERC20` pools, max number of `NFT`s for `ERC721` pools).\n     */\n    function take(\n        address        borrowerAddress_,\n        uint256        maxAmount_,\n        address        callee_,\n        bytes calldata data_\n    ) external returns (uint256 collateralTaken_);\n\n    /***********************/\n    /*** Reserve Auction ***/\n    /***********************/\n\n    /**\n     *  @notice Purchases claimable reserves during a `CRA` using `Ajna` token.\n     *  @param  maxAmount_ Maximum amount of quote token to purchase at the current auction price (`WAD` precision).\n     *  @return amount_    Actual amount of reserves taken (`WAD` precision).\n     */\n    function takeReserves(\n        uint256 maxAmount_\n    ) external returns (uint256 amount_);\n\n}"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolSettlerActions.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Settler Actions\n */\ninterface IPoolSettlerActions {\n\n    /**\n     *  @notice Called by actors to settle an amount of debt in a completed liquidation.\n     *  @param  borrowerAddress_   Address of the auctioned borrower.\n     *  @param  maxDepth_          Measured from `HPB`, maximum number of buckets deep to settle debt.\n     *  @return collateralSettled_ Amount of collateral settled.\n     *  @return isBorrowerSettled_ True if all borrower's debt is settled.\n     *  @dev    `maxDepth_` is used to prevent unbounded iteration clearing large liquidations.\n     */\n    function settle(\n        address borrowerAddress_,\n        uint256 maxDepth_\n    ) external returns (uint256 collateralSettled_, bool isBorrowerSettled_);\n\n}"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolImmutables.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Immutables\n */\ninterface IPoolImmutables {\n\n    /**\n     *  @notice Returns the type of the pool (`0` for `ERC20`, `1` for `ERC721`).\n     */\n    function poolType() external pure returns (uint8);\n\n    /**\n     *  @notice Returns the address of the pool's collateral token.\n     */\n    function collateralAddress() external pure returns (address);\n\n    /**\n     *  @notice Returns the address of the pool's quote token.\n     */\n    function quoteTokenAddress() external pure returns (address);\n\n    /**\n     *  @notice Returns the `quoteTokenScale` state variable.\n     *  @notice Token scale is also the minimum amount a lender may have in a bucket (dust amount).\n     *  @return The precision of the quote `ERC20` token based on decimals.\n     */\n    function quoteTokenScale() external pure returns (uint256);\n}"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolDerivedState.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Derived State\n */\ninterface IPoolDerivedState {\n\n    /**\n     *  @notice Returns the exchange rate for a given bucket index.\n     *  @param  index_        The bucket index.\n     *  @return exchangeRate_ Exchange rate of the bucket (`WAD` precision).\n     */\n    function bucketExchangeRate(\n        uint256 index_\n    ) external view returns (uint256 exchangeRate_);\n\n    /**\n     *  @notice Returns the prefix sum of a given bucket.\n     *  @param  index_   The bucket index.\n     *  @return The deposit up to given index (`WAD` precision).\n     */\n    function depositUpToIndex(\n        uint256 index_\n    ) external view returns (uint256);\n\n    /**\n     *  @notice Returns the bucket index for a given debt amount.\n     *  @param  debt_  The debt amount to calculate bucket index for (`WAD` precision).\n     *  @return Bucket index.\n     */\n    function depositIndex(\n        uint256 debt_\n    ) external view returns (uint256);\n\n    /**\n     *  @notice Returns the total amount of quote tokens deposited in pool.\n     *  @return Total amount of deposited quote tokens (`WAD` precision).\n     */\n    function depositSize() external view returns (uint256);\n\n    /**\n     *  @notice Returns the meaningful actual utilization of the pool.\n     *  @return Deposit utilization (`WAD` precision).\n     */\n    function depositUtilization() external view returns (uint256);\n\n    /**\n     *  @notice Returns the scaling value of deposit at given index.\n     *  @param  index_  Deposit index.\n     *  @return Deposit scaling (`WAD` precision).\n     */\n    function depositScale(\n        uint256 index_\n    ) external view returns (uint256);\n\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolEvents.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Events\n */\ninterface IPoolEvents {\n\n    /*********************/\n    /*** Lender events ***/\n    /*********************/\n\n    /**\n     *  @notice Emitted when lender adds quote token to the pool.\n     *  @param  lender    Recipient that added quote tokens.\n     *  @param  index     Index at which quote tokens were added.\n     *  @param  amount    Amount of quote tokens added to the pool (`WAD` precision).\n     *  @param  lpAwarded Amount of `LP` awarded for the deposit (`WAD` precision).\n     *  @param  lup       `LUP` calculated after deposit.\n     */\n    event AddQuoteToken(\n        address indexed lender,\n        uint256 indexed index,\n        uint256 amount,\n        uint256 lpAwarded,\n        uint256 lup\n    );\n\n    /**\n     *  @notice Emitted when lender moves quote token from a bucket price to another.\n     *  @param  lender         Recipient that moved quote tokens.\n     *  @param  from           Price bucket from which quote tokens were moved.\n     *  @param  to             Price bucket where quote tokens were moved.\n     *  @param  amount         Amount of quote tokens moved (`WAD` precision).\n     *  @param  lpRedeemedFrom Amount of `LP` removed from the `from` bucket (`WAD` precision).\n     *  @param  lpAwardedTo    Amount of `LP` credited to the `to` bucket (`WAD` precision).\n     *  @param  lup            `LUP` calculated after removal.\n     */\n    event MoveQuoteToken(\n        address indexed lender,\n        uint256 indexed from,\n        uint256 indexed to,\n        uint256 amount,\n        uint256 lpRedeemedFrom,\n        uint256 lpAwardedTo,\n        uint256 lup\n    );\n\n    /**\n     *  @notice Emitted when lender removes quote token from the pool.\n     *  @param  lender     Recipient that removed quote tokens.\n     *  @param  index      Index at which quote tokens were removed.\n     *  @param  amount     Amount of quote tokens removed from the pool (`WAD` precision).\n     *  @param  lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).\n     *  @param  lup        `LUP` calculated after removal.\n     */\n    event RemoveQuoteToken(\n        address indexed lender,\n        uint256 indexed index,\n        uint256 amount,\n        uint256 lpRedeemed,\n        uint256 lup\n    );\n\n    /**\n     *  @notice Emitted when lender claims collateral from a bucket.\n     *  @param  claimer    Recipient that claimed collateral.\n     *  @param  index      Index at which collateral was claimed.\n     *  @param  amount     The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.\n     *  @param  lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision).\n     */\n    event RemoveCollateral(\n        address indexed claimer,\n        uint256 indexed index,\n        uint256 amount,\n        uint256 lpRedeemed\n    );\n\n    /***********************/\n    /*** Borrower events ***/\n    /***********************/\n\n    /**\n     *  @notice Emitted when borrower repays quote tokens to the pool and/or pulls collateral from the pool.\n     *  @param  borrower         `msg.sender` or on behalf of sender.\n     *  @param  quoteRepaid      Amount of quote tokens repaid to the pool (`WAD` precision).\n     *  @param  collateralPulled The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer.\n     *  @param  lup              `LUP` after repay.\n     */\n    event RepayDebt(\n        address indexed borrower,\n        uint256 quoteRepaid,\n        uint256 collateralPulled,\n        uint256 lup\n    );\n\n    /**********************/\n    /*** Auction events ***/\n    /**********************/\n\n    /**\n     *  @notice Emitted when a liquidation is initiated.\n     *  @param  borrower   Identifies the loan being liquidated.\n     *  @param  debt       Debt the liquidation will attempt to cover (`WAD` precision).\n     *  @param  collateral Amount of collateral up for liquidation (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools).\n     *  @param  bond       Bond amount locked by kicker (`WAD` precision).\n     */\n    event Kick(\n        address indexed borrower,\n        uint256 debt,\n        uint256 collateral,\n        uint256 bond\n    );\n\n    /**\n     *  @notice Emitted when kickers are withdrawing funds posted as auction bonds.\n     *  @param  kicker   The kicker withdrawing bonds.\n     *  @param  reciever The address receiving withdrawn bond amount.\n     *  @param  amount   The bond amount that was withdrawn (`WAD` precision).\n     */\n    event BondWithdrawn(\n        address indexed kicker,\n        address indexed reciever,\n        uint256 amount\n    );\n\n    /**\n     *  @notice Emitted when an actor uses quote token to arb higher-priced deposit off the book.\n     *  @param  borrower    Identifies the loan being liquidated.\n     *  @param  index       The index of the `Highest Price Bucket` used for this take.\n     *  @param  amount      Amount of quote token used to purchase collateral (`WAD` precision).\n     *  @param  collateral  Amount of collateral purchased with quote token (`WAD` precision).\n     *  @param  bondChange  Impact of this take to the liquidation bond (`WAD` precision).\n     *  @param  isReward    `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.\n     *  @dev    amount / collateral implies the auction price.\n     */\n    event BucketTake(\n        address indexed borrower,\n        uint256 index,\n        uint256 amount,\n        uint256 collateral,\n        uint256 bondChange,\n        bool    isReward\n    );\n\n    /**\n     *  @notice Emitted when `LP` are awarded to a taker or kicker in a bucket take.\n     *  @param  taker           Actor who invoked the bucket take.\n     *  @param  kicker          Actor who started the auction.\n     *  @param  lpAwardedTaker  Amount of `LP` awarded to the taker (`WAD` precision).\n     *  @param  lpAwardedKicker Amount of `LP` awarded to the actor who started the auction (`WAD` precision).\n     */\n    event BucketTakeLPAwarded(\n        address indexed taker,\n        address indexed kicker,\n        uint256 lpAwardedTaker,\n        uint256 lpAwardedKicker\n    );\n\n    /**\n     *  @notice Emitted when an actor uses quote token outside of the book to purchase collateral under liquidation.\n     *  @param  borrower   Identifies the loan being liquidated.\n     *  @param  amount     Amount of quote token used to purchase collateral (`WAD` precision).\n     *  @param  collateral Amount of collateral purchased with quote token (for `ERC20` pool, `WAD` precision) or number of `NFT`s purchased (for `ERC721` pool).\n     *  @param  bondChange Impact of this take to the liquidation bond (`WAD` precision).\n     *  @param  isReward   `True` if kicker was rewarded with `bondChange` amount, `false` if kicker was penalized.\n     *  @dev    amount / collateral implies the auction price.\n     */\n    event Take(\n        address indexed borrower,\n        uint256 amount,\n        uint256 collateral,\n        uint256 bondChange,\n        bool    isReward\n    );\n\n    /**\n     *  @notice Emitted when an actor settles debt in a completed liquidation\n     *  @param  borrower    Identifies the loan under liquidation.\n     *  @param  settledDebt Amount of pool debt settled in this transaction (`WAD` precision).\n     *  @dev    When `amountRemaining_ == 0`, the auction has been completed cleared and removed from the queue.\n     */\n    event Settle(\n        address indexed borrower,\n        uint256 settledDebt\n    );\n\n    /**\n     *  @notice Emitted when auction is completed.\n     *  @param  borrower   Address of borrower that exits auction.\n     *  @param  collateral Borrower's remaining collateral when auction completed (`WAD` precision).\n     */\n    event AuctionSettle(\n        address indexed borrower,\n        uint256 collateral\n    );\n\n    /**\n     *  @notice Emitted when `NFT` auction is completed.\n     *  @param  borrower   Address of borrower that exits auction.\n     *  @param  collateral Borrower's remaining collateral when auction completed.\n     *  @param  lp         Amount of `LP` given to the borrower to compensate fractional collateral (if any, `WAD` precision).\n     *  @param  index      Index of the bucket with `LP` to compensate fractional collateral.\n     */\n    event AuctionNFTSettle(\n        address indexed borrower,\n        uint256 collateral,\n        uint256 lp,\n        uint256 index\n    );\n\n    /**\n     *  @notice Emitted when a `Claimaible Reserve Auction` is started.\n     *  @param  claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).\n     *  @param  auctionPrice               Current price at which `1` quote token may be purchased, denominated in `Ajna`.\n     *  @param  currentBurnEpoch           Current burn epoch.\n     */\n    event KickReserveAuction(\n        uint256 claimableReservesRemaining,\n        uint256 auctionPrice,\n        uint256 currentBurnEpoch\n    );\n\n    /**\n     *  @notice Emitted when a `Claimaible Reserve Auction` is taken.\n     *  @param  claimableReservesRemaining Amount of claimable reserves which has not yet been taken (`WAD` precision).\n     *  @param  auctionPrice               Current price at which `1` quote token may be purchased, denominated in `Ajna`.\n     *  @param  currentBurnEpoch           Current burn epoch.\n     */\n    event ReserveAuction(\n        uint256 claimableReservesRemaining,\n        uint256 auctionPrice,\n        uint256 currentBurnEpoch\n    );\n\n    /**************************/\n    /*** LP transfer events ***/\n    /**************************/\n\n    /**\n     *  @notice Emitted when owner increase the `LP` allowance of a spender at specified indexes with specified amounts.\n     *  @param  owner     `LP` owner.\n     *  @param  spender   Address approved to transfer `LP`.\n     *  @param  indexes   Bucket indexes of `LP` approved.\n     *  @param  amounts   `LP` amounts added (ordered by indexes, `WAD` precision).\n     */\n    event IncreaseLPAllowance(\n        address indexed owner,\n        address indexed spender,\n        uint256[] indexes,\n        uint256[] amounts\n    );\n\n    /**\n     *  @notice Emitted when owner decrease the `LP` allowance of a spender at specified indexes with specified amounts.\n     *  @param  owner     `LP` owner.\n     *  @param  spender   Address approved to transfer `LP`.\n     *  @param  indexes   Bucket indexes of `LP` approved.\n     *  @param  amounts   `LP` amounts removed (ordered by indexes, `WAD` precision).\n     */\n    event DecreaseLPAllowance(\n        address indexed owner,\n        address indexed spender,\n        uint256[] indexes,\n        uint256[] amounts\n    );\n\n    /**\n     *  @notice Emitted when lender removes the allowance of a spender for their `LP`.\n     *  @param  owner   `LP` owner.\n     *  @param  spender Address that is having it's allowance revoked.\n     *  @param  indexes List of bucket index to remove the allowance from.\n     */\n    event RevokeLPAllowance(\n        address indexed owner,\n        address indexed spender,\n        uint256[] indexes\n    );\n\n    /**\n     *  @notice Emitted when lender whitelists addresses to accept `LP` from.\n     *  @param  lender      Recipient that approves new owner for `LP`.\n     *  @param  transferors List of addresses that can transfer `LP` to lender.\n     */\n    event ApproveLPTransferors(\n        address indexed lender,\n        address[] transferors\n    );\n\n    /**\n     *  @notice Emitted when lender removes addresses from the `LP` transferors whitelist.\n     *  @param  lender      Recipient that approves new owner for `LP`.\n     *  @param  transferors List of addresses that won't be able to transfer `LP` to lender anymore.\n     */\n    event RevokeLPTransferors(\n        address indexed lender,\n        address[] transferors\n    );\n\n    /**\n     *  @notice Emitted when a lender transfers their `LP` to a different address.\n     *  @dev    Used by `PositionManager.memorializePositions()`.\n     *  @param  owner    The original owner address of the position.\n     *  @param  newOwner The new owner address of the position.\n     *  @param  indexes  Array of price bucket indexes at which `LP` were transferred.\n     *  @param  lp       Amount of `LP` transferred (`WAD` precision).\n     */\n    event TransferLP(\n        address owner,\n        address newOwner,\n        uint256[] indexes,\n        uint256 lp\n    );\n\n    /**************************/\n    /*** Pool common events ***/\n    /**************************/\n\n    /**\n     *  @notice Emitted when `LP` are forfeited as a result of the bucket losing all assets.\n     *  @param  index       The index of the bucket.\n     *  @param  lpForfeited Amount of `LP` forfeited by lenders (`WAD` precision).\n     */\n    event BucketBankruptcy(\n        uint256 indexed index,\n        uint256 lpForfeited\n    );\n\n    /**\n     *  @notice Emitted when a flashloan is taken from pool.\n     *  @param  receiver The address receiving the flashloan.\n     *  @param  token    The address of token flashloaned from pool.\n     *  @param  amount   The amount of tokens flashloaned from pool (token precision).\n     */\n    event Flashloan(\n        address indexed receiver,\n        address indexed token,\n        uint256 amount\n    );\n\n    /**\n     *  @notice Emitted when a loan `Np to Tp ratio` is restamped.\n     *  @param  borrower Identifies the loan to update the `Np to Tp ratio`.\n     */\n    event LoanStamped(\n        address indexed borrower\n    );\n\n    /**\n     *  @notice Emitted when pool interest rate is reset. This happens when `interest rate > 10%` and `debtEma < 5%` of `depositEma`\n     *  @param  oldRate Old pool interest rate.\n     *  @param  newRate New pool interest rate.\n     */\n    event ResetInterestRate(\n        uint256 oldRate,\n        uint256 newRate\n    );\n\n    /**\n     *  @notice Emitted when pool interest rate is updated.\n     *  @param  oldRate Old pool interest rate.\n     *  @param  newRate New pool interest rate.\n     */\n    event UpdateInterestRate(\n        uint256 oldRate,\n        uint256 newRate\n    );\n\n    /**\n     *  @notice Emitted when interest accural or update interest overflows.\n     */\n    event InterestUpdateFailure();\n\n}"
      },
      "lib/ajna-core/src/interfaces/pool/commons/IPoolErrors.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\n\n/**\n * @title Pool Errors.\n */\ninterface IPoolErrors {\n    /**************************/\n    /*** Common Pool Errors ***/\n    /**************************/\n\n    /**\n     *  @notice Adding liquidity above current auction price.\n     */\n    error AddAboveAuctionPrice();\n\n    /**\n     *  @notice The action cannot be executed on an active auction.\n     */\n    error AuctionActive();\n\n    /**\n     *  @notice Attempted auction to clear doesn't meet conditions.\n     */\n    error AuctionNotClearable();\n\n    /**\n     *  @notice Auction does not meet requirements to take liquidity.\n     */\n    error AuctionNotTakeable();\n\n    /**\n     *  @notice Head auction should be cleared prior of executing this action.\n     */\n    error AuctionNotCleared();\n\n    /**\n     *  @notice The auction price is greater than the arbed bucket price.\n     */\n    error AuctionPriceGtBucketPrice();\n\n    /**\n     *  @notice Pool already initialized.\n     */\n    error AlreadyInitialized();\n\n    /**\n     *  @notice Borrower is attempting to create or modify a loan such that their loan's quote token would be less than the pool's minimum debt amount.\n     */\n    error AmountLTMinDebt();\n\n    /**\n     *  @notice Recipient of borrowed quote tokens doesn't match the caller of the `drawDebt` function.\n     */\n    error BorrowerNotSender();\n\n    /**\n     *  @notice Borrower has a healthy over-collateralized position.\n     */\n    error BorrowerOk();\n\n    /**\n     *  @notice Borrower is attempting to borrow more quote token than they have collateral for.\n     */\n    error BorrowerUnderCollateralized();\n\n    /**\n     *  @notice Operation cannot be executed in the same block when bucket becomes insolvent.\n     */\n    error BucketBankruptcyBlock();\n\n    /**\n     *  @notice User attempted to merge collateral from a lower price bucket into a higher price bucket.\n     */\n    error CannotMergeToHigherPrice();\n\n    /**\n     *  @notice User attempted an operation which does not exceed the dust amount, or leaves behind less than the dust amount.\n     */\n    error DustAmountNotExceeded();\n\n    /**\n     *  @notice Callback invoked by `flashLoan` function did not return the expected hash (see `ERC-3156` spec).\n     */\n    error FlashloanCallbackFailed();\n\n    /**\n     *  @notice Balance of pool contract before flashloan is different than the balance after flashloan.\n     */\n    error FlashloanIncorrectBalance();\n\n    /**\n     *  @notice Pool cannot facilitate a flashloan for the specified token address.\n     */\n    error FlashloanUnavailableForToken();\n\n    /**\n     *  @notice User is attempting to move or pull more collateral than is available.\n     */\n    error InsufficientCollateral();\n\n    /**\n     *  @notice Lender is attempting to move or remove more collateral they have claim to in the bucket.\n     *  @notice Lender is attempting to remove more collateral they have claim to in the bucket.\n     *  @notice Lender must have enough `LP` to claim the desired amount of quote from the bucket.\n     */\n    error InsufficientLP();\n\n    /**\n     *  @notice Bucket must have more quote available in the bucket than the lender is attempting to claim.\n     */\n    error InsufficientLiquidity();\n\n    /**\n     *  @notice When increasing / decreasing `LP` allowances indexes and amounts arrays parameters should have same length.\n     */\n    error InvalidAllowancesInput();\n\n    /**\n     *  @notice When transferring `LP` between indices, the new index must be a valid index.\n     */\n    error InvalidIndex();\n\n    /**\n     *  @notice The amount used for performed action should be greater than `0`.\n     */\n    error InvalidAmount();\n\n    /**\n     *  @notice Borrower is attempting to borrow more quote token than is available before the supplied `limitIndex`.\n     */\n    error LimitIndexExceeded();\n\n    /**\n     *  @notice When moving quote token `HTP` must stay below `LUP`.\n     *  @notice When removing quote token `HTP` must stay below `LUP`.\n     */\n    error LUPBelowHTP();\n\n    /**\n     *  @notice From index and to index arguments to move are the same.\n     */\n    error MoveToSameIndex();\n\n    /**\n     *  @notice Owner of the `LP` must have approved the new owner prior to transfer.\n     */\n    error NoAllowance();\n\n    /**\n     *  @notice Actor is attempting to take or clear an inactive auction.\n     */\n    error NoAuction();\n\n    /**\n     *  @notice No pool reserves are claimable.\n     */\n    error NoReserves();\n\n    /**\n     *  @notice Actor is attempting to take or clear an inactive reserves auction.\n     */\n    error NoReservesAuction();\n\n    /**\n     *  @notice Lender must have non-zero `LP` when attemptign to remove quote token from the pool.\n     */\n    error NoClaim();\n\n    /**\n     *  @notice Borrower has no debt to liquidate.\n     *  @notice Borrower is attempting to repay when they have no outstanding debt.\n     */\n    error NoDebt();\n\n    /**\n     *  @notice Actor is attempting to kick with bucket price below the `LUP`.\n     */\n    error PriceBelowLUP();\n\n    /**\n     *  @notice Lender is attempting to remove quote tokens from a bucket that exists above active auction debt from top-of-book downward.\n     */\n    error RemoveDepositLockedByAuctionDebt();\n\n    /**\n     * @notice User attempted to kick off a new auction less than `2` weeks since the last auction completed.\n     */\n    error ReserveAuctionTooSoon();\n\n    /**\n     *  @notice Current block timestamp has reached or exceeded a user-provided expiration.\n     */\n    error TransactionExpired();\n\n    /**\n     *  @notice The address that transfer `LP` is not approved by the `LP` receiving address.\n     */\n    error TransferorNotApproved();\n\n    /**\n     *  @notice Owner of the `LP` attemps to transfer `LP` to same address.\n     */\n    error TransferToSameOwner();\n\n    /**\n     *  @notice The DebtToCollateral of the loan to be inserted in loans heap is zero.\n     */\n    error ZeroDebtToCollateral();\n\n}\n"
      },
      "lib/ajna-core/src/interfaces/pool/IERC3156FlashLender.sol": {
        "content": "// SPDX-License-Identifier: MIT\n\npragma solidity 0.8.18;\nimport { IERC3156FlashBorrower } from \"./IERC3156FlashBorrower.sol\";\n\n\ninterface IERC3156FlashLender {\n\n    /**\n     * @dev    The amount of currency available to be lent.\n     * @param  token_ The loan currency.\n     * @return The amount of `token` that can be borrowed (token precision).\n     */\n    function maxFlashLoan(\n        address token_\n    ) external view returns (uint256);\n\n    /**\n     * @dev    The fee to be charged for a given loan.\n     * @param  token_    The loan currency.\n     * @param  amount_   The amount of tokens lent (token precision).\n     * @return The amount of `token` to be charged for the loan (token precision), on top of the returned principal .\n     */\n    function flashFee(\n        address token_,\n        uint256 amount_\n    ) external view returns (uint256);\n\n    /**\n     * @dev    Initiate a flash loan.\n     * @param  receiver_ The receiver of the tokens in the loan, and the receiver of the callback.\n     * @param  token_    The loan currency.\n     * @param  amount_   The amount of tokens lent (token precision).\n     * @param  data_     Arbitrary data structure, intended to contain user-defined parameters.\n     * @return `True` when successful flashloan, `false` otherwise.\n     */\n    function flashLoan(\n        IERC3156FlashBorrower receiver_,\n        address token_,\n        uint256 amount_,\n        bytes   calldata data_\n    ) external returns (bool);\n}"
      },
      "lib/ajna-core/lib/prb-math/contracts/PRBMath.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity >=0.8.4;\n\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivFixedPointOverflow(uint256 prod1);\n\n/// @notice Emitted when the result overflows uint256.\nerror PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);\n\n/// @notice Emitted when one of the inputs is type(int256).min.\nerror PRBMath__MulDivSignedInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows int256.\nerror PRBMath__MulDivSignedOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is MIN_SD59x18.\nerror PRBMathSD59x18__AbsInputTooSmall();\n\n/// @notice Emitted when ceiling a number overflows SD59x18.\nerror PRBMathSD59x18__CeilOverflow(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__DivInputTooSmall();\n\n/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.\nerror PRBMathSD59x18__DivOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathSD59x18__ExpInputTooBig(int256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathSD59x18__Exp2InputTooBig(int256 x);\n\n/// @notice Emitted when flooring a number underflows SD59x18.\nerror PRBMathSD59x18__FloorUnderflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.\nerror PRBMathSD59x18__FromIntOverflow(int256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.\nerror PRBMathSD59x18__FromIntUnderflow(int256 x);\n\n/// @notice Emitted when the product of the inputs is negative.\nerror PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);\n\n/// @notice Emitted when multiplying the inputs overflows SD59x18.\nerror PRBMathSD59x18__GmOverflow(int256 x, int256 y);\n\n/// @notice Emitted when the input is less than or equal to zero.\nerror PRBMathSD59x18__LogInputTooSmall(int256 x);\n\n/// @notice Emitted when one of the inputs is MIN_SD59x18.\nerror PRBMathSD59x18__MulInputTooSmall();\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__MulOverflow(uint256 rAbs);\n\n/// @notice Emitted when the intermediary absolute result overflows SD59x18.\nerror PRBMathSD59x18__PowuOverflow(uint256 rAbs);\n\n/// @notice Emitted when the input is negative.\nerror PRBMathSD59x18__SqrtNegativeInput(int256 x);\n\n/// @notice Emitted when the calculating the square root overflows SD59x18.\nerror PRBMathSD59x18__SqrtOverflow(int256 x);\n\n/// @notice Emitted when addition overflows UD60x18.\nerror PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when ceiling a number overflows UD60x18.\nerror PRBMathUD60x18__CeilOverflow(uint256 x);\n\n/// @notice Emitted when the input is greater than 133.084258667509499441.\nerror PRBMathUD60x18__ExpInputTooBig(uint256 x);\n\n/// @notice Emitted when the input is greater than 192.\nerror PRBMathUD60x18__Exp2InputTooBig(uint256 x);\n\n/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.\nerror PRBMathUD60x18__FromUintOverflow(uint256 x);\n\n/// @notice Emitted when multiplying the inputs overflows UD60x18.\nerror PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);\n\n/// @notice Emitted when the input is less than 1.\nerror PRBMathUD60x18__LogInputTooSmall(uint256 x);\n\n/// @notice Emitted when the calculating the square root overflows UD60x18.\nerror PRBMathUD60x18__SqrtOverflow(uint256 x);\n\n/// @notice Emitted when subtraction underflows UD60x18.\nerror PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);\n\n/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library\n/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point\n/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.\nlibrary PRBMath {\n    /// STRUCTS ///\n\n    struct SD59x18 {\n        int256 value;\n    }\n\n    struct UD60x18 {\n        uint256 value;\n    }\n\n    /// STORAGE ///\n\n    /// @dev How many trailing decimals can be represented.\n    uint256 internal constant SCALE = 1e18;\n\n    /// @dev Largest power of two divisor of SCALE.\n    uint256 internal constant SCALE_LPOTD = 262144;\n\n    /// @dev SCALE inverted mod 2^256.\n    uint256 internal constant SCALE_INVERSE =\n        78156646155174841979727994598816262306175212592076161876661_508869554232690281;\n\n    /// FUNCTIONS ///\n\n    /// @notice Calculates the binary exponent of x using the binary fraction method.\n    /// @dev Has to use 192.64-bit fixed-point numbers.\n    /// See https://ethereum.stackexchange.com/a/96594/24693.\n    /// @param x The exponent as an unsigned 192.64-bit fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function exp2(uint256 x) internal pure returns (uint256 result) {\n        unchecked {\n            // Start from 0.5 in the 192.64-bit fixed-point format.\n            result = 0x800000000000000000000000000000000000000000000000;\n\n            // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows\n            // because the initial result is 2^191 and all magic factors are less than 2^65.\n            if (x & 0x8000000000000000 > 0) {\n                result = (result * 0x16A09E667F3BCC909) >> 64;\n            }\n            if (x & 0x4000000000000000 > 0) {\n                result = (result * 0x1306FE0A31B7152DF) >> 64;\n            }\n            if (x & 0x2000000000000000 > 0) {\n                result = (result * 0x1172B83C7D517ADCE) >> 64;\n            }\n            if (x & 0x1000000000000000 > 0) {\n                result = (result * 0x10B5586CF9890F62A) >> 64;\n            }\n            if (x & 0x800000000000000 > 0) {\n                result = (result * 0x1059B0D31585743AE) >> 64;\n            }\n            if (x & 0x400000000000000 > 0) {\n                result = (result * 0x102C9A3E778060EE7) >> 64;\n            }\n            if (x & 0x200000000000000 > 0) {\n                result = (result * 0x10163DA9FB33356D8) >> 64;\n            }\n            if (x & 0x100000000000000 > 0) {\n                result = (result * 0x100B1AFA5ABCBED61) >> 64;\n            }\n            if (x & 0x80000000000000 > 0) {\n                result = (result * 0x10058C86DA1C09EA2) >> 64;\n            }\n            if (x & 0x40000000000000 > 0) {\n                result = (result * 0x1002C605E2E8CEC50) >> 64;\n            }\n            if (x & 0x20000000000000 > 0) {\n                result = (result * 0x100162F3904051FA1) >> 64;\n            }\n            if (x & 0x10000000000000 > 0) {\n                result = (result * 0x1000B175EFFDC76BA) >> 64;\n            }\n            if (x & 0x8000000000000 > 0) {\n                result = (result * 0x100058BA01FB9F96D) >> 64;\n            }\n            if (x & 0x4000000000000 > 0) {\n                result = (result * 0x10002C5CC37DA9492) >> 64;\n            }\n            if (x & 0x2000000000000 > 0) {\n                result = (result * 0x1000162E525EE0547) >> 64;\n            }\n            if (x & 0x1000000000000 > 0) {\n                result = (result * 0x10000B17255775C04) >> 64;\n            }\n            if (x & 0x800000000000 > 0) {\n                result = (result * 0x1000058B91B5BC9AE) >> 64;\n            }\n            if (x & 0x400000000000 > 0) {\n                result = (result * 0x100002C5C89D5EC6D) >> 64;\n            }\n            if (x & 0x200000000000 > 0) {\n                result = (result * 0x10000162E43F4F831) >> 64;\n            }\n            if (x & 0x100000000000 > 0) {\n                result = (result * 0x100000B1721BCFC9A) >> 64;\n            }\n            if (x & 0x80000000000 > 0) {\n                result = (result * 0x10000058B90CF1E6E) >> 64;\n            }\n            if (x & 0x40000000000 > 0) {\n                result = (result * 0x1000002C5C863B73F) >> 64;\n            }\n            if (x & 0x20000000000 > 0) {\n                result = (result * 0x100000162E430E5A2) >> 64;\n            }\n            if (x & 0x10000000000 > 0) {\n                result = (result * 0x1000000B172183551) >> 64;\n            }\n            if (x & 0x8000000000 > 0) {\n                result = (result * 0x100000058B90C0B49) >> 64;\n            }\n            if (x & 0x4000000000 > 0) {\n                result = (result * 0x10000002C5C8601CC) >> 64;\n            }\n            if (x & 0x2000000000 > 0) {\n                result = (result * 0x1000000162E42FFF0) >> 64;\n            }\n            if (x & 0x1000000000 > 0) {\n                result = (result * 0x10000000B17217FBB) >> 64;\n            }\n            if (x & 0x800000000 > 0) {\n                result = (result * 0x1000000058B90BFCE) >> 64;\n            }\n            if (x & 0x400000000 > 0) {\n                result = (result * 0x100000002C5C85FE3) >> 64;\n            }\n            if (x & 0x200000000 > 0) {\n                result = (result * 0x10000000162E42FF1) >> 64;\n            }\n            if (x & 0x100000000 > 0) {\n                result = (result * 0x100000000B17217F8) >> 64;\n            }\n            if (x & 0x80000000 > 0) {\n                result = (result * 0x10000000058B90BFC) >> 64;\n            }\n            if (x & 0x40000000 > 0) {\n                result = (result * 0x1000000002C5C85FE) >> 64;\n            }\n            if (x & 0x20000000 > 0) {\n                result = (result * 0x100000000162E42FF) >> 64;\n            }\n            if (x & 0x10000000 > 0) {\n                result = (result * 0x1000000000B17217F) >> 64;\n            }\n            if (x & 0x8000000 > 0) {\n                result = (result * 0x100000000058B90C0) >> 64;\n            }\n            if (x & 0x4000000 > 0) {\n                result = (result * 0x10000000002C5C860) >> 64;\n            }\n            if (x & 0x2000000 > 0) {\n                result = (result * 0x1000000000162E430) >> 64;\n            }\n            if (x & 0x1000000 > 0) {\n                result = (result * 0x10000000000B17218) >> 64;\n            }\n            if (x & 0x800000 > 0) {\n                result = (result * 0x1000000000058B90C) >> 64;\n            }\n            if (x & 0x400000 > 0) {\n                result = (result * 0x100000000002C5C86) >> 64;\n            }\n            if (x & 0x200000 > 0) {\n                result = (result * 0x10000000000162E43) >> 64;\n            }\n            if (x & 0x100000 > 0) {\n                result = (result * 0x100000000000B1721) >> 64;\n            }\n            if (x & 0x80000 > 0) {\n                result = (result * 0x10000000000058B91) >> 64;\n            }\n            if (x & 0x40000 > 0) {\n                result = (result * 0x1000000000002C5C8) >> 64;\n            }\n            if (x & 0x20000 > 0) {\n                result = (result * 0x100000000000162E4) >> 64;\n            }\n            if (x & 0x10000 > 0) {\n                result = (result * 0x1000000000000B172) >> 64;\n            }\n            if (x & 0x8000 > 0) {\n                result = (result * 0x100000000000058B9) >> 64;\n            }\n            if (x & 0x4000 > 0) {\n                result = (result * 0x10000000000002C5D) >> 64;\n            }\n            if (x & 0x2000 > 0) {\n                result = (result * 0x1000000000000162E) >> 64;\n            }\n            if (x & 0x1000 > 0) {\n                result = (result * 0x10000000000000B17) >> 64;\n            }\n            if (x & 0x800 > 0) {\n                result = (result * 0x1000000000000058C) >> 64;\n            }\n            if (x & 0x400 > 0) {\n                result = (result * 0x100000000000002C6) >> 64;\n            }\n            if (x & 0x200 > 0) {\n                result = (result * 0x10000000000000163) >> 64;\n            }\n            if (x & 0x100 > 0) {\n                result = (result * 0x100000000000000B1) >> 64;\n            }\n            if (x & 0x80 > 0) {\n                result = (result * 0x10000000000000059) >> 64;\n            }\n            if (x & 0x40 > 0) {\n                result = (result * 0x1000000000000002C) >> 64;\n            }\n            if (x & 0x20 > 0) {\n                result = (result * 0x10000000000000016) >> 64;\n            }\n            if (x & 0x10 > 0) {\n                result = (result * 0x1000000000000000B) >> 64;\n            }\n            if (x & 0x8 > 0) {\n                result = (result * 0x10000000000000006) >> 64;\n            }\n            if (x & 0x4 > 0) {\n                result = (result * 0x10000000000000003) >> 64;\n            }\n            if (x & 0x2 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n            if (x & 0x1 > 0) {\n                result = (result * 0x10000000000000001) >> 64;\n            }\n\n            // We're doing two things at the same time:\n            //\n            //   1. Multiply the result by 2^n + 1, where \"2^n\" is the integer part and the one is added to account for\n            //      the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191\n            //      rather than 192.\n            //   2. Convert the result to the unsigned 60.18-decimal fixed-point format.\n            //\n            // This works because 2^(191-ip) = 2^ip / 2^191, where \"ip\" is the integer part \"2^n\".\n            result *= SCALE;\n            result >>= (191 - (x >> 64));\n        }\n    }\n\n    /// @notice Finds the zero-based index of the first one in the binary representation of x.\n    /// @dev See the note on msb in the \"Find First Set\" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set\n    /// @param x The uint256 number for which to find the index of the most significant bit.\n    /// @return msb The index of the most significant bit as an uint256.\n    function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {\n        if (x >= 2**128) {\n            x >>= 128;\n            msb += 128;\n        }\n        if (x >= 2**64) {\n            x >>= 64;\n            msb += 64;\n        }\n        if (x >= 2**32) {\n            x >>= 32;\n            msb += 32;\n        }\n        if (x >= 2**16) {\n            x >>= 16;\n            msb += 16;\n        }\n        if (x >= 2**8) {\n            x >>= 8;\n            msb += 8;\n        }\n        if (x >= 2**4) {\n            x >>= 4;\n            msb += 4;\n        }\n        if (x >= 2**2) {\n            x >>= 2;\n            msb += 2;\n        }\n        if (x >= 2**1) {\n            // No need to shift x any more.\n            msb += 1;\n        }\n    }\n\n    /// @notice Calculates floor(x*y÷denominator) with full precision.\n    ///\n    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.\n    ///\n    /// Requirements:\n    /// - The denominator cannot be zero.\n    /// - The result must fit within uint256.\n    ///\n    /// Caveats:\n    /// - This function does not work with fixed-point numbers.\n    ///\n    /// @param x The multiplicand as an uint256.\n    /// @param y The multiplier as an uint256.\n    /// @param denominator The divisor as an uint256.\n    /// @return result The result as an uint256.\n    function mulDiv(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 result) {\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            unchecked {\n                result = prod0 / denominator;\n            }\n            return result;\n        }\n\n        // Make sure the result is less than 2^256. Also prevents denominator == 0.\n        if (prod1 >= denominator) {\n            revert PRBMath__MulDivOverflow(prod1, denominator);\n        }\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        unchecked {\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 lpotdod = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by lpotdod.\n                denominator := div(denominator, lpotdod)\n\n                // Divide [prod1 prod0] by lpotdod.\n                prod0 := div(prod0, lpotdod)\n\n                // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.\n                lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * lpotdod;\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    /// @notice Calculates floor(x*y÷1e18) with full precision.\n    ///\n    /// @dev Variant of \"mulDiv\" with constant folding, i.e. in which the denominator is always 1e18. Before returning the\n    /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of\n    /// being rounded to 1e-18.  See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717.\n    ///\n    /// Requirements:\n    /// - The result must fit within uint256.\n    ///\n    /// Caveats:\n    /// - The body is purposely left uncommented; see the NatSpec comments in \"PRBMath.mulDiv\" to understand how this works.\n    /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:\n    ///     1. x * y = type(uint256).max * SCALE\n    ///     2. (x * y) % SCALE >= SCALE / 2\n    ///\n    /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.\n    /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.\n    /// @return result The result as an unsigned 60.18-decimal fixed-point number.\n    function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {\n        uint256 prod0;\n        uint256 prod1;\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        if (prod1 >= SCALE) {\n            revert PRBMath__MulDivFixedPointOverflow(prod1);\n        }\n\n        uint256 remainder;\n        uint256 roundUpUnit;\n        assembly {\n            remainder := mulmod(x, y, SCALE)\n            roundUpUnit := gt(remainder, 499999999999999999)\n        }\n\n        if (prod1 == 0) {\n            unchecked {\n                result = (prod0 / SCALE) + roundUpUnit;\n                return result;\n            }\n        }\n\n        assembly {\n            result := add(\n                mul(\n                    or(\n                        div(sub(prod0, remainder), SCALE_LPOTD),\n                        mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))\n                    ),\n                    SCALE_INVERSE\n                ),\n                roundUpUnit\n            )\n        }\n    }\n\n    /// @notice Calculates floor(x*y÷denominator) with full precision.\n    ///\n    /// @dev An extension of \"mulDiv\" for signed numbers. Works by computing the signs and the absolute values separately.\n    ///\n    /// Requirements:\n    /// - None of the inputs can be type(int256).min.\n    /// - The result must fit within int256.\n    ///\n    /// @param x The multiplicand as an int256.\n    /// @param y The multiplier as an int256.\n    /// @param denominator The divisor as an int256.\n    /// @return result The result as an int256.\n    function mulDivSigned(\n        int256 x,\n        int256 y,\n        int256 denominator\n    ) internal pure returns (int256 result) {\n        if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {\n            revert PRBMath__MulDivSignedInputTooSmall();\n        }\n\n        // Get hold of the absolute values of x, y and the denominator.\n        uint256 ax;\n        uint256 ay;\n        uint256 ad;\n        unchecked {\n            ax = x < 0 ? uint256(-x) : uint256(x);\n            ay = y < 0 ? uint256(-y) : uint256(y);\n            ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);\n        }\n\n        // Compute the absolute value of (x*y)÷denominator. The result must fit within int256.\n        uint256 rAbs = mulDiv(ax, ay, ad);\n        if (rAbs > uint256(type(int256).max)) {\n            revert PRBMath__MulDivSignedOverflow(rAbs);\n        }\n\n        // Get the signs of x, y and the denominator.\n        uint256 sx;\n        uint256 sy;\n        uint256 sd;\n        assembly {\n            sx := sgt(x, sub(0, 1))\n            sy := sgt(y, sub(0, 1))\n            sd := sgt(denominator, sub(0, 1))\n        }\n\n        // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.\n        // If yes, the result should be negative.\n        result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);\n    }\n\n    /// @notice Calculates the square root of x, rounding down.\n    /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.\n    ///\n    /// Caveats:\n    /// - This function does not work with fixed-point numbers.\n    ///\n    /// @param x The uint256 number for which to calculate the square root.\n    /// @return result The result as an uint256.\n    function sqrt(uint256 x) internal pure returns (uint256 result) {\n        if (x == 0) {\n            return 0;\n        }\n\n        // Set the initial guess to the least power of two that is greater than or equal to sqrt(x).\n        uint256 xAux = uint256(x);\n        result = 1;\n        if (xAux >= 0x100000000000000000000000000000000) {\n            xAux >>= 128;\n            result <<= 64;\n        }\n        if (xAux >= 0x10000000000000000) {\n            xAux >>= 64;\n            result <<= 32;\n        }\n        if (xAux >= 0x100000000) {\n            xAux >>= 32;\n            result <<= 16;\n        }\n        if (xAux >= 0x10000) {\n            xAux >>= 16;\n            result <<= 8;\n        }\n        if (xAux >= 0x100) {\n            xAux >>= 8;\n            result <<= 4;\n        }\n        if (xAux >= 0x10) {\n            xAux >>= 4;\n            result <<= 2;\n        }\n        if (xAux >= 0x8) {\n            result <<= 1;\n        }\n\n        // The operations can never overflow because the result is max 2^127 when it enters this block.\n        unchecked {\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1;\n            result = (result + x / result) >> 1; // Seven iterations should be enough\n            uint256 roundedDownResult = x / result;\n            return result >= roundedDownResult ? roundedDownResult : result;\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/libraries/Maths.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.18;\n\n// Math library from https://github.com/ajna-finance/ajna-core/blob/master/src/libraries/internal/Maths.sol\n\n/**\n    @title  Maths library\n    @notice Internal library containing common maths.\n */\nlibrary Maths {\n    uint256 internal constant WAD = 1e18;\n    uint256 internal constant RAY = 1e27;\n\n    function wmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + WAD / 2) / WAD;\n    }\n\n    function floorWmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y) / WAD;\n    }\n\n    function ceilWmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + WAD - 1) / WAD;\n    }\n\n    function wdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD + y / 2) / y;\n    }\n\n    function floorWdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD) / y;\n    }\n\n    function ceilWdiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * WAD + y - 1) / y;\n    }\n\n    function ceilDiv(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x + y - 1) / y;\n    }\n\n    function max(uint256 x, uint256 y) internal pure returns (uint256) {\n        return x >= y ? x : y;\n    }\n\n    function min(uint256 x, uint256 y) internal pure returns (uint256) {\n        return x <= y ? x : y;\n    }\n\n    function wad(uint256 x) internal pure returns (uint256) {\n        return x * WAD;\n    }\n\n    function rmul(uint256 x, uint256 y) internal pure returns (uint256) {\n        return (x * y + RAY / 2) / RAY;\n    }\n\n    function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {\n        z = n % 2 != 0 ? x : RAY;\n\n        for (n /= 2; n != 0; n /= 2) {\n            x = rmul(x, x);\n\n            if (n % 2 != 0) {\n                z = rmul(z, x);\n            }\n        }\n    }\n\n    /*************************/\n    /*** Integer Functions ***/\n    /*************************/\n\n    function maxInt(int256 x, int256 y) internal pure returns (int256) {\n        return x >= y ? x : y;\n    }\n\n    function minInt(int256 x, int256 y) internal pure returns (int256) {\n        return x <= y ? x : y;\n    }\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/utils/Governance.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\ncontract Governance {\n    /// @notice Emitted when the governance address is updated.\n    event GovernanceTransferred(\n        address indexed previousGovernance,\n        address indexed newGovernance\n    );\n\n    modifier onlyGovernance() {\n        _checkGovernance();\n        _;\n    }\n\n    /// @notice Checks if the msg sender is the governance.\n    function _checkGovernance() internal view virtual {\n        require(governance == msg.sender, \"!governance\");\n    }\n\n    /// @notice Address that can set the default base fee and provider\n    address public governance;\n\n    constructor(address _governance) {\n        governance = _governance;\n\n        emit GovernanceTransferred(address(0), _governance);\n    }\n\n    /**\n     * @notice Sets a new address as the governance of the contract.\n     * @dev Throws if the caller is not current governance.\n     * @param _newGovernance The new governance address.\n     */\n    function transferGovernance(\n        address _newGovernance\n    ) external virtual onlyGovernance {\n        require(_newGovernance != address(0), \"ZERO ADDRESS\");\n        address oldGovernance = governance;\n        governance = _newGovernance;\n\n        emit GovernanceTransferred(oldGovernance, _newGovernance);\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "lib/tokenized-strategy-periphery/src/interfaces/ITaker.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0\npragma solidity >=0.8.18;\n\ninterface ITaker {\n    function auctionTakeCallback(\n        bytes32 _auctionId,\n        address _sender,\n        uint256 _amountTaken,\n        uint256 _amountNeeded,\n        bytes calldata _data\n    ) external;\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "@openzeppelin/=lib/openzeppelin-contracts/",
        "forge-std/=lib/forge-std/src/",
        "@tokenized-strategy/=lib/tokenized-strategy/src/",
        "@periphery/=lib/tokenized-strategy-periphery/src/",
        "@ajna-core/=lib/ajna-core/src/",
        "@uniswap/v3-core/=lib/v3-core/",
        "@uniswap-v3-core/=lib/v3-core/contracts/",
        "@uniswap-v3-periphery/=lib/v3-periphery/contracts/",
        "src/=src/",
        "@base64-sol/=lib/ajna-core/lib/base64/",
        "@clones/=lib/ajna-core/lib/clones-with-immutable-args/src/",
        "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
        "@prb-math/=lib/ajna-core/lib/prb-math/",
        "@solmate/=lib/ajna-core/lib/solmate/src/",
        "@std/=lib/ajna-core/lib/forge-std/src/",
        "@yearn-vaults/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/contracts/",
        "ajna-core/=lib/ajna-core/",
        "base64/=lib/ajna-core/lib/base64/",
        "clones-with-immutable-args/=lib/ajna-core/lib/clones-with-immutable-args/src/",
        "ds-test/=lib/tokenized-strategy-periphery/lib/forge-std/lib/ds-test/src/",
        "erc4626-tests/=lib/tokenized-strategy/lib/erc4626-tests/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "openzeppelin/=lib/openzeppelin-contracts/contracts/",
        "prb-math/=lib/ajna-core/lib/prb-math/contracts/",
        "tokenized-strategy-periphery/=lib/tokenized-strategy-periphery/",
        "tokenized-strategy/=lib/tokenized-strategy/",
        "v3-core/=lib/v3-core/contracts/",
        "v3-periphery/=lib/v3-periphery/contracts/",
        "yearn-vaults-v3/=lib/tokenized-strategy-periphery/lib/yearn-vaults-v3/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 2000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": true,
      "libraries": {
        "lib/ajna-core/src/libraries/external/PoolCommons.sol": {
          "PoolCommons": "0xe88aaF46C9124b7B08C2Dcc2505429cE72979648"
        }
      }
    }
  }}