creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/Borrower.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {ImmutableArgs} from \"clones-with-immutable-args/ImmutableArgs.sol\";\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\nimport {ERC20, SafeTransferLib} from \"solmate/utils/SafeTransferLib.sol\";\nimport {IUniswapV3MintCallback} from \"v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol\";\nimport {IUniswapV3Pool} from \"v3-core/contracts/interfaces/IUniswapV3Pool.sol\";\n\nimport {TERMINATING_CLOSE_FACTOR} from \"./libraries/constants/Constants.sol\";\nimport {BalanceSheet, AuctionAmounts, Assets, Prices} from \"./libraries/BalanceSheet.sol\";\nimport {LiquidityAmounts} from \"./libraries/LiquidityAmounts.sol\";\nimport {extract} from \"./libraries/Positions.sol\";\nimport {TickMath} from \"./libraries/TickMath.sol\";\n\nimport {Factory} from \"./Factory.sol\";\nimport {Lender} from \"./Lender.sol\";\nimport {VolatilityOracle} from \"./VolatilityOracle.sol\";\n\ninterface ILiquidator {\n    receive() external payable;\n\n    /**\n     * @notice Transfers `amounts.out0` and `amounts.out1` to the liquidator with the expectation that they'll\n     * transfer `amounts.repay0` and `amounts.repay1` to the appropriate `Lender`s, executing swaps if necessary.\n     * The liquidator can keep leftover funds as a reward.\n     * @param data Encoded parameters that were passed to `Borrower.liquidate`\n     * @param caller The address that called `Borrower.liquidate`\n     * @param amounts The key amounts involved in the liquidation\n     */\n    function callback(bytes calldata data, address caller, AuctionAmounts memory amounts) external;\n}\n\ninterface IManager {\n    /**\n     * @notice Gives the `IManager` full control of the `Borrower`. Called within `Borrower.modify`.\n     * @dev In most cases, you'll want to verify that `msg.sender` is, in fact, a `Borrower` using\n     * `factory.isBorrower(msg.sender)`.\n     * @param data Encoded parameters that were passed to `Borrower.modify`\n     * @param owner The owner of the `Borrower`\n     * @param positions The `Borrower`'s current Uniswap positions. You can convert them to an array using\n     * `Positions.extract`\n     * @return Updated positions, encoded using `Positions.zip`. Return 0 if you don't wish to make any changes.\n     */\n    function callback(bytes calldata data, address owner, uint208 positions) external returns (uint208);\n}\n\n/// @title Borrower\n/// @author Aloe Labs, Inc.\n/// @dev \"Test everything; hold fast what is good.\" - 1 Thessalonians 5:21\ncontract Borrower is IUniswapV3MintCallback {\n    using SoladyMath for uint256;\n    using SafeTransferLib for ERC20;\n\n    /**\n     * @notice Emitted when the account gets `warn`ed. The liquidation incentive will be 0 for 5 minutes,\n     * giving the account owner time to regain health on their own. After this `LIQUIDATION_GRACE_PERIOD`,\n     * the incentive starts increasing (following the Dutch Auction curve in `BalanceSheet`).\n     * @dev Simply regaining health is not enough. To clear the warning, you must replenish the `ante` and\n     * call `modify`.\n     */\n    event Warn();\n\n    /// @notice Emitted when the account gets `liquidate`d\n    event Liquidate();\n\n    enum State {\n        Ready,\n        Locked,\n        InModifyCallback\n    }\n\n    uint256 private constant SLOT0_MASK_POSITIONS = 0x000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffff;\n    uint256 private constant SLOT0_MASK_USERSPACE = 0x000000000000ffffffffffffffff000000000000000000000000000000000000; // prettier-ignore\n    uint256 private constant SLOT0_MASK_AUCTION   = 0x00ffffffffff0000000000000000000000000000000000000000000000000000; // prettier-ignore\n    uint256 private constant SLOT0_MASK_STATE     = 0x7f00000000000000000000000000000000000000000000000000000000000000; // prettier-ignore\n    uint256 private constant SLOT0_DIRT           = 0x8000000000000000000000000000000000000000000000000000000000000000; // prettier-ignore\n\n    /// @notice The factory that created this contract\n    Factory public immutable FACTORY;\n\n    /// @notice The oracle to use for prices and implied volatility\n    VolatilityOracle public immutable ORACLE;\n\n    /// @notice The Uniswap pair in which this `Borrower` can manage positions\n    IUniswapV3Pool public immutable UNISWAP_POOL;\n\n    /// @notice The first token of the Uniswap pair\n    ERC20 public immutable TOKEN0;\n\n    /// @notice The second token of the Uniswap pair\n    ERC20 public immutable TOKEN1;\n\n    /// @notice The lender of `TOKEN0`\n    Lender public immutable LENDER0;\n\n    /// @notice The lender of `TOKEN1`\n    Lender public immutable LENDER1;\n\n    /**\n     * @notice The `Borrower`'s only mutable storage. Lowest 144 bits store the lower/upper bounds of up to 3 Uniswap\n     * positions, encoded by `Positions.zip`. Next 64 bits are unused within the `Borrower` and available to users as\n     * \"free\" storage － no additional sstore's. These 208 bits (144 + 64) are passed to `IManager.callback`, and get\n     * updated when the callback returns a non-zero value. The next 40 bits are either 0 or the warning time. The\n     * highest 8 bits represent the current `State` enum, plus 128. We add 128 (i.e. set the highest bit to 1) so that\n     * the slot is always non-zero, even in the absence of Uniswap positions － this saves gas.\n     */\n    uint256 public slot0;\n\n    modifier onlyInModifyCallback() {\n        require(slot0 & SLOT0_MASK_STATE == uint256(State.InModifyCallback) << 248);\n        _;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                              CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(VolatilityOracle oracle, IUniswapV3Pool pool, Lender lender0, Lender lender1) {\n        FACTORY = Factory(msg.sender);\n        ORACLE = oracle;\n        UNISWAP_POOL = pool;\n        LENDER0 = lender0;\n        LENDER1 = lender1;\n\n        TOKEN0 = lender0.asset();\n        TOKEN1 = lender1.asset();\n    }\n\n    receive() external payable {}\n\n    function owner() public pure returns (address) {\n        return ImmutableArgs.addr();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                           MAIN ENTRY POINTS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Warns the borrower that they're about to be liquidated\n     * @param oracleSeed The indices of `UNISWAP_POOL.observations` where we start our search for\n     * the 30-minute-old (lowest 16 bits) and 60-minute-old (next 16 bits) observations when getting\n     * TWAPs. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     */\n    function warn(uint40 oracleSeed) external {\n        uint256 slot0_ = slot0;\n        // Essentially `slot0.state == State.Ready && slot0.warnTime == 0`\n        require(slot0_ & (SLOT0_MASK_STATE | SLOT0_MASK_AUCTION) == 0);\n\n        // Fetch prices from oracle\n        (Prices memory prices, , , uint208 ante) = getPrices(oracleSeed);\n        // Tally assets\n        Assets memory assets = _getAssets(slot0_, prices);\n        // Fetch liabilities from lenders\n        (uint256 liabilities0, uint256 liabilities1) = getLiabilities();\n        // Ensure only unhealthy accounts get warned and liquidated\n        require(!BalanceSheet.isHealthy(prices, assets, liabilities0, liabilities1), \"Aloe: healthy\");\n\n        // Start auction\n        slot0 = slot0_ | (block.timestamp << 208);\n        emit Warn();\n\n        SafeTransferLib.safeTransferETH(msg.sender, address(this).balance.min(ante / 4));\n    }\n\n    /**\n     * @notice Clears the warning state if the account is healthy and has a full ante\n     * @dev If you bring the account back to health via a `modify` call, the warning state is cleared\n     * automatically. However, if borrowing is paused and `modify` is restricted, you may want to repay\n     * the `Lender`(s) directly and use this to clear the warning.\n     * @param oracleSeed The indices of `UNISWAP_POOL.observations` where we start our search for\n     * the 30-minute-old (lowest 16 bits) and 60-minute-old (next 16 bits) observations when getting\n     * TWAPs. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     */\n    function clear(uint40 oracleSeed) external payable {\n        uint256 slot0_ = slot0;\n        // Essentially `slot0.state == State.Ready && slot0.warnTime > 0`\n        require(slot0_ & SLOT0_MASK_STATE == 0 && slot0_ & SLOT0_MASK_AUCTION > 0);\n\n        // Fetch prices from oracle\n        (Prices memory prices, , , uint208 ante) = getPrices(oracleSeed);\n        // Tally assets\n        Assets memory assets = _getAssets(slot0_, prices);\n        // Fetch liabilities from lenders\n        (uint256 liabilities0, uint256 liabilities1) = getLiabilities();\n        // Ensure the warning can only be cleared for healthy accounts with replenished ante\n        require(address(this).balance >= ante, \"Aloe: conditions\");\n        require(BalanceSheet.isHealthy(prices, assets, liabilities0, liabilities1), \"Aloe: unhealthy\");\n\n        // End auction\n        slot0 = slot0_ & ~SLOT0_MASK_AUCTION;\n    }\n\n    /* solhint-disable code-complexity */\n    /**\n     * @notice Liquidates the borrower, using all available assets to pay down liabilities. `callee` must\n     * transfer at least `amounts.repay0` and `amounts.repay1` to `LENDER0` and `LENDER1`, respectively.\n     * `amounts.out0` and `amounts.out1` start at 0 and increase over time. Once their value exceeds what\n     * must be repaid, the excess acts as a liquidation incentive.\n     * @dev The amounts out are 0 for the entirety of the `LIQUIDATION_GRACE_PERIOD`. They start rising\n     * afterwards, reaching 105% of the repay value after 5 minutes and 112% after 55 minutes.\n     * @param callee The smart contract responsible for swapping and repaying\n     * @param data Encoded parameters that get forwarded to `callee`\n     * @param closeFactor The fraction of liabilities to repay, expressed in basis points\n     * @param oracleSeed The indices of `UNISWAP_POOL.observations` where we start our search for\n     * the 30-minute-old (lowest 16 bits) and 60-minute-old (next 16 bits) observations when getting\n     * TWAPs. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     */\n    function liquidate(ILiquidator callee, bytes calldata data, uint256 closeFactor, uint40 oracleSeed) external {\n        require(0 < closeFactor && closeFactor <= 10000, \"Aloe: close\");\n\n        uint256 slot0_ = slot0;\n        // Essentially `slot0.state == State.Ready && slot0.warnTime > 0`\n        require(slot0_ & SLOT0_MASK_STATE == 0 && slot0_ & SLOT0_MASK_AUCTION > 0);\n        slot0 = slot0_ | (uint256(State.Locked) << 248);\n\n        // Withdraw all Uniswap positions\n        _uniswapWithdraw(slot0_);\n\n        // Fetch prices from oracle\n        (Prices memory prices, , , ) = getPrices(oracleSeed);\n        // Tally assets\n        (uint256 assets0, uint256 assets1) = (TOKEN0.balanceOf(address(this)), TOKEN1.balanceOf(address(this)));\n        // Fetch liabilities from lenders\n        (uint256 liabilities0, uint256 liabilities1) = getLiabilities();\n        // Sanity check\n        {\n            (uint160 sqrtPriceX96, , , , , , ) = UNISWAP_POOL.slot0();\n            require(prices.a < sqrtPriceX96 && sqrtPriceX96 < prices.b);\n        }\n\n        AuctionAmounts memory amounts = BalanceSheet.computeAuctionAmounts(\n            prices.c,\n            assets0,\n            assets1,\n            liabilities0,\n            liabilities1,\n            BalanceSheet.auctionTime((slot0_ & SLOT0_MASK_AUCTION) >> 208),\n            closeFactor\n        );\n\n        if (amounts.out0 > 0) TOKEN0.safeTransfer(address(callee), amounts.out0);\n        if (amounts.out1 > 0) TOKEN1.safeTransfer(address(callee), amounts.out1);\n\n        callee.callback(data, msg.sender, amounts);\n\n        if (amounts.repay0 > 0) LENDER0.repay(amounts.repay0, address(this));\n        if (amounts.repay1 > 0) LENDER1.repay(amounts.repay1, address(this));\n\n        if (closeFactor == 10000) {\n            // Everything was repaid → no need to `warn` again → can pay out remaining ETH as incentive\n            SafeTransferLib.safeTransferETH(payable(callee), address(this).balance);\n            // End auction since account is definitely healthy\n            slot0_ &= ~SLOT0_MASK_AUCTION;\n        } else if (closeFactor > TERMINATING_CLOSE_FACTOR) {\n            // End auction if account is healthy\n            if (\n                BalanceSheet.isHealthy(\n                    prices,\n                    assets0 - amounts.out0,\n                    assets1 - amounts.out1,\n                    liabilities0 - amounts.repay0,\n                    liabilities1 - amounts.repay1\n                )\n            ) slot0_ &= ~SLOT0_MASK_AUCTION;\n        }\n\n        slot0 = (slot0_ & (SLOT0_MASK_USERSPACE | SLOT0_MASK_AUCTION)) | SLOT0_DIRT;\n        emit Liquidate();\n    }\n\n    /* solhint-enable code-complexity */\n\n    /**\n     * @notice Allows the owner to manage their account by handing control to some `callee`. Inside the\n     * callback `callee` has access to all sub-commands (`uniswapDeposit`, `uniswapWithdraw`, `transfer`,\n     * `borrow`, `repay`, and `withdrawAnte`). Whatever `callee` does, the account MUST be healthy\n     * after the callback.\n     * @param callee The smart contract that will get temporary control of this account\n     * @param data Encoded parameters that get forwarded to `callee`\n     * @param oracleSeed The indices of `UNISWAP_POOL.observations` where we start our search for\n     * the 30-minute-old (lowest 16 bits) and 60-minute-old (next 16 bits) observations when getting\n     * TWAPs. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     */\n    function modify(IManager callee, bytes calldata data, uint40 oracleSeed) external payable {\n        uint256 slot0_ = slot0;\n        // Essentially `slot0.state == State.Ready && msg.sender == owner()`\n        require(slot0_ & SLOT0_MASK_STATE == 0 && msg.sender == owner(), \"Aloe: only owner\");\n\n        slot0 = slot0_ | (uint256(State.InModifyCallback) << 248);\n        {\n            uint208 positions = callee.callback(data, msg.sender, uint208(slot0_));\n            assembly (\"memory-safe\") {\n                // Equivalent to `if (positions > 0) slot0_ = positions`\n                slot0_ := or(positions, mul(slot0_, iszero(positions)))\n            }\n        }\n        slot0 = (slot0_ & SLOT0_MASK_POSITIONS) | SLOT0_DIRT;\n\n        (uint256 liabilities0, uint256 liabilities1) = getLiabilities();\n        if (liabilities0 > 0 || liabilities1 > 0) {\n            // Fetch prices from oracle\n            (Prices memory prices, bool seemsLegit, bool isPaused, uint208 ante) = getPrices(oracleSeed);\n            // Tally assets\n            Assets memory assets = _getAssets(slot0_, prices);\n            // Ensure account is healthy and meets the conditions for borrowing\n            require(seemsLegit && !isPaused && address(this).balance >= ante, \"Aloe: conditions\");\n            require(BalanceSheet.isHealthy(prices, assets, liabilities0, liabilities1), \"Aloe: unhealthy\");\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                              SUB-COMMANDS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Callback for Uniswap V3 pool; necessary for `uniswapDeposit` to work\n     * @param amount0 The amount of `TOKEN0` owed to the `UNISWAP_POOL`\n     * @param amount1 The amount of `TOKEN1` owed to the `UNISWAP_POOL`\n     */\n    function uniswapV3MintCallback(uint256 amount0, uint256 amount1, bytes calldata) external {\n        require(msg.sender == address(UNISWAP_POOL));\n\n        if (amount0 > 0) TOKEN0.safeTransfer(msg.sender, amount0);\n        if (amount1 > 0) TOKEN1.safeTransfer(msg.sender, amount1);\n    }\n\n    /**\n     * @notice Allows the `owner()` to add liquidity to a Uniswap position (or create a new one). Only works\n     * within the `modify` callback.\n     * @dev The `LiquidityAmounts` library can help convert underlying amounts to units of `liquidity`.\n     * NOTE: Depending on your use-case, it may be more gas-efficient to call `UNISWAP_POOL.mint` in your\n     * own contract, instead of doing `uniswapDeposit` inside of `modify`'s callback. As long as you set\n     * this `Borrower` as the recipient in `UNISWAP_POOL.mint`, the result is the same.\n     * @param lower The tick at the position's lower bound\n     * @param upper The tick at the position's upper bound\n     * @param liquidity The amount of liquidity to add, in Uniswap's internal units\n     * @return amount0 The precise amount of `TOKEN0` that went into the Uniswap position\n     * @return amount1 The precise amount of `TOKEN1` that went into the Uniswap position\n     */\n    function uniswapDeposit(\n        int24 lower,\n        int24 upper,\n        uint128 liquidity\n    ) external onlyInModifyCallback returns (uint256 amount0, uint256 amount1) {\n        (amount0, amount1) = UNISWAP_POOL.mint(address(this), lower, upper, liquidity, \"\");\n    }\n\n    /**\n     * @notice Allows the `owner()` to withdraw liquidity from one of their Uniswap positions. Only works within\n     * the `modify` callback.\n     * @dev The `LiquidityAmounts` library can help convert underlying amounts to units of `liquidity`\n     * @param lower The tick at the position's lower bound\n     * @param upper The tick at the position's upper bound\n     * @param liquidity The amount of liquidity to remove, in Uniswap's internal units. Pass 0 to collect\n     * fees without burning any liquidity.\n     * @param recipient Receives the tokens from Uniswap. Usually the address of this `Borrower` account.\n     * @return burned0 The amount of `TOKEN0` that was removed from the Uniswap position\n     * @return burned1 The amount of `TOKEN1` that was removed from the Uniswap position\n     * @return collected0 Equal to `burned0` plus any earned `TOKEN0` fees that hadn't yet been claimed\n     * @return collected1 Equal to `burned1` plus any earned `TOKEN1` fees that hadn't yet been claimed\n     */\n    function uniswapWithdraw(\n        int24 lower,\n        int24 upper,\n        uint128 liquidity,\n        address recipient\n    ) external onlyInModifyCallback returns (uint256 burned0, uint256 burned1, uint256 collected0, uint256 collected1) {\n        (burned0, burned1, collected0, collected1) = _uniswapWithdraw(lower, upper, liquidity, recipient);\n    }\n\n    /**\n     * @notice The most flexible sub-command. Allows the `owner()` to transfer amounts of `TOKEN0` and `TOKEN1`\n     * to any `recipient` they want. Only works within the `modify` callback.\n     * @param amount0 The amount of `TOKEN0` to transfer\n     * @param amount1 The amount of `TOKEN1` to transfer\n     * @param recipient Receives the transferred tokens\n     */\n    function transfer(uint256 amount0, uint256 amount1, address recipient) external onlyInModifyCallback {\n        if (amount0 > 0) TOKEN0.safeTransfer(recipient, amount0);\n        if (amount1 > 0) TOKEN1.safeTransfer(recipient, amount1);\n    }\n\n    /**\n     * @notice Allows the `owner()` to transfer an `amount` of ETH to any `recipient` they want. Only works within\n     * the `modify` callback.\n     * @param amount The amount of ETH to transfer\n     * @param recipient Receives the ETH\n     */\n    function transferEth(uint256 amount, address payable recipient) external onlyInModifyCallback {\n        // WARNING: External call to user-specified address\n        SafeTransferLib.safeTransferETH(recipient, amount);\n    }\n\n    /**\n     * @notice Allows the `owner()` to borrow funds from `LENDER0` and `LENDER1`. Only works within the `modify`\n     * callback.\n     * @dev If `amount0 > 0` and interest hasn't yet accrued in this block for `LENDER0`, it will accrue\n     * prior to processing your new borrow. Same goes for `amount1 > 0` and `LENDER1`.\n     * @param amount0 The amount of `TOKEN0` to borrow\n     * @param amount1 The amount of `TOKEN1` to borrow\n     * @param recipient Receives the borrowed tokens. Usually the address of this `Borrower` account.\n     */\n    function borrow(uint256 amount0, uint256 amount1, address recipient) external onlyInModifyCallback {\n        if (amount0 > 0) LENDER0.borrow(amount0, recipient);\n        if (amount1 > 0) LENDER1.borrow(amount1, recipient);\n    }\n\n    /**\n     * @notice Allows the `owner()` to repay debts to `LENDER0` and `LENDER1`. Only works within the `modify`\n     * callback.\n     * @dev This is technically unnecessary since you could call `Lender.repay` directly, specifying this\n     * contract as the `beneficiary` and using the `transfer` sub-command to make payments. We include it\n     * because it's convenient and gas-efficient for common use-cases.\n     * @param amount0 The amount of `TOKEN0` to repay\n     * @param amount1 The amount of `TOKEN1` to repay\n     */\n    function repay(uint256 amount0, uint256 amount1) external onlyInModifyCallback {\n        if (amount0 > 0) {\n            TOKEN0.safeTransfer(address(LENDER0), amount0);\n            LENDER0.repay(amount0, address(this));\n        }\n        if (amount1 > 0) {\n            TOKEN1.safeTransfer(address(LENDER1), amount1);\n            LENDER1.repay(amount1, address(this));\n        }\n    }\n\n    /**\n     * @notice Allows the `owner()` to perform arbitrary transfers. Useful for rescuing misplaced funds. Only\n     * works within the `modify` callback.\n     * @param token The ERC20 token to transfer\n     * @param amount The amount to transfer\n     * @param recipient Receives the transferred tokens\n     */\n    function rescue(ERC20 token, uint256 amount, address recipient) external onlyInModifyCallback {\n        // WARNING: External call to user-specified address\n        token.safeTransfer(recipient, amount);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             BALANCE SHEET\n    //////////////////////////////////////////////////////////////*/\n\n    function getUniswapPositions() external view returns (int24[] memory) {\n        return extract(slot0);\n    }\n\n    function getAssets() external view returns (Assets memory) {\n        (Prices memory prices, , , ) = getPrices(1 << 32);\n        return _getAssets(slot0, prices);\n    }\n\n    function getLiabilities() public view returns (uint256 amount0, uint256 amount1) {\n        amount0 = LENDER0.borrowBalance(address(this));\n        amount1 = LENDER1.borrowBalance(address(this));\n    }\n\n    /**\n     * @notice Summarizes all oracle data pertinent to account health\n     * @dev If `seemsLegit == false`, you can call `Factory.pause` to temporarily disable borrows\n     * @param oracleSeed The indices of `UNISWAP_POOL.observations` where we start our search for\n     * the 30-minute-old (lowest 16 bits) and 60-minute-old (next 16 bits) observations when getting\n     * TWAPs. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     * @return The probe prices currently being used to evaluate account health\n     * @return Whether the Uniswap TWAP seems to have been manipulated or not\n     * @return Whether the factory has paused this market\n     * @return The current ante that must be posted before borrowing\n     */\n    function getPrices(uint40 oracleSeed) public view returns (Prices memory, bool, bool, uint208) {\n        Prices memory prices;\n        uint56 metric;\n        uint256 iv;\n        bool seemsLegit;\n\n        // compute current price and volatility\n        (metric, prices.c, iv) = ORACLE.consult(UNISWAP_POOL, oracleSeed);\n        // get parameters from factory\n        (uint208 ante, uint8 nSigma, uint8 mtd, uint32 pausedUntilTime) = FACTORY.getParameters(UNISWAP_POOL);\n        // compute prices at which solvency will be checked\n        (prices.a, prices.b, seemsLegit) = BalanceSheet.computeProbePrices(metric, prices.c, iv, nSigma, mtd);\n\n        return (prices, seemsLegit, block.timestamp < pausedUntilTime, ante);\n    }\n\n    function _getAssets(uint256 slot0_, Prices memory prices) private view returns (Assets memory assets) {\n        assets.amount0AtA = assets.amount0AtB = TOKEN0.balanceOf(address(this));\n        assets.amount1AtA = assets.amount1AtB = TOKEN1.balanceOf(address(this));\n\n        int24[] memory positions = extract(slot0_);\n        uint256 count = positions.length;\n        unchecked {\n            for (uint256 i; i < count; i += 2) {\n                // Load lower and upper ticks from the `positions` array\n                int24 l = positions[i];\n                int24 u = positions[i + 1];\n                // Fetch amount of `liquidity` in the position\n                (uint128 liquidity, , , , ) = UNISWAP_POOL.positions(keccak256(abi.encodePacked(address(this), l, u)));\n\n                if (liquidity == 0) continue;\n\n                // Compute lower and upper sqrt ratios\n                uint160 L = TickMath.getSqrtRatioAtTick(l);\n                uint160 U = TickMath.getSqrtRatioAtTick(u);\n\n                uint256 amount0;\n                uint256 amount1;\n                // Compute what amounts underlie `liquidity` at both probe prices\n                (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(prices.a, L, U, liquidity);\n                assets.amount0AtA += amount0;\n                assets.amount1AtA += amount1;\n                (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(prices.b, L, U, liquidity);\n                assets.amount0AtB += amount0;\n                assets.amount1AtB += amount1;\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                                 HELPERS\n    //////////////////////////////////////////////////////////////*/\n\n    function _uniswapWithdraw(uint256 slot0_) private {\n        int24[] memory positions = extract(slot0_);\n        uint256 count = positions.length;\n        unchecked {\n            for (uint256 i; i < count; i += 2) {\n                // Load lower and upper ticks from the `positions` array\n                int24 l = positions[i];\n                int24 u = positions[i + 1];\n                // Fetch amount of `liquidity` in the position\n                (uint128 liquidity, , , , ) = UNISWAP_POOL.positions(keccak256(abi.encodePacked(address(this), l, u)));\n\n                if (liquidity == 0) continue;\n\n                // Withdraw all `liquidity` from the position\n                _uniswapWithdraw(l, u, liquidity, address(this));\n            }\n        }\n    }\n\n    function _uniswapWithdraw(\n        int24 lower,\n        int24 upper,\n        uint128 liquidity,\n        address recipient\n    ) private returns (uint256 burned0, uint256 burned1, uint256 collected0, uint256 collected1) {\n        (burned0, burned1) = UNISWAP_POOL.burn(lower, upper, liquidity);\n        (collected0, collected1) = UNISWAP_POOL.collect(recipient, lower, upper, type(uint128).max, type(uint128).max);\n    }\n}\n"
      },
      "lib/clones-with-immutable-args/src/ImmutableArgs.sol": {
        "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.15;\n\n/// @title ImmutableArgs\n/// @author zefram.eth, Saw-mon & Natalie\n/// @notice Provides helper functions for reading immutable args from calldata\nlibrary ImmutableArgs {\n    function addr() internal pure returns (address arg) {\n        assembly {\n            arg := shr(0x60, calldataload(sub(calldatasize(), 22)))\n        }\n    }\n\n    /// @notice Reads an immutable arg with type address\n    /// @param offset The offset of the arg in the packed data\n    /// @return arg The arg value\n    function addressAt(uint256 offset) internal pure returns (address arg) {\n        uint256 start = _startOfImmutableArgs();\n        assembly {\n            arg := shr(0x60, calldataload(add(start, offset)))\n        }\n    }\n\n    /// @notice Reads an immutable arg with type uint256\n    /// @param offset The offset of the arg in the packed data\n    /// @return arg The arg value\n    function uint256At(uint256 offset) internal pure returns (uint256 arg) {\n        uint256 start = _startOfImmutableArgs();\n        assembly {\n            arg := calldataload(add(start, offset))\n        }\n    }\n\n    function all() internal pure returns (bytes memory args) {\n        uint256 start = _startOfImmutableArgs();\n        unchecked {\n            args = msg.data[start:msg.data.length - 2];\n        }\n    }\n\n    /// @return offset The offset of the packed immutable args in calldata\n    function _startOfImmutableArgs() private pure returns (uint256 offset) {\n        assembly {\n            //                                      read final 2 bytes of calldata, i.e. `extraLength`\n            offset := sub(calldatasize(), shr(0xf0, calldataload(sub(calldatasize(), 2))))\n        }\n    }\n}\n"
      },
      "lib/solady/src/utils/FixedPointMathLib.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\nlibrary FixedPointMathLib {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                       CUSTOM ERRORS                        */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The operation failed, as the output exceeds the maximum value of uint256.\n    error ExpOverflow();\n\n    /// @dev The operation failed, as the output exceeds the maximum value of uint256.\n    error FactorialOverflow();\n\n    /// @dev The operation failed, due to an multiplication overflow.\n    error MulWadFailed();\n\n    /// @dev The operation failed, either due to a\n    /// multiplication overflow, or a division by a zero.\n    error DivWadFailed();\n\n    /// @dev The multiply-divide operation failed, either due to a\n    /// multiplication overflow, or a division by a zero.\n    error MulDivFailed();\n\n    /// @dev The division failed, as the denominator is zero.\n    error DivFailed();\n\n    /// @dev The full precision multiply-divide operation failed, either due\n    /// to the result being larger than 256 bits, or a division by a zero.\n    error FullMulDivFailed();\n\n    /// @dev The output is undefined, as the input is less-than-or-equal to zero.\n    error LnWadUndefined();\n\n    /// @dev The output is undefined, as the input is zero.\n    error Log2Undefined();\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                         CONSTANTS                          */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev The scalar of ETH and most ERC20s.\n    uint256 internal constant WAD = 1e18;\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*              SIMPLIFIED FIXED POINT OPERATIONS             */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Equivalent to `(x * y) / WAD` rounded down.\n    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n            if mul(y, gt(x, div(not(0), y))) {\n                // Store the function selector of `MulWadFailed()`.\n                mstore(0x00, 0xbac65e5b)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, y), WAD)\n        }\n    }\n\n    /// @dev Equivalent to `(x * y) / WAD` rounded up.\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.\n            if mul(y, gt(x, div(not(0), y))) {\n                // Store the function selector of `MulWadFailed()`.\n                mstore(0x00, 0xbac65e5b)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))\n        }\n    }\n\n    /// @dev Equivalent to `(x * WAD) / y` rounded down.\n    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.\n            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {\n                // Store the function selector of `DivWadFailed()`.\n                mstore(0x00, 0x7c5f487d)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, WAD), y)\n        }\n    }\n\n    /// @dev Equivalent to `(x * WAD) / y` rounded up.\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.\n            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {\n                // Store the function selector of `DivWadFailed()`.\n                mstore(0x00, 0x7c5f487d)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))\n        }\n    }\n\n    /// @dev Equivalent to `x` to the power of `y`.\n    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.\n    function powWad(int256 x, int256 y) internal pure returns (int256) {\n        // Using `ln(x)` means `x` must be greater than 0.\n        return expWad((lnWad(x) * y) / int256(WAD));\n    }\n\n    /// @dev Returns `exp(x)`, denominated in `WAD`.\n    function expWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            // When the result is < 0.5 we return zero. This happens when\n            // x <= floor(log(0.5e18) * 1e18) ~ -42e18\n            if (x <= -42139678854452767551) return r;\n\n            /// @solidity memory-safe-assembly\n            assembly {\n                // When the result is > (2**255 - 1) / 1e18 we can not represent it as an\n                // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.\n                if iszero(slt(x, 135305999368893231589)) {\n                    // Store the function selector of `ExpOverflow()`.\n                    mstore(0x00, 0xa37bfec9)\n                    // Revert with (offset, size).\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96\n            // for more intermediate precision and a binary basis. This base conversion\n            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.\n            x = (x << 78) / 5 ** 18;\n\n            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers\n            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.\n            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).\n            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;\n            x = x - k * 54916777467707473351141471128;\n\n            // k is in the range [-61, 195].\n\n            // Evaluate using a (6, 7)-term rational approximation.\n            // p is made monic, we'll multiply by a scale factor later.\n            int256 y = x + 1346386616545796478920950773328;\n            y = ((y * x) >> 96) + 57155421227552351082224309758442;\n            int256 p = y + x - 94201549194550492254356042504812;\n            p = ((p * y) >> 96) + 28719021644029726153956944680412240;\n            p = p * x + (4385272521454847904659076985693276 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            int256 q = x - 2855989394907223263936484059900;\n            q = ((q * x) >> 96) + 50020603652535783019961831881945;\n            q = ((q * x) >> 96) - 533845033583426703283633433725380;\n            q = ((q * x) >> 96) + 3604857256930695427073651918091429;\n            q = ((q * x) >> 96) - 14423608567350463180887372962807573;\n            q = ((q * x) >> 96) + 26449188498355588339934803723976023;\n\n            /// @solidity memory-safe-assembly\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial won't have zeros in the domain as all its roots are complex.\n                // No scaling is necessary because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r should be in the range (0.09, 0.25) * 2**96.\n\n            // We now need to multiply r by:\n            // * the scale factor s = ~6.031367120.\n            // * the 2**k factor from the range reduction.\n            // * the 1e18 / 2**96 factor for base conversion.\n            // We do this all at once, with an intermediate result in 2**213\n            // basis, so the final right shift is always by a positive amount.\n            r = int256(\n                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)\n            );\n        }\n    }\n\n    /// @dev Returns `ln(x)`, denominated in `WAD`.\n    function lnWad(int256 x) internal pure returns (int256 r) {\n        unchecked {\n            /// @solidity memory-safe-assembly\n            assembly {\n                if iszero(sgt(x, 0)) {\n                    // Store the function selector of `LnWadUndefined()`.\n                    mstore(0x00, 0x1615e638)\n                    // Revert with (offset, size).\n                    revert(0x1c, 0x04)\n                }\n            }\n\n            // We want to convert x from 10**18 fixed point to 2**96 fixed point.\n            // We do this by multiplying by 2**96 / 10**18. But since\n            // ln(x * C) = ln(x) + ln(C), we can simply do nothing here\n            // and add ln(2**96 / 10**18) at the end.\n\n            // Compute k = log2(x) - 96.\n            int256 k;\n            /// @solidity memory-safe-assembly\n            assembly {\n                let v := x\n                k := shl(7, lt(0xffffffffffffffffffffffffffffffff, v))\n                k := or(k, shl(6, lt(0xffffffffffffffff, shr(k, v))))\n                k := or(k, shl(5, lt(0xffffffff, shr(k, v))))\n\n                // For the remaining 32 bits, use a De Bruijn lookup.\n                // See: https://graphics.stanford.edu/~seander/bithacks.html\n                v := shr(k, v)\n                v := or(v, shr(1, v))\n                v := or(v, shr(2, v))\n                v := or(v, shr(4, v))\n                v := or(v, shr(8, v))\n                v := or(v, shr(16, v))\n\n                // forgefmt: disable-next-item\n                k := sub(or(k, byte(shr(251, mul(v, shl(224, 0x07c4acdd))),\n                    0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f)), 96)\n            }\n\n            // Reduce range of x to (1, 2) * 2**96\n            // ln(2^k * x) = k * ln(2) + ln(x)\n            x <<= uint256(159 - k);\n            x = int256(uint256(x) >> 159);\n\n            // Evaluate using a (8, 8)-term rational approximation.\n            // p is made monic, we will multiply by a scale factor later.\n            int256 p = x + 3273285459638523848632254066296;\n            p = ((p * x) >> 96) + 24828157081833163892658089445524;\n            p = ((p * x) >> 96) + 43456485725739037958740375743393;\n            p = ((p * x) >> 96) - 11111509109440967052023855526967;\n            p = ((p * x) >> 96) - 45023709667254063763336534515857;\n            p = ((p * x) >> 96) - 14706773417378608786704636184526;\n            p = p * x - (795164235651350426258249787498 << 96);\n\n            // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n            // q is monic by convention.\n            int256 q = x + 5573035233440673466300451813936;\n            q = ((q * x) >> 96) + 71694874799317883764090561454958;\n            q = ((q * x) >> 96) + 283447036172924575727196451306956;\n            q = ((q * x) >> 96) + 401686690394027663651624208769553;\n            q = ((q * x) >> 96) + 204048457590392012362485061816622;\n            q = ((q * x) >> 96) + 31853899698501571402653359427138;\n            q = ((q * x) >> 96) + 909429971244387300277376558375;\n            /// @solidity memory-safe-assembly\n            assembly {\n                // Div in assembly because solidity adds a zero check despite the unchecked.\n                // The q polynomial is known not to have zeros in the domain.\n                // No scaling required because p is already 2**96 too large.\n                r := sdiv(p, q)\n            }\n\n            // r is in the range (0, 0.125) * 2**96\n\n            // Finalization, we need to:\n            // * multiply by the scale factor s = 5.549…\n            // * add ln(2**96 / 10**18)\n            // * add k * ln(2)\n            // * multiply by 10**18 / 2**96 = 5**18 >> 78\n\n            // mul s * 5e18 * 2**96, base is now 5**18 * 2**192\n            r *= 1677202110996718588342820967067443963516166;\n            // add ln(2) * k * 5e18 * 2**192\n            r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;\n            // add ln(2**96 / 10**18) * 5e18 * 2**192\n            r += 600920179829731861736702779321621459595472258049074101567377883020018308;\n            // base conversion: mul 2**18 / 2**192\n            r >>= 174;\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                  GENERAL NUMBER UTILITIES                  */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Calculates `floor(a * b / d)` with full precision.\n    /// Throws if result overflows a uint256 or when `d` is zero.\n    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv\n    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // forgefmt: disable-next-item\n            for {} 1 {} {\n                // 512-bit multiply `[prod1 prod0] = x * y`.\n                // Compute the product mod `2**256` and mod `2**256 - 1`\n                // then use the Chinese Remainder Theorem to reconstruct\n                // the 512 bit result. The result is stored in two 256\n                // variables such that `product = prod1 * 2**256 + prod0`.\n\n                // Least significant 256 bits of the product.\n                let prod0 := mul(x, y)\n                let mm := mulmod(x, y, not(0))\n                // Most significant 256 bits of the product.\n                let prod1 := sub(mm, add(prod0, lt(mm, prod0)))\n\n                // Handle non-overflow cases, 256 by 256 division.\n                if iszero(prod1) {\n                    if iszero(d) {\n                        // Store the function selector of `FullMulDivFailed()`.\n                        mstore(0x00, 0xae47f702)\n                        // Revert with (offset, size).\n                        revert(0x1c, 0x04)\n                    }\n                    result := div(prod0, d)\n                    break       \n                }\n\n                // Make sure the result is less than `2**256`.\n                // Also prevents `d == 0`.\n                if iszero(gt(d, prod1)) {\n                    // Store the function selector of `FullMulDivFailed()`.\n                    mstore(0x00, 0xae47f702)\n                    // Revert with (offset, size).\n                    revert(0x1c, 0x04)\n                }\n\n                ///////////////////////////////////////////////\n                // 512 by 256 division.\n                ///////////////////////////////////////////////\n\n                // Make division exact by subtracting the remainder from `[prod1 prod0]`.\n                // Compute remainder using mulmod.\n                let remainder := mulmod(x, y, d)\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n                // Factor powers of two out of `d`.\n                // Compute largest power of two divisor of `d`.\n                // Always greater or equal to 1.\n                let twos := and(d, sub(0, d))\n                // Divide d by power of two.\n                d := div(d, twos)\n                // Divide [prod1 prod0] by the factors of two.\n                prod0 := div(prod0, twos)\n                // Shift in bits from `prod1` into `prod0`. For this we need\n                // to flip `twos` such that it is `2**256 / twos`.\n                // If `twos` is zero, then it becomes one.\n                prod0 := or(prod0, mul(prod1, add(div(sub(0, twos), twos), 1)))\n                // Invert `d mod 2**256`\n                // Now that `d` is an odd number, it has an inverse\n                // modulo `2**256` such that `d * inv = 1 mod 2**256`.\n                // Compute the inverse by starting with a seed that is correct\n                // correct for four bits. That is, `d * inv = 1 mod 2**4`.\n                let inv := xor(mul(3, d), 2)\n                // Now use Newton-Raphson iteration to improve the precision.\n                // Thanks to Hensel's lifting lemma, this also works in modular\n                // arithmetic, doubling the correct bits in each step.\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64\n                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128\n                result := mul(prod0, mul(inv, sub(2, mul(d, inv)))) // inverse mod 2**256\n                break\n            }\n        }\n    }\n\n    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.\n    /// Throws if result overflows a uint256 or when `d` is zero.\n    /// Credit to Uniswap-v3-core under MIT license:\n    /// https://github.com/Uniswap/v3-core/blob/contracts/libraries/FullMath.sol\n    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {\n        result = fullMulDiv(x, y, d);\n        /// @solidity memory-safe-assembly\n        assembly {\n            if mulmod(x, y, d) {\n                if iszero(add(result, 1)) {\n                    // Store the function selector of `FullMulDivFailed()`.\n                    mstore(0x00, 0xae47f702)\n                    // Revert with (offset, size).\n                    revert(0x1c, 0x04)\n                }\n                result := add(result, 1)\n            }\n        }\n    }\n\n    /// @dev Returns `floor(x * y / d)`.\n    /// Reverts if `x * y` overflows, or `d` is zero.\n    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n                // Store the function selector of `MulDivFailed()`.\n                mstore(0x00, 0xad251c27)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := div(mul(x, y), d)\n        }\n    }\n\n    /// @dev Returns `ceil(x * y / d)`.\n    /// Reverts if `x * y` overflows, or `d` is zero.\n    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n                // Store the function selector of `MulDivFailed()`.\n                mstore(0x00, 0xad251c27)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))\n        }\n    }\n\n    /// @dev Returns `ceil(x / d)`.\n    /// Reverts if `d` is zero.\n    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(d) {\n                // Store the function selector of `DivFailed()`.\n                mstore(0x00, 0x65244e4e)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            z := add(iszero(iszero(mod(x, d))), div(x, d))\n        }\n    }\n\n    /// @dev Returns `max(0, x - y)`.\n    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mul(gt(x, y), sub(x, y))\n        }\n    }\n\n    /// @dev Returns the square root of `x`.\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // Let `y = x / 2**r`.\n            // We check `y >= 2**(k + 8)` but shift right by `k` bits\n            // each branch to ensure that if `x >= 256`, then `y >= 256`.\n            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffffff, shr(r, x))))\n            z := shl(shr(1, r), z)\n\n            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could\n            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.\n            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.\n            // That's not possible if `x < 256` but we can just verify those cases exhaustively.\n\n            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.\n            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.\n            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.\n\n            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`\n            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,\n            // with largest error when `s = 1` and when `s = 256` or `1/256`.\n\n            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.\n            // Then we can estimate `sqrt(y)` using\n            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.\n\n            // There is no overflow risk here since `y < 2**136` after the first branch above.\n            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If `x+1` is a perfect square, the Babylonian method cycles between\n            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    /// @dev Returns the cube root of `x`.\n    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:\n    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy\n    function cbrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n\n            z := shl(add(div(r, 3), lt(0xf, shr(r, x))), 0xff)\n            z := div(z, byte(mod(r, 3), shl(232, 0x7f624b)))\n\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n            z := div(add(add(div(x, mul(z, z)), z), z), 3)\n\n            z := sub(z, lt(div(x, mul(z, z)), z))\n        }\n    }\n\n    /// @dev Returns the factorial of `x`.\n    function factorial(uint256 x) internal pure returns (uint256 result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(lt(x, 58)) {\n                // Store the function selector of `FactorialOverflow()`.\n                mstore(0x00, 0xaba0f2a2)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            for { result := 1 } x {} {\n                result := mul(result, x)\n                x := sub(x, 1)\n            }\n        }\n    }\n\n    /// @dev Returns the log2 of `x`.\n    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            if iszero(x) {\n                // Store the function selector of `Log2Undefined()`.\n                mstore(0x00, 0x5be3aa5c)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n\n            // For the remaining 32 bits, use a De Bruijn lookup.\n            // See: https://graphics.stanford.edu/~seander/bithacks.html\n            x := shr(r, x)\n            x := or(x, shr(1, x))\n            x := or(x, shr(2, x))\n            x := or(x, shr(4, x))\n            x := or(x, shr(8, x))\n            x := or(x, shr(16, x))\n\n            // forgefmt: disable-next-item\n            r := or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),\n                0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f))\n        }\n    }\n\n    /// @dev Returns the log2 of `x`, rounded up.\n    function log2Up(uint256 x) internal pure returns (uint256 r) {\n        unchecked {\n            uint256 isNotPo2;\n            assembly {\n                isNotPo2 := iszero(iszero(and(x, sub(x, 1))))\n            }\n            return log2(x) + isNotPo2;\n        }\n    }\n\n    /// @dev Returns the average of `x` and `y`.\n    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = (x & y) + ((x ^ y) >> 1);\n        }\n    }\n\n    /// @dev Returns the average of `x` and `y`.\n    function avg(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = (x >> 1) + (y >> 1) + (((x & 1) + (y & 1)) >> 1);\n        }\n    }\n\n    /// @dev Returns the absolute value of `x`.\n    function abs(int256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let mask := sub(0, shr(255, x))\n            z := xor(mask, add(mask, x))\n        }\n    }\n\n    /// @dev Returns the absolute distance between `x` and `y`.\n    function dist(int256 x, int256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let a := sub(y, x)\n            z := xor(a, mul(xor(a, sub(x, y)), sgt(x, y)))\n        }\n    }\n\n    /// @dev Returns the minimum of `x` and `y`.\n    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), lt(y, x)))\n        }\n    }\n\n    /// @dev Returns the minimum of `x` and `y`.\n    function min(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), slt(y, x)))\n        }\n    }\n\n    /// @dev Returns the maximum of `x` and `y`.\n    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), gt(y, x)))\n        }\n    }\n\n    /// @dev Returns the maximum of `x` and `y`.\n    function max(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := xor(x, mul(xor(x, y), sgt(y, x)))\n        }\n    }\n\n    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.\n    function clamp(uint256 x, uint256 minValue, uint256 maxValue)\n        internal\n        pure\n        returns (uint256 z)\n    {\n        z = min(max(x, minValue), maxValue);\n    }\n\n    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.\n    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {\n        z = min(max(x, minValue), maxValue);\n    }\n\n    /// @dev Returns greatest common divisor of `x` and `y`.\n    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // forgefmt: disable-next-item\n            for { z := x } y {} {\n                let t := y\n                y := mod(z, y)\n                z := t\n            }\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                   RAW NUMBER OPERATIONS                    */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Returns `x + y`, without checking for overflow.\n    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x + y;\n        }\n    }\n\n    /// @dev Returns `x + y`, without checking for overflow.\n    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x + y;\n        }\n    }\n\n    /// @dev Returns `x - y`, without checking for underflow.\n    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x - y;\n        }\n    }\n\n    /// @dev Returns `x - y`, without checking for underflow.\n    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x - y;\n        }\n    }\n\n    /// @dev Returns `x * y`, without checking for overflow.\n    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        unchecked {\n            z = x * y;\n        }\n    }\n\n    /// @dev Returns `x * y`, without checking for overflow.\n    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {\n        unchecked {\n            z = x * y;\n        }\n    }\n\n    /// @dev Returns `x / y`, returning 0 if `y` is zero.\n    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := div(x, y)\n        }\n    }\n\n    /// @dev Returns `x / y`, returning 0 if `y` is zero.\n    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := sdiv(x, y)\n        }\n    }\n\n    /// @dev Returns `x % y`, returning 0 if `y` is zero.\n    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mod(x, y)\n        }\n    }\n\n    /// @dev Returns `x % y`, returning 0 if `y` is zero.\n    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := smod(x, y)\n        }\n    }\n\n    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.\n    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := addmod(x, y, d)\n        }\n    }\n\n    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.\n    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := mulmod(x, y, d)\n        }\n    }\n}\n"
      },
      "lib/solmate/src/utils/SafeTransferLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n    /*//////////////////////////////////////////////////////////////\n                             ETH OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferETH(address to, uint256 amount) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Transfer the ETH and store if it succeeded or not.\n            success := call(gas(), to, amount, 0, 0, 0, 0)\n        }\n\n        require(success, \"ETH_TRANSFER_FAILED\");\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC20 OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function safeTransferFrom(\n        ERC20 token,\n        address from,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n            mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FROM_FAILED\");\n    }\n\n    function safeTransfer(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"TRANSFER_FAILED\");\n    }\n\n    function safeApprove(\n        ERC20 token,\n        address to,\n        uint256 amount\n    ) internal {\n        bool success;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Get a pointer to some free memory.\n            let freeMemoryPointer := mload(0x40)\n\n            // Write the abi-encoded calldata into memory, beginning with the function selector.\n            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n            mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n            mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n            success := and(\n                // Set success to whether the call reverted, if not we check it either\n                // returned exactly 1 (can't just be non-zero data), or had no return data.\n                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n                // Counterintuitively, this call must be positioned second to the or() call in the\n                // surrounding and() call or else returndatasize() will be zero during the computation.\n                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n            )\n        }\n\n        require(success, \"APPROVE_FAILED\");\n    }\n}\n"
      },
      "lib/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#mint\n/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface\ninterface IUniswapV3MintCallback {\n    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.\n    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.\n    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity\n    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity\n    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call\n    function uniswapV3MintCallback(\n        uint256 amount0Owed,\n        uint256 amount1Owed,\n        bytes calldata data\n    ) external;\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 './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './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    IUniswapV3PoolEvents\n{\n\n}\n"
      },
      "src/libraries/constants/Constants.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\n/// @dev The initial value of `Lender`'s `borrowIndex`\nuint256 constant ONE = 1e12;\n\n/// @dev An additional scaling factor applied to borrowed amounts before dividing by `borrowIndex` and storing.\n/// 72 matches the type of `borrowIndex` in `Ledger` to guarantee that the stored borrow units fit in uint256.\nuint256 constant BORROWS_SCALER = ONE << 72;\n\n/// @dev The maximum percentage yield per second, scaled up by 1e12. The current value is equivalent to\n/// `((1 + 706354 / 1e12) ** (24 * 60 * 60)) - 1` ⇒ +6.3% per day or +53% per week. If the rate is consistently at\n/// this maximum value, the `Lender` will function for 1 year before `borrowIndex` overflows.\n/// @custom:math\n/// > 📘 Useful Math\n/// >\n/// > - T: number of years before overflow, assuming maximum rate\n/// > - borrowIndexInit: `ONE`\n/// > - borrowIndexMax: 2^72 - 1\n/// >\n/// > - maxAPR: ln(borrowIndexMax / borrowIndexInit) / T\n/// > - maxAPY: exp(maxAPR) - 1\n/// > - MAX_RATE: (exp(maxAPR / secondsPerYear) - 1) * 1e12\nuint256 constant MAX_RATE = 706354;\n\n/*//////////////////////////////////////////////////////////////\n                        FACTORY DEFAULTS\n//////////////////////////////////////////////////////////////*/\n\n/// @dev The default amount of Ether required to take on debt in a `Borrower`. The `Factory` can override this value\n/// on a per-market basis. Incentivizes calls to `Borrower.warn`.\nuint208 constant DEFAULT_ANTE = 0.01 ether;\n\n/// @dev The default number of standard deviations of price movement used to determine probe prices for `Borrower`\n/// solvency. The `Factory` can override this value on a per-market basis. Expressed x10, e.g. 50 → 5σ\nuint8 constant DEFAULT_N_SIGMA = 50;\n\n/// @dev Assume someone is manipulating the Uniswap TWAP oracle. To steal money from the protocol and create bad debt,\n/// they would need to change the TWAP by a factor of (1 / LTV), where the LTV is a function of volatility. We have a\n/// manipulation metric that increases as an attacker tries to change the TWAP. If this metric rises above a certain\n/// threshold, certain functionality will be paused, e.g. no new debt can be created. The threshold is calculated as\n/// follows:\n///\n/// \\\\( \\text{manipulationThreshold} =\n/// \\frac{log_{1.0001}\\left( \\frac{1}{\\text{LTV}} \\right)}{\\text{MANIPULATION_THRESHOLD_DIVISOR}} \\\\)\nuint8 constant DEFAULT_MANIPULATION_THRESHOLD_DIVISOR = 12;\n\n/// @dev The default portion of interest that will accrue to a `Lender`'s `RESERVE` address.\n/// Expressed as a reciprocal, e.g. 16 → 6.25%\nuint8 constant DEFAULT_RESERVE_FACTOR = 16;\n\n/*//////////////////////////////////////////////////////////////\n                        GOVERNANCE CONSTRAINTS\n//////////////////////////////////////////////////////////////*/\n\n/// @dev The lowest number of standard deviations of price movement allowed for determining `Borrower` probe prices.\n/// Expressed x10, e.g. 40 → 4σ\nuint8 constant CONSTRAINT_N_SIGMA_MIN = 40;\n\n/// @dev The highest number of standard deviations of price movement allowed for determining `Borrower` probe prices.\n/// Expressed x10, e.g. 80 → 8σ\nuint8 constant CONSTRAINT_N_SIGMA_MAX = 80;\n\n/// @dev The minimum value of the `manipulationThresholdDivisor`, described above\nuint8 constant CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MIN = 10;\n\n/// @dev The maximum value of the `manipulationThresholdDivisor`, described above\nuint8 constant CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MAX = 16;\n\n/// @dev The lower bound on what any `Lender`'s reserve factor can be. Expressed as reciprocal, e.g. 4 → 25%\nuint8 constant CONSTRAINT_RESERVE_FACTOR_MIN = 4;\n\n/// @dev The upper bound on what any `Lender`'s reserve factor can be. Expressed as reciprocal, e.g. 20 → 5%\nuint8 constant CONSTRAINT_RESERVE_FACTOR_MAX = 20;\n\n/// @dev The maximum amount of Ether that `Borrower`s can be required to post before taking on debt\nuint216 constant CONSTRAINT_ANTE_MAX = 0.5 ether;\n\n/*//////////////////////////////////////////////////////////////\n                            LIQUIDATION\n//////////////////////////////////////////////////////////////*/\n\n/// @dev \\\\( 1 + \\frac{1}{\\text{MAX_LEVERAGE}} \\\\) should be greater than the maximum feasible single-block\n/// `accrualFactor` so that liquidators have time to respond to interest updates\nuint256 constant MAX_LEVERAGE = 200;\n\n/// @dev The minimum discount that a healthy `Borrower` should be able to offer a liquidator when swapping\n/// assets. Expressed as reciprocal, e.g. 20 → 5%\nuint256 constant LIQUIDATION_INCENTIVE = 20;\n\n/// @dev The minimum time that must pass between calls to `Borrower.warn` and `Borrower.liquidate`.\nuint256 constant LIQUIDATION_GRACE_PERIOD = 5 minutes;\n\n/// @dev The minimum `closeFactor` necessary to conclude a liquidation auction. To actually conclude the auction,\n/// `Borrower.liquidate` must result in a healthy balance sheet (in addition to this `closeFactor` requirement).\n/// Expressed in basis points.\n/// NOTE: The ante is depleted after just 4 `Borrower.warn`ings. By requiring that each auction repay at least\n/// 68%, we ensure that after 4 auctions, no more than 1% of debt remains ((1 - 0.6838)^4). Increasing the threshold\n/// would reduce that further, but we don't want to prolong individual auctions unnecessarily since the incentive\n/// (and loss to `Borrower`s) increases with time.\nuint256 constant TERMINATING_CLOSE_FACTOR = 6837;\n\n/// @dev The minimum scaling factor by which `sqrtMeanPriceX96` is multiplied or divided to get probe prices\nuint256 constant PROBE_SQRT_SCALER_MIN = 1.026248453011e12;\n\n/// @dev The maximum scaling factor by which `sqrtMeanPriceX96` is multiplied or divided to get probe prices\nuint256 constant PROBE_SQRT_SCALER_MAX = 3.078745359035e12;\n\n/// @dev Equivalent to \\\\( \\frac{10^{36}}{1 + \\frac{1}{liquidationIncentive} + \\frac{1}{maxLeverage}} \\\\)\nuint256 constant LTV_NUMERATOR = uint256(LIQUIDATION_INCENTIVE * MAX_LEVERAGE * 1e36) /\n    (LIQUIDATION_INCENTIVE * MAX_LEVERAGE + LIQUIDATION_INCENTIVE + MAX_LEVERAGE);\n\n/// @dev The minimum loan-to-value ratio. Actual ratio is based on implied volatility; this is just a lower bound.\n/// Expressed as a 1e12 percentage, e.g. 0.10e12 → 10%. Must be greater than `TickMath.MIN_SQRT_RATIO` because\n/// we reuse a base 1.0001 logarithm in `BalanceSheet`\nuint256 constant LTV_MIN = LTV_NUMERATOR / (PROBE_SQRT_SCALER_MAX * PROBE_SQRT_SCALER_MAX);\n\n/// @dev The maximum loan-to-value ratio. Actual ratio is based on implied volatility; this is just a upper bound.\n/// Expressed as a 1e12 percentage, e.g. 0.90e12 → 90%\nuint256 constant LTV_MAX = LTV_NUMERATOR / (PROBE_SQRT_SCALER_MIN * PROBE_SQRT_SCALER_MIN);\n\n/*//////////////////////////////////////////////////////////////\n                            IV AND TWAP\n//////////////////////////////////////////////////////////////*/\n\n/// @dev The timescale of implied volatility, applied to measurements and calculations. When `BalanceSheet` detects\n/// that an `nSigma` event would cause insolvency in this time period, it enables liquidations. So if you squint your\n/// eyes and wave your hands enough, this is (in expectation) the time liquidators have to act before the protocol\n/// accrues bad debt.\nuint32 constant IV_SCALE = 24 hours;\n\n/// @dev The initial value of implied volatility, used when `VolatilityOracle.prepare` is called for a new pool.\n/// Expressed as a 1e12 percentage at `IV_SCALE`, e.g. {0.12e12, 24 hours} → 12% daily → 229% annual. Error on the\n/// side of making this too large (resulting in low LTV).\nuint104 constant IV_COLD_START = 0.127921282726e12;\n\n/// @dev The maximum rate at which (reported) implied volatility can change. Raw samples in `VolatilityOracle.update`\n/// are clamped (before being stored) so as not to exceed this rate.\n/// Expressed in 1e12 percentage points at `IV_SCALE` **per second**, e.g. {115740, 24 hours} means daily IV can\n/// change by 0.0000116 percentage points per second → 1 percentage point per day.\nuint256 constant IV_CHANGE_PER_SECOND = 115740;\n\n/// @dev The maximum amount by which (reported) implied volatility can change with a single `VolatilityOracle.update`\n/// call. If updates happen as frequently as possible (every `FEE_GROWTH_SAMPLE_PERIOD`), this cap is no different\n/// from `IV_CHANGE_PER_SECOND` alone.\nuint104 constant IV_CHANGE_PER_UPDATE = uint104(IV_CHANGE_PER_SECOND * FEE_GROWTH_SAMPLE_PERIOD);\n\n/// @dev The gain on the EMA update when IV is increasing. Expressed as reciprocal, e.g. 20 → 0.05\nint256 constant IV_EMA_GAIN_POS = 20;\n\n/// @dev The gain on the EMA update when IV is decreasing. Expressed as reciprocal, e.g. 100 → 0.01\nint256 constant IV_EMA_GAIN_NEG = 100;\n\n/// @dev To estimate volume, we need 2 samples. One is always at the current block, the other is from\n/// `FEE_GROWTH_AVG_WINDOW` seconds ago, +/- `FEE_GROWTH_SAMPLE_PERIOD / 2`. Larger values make the resulting volume\n/// estimate more robust, but may cause the oracle to miss brief spikes in activity.\nuint256 constant FEE_GROWTH_AVG_WINDOW = 72 hours;\n\n/// @dev The length of the circular buffer that stores feeGrowthGlobals samples.\n/// Must be in interval\n/// \\\\( \\left[ \\frac{\\text{FEE_GROWTH_AVG_WINDOW}}{\\text{FEE_GROWTH_SAMPLE_PERIOD}}, 256 \\right) \\\\)\nuint256 constant FEE_GROWTH_ARRAY_LENGTH = 32;\n\n/// @dev The minimum number of seconds that must elapse before a new feeGrowthGlobals sample will be stored. This\n/// controls how often the oracle can update IV.\nuint256 constant FEE_GROWTH_SAMPLE_PERIOD = 4 hours;\n\n/// @dev To compute Uniswap mean price & liquidity, we need 2 samples. One is always at the current block, the other is\n/// from `UNISWAP_AVG_WINDOW` seconds ago. Larger values make the resulting price/liquidity values harder to\n/// manipulate, but also make the oracle slower to respond to changes.\nuint32 constant UNISWAP_AVG_WINDOW = 30 minutes;\n"
      },
      "src/libraries/BalanceSheet.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\n\nimport {\n    MAX_LEVERAGE,\n    LIQUIDATION_INCENTIVE,\n    LIQUIDATION_GRACE_PERIOD,\n    PROBE_SQRT_SCALER_MIN,\n    PROBE_SQRT_SCALER_MAX,\n    LTV_NUMERATOR\n} from \"./constants/Constants.sol\";\nimport {exp1e12} from \"./Exp.sol\";\nimport {square, mulDiv128, mulDiv128Up} from \"./MulDiv.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\nstruct AuctionAmounts {\n    // The amount of `TOKEN0` sent to the liquidator in exchange for repaying `repay0` and `repay1`\n    uint256 out0;\n    // The amount of `TOKEN1` sent to the liquidator in exchange for repaying `repay0` and `repay1`\n    uint256 out1;\n    // The amount of `TOKEN0` the liquidator must send to `LENDER0` in order to complete the liquidation\n    uint256 repay0;\n    // The amount of `TOKEN1` the liquidator must send to `LENDER1` in order to complete the liquidation\n    uint256 repay1;\n}\n\nstruct Assets {\n    // `TOKEN0.balanceOf(borrower)`, plus the amount of `TOKEN0` underlying its Uniswap liquidity at `Prices.a`\n    uint256 amount0AtA;\n    // `TOKEN1.balanceOf(borrower)`, plus the amount of `TOKEN1` underlying its Uniswap liquidity at `Prices.a`\n    uint256 amount1AtA;\n    // `TOKEN0.balanceOf(borrower)`, plus the amount of `TOKEN0` underlying its Uniswap liquidity at `Prices.b`\n    uint256 amount0AtB;\n    // `TOKEN1.balanceOf(borrower)`, plus the amount of `TOKEN1` underlying its Uniswap liquidity at `Prices.b`\n    uint256 amount1AtB;\n}\n\nstruct Prices {\n    // Some sqrtPriceX96 *less* than the current TWAP\n    uint160 a;\n    // Some sqrtPriceX96 *greater* than the current TWAP\n    uint160 b;\n    // The current TWAP, expressed as a sqrtPriceX96\n    uint160 c;\n}\n\n/// @title BalanceSheet\n/// @notice Provides functions for computing a `Borrower`'s health\n/// @author Aloe Labs, Inc.\nlibrary BalanceSheet {\n    using SoladyMath for uint256;\n\n    // During liquidation auctions, the usable fraction is given by S + (R / (N - t)) - (Q / (M + 1000000t)),\n    // where `t` is the time elapsed since the end of the `LIQUIDATION_GRACE_PERIOD`.\n    //\n    // | time since warning |      t | usable fraction |\n    // | ------------------ | ------ | --------------- |\n    // | 0 minutes          |      0 |              0% |\n    // | 1 minute           |      0 |              0% |\n    // | 4 minutes          |      0 |              0% |\n    // | 5 minutes          |      0 |              0% |\n    // | 5 minutes + 12 sec |     12 |             42% |\n    // | 5 minutes + 24 sec |     24 |             61% |\n    // | 6 minutes          |     60 |             84% |\n    // | 7 minutes          |    132 |             96% |\n    // | 10 minutes         |    300 |            105% |\n    // | 60 minutes         |   3300 |            112% |\n    // | ~1 days            |  86100 |            115% |\n    // | ~3 days            | 258900 |            125% |\n    // | ~7 days            | 604500 |               ∞ |\n    //\n    uint256 private constant _Q = 22.8811827075e18;\n    uint256 private constant _R = 103567.889099532e12;\n    uint256 private constant _S = 0.95e12;\n    uint256 private constant _M = 20.405429e6;\n    uint256 private constant _N = 7 days - LIQUIDATION_GRACE_PERIOD;\n\n    function auctionTime(uint256 warnTime) internal view returns (uint256) {\n        unchecked {\n            require(warnTime > 0 && block.timestamp >= warnTime + LIQUIDATION_GRACE_PERIOD, \"Aloe: grace\");\n            return block.timestamp - (warnTime + LIQUIDATION_GRACE_PERIOD);\n        }\n    }\n\n    function auctionCurve(uint256 t) internal pure returns (uint256) {\n        unchecked {\n            return _S + _R.rawDiv(_N - t) - _Q.rawDiv(_M + 1e6 * t);\n        }\n    }\n\n    function computeAuctionAmounts(\n        uint160 sqrtPriceX96,\n        uint256 assets0,\n        uint256 assets1,\n        uint256 liabilities0,\n        uint256 liabilities1,\n        uint256 t,\n        uint256 closeFactor\n    ) internal pure returns (AuctionAmounts memory amounts) {\n        uint256 priceX128 = square(sqrtPriceX96);\n        uint256 liabilities = liabilities1 + mulDiv128Up(liabilities0, priceX128);\n        uint256 assets = assets1 + mulDiv128Up(assets0, priceX128);\n\n        unchecked {\n            if (t < _N) {\n                liabilities *= auctionCurve(t);\n                assets *= 1e12;\n\n                if (liabilities < assets) {\n                    assets0 = assets0.fullMulDiv(liabilities, assets);\n                    assets1 = assets1.fullMulDiv(liabilities, assets);\n                }\n            }\n\n            // All amounts scale with `closeFactor`\n            amounts.out0 = (assets0 * closeFactor) / 10000;\n            amounts.out1 = (assets1 * closeFactor) / 10000;\n            amounts.repay0 = (liabilities0 * closeFactor).divUp(10000);\n            amounts.repay1 = (liabilities1 * closeFactor).divUp(10000);\n        }\n    }\n\n    /**\n     * @dev Checks whether a `Borrower` is healthy given the probe prices and its current assets and liabilities.\n     * Should be used when `assets` at `prices.a` differ from those at `prices.b` (due to Uniswap positions).\n     */\n    function isHealthy(\n        Prices memory prices,\n        Assets memory assets,\n        uint256 liabilities0,\n        uint256 liabilities1\n    ) internal pure returns (bool) {\n        unchecked {\n            uint256 augmented0;\n            uint256 augmented1;\n\n            // The optimizer eliminates the conditional in `divUp`; don't worry about gas golfing that\n            augmented0 =\n                liabilities0 +\n                liabilities0.divUp(MAX_LEVERAGE) +\n                liabilities0.zeroFloorSub(assets.amount0AtA).divUp(LIQUIDATION_INCENTIVE);\n            augmented1 =\n                liabilities1 +\n                liabilities1.divUp(MAX_LEVERAGE) +\n                liabilities1.zeroFloorSub(assets.amount1AtA).divUp(LIQUIDATION_INCENTIVE);\n\n            if (!isSolvent(prices.a, assets.amount0AtA, assets.amount1AtA, augmented0, augmented1)) return false;\n\n            augmented0 =\n                liabilities0 +\n                liabilities0.divUp(MAX_LEVERAGE) +\n                liabilities0.zeroFloorSub(assets.amount0AtB).divUp(LIQUIDATION_INCENTIVE);\n            augmented1 =\n                liabilities1 +\n                liabilities1.divUp(MAX_LEVERAGE) +\n                liabilities1.zeroFloorSub(assets.amount1AtB).divUp(LIQUIDATION_INCENTIVE);\n\n            if (!isSolvent(prices.b, assets.amount0AtB, assets.amount1AtB, augmented0, augmented1)) return false;\n\n            return true;\n        }\n    }\n\n    /**\n     * @dev Checks whether a `Borrower` is healthy given the probe prices and its current assets and liabilities.\n     * Can be used when `assets` at `prices.a` are the same as those at `prices.b` (no Uniswap positions).\n     */\n    function isHealthy(\n        Prices memory prices,\n        uint256 assets0,\n        uint256 assets1,\n        uint256 liabilities0,\n        uint256 liabilities1\n    ) internal pure returns (bool) {\n        unchecked {\n            // The optimizer eliminates the conditional in `divUp`; don't worry about gas golfing that\n            liabilities0 +=\n                liabilities0.divUp(MAX_LEVERAGE) +\n                liabilities0.zeroFloorSub(assets0).divUp(LIQUIDATION_INCENTIVE);\n            liabilities1 +=\n                liabilities1.divUp(MAX_LEVERAGE) +\n                liabilities1.zeroFloorSub(assets1).divUp(LIQUIDATION_INCENTIVE);\n\n            if (!isSolvent(prices.a, assets0, assets1, liabilities0, liabilities1)) return false;\n            if (!isSolvent(prices.b, assets0, assets1, liabilities0, liabilities1)) return false;\n            return true;\n        }\n    }\n\n    function isSolvent(\n        uint160 sqrtPriceX96,\n        uint256 assets0,\n        uint256 assets1,\n        uint256 liabilities0,\n        uint256 liabilities1\n    ) internal pure returns (bool) {\n        uint256 priceX128 = square(sqrtPriceX96);\n        uint256 liabilities = liabilities1 + mulDiv128Up(liabilities0, priceX128);\n        uint256 assets = assets1 + mulDiv128(assets0, priceX128);\n        return assets >= liabilities;\n    }\n\n    /**\n     * Given data from the `ORACLE` (first 3 args) and parameters from the `FACTORY` (last 2 args), computes\n     * the probe prices at which to check the account's health\n     * @param metric The manipulation metric (from oracle)\n     * @param sqrtMeanPriceX96 The current TWAP, expressed as a sqrtPriceX96 (from oracle)\n     * @param iv The estimated implied volatility, expressed as a 1e12 percentage (from oracle)\n     * @param nSigma The number of standard deviations of price movement to account for (from factory)\n     * @param manipulationThresholdDivisor Helps compute the manipulation threshold (from factory). See `Constants.sol`\n     * @return a \\\\( \\text{TWAP} \\cdot e^{-n \\cdot \\sigma} \\\\) expressed as a sqrtPriceX96\n     * @return b \\\\( \\text{TWAP} \\cdot e^{+n \\cdot \\sigma} \\\\) expressed as a sqrtPriceX96\n     * @return seemsLegit Whether the Uniswap TWAP has been manipulated enough to create bad debt at the effective LTV\n     */\n    function computeProbePrices(\n        uint56 metric,\n        uint256 sqrtMeanPriceX96,\n        uint256 iv,\n        uint8 nSigma,\n        uint8 manipulationThresholdDivisor\n    ) internal pure returns (uint160 a, uint160 b, bool seemsLegit) {\n        unchecked {\n            // Essentially sqrt(e^{nSigma*iv}). Note the `Factory` defines `nSigma` with an extra factor of 10\n            uint256 sqrtScaler = uint256(exp1e12(int256((nSigma * iv) / 20))).clamp(\n                PROBE_SQRT_SCALER_MIN,\n                PROBE_SQRT_SCALER_MAX\n            );\n\n            seemsLegit = metric < _manipulationThreshold(_ltv(sqrtScaler), manipulationThresholdDivisor);\n\n            a = uint160((sqrtMeanPriceX96 * 1e12).rawDiv(sqrtScaler).max(TickMath.MIN_SQRT_RATIO));\n            b = uint160((sqrtMeanPriceX96 * sqrtScaler).rawDiv(1e12).min(TickMath.MAX_SQRT_RATIO));\n        }\n    }\n\n    /// @dev Equivalent to \\\\( \\frac{log_{1.0001} \\left( \\frac{10^{12}}{ltv} \\right)}{\\text{MANIPULATION_THRESHOLD_DIVISOR}} \\\\)\n    function _manipulationThreshold(uint160 ltv, uint8 manipulationThresholdDivisor) private pure returns (uint24) {\n        unchecked {\n            return uint24(-TickMath.getTickAtSqrtRatio(ltv) - 778261) / (2 * manipulationThresholdDivisor);\n        }\n    }\n\n    /**\n     * @notice The effective LTV implied by `sqrtScaler`. This LTV is accurate for fixed assets and out-of-range\n     * Uniswap positions, but not for in-range Uniswap positions (impermanent losses make their effective LTV\n     * slightly smaller).\n     */\n    function _ltv(uint256 sqrtScaler) private pure returns (uint160 ltv) {\n        unchecked {\n            ltv = uint160(LTV_NUMERATOR.rawDiv(sqrtScaler * sqrtScaler));\n        }\n    }\n}\n"
      },
      "src/libraries/LiquidityAmounts.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.23;\n\nimport {Math} from \"openzeppelin-contracts/contracts/utils/math/Math.sol\";\n\nimport {square, mulDiv96, mulDiv224} from \"./MulDiv.sol\";\n\n/// @title LiquidityAmounts\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\n/// @author Aloe Labs, Inc.\n/// @author Modified from [Uniswap](https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/LiquidityAmounts.sol)\nlibrary LiquidityAmounts {\n    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n    /// pool prices and the prices at the tick boundaries\n    /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n    /// @param liquidity The liquidity being valued\n    /// @return amount0 The amount of token0\n    /// @return amount1 The amount of token1\n    function getAmountsForLiquidity(\n        uint160 sqrtRatioX96,\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity\n    ) internal pure returns (uint256 amount0, uint256 amount1) {\n        assert(sqrtRatioAX96 <= sqrtRatioBX96);\n\n        if (sqrtRatioX96 <= sqrtRatioAX96) {\n            amount0 = _getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n        } else if (sqrtRatioX96 < sqrtRatioBX96) {\n            amount0 = _getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n            amount1 = _getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n        } else {\n            amount1 = _getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n        }\n    }\n\n    /// @notice Computes the value of each portion of the liquidity in terms of token1\n    /// @dev Each return value can fit in a uint192 if necessary\n    /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n    /// @param sqrtRatioAX96 A sqrt price representing the lower tick boundary\n    /// @param sqrtRatioBX96 A sqrt price representing the upper tick boundary\n    /// @param liquidity The liquidity being valued\n    /// @return value0 The value of amount0 underlying `liquidity`, in terms of token1\n    /// @return value1 The amount of token1\n    function getValuesOfLiquidity(\n        uint160 sqrtRatioX96,\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity\n    ) internal pure returns (uint256 value0, uint256 value1) {\n        assert(sqrtRatioAX96 <= sqrtRatioBX96);\n\n        unchecked {\n            if (sqrtRatioX96 <= sqrtRatioAX96) {\n                uint256 priceX128 = square(sqrtRatioX96);\n                uint256 amount0XSqrtRatioAX64 = Math.mulDiv(\n                    uint256(liquidity) << 64,\n                    sqrtRatioBX96 - sqrtRatioAX96,\n                    sqrtRatioBX96\n                );\n\n                value0 = Math.mulDiv(amount0XSqrtRatioAX64, priceX128, uint256(sqrtRatioAX96) << 96);\n            } else if (sqrtRatioX96 < sqrtRatioBX96) {\n                uint256 numerator = Math.mulDiv(uint256(liquidity) << 128, sqrtRatioX96, sqrtRatioBX96);\n\n                value0 = mulDiv224(numerator, sqrtRatioBX96 - sqrtRatioX96);\n                value1 = mulDiv96(liquidity, sqrtRatioX96 - sqrtRatioAX96);\n            } else {\n                value1 = mulDiv96(liquidity, sqrtRatioBX96 - sqrtRatioAX96);\n            }\n        }\n    }\n\n    /// @notice Computes the value of the liquidity in terms of token1\n    /// @dev The return value can fit in a uint192 if necessary\n    /// @param sqrtRatioX96 A sqrt price representing the current pool prices\n    /// @param sqrtRatioAX96 A sqrt price representing the lower tick boundary\n    /// @param sqrtRatioBX96 A sqrt price representing the upper tick boundary\n    /// @param liquidity The liquidity being valued\n    /// @return The value of the underlying `liquidity`, in terms of token1\n    function getValueOfLiquidity(\n        uint160 sqrtRatioX96,\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity\n    ) internal pure returns (uint256) {\n        (uint256 value0, uint256 value1) = getValuesOfLiquidity(sqrtRatioX96, sqrtRatioAX96, sqrtRatioBX96, liquidity);\n        unchecked {\n            return value0 + value1;\n        }\n    }\n\n    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n    /// @param liquidity The liquidity being valued\n    /// @return amount0 The amount of token0. Will fit in a uint224 if you need it to\n    function _getAmount0ForLiquidity(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity\n    ) private pure returns (uint256 amount0) {\n        amount0 = Math.mulDiv(uint256(liquidity) << 96, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96) / sqrtRatioAX96;\n    }\n\n    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary\n    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary\n    /// @param liquidity The liquidity being valued\n    /// @return amount1 The amount of token1. Will fit in a uint192 if you need it to\n    function _getAmount1ForLiquidity(\n        uint160 sqrtRatioAX96,\n        uint160 sqrtRatioBX96,\n        uint128 liquidity\n    ) private pure returns (uint256 amount1) {\n        amount1 = mulDiv96(liquidity, sqrtRatioBX96 - sqrtRatioAX96);\n    }\n}\n"
      },
      "src/libraries/Positions.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {Q24, Q48} from \"./constants/Q.sol\"; // solhint-disable-line no-unused-import\n\n/**\n * @notice Compresses `positions` into `zipped`. Useful for creating the return value of `IManager.callback`\n * @param positions A flattened array of ticks, each consecutive pair of indices representing one Uniswap position\n * @param zipped Encoded Uniswap positions\n */\nfunction zip(int24[6] memory positions) pure returns (uint144 zipped) {\n    assembly (\"memory-safe\") {\n        zipped := mod(mload(positions), Q24)\n        zipped := add(zipped, shl(24, mod(mload(add(positions, 32)), Q24)))\n        zipped := add(zipped, shl(48, mod(mload(add(positions, 64)), Q24)))\n        zipped := add(zipped, shl(72, mod(mload(add(positions, 96)), Q24)))\n        zipped := add(zipped, shl(96, mod(mload(add(positions, 128)), Q24)))\n        zipped := add(zipped, shl(120, mod(mload(add(positions, 160)), Q24)))\n    }\n}\n\n/**\n * @notice Extracts up to three Uniswap positions from `zipped`. Each position consists of an `int24 lower` and\n * `int24 upper`, and will be included in the output array *iff* `lower != upper`. The output array is flattened\n * such that lower and upper ticks are next to each other, e.g. one position may be at indices 0 & 1, and another\n * at indices 2 & 3.\n * @dev The output array's length will be one of {0, 2, 4, 6}. We do *not* validate that `lower < upper`, nor do\n * we check whether positions actually hold liquidity. Also note that this function will revert if `zipped`\n * contains duplicate positions like [-100, 100, -100, 100].\n * @param zipped Encoded Uniswap positions. Equivalent to the layout of `int24[6] storage yourPositions`\n * @return positionsOfNonZeroWidth Flattened array of Uniswap positions that may or may not hold liquidity\n */\nfunction extract(uint256 zipped) pure returns (int24[] memory positionsOfNonZeroWidth) {\n    assembly (\"memory-safe\") {\n        // zipped:\n        // -->  xl + (xu << 24) + (yl << 48) + (yu << 72) + (zl << 96) + (zu << 120)\n        // -->  |-------|-----|----|----|----|----|----|\n        //      | shift | 120 | 96 | 72 | 48 | 24 |  0 |\n        //      | value |  zu | zl | yu | yl | xu | xl |\n        //      |-------|-----|----|----|----|----|----|\n\n        positionsOfNonZeroWidth := mload(0x40)\n        let offset := 32\n\n        // if xl != xu\n        let l := mod(zipped, Q24)\n        let u := mod(shr(24, zipped), Q24)\n        if iszero(eq(l, u)) {\n            mstore(add(positionsOfNonZeroWidth, 32), l)\n            mstore(add(positionsOfNonZeroWidth, 64), u)\n            offset := 96\n        }\n\n        // if yl != yu\n        l := mod(shr(48, zipped), Q24)\n        u := mod(shr(72, zipped), Q24)\n        if iszero(eq(l, u)) {\n            let isSameAsX := eq(mod(shr(48, zipped), Q48), mod(zipped, Q48))\n            if isSameAsX {\n                // revert with `DuplicatePosition()`\n                mstore(0x00, 0xe13355df)\n                revert(0x1c, 0x04)\n            }\n\n            mstore(add(positionsOfNonZeroWidth, offset), l)\n            mstore(add(positionsOfNonZeroWidth, add(offset, 32)), u)\n            offset := add(offset, 64)\n        }\n\n        // if zl != zu\n        l := mod(shr(96, zipped), Q24)\n        u := mod(shr(120, zipped), Q24)\n        if iszero(eq(l, u)) {\n            let isSameAsX := eq(mod(shr(96, zipped), Q48), mod(zipped, Q48))\n            let isSameAsY := eq(mod(shr(96, zipped), Q48), mod(shr(48, zipped), Q48))\n            if or(isSameAsX, isSameAsY) {\n                // revert with `DuplicatePosition()`\n                mstore(0x00, 0xe13355df)\n                revert(0x1c, 0x04)\n            }\n\n            mstore(add(positionsOfNonZeroWidth, offset), l)\n            mstore(add(positionsOfNonZeroWidth, add(offset, 32)), u)\n            offset := add(offset, 64)\n        }\n\n        mstore(positionsOfNonZeroWidth, shr(5, sub(offset, 32)))\n        mstore(0x40, add(positionsOfNonZeroWidth, offset))\n    }\n}\n"
      },
      "src/libraries/TickMath.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. \\\\(\\sqrt{1.0001^{tick}}\\\\) as fixed point Q64.96 numbers. Supports\n/// prices between \\\\(2^{-128}\\\\) and \\\\(2^{128}\\\\)\n/// @author Aloe Labs, Inc.\n/// @author Modified from [Uniswap](https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/TickMath.sol) and\n/// [Aperture Finance](https://github.com/Aperture-Finance/uni-v3-lib/blob/main/src/TickMath.sol)\nlibrary TickMath {\n    /// @dev The minimum tick that may be passed to `getSqrtRatioAtTick` computed from \\\\( log_{1.0001}2^{-128} \\\\)\n    int24 internal constant MIN_TICK = -887272;\n    /// @dev The maximum tick that may be passed to `getSqrtRatioAtTick` computed from \\\\( log_{1.0001}2^{128} \\\\)\n    int24 internal constant MAX_TICK = 887272;\n\n    /// @dev The minimum value that can be returned from `getSqrtRatioAtTick`. Equivalent to `getSqrtRatioAtTick(MIN_TICK)`\n    uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n    /// @dev The maximum value that can be returned from `getSqrtRatioAtTick`. Equivalent to `getSqrtRatioAtTick(MAX_TICK)`\n    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1`\n    uint160 private constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE =\n        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;\n\n    /* solhint-disable code-complexity */\n\n    /// @notice Calculates \\\\( \\sqrt{1.0001^{tick}} * 2^{96} \\\\)\n    /// @dev Throws if |tick| > max tick\n    /// @param tick The input tick for the above formula\n    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n    /// at the given tick\n    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n        unchecked {\n            int256 tick256;\n            uint256 absTick;\n\n            assembly (\"memory-safe\") {\n                // sign extend to make tick an int256 in twos complement\n                tick256 := signextend(2, tick)\n\n                // compute absolute value (in-lined method from solady)\n                // --> mask = 0 if x >= 0 else -1\n                let mask := sub(0, slt(tick256, 0))\n                // --> If x >= 0, |x| = x = 0 ^ x\n                // --> If x < 0, |x| = ~~|x| = ~(-|x| - 1) = ~(x - 1) = -1 ^ (x - 1)\n                // --> Either case, |x| = mask ^ (x + mask)\n                absTick := xor(mask, add(mask, tick256))\n\n                // Equivalent: if (absTick > MAX_TICK) revert(\"T\")\n                if gt(absTick, MAX_TICK) {\n                    // selector \"Error(string)\", [0x1c, 0x20)\n                    mstore(0, 0x08c379a0)\n                    // abi encoding offset\n                    mstore(0x20, 0x20)\n                    // reason string length 1 and 'T', [0x5f, 0x61)\n                    mstore(0x41, 0x0154)\n                    // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason\n                    revert(0x1c, 0x45)\n                }\n            }\n\n            // Equivalent: ratio = 2**128 / sqrt(1.0001) if absTick & 0x1 else 1 << 128\n            uint256 ratio;\n            assembly (\"memory-safe\") {\n                ratio := and(\n                    shr(\n                        // 128 if absTick & 0x1 else 0\n                        shl(7, and(absTick, 0x1)),\n                        // upper 128 bits of 2**256 / sqrt(1.0001) where the 128th bit is 1\n                        0xfffcb933bd6fad37aa2d162d1a59400100000000000000000000000000000000\n                    ),\n                    0x1ffffffffffffffffffffffffffffffff // mask lower 129 bits\n                )\n            }\n            // Iterate through 1st to 19th bit of absTick because MAX_TICK < 2**20\n            // Equivalent to:\n            //      for i in range(1, 20):\n            //          if absTick & 2 ** i:\n            //              ratio = ratio * (2 ** 128 / 1.0001 ** (2 ** (i - 1))) / 2 ** 128\n            if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n            if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n            if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n            if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n            if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n            if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n            if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n            if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n            if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n            if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n            if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n            if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n            if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n            if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n            if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n            if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n            if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n            if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n            if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n            // Equivalent: if (tick > 0) ratio = type(uint256).max / ratio\n            assembly (\"memory-safe\") {\n                if sgt(tick256, 0) {\n                    ratio := div(not(0), ratio)\n                }\n            }\n\n            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n            assembly (\"memory-safe\") {\n                sqrtPriceX96 := shr(32, add(ratio, 0xffffffff))\n            }\n        }\n    }\n\n    /* solhint-enable code-complexity */\n\n    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n    /// ever return.\n    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n        // Equivalent: require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, \"R\")\n        assembly (\"memory-safe\") {\n            // if sqrtPriceX96 < MIN_SQRT_RATIO, the `sub` underflows and `gt` is true\n            // if sqrtPriceX96 >= MAX_SQRT_RATIO, sqrtPriceX96 - MIN_SQRT_RATIO > MAX_SQRT_RATIO - MAX_SQRT_RATIO - 1\n            if gt(sub(sqrtPriceX96, MIN_SQRT_RATIO), MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) {\n                // selector \"Error(string)\", [0x1c, 0x20)\n                mstore(0, 0x08c379a0)\n                // abi encoding offset\n                mstore(0x20, 0x20)\n                // reason string length 1 and 'R', [0x5f, 0x61)\n                mstore(0x41, 0x0152)\n                // 4 byte selector + 32 byte offset + 32 byte length + 1 byte reason\n                revert(0x1c, 0x45)\n            }\n        }\n\n        // Compute the integer part of the logarithm\n        // n ∈ [32, 160) so it could fit in uint8 if we wanted\n        uint256 n = SoladyMath.log2(sqrtPriceX96);\n\n        int256 log_2;\n        assembly (\"memory-safe\") {\n            log_2 := shl(64, sub(n, 96))\n            let r := shr(sub(n, 31), shl(96, sqrtPriceX96))\n\n            r := shr(127, mul(r, r))\n            let f := shr(128, r)\n            log_2 := or(log_2, shl(63, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(62, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(61, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(60, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(59, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(58, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(57, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(56, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(55, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(54, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(53, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(52, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(51, f))\n            r := shr(f, r)\n\n            r := shr(127, mul(r, r))\n            f := shr(128, r)\n            log_2 := or(log_2, shl(50, f))\n        }\n\n        unchecked {\n            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n            tick = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n            // Equivalent: tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow\n            if (tickLow != tick) {\n                uint160 sqrtRatioAtTickHi = getSqrtRatioAtTick(tick);\n                assembly (\"memory-safe\") {\n                    tick := sub(tick, gt(sqrtRatioAtTickHi, sqrtPriceX96))\n                }\n            }\n        }\n    }\n\n    /// @notice Rounds down to the nearest tick where tick % tickSpacing == 0\n    /// @param tick The tick to round\n    /// @param tickSpacing The tick spacing to round to\n    /// @return the floored tick\n    /// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24\n    function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {\n        int24 mod = tick % tickSpacing;\n\n        unchecked {\n            if (mod >= 0) return tick - mod;\n            return tick - mod - tickSpacing;\n        }\n    }\n\n    /// @notice Rounds up to the nearest tick where tick % tickSpacing == 0\n    /// @param tick The tick to round\n    /// @param tickSpacing The tick spacing to round to\n    /// @return the ceiled tick\n    /// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24\n    function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {\n        int24 mod = tick % tickSpacing;\n\n        unchecked {\n            if (mod > 0) return tick - mod + tickSpacing;\n            return tick - mod;\n        }\n    }\n}\n"
      },
      "src/Factory.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {ClonesWithImmutableArgs} from \"clones-with-immutable-args/ClonesWithImmutableArgs.sol\";\nimport {ERC20, SafeTransferLib} from \"solmate/utils/SafeTransferLib.sol\";\nimport {IUniswapV3Pool} from \"v3-core/contracts/interfaces/IUniswapV3Pool.sol\";\n\nimport {\n    DEFAULT_ANTE,\n    DEFAULT_N_SIGMA,\n    DEFAULT_MANIPULATION_THRESHOLD_DIVISOR,\n    DEFAULT_RESERVE_FACTOR,\n    CONSTRAINT_N_SIGMA_MIN,\n    CONSTRAINT_N_SIGMA_MAX,\n    CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MIN,\n    CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MAX,\n    CONSTRAINT_RESERVE_FACTOR_MIN,\n    CONSTRAINT_RESERVE_FACTOR_MAX,\n    CONSTRAINT_ANTE_MAX,\n    UNISWAP_AVG_WINDOW\n} from \"./libraries/constants/Constants.sol\";\n\nimport {Borrower} from \"./Borrower.sol\";\nimport {Lender} from \"./Lender.sol\";\nimport {IRateModel} from \"./RateModel.sol\";\nimport {VolatilityOracle} from \"./VolatilityOracle.sol\";\n\n/// @title Factory\n/// @author Aloe Labs, Inc.\n/// @dev \"Test everything; hold fast what is good.\" - 1 Thessalonians 5:21\ncontract Factory {\n    using ClonesWithImmutableArgs for address;\n    using SafeTransferLib for ERC20;\n\n    event CreateMarket(IUniswapV3Pool indexed pool, Lender lender0, Lender lender1);\n\n    event CreateBorrower(IUniswapV3Pool indexed pool, address indexed owner, Borrower account);\n\n    event EnrollCourier(uint32 indexed id, address indexed wallet, uint16 cut);\n\n    event SetMarketConfig(IUniswapV3Pool indexed pool, MarketConfig config);\n\n    // This `Factory` can create a `Market` for any Uniswap V3 pool\n    struct Market {\n        // The `Lender` of `token0` in the Uniswap pool\n        Lender lender0;\n        // The `Lender` of `token1` in the Uniswap pool\n        Lender lender1;\n        // The implementation to which all `Borrower` clones will point\n        Borrower borrowerImplementation;\n    }\n\n    // Each `Market` has a set of borrowing `Parameters` to help manage risk\n    struct Parameters {\n        // The amount of Ether a `Borrower` must hold in order to borrow assets\n        uint208 ante;\n        // To avoid liquidation, a `Borrower` must be solvent at TWAP * e^{± nSigma * IV}\n        uint8 nSigma;\n        // Borrowing is paused when the manipulation metric > threshold; this scales the threshold up/down\n        uint8 manipulationThresholdDivisor;\n        // The time at which borrowing can resume\n        uint32 pausedUntilTime;\n    }\n\n    // The set of all governable `Market` properties\n    struct MarketConfig {\n        // Described above\n        uint208 ante;\n        // Described above\n        uint8 nSigma;\n        // Described above\n        uint8 manipulationThresholdDivisor;\n        // The reserve factor for `market.lender0`, expressed as a reciprocal\n        uint8 reserveFactor0;\n        // The reserve factor for `market.lender1`, expressed as a reciprocal\n        uint8 reserveFactor1;\n        // The rate model for `market.lender0`\n        IRateModel rateModel0;\n        // The rate model for `market.lender1`\n        IRateModel rateModel1;\n    }\n\n    // By enrolling as a `Courier`, frontends can earn a portion of their users' interest\n    struct Courier {\n        // The address that receives earnings whenever users withdraw\n        address wallet;\n        // The portion of users' interest to take, expressed in basis points\n        uint16 cut;\n    }\n\n    /// @notice The only address that can propose new `MarketConfig`s and rewards programs\n    address public immutable GOVERNOR;\n\n    /// @notice The oracle to use for prices and implied volatility\n    VolatilityOracle public immutable ORACLE;\n\n    /// @notice The implementation to which all `Lender` clones will point\n    address public immutable LENDER_IMPLEMENTATION;\n\n    /// @notice A simple contract that deploys `Borrower`s to keep `Factory` bytecode size down\n    BorrowerDeployer private immutable _BORROWER_DEPLOYER;\n\n    /// @notice The rate model that `Lender`s will use when first created\n    IRateModel public immutable DEFAULT_RATE_MODEL;\n\n    /*//////////////////////////////////////////////////////////////\n                             WORLD STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Returns the `Market` addresses associated with a Uniswap V3 pool\n    mapping(IUniswapV3Pool => Market) public getMarket;\n\n    /// @notice Returns the borrowing `Parameters` associated with a Uniswap V3 pool\n    mapping(IUniswapV3Pool => Parameters) public getParameters;\n\n    /// @notice Returns the other `Lender` in the `Market` iff input is itself a `Lender`, otherwise 0\n    mapping(address => address) public peer;\n\n    /// @notice Returns whether the given address is a `Borrower` deployed by this `Factory`\n    mapping(address => bool) public isBorrower;\n\n    /*//////////////////////////////////////////////////////////////\n                           INCENTIVE STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice The token in which rewards are paid out\n    ERC20 public rewardsToken;\n\n    /// @notice Returns the `Courier` for any given ID\n    mapping(uint32 => Courier) public couriers;\n\n    /*//////////////////////////////////////////////////////////////\n                              CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        address governor,\n        address reserve,\n        VolatilityOracle oracle,\n        BorrowerDeployer borrowerDeployer,\n        IRateModel defaultRateModel\n    ) {\n        GOVERNOR = governor;\n        ORACLE = oracle;\n        LENDER_IMPLEMENTATION = address(new Lender(reserve));\n        _BORROWER_DEPLOYER = borrowerDeployer;\n        DEFAULT_RATE_MODEL = defaultRateModel;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               EMERGENCY\n    //////////////////////////////////////////////////////////////*/\n\n    function pause(IUniswapV3Pool pool, uint40 oracleSeed) external {\n        (, bool seemsLegit, , ) = getMarket[pool].borrowerImplementation.getPrices(oracleSeed);\n        if (seemsLegit) return;\n\n        unchecked {\n            getParameters[pool].pausedUntilTime = uint32(block.timestamp) + UNISWAP_AVG_WINDOW;\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             WORLD CREATION\n    //////////////////////////////////////////////////////////////*/\n\n    function createMarket(IUniswapV3Pool pool) external {\n        ORACLE.prepare(pool);\n\n        address asset0 = pool.token0();\n        address asset1 = pool.token1();\n\n        // Deploy market-specific components\n        bytes32 salt = keccak256(abi.encodePacked(pool));\n        Lender lender0 = Lender(LENDER_IMPLEMENTATION.cloneDeterministic({salt: salt, data: abi.encodePacked(asset0)}));\n        Lender lender1 = Lender(LENDER_IMPLEMENTATION.cloneDeterministic({salt: salt, data: abi.encodePacked(asset1)}));\n        Borrower borrowerImplementation = _newBorrower(pool, lender0, lender1);\n\n        // Store deployment addresses\n        getMarket[pool] = Market(lender0, lender1, borrowerImplementation);\n        peer[address(lender0)] = address(lender1);\n        peer[address(lender1)] = address(lender0);\n\n        // Initialize lenders and set default market config\n        lender0.initialize();\n        lender1.initialize();\n        _setMarketConfig(\n            pool,\n            MarketConfig(\n                DEFAULT_ANTE,\n                DEFAULT_N_SIGMA,\n                DEFAULT_MANIPULATION_THRESHOLD_DIVISOR,\n                DEFAULT_RESERVE_FACTOR,\n                DEFAULT_RESERVE_FACTOR,\n                DEFAULT_RATE_MODEL,\n                DEFAULT_RATE_MODEL\n            ),\n            0\n        );\n\n        emit CreateMarket(pool, lender0, lender1);\n    }\n\n    function createBorrower(IUniswapV3Pool pool, address owner, bytes12 salt) external returns (Borrower borrower) {\n        Market memory market = getMarket[pool];\n\n        borrower = Borrower(\n            address(market.borrowerImplementation).cloneDeterministic({\n                salt: bytes32(bytes.concat(bytes20(msg.sender), salt)),\n                data: abi.encodePacked(owner)\n            })\n        );\n        isBorrower[address(borrower)] = true;\n\n        market.lender0.whitelist(address(borrower));\n        market.lender1.whitelist(address(borrower));\n\n        emit CreateBorrower(pool, owner, borrower);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               INCENTIVES\n    //////////////////////////////////////////////////////////////*/\n\n    function claimRewards(Lender[] calldata lenders, address beneficiary) external returns (uint256 earned) {\n        unchecked {\n            uint256 count = lenders.length;\n            for (uint256 i = 0; i < count; i++) {\n                // Make sure it is, in fact, a `Lender`\n                require(peer[address(lenders[i])] != address(0));\n                earned += lenders[i].claimRewards(msg.sender);\n            }\n        }\n\n        require(address(rewardsToken).code.length > 0);\n        rewardsToken.safeTransfer(beneficiary, earned);\n    }\n\n    /**\n     * @notice Enrolls `msg.sender` in the referral program. This allows frontends/wallets/apps to\n     * credit themselves for a given user's deposit, and receive a portion of their interest. Note\n     * that after enrolling, `msg.sender` will not be eligible for `REWARDS_TOKEN` rewards.\n     * @dev See `Lender.creditCourier`\n     * @param id A unique identifier for the courier\n     * @param cut The portion of interest the courier will receive. Should be in the range [0, 10000),\n     * with 10000 being 100%.\n     */\n    function enrollCourier(uint32 id, uint16 cut) external {\n        // Requirements:\n        // - `id != 0` because 0 is reserved as the no-courier case\n        // - `cut != 0 && cut < 10_000` just means between 0 and 100%\n        require(id != 0 && cut != 0 && cut < 10_000);\n        // Once an `id` has been enrolled, its info can't be changed\n        require(couriers[id].cut == 0);\n\n        couriers[id] = Courier(msg.sender, cut);\n        emit EnrollCourier(id, msg.sender, cut);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               GOVERNANCE\n    //////////////////////////////////////////////////////////////*/\n\n    function governRewardsToken(ERC20 rewardsToken_) external {\n        require(msg.sender == GOVERNOR && address(rewardsToken) == address(0));\n        rewardsToken = rewardsToken_;\n    }\n\n    function governRewardsRate(Lender lender, uint64 rate) external {\n        require(msg.sender == GOVERNOR);\n        lender.setRewardsRate(rate);\n    }\n\n    function governMarketConfig(IUniswapV3Pool pool, MarketConfig memory config) external {\n        require(msg.sender == GOVERNOR);\n\n        require(\n            // ante: max\n            (config.ante <= CONSTRAINT_ANTE_MAX) &&\n                // nSigma: min, max\n                (CONSTRAINT_N_SIGMA_MIN <= config.nSigma && config.nSigma <= CONSTRAINT_N_SIGMA_MAX) &&\n                // manipulationThresholdDivisor: min, max\n                (CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MIN <= config.manipulationThresholdDivisor &&\n                    config.manipulationThresholdDivisor <= CONSTRAINT_MANIPULATION_THRESHOLD_DIVISOR_MAX) &&\n                // reserveFactor0: min, max\n                (CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor0 &&\n                    config.reserveFactor0 <= CONSTRAINT_RESERVE_FACTOR_MAX) &&\n                // reserveFactor1: min, max\n                (CONSTRAINT_RESERVE_FACTOR_MIN <= config.reserveFactor1 &&\n                    config.reserveFactor1 <= CONSTRAINT_RESERVE_FACTOR_MAX),\n            \"Aloe: constraints\"\n        );\n\n        _setMarketConfig(pool, config, getParameters[pool].pausedUntilTime);\n    }\n\n    function _setMarketConfig(IUniswapV3Pool pool, MarketConfig memory config, uint32 pausedUntilTime) private {\n        getParameters[pool] = Parameters({\n            ante: config.ante,\n            nSigma: config.nSigma,\n            manipulationThresholdDivisor: config.manipulationThresholdDivisor,\n            pausedUntilTime: pausedUntilTime\n        });\n\n        Market memory market = getMarket[pool];\n        market.lender0.setRateModelAndReserveFactor(config.rateModel0, config.reserveFactor0);\n        market.lender1.setRateModelAndReserveFactor(config.rateModel1, config.reserveFactor1);\n\n        emit SetMarketConfig(pool, config);\n    }\n\n    function _newBorrower(IUniswapV3Pool pool, Lender lender0, Lender lender1) private returns (Borrower) {\n        (bool success, bytes memory data) = address(_BORROWER_DEPLOYER).delegatecall(\n            abi.encodeCall(BorrowerDeployer.deploy, (ORACLE, pool, lender0, lender1))\n        );\n        require(success);\n        return abi.decode(data, (Borrower));\n    }\n}\n\ncontract BorrowerDeployer {\n    function deploy(\n        VolatilityOracle oracle,\n        IUniswapV3Pool pool,\n        Lender lender0,\n        Lender lender1\n    ) external returns (Borrower) {\n        return new Borrower(oracle, pool, lender0, lender1);\n    }\n}\n"
      },
      "src/Lender.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib} from \"solmate/utils/FixedPointMathLib.sol\";\nimport {ERC20, SafeTransferLib} from \"solmate/utils/SafeTransferLib.sol\";\nimport {SafeCastLib} from \"solmate/utils/SafeCastLib.sol\";\n\nimport {BORROWS_SCALER, ONE} from \"./libraries/constants/Constants.sol\";\nimport {Q112} from \"./libraries/constants/Q.sol\";\nimport {Rewards} from \"./libraries/Rewards.sol\";\n\nimport {Ledger} from \"./Ledger.sol\";\nimport {IRateModel} from \"./RateModel.sol\";\n\n/// @title Lender\n/// @author Aloe Labs, Inc.\n/// @dev \"Test everything; hold fast what is good.\" - 1 Thessalonians 5:21\ncontract Lender is Ledger {\n    using FixedPointMathLib for uint256;\n    using SafeCastLib for uint256;\n    using SafeTransferLib for ERC20;\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed caller,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    event Borrow(address indexed caller, address indexed recipient, uint256 amount, uint256 units);\n\n    event Repay(address indexed caller, address indexed beneficiary, uint256 amount, uint256 units);\n\n    event CreditCourier(uint32 indexed id, address indexed account);\n\n    /*//////////////////////////////////////////////////////////////\n                       CONSTRUCTOR & INITIALIZER\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(address reserve) Ledger(reserve) {}\n\n    function initialize() external {\n        require(borrowIndex == 0);\n        borrowIndex = uint72(ONE);\n        lastAccrualTime = uint32(block.timestamp);\n    }\n\n    /// @notice Sets the `rateModel` and `reserveFactor`. Only the `FACTORY` can call this.\n    function setRateModelAndReserveFactor(IRateModel rateModel_, uint8 reserveFactor_) external {\n        require(msg.sender == address(FACTORY) && reserveFactor_ > 0);\n\n        accrueInterest();\n        rateModel = rateModel_;\n        reserveFactor = reserveFactor_;\n    }\n\n    /**\n     * @notice Sets the rewards rate. May be 0. Only the `FACTORY` can call this.\n     * @param rate The rewards rate, specified in [token units per second]. If non-zero, keep between 10^17 and\n     * 10^28 token units per year for smooth operation. Assuming `FACTORY.rewardsToken()` has 18 decimals, this is\n     * between 0.1 and 10 billion tokens per year.\n     */\n    function setRewardsRate(uint64 rate) external {\n        require(msg.sender == address(FACTORY));\n\n        (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply);\n        Rewards.setRate(s, a, rate);\n    }\n\n    /// @notice Allows `borrower` to call `borrow`. One the `FACTORY` can call this.\n    function whitelist(address borrower) external {\n        // Requirements:\n        // - `msg.sender == FACTORY` so that only the factory can whitelist borrowers\n        // - `borrows[borrower] == 0` ensures we don't accidentally erase debt\n        require(msg.sender == address(FACTORY) && borrows[borrower] == 0);\n\n        // `borrow` and `repay` have to read the `borrows` mapping anyway, so setting this to 1\n        // allows them to efficiently check whether a given borrower is whitelisted. This extra\n        // unit of debt won't accrue interest or impact solvency calculations.\n        borrows[borrower] = 1;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                                REWARDS\n    //////////////////////////////////////////////////////////////*/\n\n    function claimRewards(address owner) external returns (uint96 earned) {\n        // All claims are made through the `FACTORY`\n        require(msg.sender == address(FACTORY));\n\n        (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply);\n        earned = Rewards.claim(s, a, owner, balanceOf(owner));\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        DEPOSIT/WITHDRAWAL LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Mints `shares` to `beneficiary` by depositing exactly `amount` of underlying tokens\n     * @dev `deposit` is more efficient than `mint` and is the recommended way of depositing. Also\n     * supports the additional flow where you prepay `amount` instead of relying on approve/transferFrom.\n     * @param amount The amount of underlying tokens to deposit\n     * @param beneficiary The receiver of `shares`\n     * @param courierId The ID of the courier (or 0, to indicate lack thereof) that will receive a cut of\n     * `beneficiary`'s future interest. Only takes effect when `balanceOf(beneficiary) == 0`. In\n     * all other cases, pass 0 to avoid wasting gas on courier-related checks.\n     * @return shares The number of shares (banknotes) minted to `beneficiary`\n     */\n    function deposit(uint256 amount, address beneficiary, uint32 courierId) public returns (uint256 shares) {\n        if (courierId != 0) {\n            // Callers are free to set their own courier, but they need permission to mess with others'\n            if (msg.sender != beneficiary) {\n                require(allowance[beneficiary][msg.sender] > 0, \"Aloe: courier\");\n                allowance[beneficiary][msg.sender] = 0;\n            }\n\n            (address courier, uint16 cut) = FACTORY.couriers(courierId);\n\n            require(\n                // Prevent `RESERVE` from having a courier, since its principle wouldn't be tracked properly\n                (beneficiary != RESERVE) &&\n                    // Payout logic can't handle self-reference, so don't let accounts credit themselves\n                    (beneficiary != courier) &&\n                    // Make sure `cut` has been set\n                    (cut != 0),\n                \"Aloe: courier\"\n            );\n        }\n\n        // Accrue interest and update reserves\n        (Cache memory cache, uint256 inventory) = _load();\n\n        // Convert `amount` to `shares`\n        shares = _convertToShares(amount, inventory, cache.totalSupply, /* roundUp: */ false);\n        require(shares != 0, \"Aloe: zero impact\");\n\n        // Mint shares, track rewards, and (if applicable) handle courier accounting\n        cache.totalSupply = _mint(beneficiary, shares, amount, cache.totalSupply, courierId);\n        // Assume tokens are transferred\n        cache.lastBalance += amount;\n\n        // Save state to storage (thus far, only mappings have been updated, so we must address everything else)\n        _save(cache, /* didChangeBorrowBase: */ false);\n\n        // Ensure tokens are transferred\n        ERC20 asset_ = asset();\n        bool didPrepay = cache.lastBalance <= asset_.balanceOf(address(this));\n        if (!didPrepay) {\n            asset_.safeTransferFrom(msg.sender, address(this), amount);\n        }\n\n        emit Deposit(msg.sender, beneficiary, amount, shares);\n    }\n\n    function deposit(uint256 amount, address beneficiary) external returns (uint256 shares) {\n        shares = deposit(amount, beneficiary, 0);\n    }\n\n    function mint(uint256 shares, address beneficiary) external returns (uint256 amount) {\n        amount = previewMint(shares);\n        deposit(amount, beneficiary, 0);\n    }\n\n    /**\n     * @notice Burns `shares` from `owner` and sends `amount` of underlying tokens to `receiver`. If\n     * `owner` has a courier, additional shares will be transferred from `owner` to the courier as a fee.\n     * @dev `redeem` is more efficient than `withdraw` and is the recommended way of withdrawing\n     * @param shares The number of shares to burn in exchange for underlying tokens. To burn all your shares,\n     * you can pass `maxRedeem(owner)`. If `maxRedeem(owner)` is changing over time (due to a courier or\n     * high utilization) you can pass `type(uint256).max` and it will be computed in-place.\n     * @param recipient The receiver of `amount` of underlying tokens\n     * @param owner The user from whom shares are taken (for both the burn and possible fee transfer)\n     * @return amount The number of underlying tokens transferred to `recipient`\n     */\n    function redeem(uint256 shares, address recipient, address owner) public returns (uint256 amount) {\n        if (shares == type(uint256).max) shares = maxRedeem(owner);\n\n        if (msg.sender != owner) {\n            uint256 allowed = allowance[owner][msg.sender];\n            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n        }\n\n        // Accrue interest and update reserves\n        (Cache memory cache, uint256 inventory) = _load();\n\n        // Convert `shares` to `amount`\n        amount = _convertToAssets(shares, inventory, cache.totalSupply, /* roundUp: */ false);\n        require(amount != 0, \"Aloe: zero impact\");\n\n        // Burn shares, track rewards, and (if applicable) handle courier accounting\n        cache.totalSupply = _burn(owner, shares, inventory, cache.totalSupply);\n        // Assume tokens are transferred\n        cache.lastBalance -= amount;\n\n        // Save state to storage (thus far, only mappings have been updated, so we must address everything else)\n        _save(cache, /* didChangeBorrowBase: */ false);\n\n        // Transfer tokens\n        asset().safeTransfer(recipient, amount);\n\n        emit Withdraw(msg.sender, recipient, owner, amount, shares);\n    }\n\n    function withdraw(uint256 amount, address recipient, address owner) external returns (uint256 shares) {\n        shares = previewWithdraw(amount);\n        redeem(shares, recipient, owner);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                           BORROW/REPAY LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    /// @notice Sends `amount` of `asset` to `recipient` and increases `msg.sender`'s debt by `units`\n    function borrow(uint256 amount, address recipient) external returns (uint256 units) {\n        // Accrue interest and update reserves\n        (Cache memory cache, ) = _load();\n\n        unchecked {\n            uint256 b = borrows[msg.sender];\n            require(b != 0, \"Aloe: not a borrower\");\n\n            // Convert `amount` to `units`\n            units = (amount * BORROWS_SCALER) / cache.borrowIndex;\n\n            // Track borrows\n            borrows[msg.sender] = b + units;\n        }\n        cache.borrowBase += units;\n        // Assume tokens are transferred\n        cache.lastBalance -= amount;\n\n        // Save state to storage (thus far, only mappings have been updated, so we must address everything else)\n        _save(cache, /* didChangeBorrowBase: */ true);\n\n        // Transfer tokens\n        asset().safeTransfer(recipient, amount);\n\n        emit Borrow(msg.sender, recipient, amount, units);\n    }\n\n    /**\n     * @notice Reduces `beneficiary`'s debt by `units`, assuming someone has pre-paid `amount` of `asset`. To repay\n     * all debt for some account, call `repay(borrowBalance(account), account)`.\n     * @dev To avoid frontrunning, `amount` should be pre-paid in the same transaction as the `repay` call.\n     * @custom:example ```solidity\n     *   PERMIT2.permitTransferFrom(\n     *     permitMsg,\n     *     IPermit2.SignatureTransferDetails({to: address(lender), requestedAmount: amount}),\n     *     msg.sender,\n     *     signature\n     *   );\n     *   lender.repay(amount, beneficiary)\n     * ```\n     */\n    function repay(uint256 amount, address beneficiary) external returns (uint256 units) {\n        // Accrue interest and update reserves\n        (Cache memory cache, ) = _load();\n\n        unchecked {\n            uint256 b = borrows[beneficiary];\n\n            // Convert `amount` to `units`\n            units = (amount * BORROWS_SCALER) / cache.borrowIndex;\n            if (!(units < b)) {\n                units = b - 1;\n\n                uint256 maxRepay = (units * cache.borrowIndex).unsafeDivUp(BORROWS_SCALER);\n                require(b > 1 && amount <= maxRepay, \"Aloe: repay too much\");\n            }\n\n            // Track borrows\n            borrows[beneficiary] = b - units;\n            cache.borrowBase -= units;\n        }\n        // Assume tokens are transferred\n        cache.lastBalance += amount;\n\n        // Save state to storage (thus far, only mappings have been updated, so we must address everything else)\n        _save(cache, /* didChangeBorrowBase: */ true);\n\n        // Ensure tokens are transferred\n        require(cache.lastBalance <= asset().balanceOf(address(this)), \"Aloe: insufficient pre-pay\");\n\n        emit Repay(msg.sender, beneficiary, amount, units);\n    }\n\n    function accrueInterest() public returns (uint72) {\n        (Cache memory cache, ) = _load();\n        _save(cache, /* didChangeBorrowBase: */ false);\n        return uint72(cache.borrowIndex);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 shares) external returns (bool) {\n        allowance[msg.sender][spender] = shares;\n\n        emit Approval(msg.sender, spender, shares);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 shares) external returns (bool) {\n        accrueInterest();\n        _transfer(msg.sender, to, shares);\n\n        return true;\n    }\n\n    function transferFrom(address from, address to, uint256 shares) external returns (bool) {\n        uint256 allowed = allowance[from][msg.sender];\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - shares;\n\n        accrueInterest();\n        _transfer(from, to, shares);\n\n        return true;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             ERC2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\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        require(deadline >= block.timestamp, \"Aloe: permit expired\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            address recoveredAddress = ecrecover(\n                keccak256(\n                    abi.encodePacked(\n                        \"\\x19\\x01\",\n                        DOMAIN_SEPARATOR(),\n                        keccak256(\n                            abi.encode(\n                                keccak256(\n                                    \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n                                ),\n                                owner,\n                                spender,\n                                value,\n                                nonces[owner]++,\n                                deadline\n                            )\n                        )\n                    )\n                ),\n                v,\n                r,\n                s\n            );\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"Aloe: permit invalid\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                                HELPERS\n    //////////////////////////////////////////////////////////////*/\n\n    /// @dev Transfers `shares` from `from` to `to`, iff neither of them have a courier\n    function _transfer(address from, address to, uint256 shares) private {\n        (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply);\n\n        unchecked {\n            // From most to least significant...\n            // -------------------------------\n            // | courier id       | 32 bits  |\n            // | user's principle | 112 bits |\n            // | user's balance   | 112 bits |\n            // -------------------------------\n            uint256 data;\n\n            data = balances[from];\n            require(data >> 224 == 0 && shares <= data % Q112);\n            balances[from] = data - shares;\n\n            Rewards.updateUserState(s, a, from, data % Q112);\n\n            data = balances[to];\n            require(data >> 224 == 0);\n            balances[to] = data + shares;\n\n            Rewards.updateUserState(s, a, to, data % Q112);\n        }\n\n        emit Transfer(from, to, shares);\n    }\n\n    /// @dev Make sure to do something with the return value, `newTotalSupply`!\n    function _mint(\n        address to,\n        uint256 shares,\n        uint256 amount,\n        uint256 totalSupply_,\n        uint32 courierId\n    ) private returns (uint256 newTotalSupply) {\n        // Need to compute `newTotalSupply` with checked math to avoid overflow\n        newTotalSupply = totalSupply_ + shares;\n\n        unchecked {\n            // From most to least significant...\n            // -------------------------------\n            // | courier id       | 32 bits  |\n            // | user's principle | 112 bits |\n            // | user's balance   | 112 bits |\n            // -------------------------------\n            uint256 data = balances[to];\n\n            // Get rewards accounting out of the way\n            (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply_);\n            Rewards.updatePoolState(s, a);\n            Rewards.updateUserState(s, a, to, data % Q112);\n\n            // Only set courier if balance is 0. Otherwise previous courier may be cheated out of fees.\n            if (data % Q112 == 0) {\n                data = uint256(courierId) << 224;\n                emit CreditCourier(courierId, to);\n            }\n\n            // Keep track of principle iff `to` has a courier\n            if (data >> 224 != 0) {\n                require(amount + ((data >> 112) % Q112) < Q112);\n                data += amount << 112;\n            }\n\n            // Keep track of balance regardless of courier.\n            // Since `totalSupply` fits in uint112, the user's balance will too. No need to check here.\n            balances[to] = data + shares;\n        }\n\n        emit Transfer(address(0), to, shares);\n    }\n\n    /// @dev Make sure to do something with the return value, `newTotalSupply`!\n    function _burn(\n        address from,\n        uint256 shares,\n        uint256 inventory,\n        uint256 totalSupply_\n    ) private returns (uint256 newTotalSupply) {\n        unchecked {\n            // Can compute `newTotalSupply` with unchecked math since other checks cover underflow\n            newTotalSupply = totalSupply_ - shares;\n\n            // From most to least significant...\n            // -------------------------------\n            // | courier id       | 32 bits  |\n            // | user's principle | 112 bits |\n            // | user's balance   | 112 bits |\n            // -------------------------------\n            uint256 data = balances[from];\n            uint256 balance = data % Q112;\n\n            // Get rewards accounting out of the way\n            (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply_);\n            Rewards.updatePoolState(s, a);\n            Rewards.updateUserState(s, a, from, balance);\n\n            uint32 id = uint32(data >> 224);\n            if (id != 0) {\n                uint256 principleAssets = (data >> 112) % Q112;\n                uint256 principleShares = principleAssets.mulDivUp(totalSupply_, inventory);\n\n                if (balance > principleShares) {\n                    (address courier, uint16 cut) = FACTORY.couriers(id);\n\n                    // Compute total fee owed to courier. Take it out of balance so that\n                    // comparison is correct later on (`shares <= balance`)\n                    uint256 fee = ((balance - principleShares) * cut) / 10_000;\n                    balance -= fee;\n\n                    // Compute portion of fee to pay out during this burn.\n                    fee = (fee * shares) / balance;\n\n                    // Send `fee` from `from` to `courier`.\n                    // NOTE: We skip principle update on courier, so if couriers credit\n                    // each other, 100% of `fee` is treated as profit and will pass through\n                    // to the next courier.\n                    data -= fee;\n                    Rewards.updateUserState(s, a, courier, ((balances[courier] += fee) - fee) % Q112);\n                    emit Transfer(from, courier, fee);\n                }\n\n                // Update principle\n                data -= ((principleAssets * shares) / balance) << 112;\n            }\n\n            require(shares <= balance);\n            balances[from] = data - shares;\n        }\n\n        emit Transfer(from, address(0), shares);\n    }\n\n    function _load() private returns (Cache memory cache, uint256 inventory) {\n        // Accrue interest (only in memory)\n        uint256 newTotalSupply;\n        (cache, inventory, newTotalSupply) = _previewInterest(_getCache());\n\n        // Update reserves (new `totalSupply` is only in memory, but `balances[RESERVE]` is updated in storage)\n        if (newTotalSupply > cache.totalSupply) {\n            cache.totalSupply = _mint(RESERVE, newTotalSupply - cache.totalSupply, 0, cache.totalSupply, 0);\n        }\n    }\n\n    function _save(Cache memory cache, bool didChangeBorrowBase) private {\n        // `cache.lastAccrualTime == 0` implies that `cache.borrowIndex` was updated\n        if (cache.lastAccrualTime == 0 || didChangeBorrowBase) {\n            borrowBase = cache.borrowBase.safeCastTo184();\n            borrowIndex = cache.borrowIndex.safeCastTo72();\n        }\n\n        totalSupply = cache.totalSupply.safeCastTo112();\n        lastBalance = cache.lastBalance.safeCastTo112();\n        lastAccrualTime = uint32(block.timestamp);\n    }\n}\n"
      },
      "src/VolatilityOracle.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {IUniswapV3Pool} from \"v3-core/contracts/interfaces/IUniswapV3Pool.sol\";\n\nimport {\n    IV_SCALE,\n    IV_COLD_START,\n    IV_CHANGE_PER_UPDATE,\n    IV_EMA_GAIN_POS,\n    IV_EMA_GAIN_NEG,\n    UNISWAP_AVG_WINDOW,\n    FEE_GROWTH_AVG_WINDOW,\n    FEE_GROWTH_ARRAY_LENGTH,\n    FEE_GROWTH_SAMPLE_PERIOD\n} from \"./libraries/constants/Constants.sol\";\nimport {Oracle} from \"./libraries/Oracle.sol\";\nimport {Volatility} from \"./libraries/Volatility.sol\";\n\n/// @title VolatilityOracle\n/// @author Aloe Labs, Inc.\n/// @dev \"Test everything; hold fast what is good.\" - 1 Thessalonians 5:21\ncontract VolatilityOracle {\n    event Update(IUniswapV3Pool indexed pool, uint160 sqrtMeanPriceX96, uint104 iv);\n\n    struct LastWrite {\n        uint8 index;\n        uint40 time;\n        uint104 oldIV;\n        uint104 newIV;\n    }\n\n    mapping(IUniswapV3Pool => Volatility.PoolMetadata) public cachedMetadata;\n\n    mapping(IUniswapV3Pool => Volatility.FeeGrowthGlobals[FEE_GROWTH_ARRAY_LENGTH]) public feeGrowthGlobals;\n\n    mapping(IUniswapV3Pool => LastWrite) public lastWrites;\n\n    function prepare(IUniswapV3Pool pool) external {\n        cachedMetadata[pool] = _getPoolMetadata(pool);\n\n        if (lastWrites[pool].time == 0) {\n            feeGrowthGlobals[pool][0] = _getFeeGrowthGlobalsNow(pool);\n            lastWrites[pool] = LastWrite(0, uint40(block.timestamp), IV_COLD_START, IV_COLD_START);\n        }\n    }\n\n    function update(IUniswapV3Pool pool, uint40 seed) external returns (uint56, uint160, uint256) {\n        unchecked {\n            // Read `lastWrite` info from storage\n            LastWrite memory lastWrite = lastWrites[pool];\n            require(lastWrite.time > 0);\n\n            // We need to call `Oracle.consult` even if we're going to return early, so go ahead and do it\n            (uint56 metric, uint160 sqrtMeanPriceX96) = Oracle.consult(pool, seed);\n\n            // If fewer than `FEE_GROWTH_SAMPLE_PERIOD` seconds have elapsed, return early.\n            // We still fetch the latest TWAP, but we do not sample feeGrowthGlobals or update IV.\n            if (block.timestamp - lastWrite.time < FEE_GROWTH_SAMPLE_PERIOD) {\n                return (metric, sqrtMeanPriceX96, _interpolateIV(lastWrite));\n            }\n\n            // Populate `FeeGrowthGlobals`\n            Volatility.FeeGrowthGlobals[FEE_GROWTH_ARRAY_LENGTH] storage arr = feeGrowthGlobals[pool];\n            Volatility.FeeGrowthGlobals memory a = _getFeeGrowthGlobalsOld(arr, lastWrite.index);\n            Volatility.FeeGrowthGlobals memory b = _getFeeGrowthGlobalsNow(pool);\n\n            // Bring `lastWrite` forward so it's essentially \"currentWrite\"\n            lastWrite.index = uint8((lastWrite.index + 1) % FEE_GROWTH_ARRAY_LENGTH);\n            lastWrite.time = uint40(block.timestamp);\n            lastWrite.oldIV = lastWrite.newIV;\n            // lastWrite.newIV is updated below, iff feeGrowthGlobals samples are ≈`FEE_GROWTH_AVG_WINDOW` hours apart\n\n            if (\n                _isInInterval({\n                    min: FEE_GROWTH_AVG_WINDOW - FEE_GROWTH_SAMPLE_PERIOD / 2,\n                    x: b.timestamp - a.timestamp,\n                    max: FEE_GROWTH_AVG_WINDOW + FEE_GROWTH_SAMPLE_PERIOD / 2\n                })\n            ) {\n                // Update exponential moving average with a new IV estimate\n                lastWrite.newIV = _ema(\n                    int256(uint256(lastWrite.oldIV)),\n                    int256(Volatility.estimate(cachedMetadata[pool], sqrtMeanPriceX96, a, b, IV_SCALE))\n                );\n\n                // Clamp `newIV` so it lies within [previous - maxChange, previous + maxChange]\n                if (lastWrite.newIV > lastWrite.oldIV + IV_CHANGE_PER_UPDATE) {\n                    lastWrite.newIV = lastWrite.oldIV + IV_CHANGE_PER_UPDATE;\n                } else if (lastWrite.newIV + IV_CHANGE_PER_UPDATE < lastWrite.oldIV) {\n                    lastWrite.newIV = lastWrite.oldIV - IV_CHANGE_PER_UPDATE;\n                }\n            }\n\n            // Store the new feeGrowthGlobals sample and update `lastWrites`\n            arr[lastWrite.index] = b;\n            lastWrites[pool] = lastWrite;\n\n            emit Update(pool, sqrtMeanPriceX96, lastWrite.newIV);\n            return (metric, sqrtMeanPriceX96, lastWrite.oldIV); // `lastWrite.oldIV == _interpolateIV(lastWrite)` here\n        }\n    }\n\n    function consult(IUniswapV3Pool pool, uint40 seed) external view returns (uint56, uint160, uint256) {\n        (uint56 metric, uint160 sqrtMeanPriceX96) = Oracle.consult(pool, seed);\n        return (metric, sqrtMeanPriceX96, _interpolateIV(lastWrites[pool]));\n    }\n\n    function _ema(int256 oldIV, int256 estimate) private pure returns (uint104) {\n        unchecked {\n            int256 gain = estimate > oldIV ? IV_EMA_GAIN_POS : IV_EMA_GAIN_NEG;\n            uint256 newIV = uint256(oldIV + (estimate - oldIV) / gain);\n            return newIV > type(uint104).max ? type(uint104).max : uint104(newIV);\n        }\n    }\n\n    function _interpolateIV(LastWrite memory lastWrite) private view returns (uint256) {\n        unchecked {\n            int256 deltaT = int256(block.timestamp - lastWrite.time);\n            if (deltaT >= int256(FEE_GROWTH_SAMPLE_PERIOD)) return lastWrite.newIV;\n\n            int256 oldIV = int256(uint256(lastWrite.oldIV));\n            int256 newIV = int256(uint256(lastWrite.newIV));\n            return uint256(oldIV + ((newIV - oldIV) * deltaT) / int256(FEE_GROWTH_SAMPLE_PERIOD));\n        }\n    }\n\n    function _getPoolMetadata(IUniswapV3Pool pool) private view returns (Volatility.PoolMetadata memory metadata) {\n        (, , uint16 observationIndex, uint16 observationCardinality, , uint8 feeProtocol, ) = pool.slot0();\n        // We want observations from `UNISWAP_AVG_WINDOW` and `UNISWAP_AVG_WINDOW * 2` seconds ago. Since observation\n        // frequency varies with `pool` usage, we apply an extra 3x safety factor. If `pool` usage increases,\n        // oracle cardinality may need to be increased as well. This should be monitored off-chain.\n        require(\n            Oracle.getMaxSecondsAgo(pool, observationIndex, observationCardinality) > UNISWAP_AVG_WINDOW * 6,\n            \"Aloe: cardinality\"\n        );\n\n        uint24 fee = pool.fee();\n        metadata.gamma0 = fee;\n        metadata.gamma1 = fee;\n        unchecked {\n            if (feeProtocol % 16 != 0) metadata.gamma0 -= fee / (feeProtocol % 16);\n            if (feeProtocol >> 4 != 0) metadata.gamma1 -= fee / (feeProtocol >> 4);\n        }\n\n        metadata.tickSpacing = pool.tickSpacing();\n    }\n\n    function _getFeeGrowthGlobalsNow(IUniswapV3Pool pool) private view returns (Volatility.FeeGrowthGlobals memory) {\n        return\n            Volatility.FeeGrowthGlobals(\n                pool.feeGrowthGlobal0X128(),\n                pool.feeGrowthGlobal1X128(),\n                uint32(block.timestamp)\n            );\n    }\n\n    function _getFeeGrowthGlobalsOld(\n        Volatility.FeeGrowthGlobals[FEE_GROWTH_ARRAY_LENGTH] storage arr,\n        uint256 index\n    ) private view returns (Volatility.FeeGrowthGlobals memory) {\n        uint256 target = block.timestamp - FEE_GROWTH_AVG_WINDOW;\n\n        // See if the newest sample is nearest to `target`\n        Volatility.FeeGrowthGlobals memory sample = arr[index];\n        if (sample.timestamp <= target) return sample;\n\n        // See if the oldest sample is nearest to `target`\n        uint256 next = (index + 1) % FEE_GROWTH_ARRAY_LENGTH;\n        sample = arr[next];\n        if (sample.timestamp >= target) return sample;\n\n        // Now that we've checked the edges, we know the best sample lies somewhere within the array.\n        return _binarySearch(arr, next, target);\n    }\n\n    function _binarySearch(\n        Volatility.FeeGrowthGlobals[FEE_GROWTH_ARRAY_LENGTH] storage arr,\n        uint256 l,\n        uint256 target\n    ) private view returns (Volatility.FeeGrowthGlobals memory) {\n        Volatility.FeeGrowthGlobals memory beforeOrAt;\n        Volatility.FeeGrowthGlobals memory atOrAfter;\n\n        unchecked {\n            uint256 r = l + (FEE_GROWTH_ARRAY_LENGTH - 1);\n            uint256 i;\n            while (true) {\n                i = (l + r) / 2;\n\n                beforeOrAt = arr[i % FEE_GROWTH_ARRAY_LENGTH];\n                atOrAfter = arr[(i + 1) % FEE_GROWTH_ARRAY_LENGTH];\n\n                if (_isInInterval(beforeOrAt.timestamp, target, atOrAfter.timestamp)) break;\n\n                if (target < beforeOrAt.timestamp) r = i - 1;\n                else l = i + 1;\n            }\n\n            uint256 errorA = target - beforeOrAt.timestamp;\n            uint256 errorB = atOrAfter.timestamp - target;\n\n            return errorB < errorA ? atOrAfter : beforeOrAt;\n        }\n    }\n\n    function _isInInterval(uint256 min, uint256 x, uint256 max) private pure returns (bool) {\n        return min <= x && x <= max;\n    }\n}\n"
      },
      "lib/solmate/src/tokens/ERC20.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n    /*//////////////////////////////////////////////////////////////\n                                 EVENTS\n    //////////////////////////////////////////////////////////////*/\n\n    event Transfer(address indexed from, address indexed to, uint256 amount);\n\n    event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n    /*//////////////////////////////////////////////////////////////\n                            METADATA STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    string public name;\n\n    string public symbol;\n\n    uint8 public immutable decimals;\n\n    /*//////////////////////////////////////////////////////////////\n                              ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 public totalSupply;\n\n    mapping(address => uint256) public balanceOf;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*//////////////////////////////////////////////////////////////\n                            EIP-2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal immutable INITIAL_CHAIN_ID;\n\n    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n    mapping(address => uint256) public nonces;\n\n    /*//////////////////////////////////////////////////////////////\n                               CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(\n        string memory _name,\n        string memory _symbol,\n        uint8 _decimals\n    ) {\n        name = _name;\n        symbol = _symbol;\n        decimals = _decimals;\n\n        INITIAL_CHAIN_ID = block.chainid;\n        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                               ERC20 LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function approve(address spender, uint256 amount) public virtual returns (bool) {\n        allowance[msg.sender][spender] = amount;\n\n        emit Approval(msg.sender, spender, amount);\n\n        return true;\n    }\n\n    function transfer(address to, uint256 amount) public virtual returns (bool) {\n        balanceOf[msg.sender] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(msg.sender, to, amount);\n\n        return true;\n    }\n\n    function transferFrom(\n        address from,\n        address to,\n        uint256 amount\n    ) public virtual returns (bool) {\n        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n        balanceOf[from] -= amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(from, to, amount);\n\n        return true;\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                             EIP-2612 LOGIC\n    //////////////////////////////////////////////////////////////*/\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    ) public virtual {\n        require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n        // Unchecked because the only math done is incrementing\n        // the owner's nonce which cannot realistically overflow.\n        unchecked {\n            address recoveredAddress = ecrecover(\n                keccak256(\n                    abi.encodePacked(\n                        \"\\x19\\x01\",\n                        DOMAIN_SEPARATOR(),\n                        keccak256(\n                            abi.encode(\n                                keccak256(\n                                    \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n                                ),\n                                owner,\n                                spender,\n                                value,\n                                nonces[owner]++,\n                                deadline\n                            )\n                        )\n                    )\n                ),\n                v,\n                r,\n                s\n            );\n\n            require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n            allowance[recoveredAddress][spender] = value;\n        }\n\n        emit Approval(owner, spender, value);\n    }\n\n    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n    }\n\n    function computeDomainSeparator() internal view virtual returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(bytes(name)),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        INTERNAL MINT/BURN LOGIC\n    //////////////////////////////////////////////////////////////*/\n\n    function _mint(address to, uint256 amount) internal virtual {\n        totalSupply += amount;\n\n        // Cannot overflow because the sum of all user\n        // balances can't exceed the max uint256 value.\n        unchecked {\n            balanceOf[to] += amount;\n        }\n\n        emit Transfer(address(0), to, amount);\n    }\n\n    function _burn(address from, uint256 amount) internal virtual {\n        balanceOf[from] -= amount;\n\n        // Cannot underflow because a user's balance\n        // will never be larger than the total supply.\n        unchecked {\n            totalSupply -= amount;\n        }\n\n        emit Transfer(from, address(0), amount);\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    /// 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    /// observationIndex The index of the last oracle observation that was written,\n    /// observationCardinality The current maximum number of observations stored in the pool,\n    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n    /// 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    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    /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n    /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n    /// 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    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n    /// Returns 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    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n    /// Returns 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/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"
      },
      "src/libraries/Exp.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity 0.8.23;\n\n/// @dev Returns \\\\( 10^{12} \\cdot e^{\\frac{x}{10^{12}}} \\\\) or `type(int256).max`, whichever is smaller\n/// @custom:author Modified from [Solady](https://github.com/Vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol#L113)\nfunction exp1e12(int256 x) pure returns (int256 r) {\n    unchecked {\n        // When the result is < 0.5 we return zero. This happens when\n        // x <= floor(ln(0.5 / 1e12) * 1e12) ~ -28e12\n        if (x <= -28324168296488) return r;\n        // When the result is > (2**255 - 1) we cannot represent it as an int.\n        // This happens when x >= floor(ln((2**255 - 1) / 1e12) * 1e12) ~ 149e12.\n        if (x >= 149121509926857) return type(int256).max;\n\n        // x is now in the range (-29, 150) * 1e12. Convert to (-29, 150) * 2**96\n        // for more intermediate precision and a binary basis. This base conversion\n        // is a multiplication by 2**96 / 1e12 = 2**84 / 5**12.\n        x = (x << 84) / 5 ** 12;\n\n        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers\n        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.\n        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).\n        int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;\n        x = x - k * 54916777467707473351141471128;\n\n        // k is in the range [-41, 215].\n\n        // Evaluate using a (6, 7)-term rational approximation.\n        // p is made monic, we'll multiply by a scale factor later.\n        int256 y = x + 1346386616545796478920950773328;\n        y = ((y * x) >> 96) + 57155421227552351082224309758442;\n        int256 p = y + x - 94201549194550492254356042504812;\n        p = ((p * y) >> 96) + 28719021644029726153956944680412240;\n        p = p * x + (4385272521454847904659076985693276 << 96);\n\n        // We leave p in 2**192 basis so we don't need to scale it back up for the division.\n        int256 q = x - 2855989394907223263936484059900;\n        q = ((q * x) >> 96) + 50020603652535783019961831881945;\n        q = ((q * x) >> 96) - 533845033583426703283633433725380;\n        q = ((q * x) >> 96) + 3604857256930695427073651918091429;\n        q = ((q * x) >> 96) - 14423608567350463180887372962807573;\n        q = ((q * x) >> 96) + 26449188498355588339934803723976023;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Div in assembly because solidity adds a zero check despite the unchecked.\n            // The q polynomial won't have zeros in the domain as all its roots are complex.\n            // No scaling is necessary because p is already 2**96 too large.\n            r := sdiv(p, q)\n        }\n\n        // r should be in the range (0.09, 0.25) * 2**96.\n\n        // We now need to multiply r by:\n        // * the scale factor s = ~6.031367120.\n        // * the 2**k factor from the range reduction.\n        // * the 1e12 / 2**96 factor for base conversion.\n        r = int256((uint256(r) * 4008531014412650626985742312566589230316694133190) >> uint256(215 - k));\n    }\n}\n"
      },
      "src/libraries/MulDiv.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.23;\n\n/// @dev Equivalent to `fullMulDiv(x, x, 1 << 64)`\nfunction square(uint160 x) pure returns (uint256 result) {\n    assembly (\"memory-safe\") {\n        // 512-bit multiply [prod1 prod0] = x * x. 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\n        // Least significant 256 bits of the product.\n        let prod0 := mul(x, x)\n        let mm := mulmod(x, x, not(0))\n        // Most significant 256 bits of the product.\n        let prod1 := sub(mm, add(prod0, lt(mm, prod0)))\n\n        // Divide [prod1 prod0] by 2^64.\n        result := or(shr(64, prod0), shl(192, prod1))\n    }\n}\n\n/// @dev Equivalent to `fullMulDiv(x, y, 1 << 96)`.\n/// NOTE: Does not check for overflow, so choose `x` and `y` carefully.\nfunction mulDiv96(uint256 x, uint256 y) pure returns (uint256 result) {\n    assembly (\"memory-safe\") {\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\n        // Least significant 256 bits of the product.\n        let prod0 := mul(x, y)\n        let mm := mulmod(x, y, not(0))\n        // Most significant 256 bits of the product.\n        let prod1 := sub(mm, add(prod0, lt(mm, prod0)))\n\n        // Divide [prod1 prod0] by 2^96.\n        result := or(shr(96, prod0), shl(160, prod1))\n    }\n}\n\n/// @dev Equivalent to `fullMulDiv(x, x, 1 << 128)`\nfunction mulDiv128(uint256 x, uint256 y) pure returns (uint256 result) {\n    assembly (\"memory-safe\") {\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\n        // Least significant 256 bits of the product.\n        let prod0 := mul(x, y)\n        let mm := mulmod(x, y, not(0))\n        // Most significant 256 bits of the product.\n        let prod1 := sub(mm, add(prod0, lt(mm, prod0)))\n\n        // Make sure the result is less than `2**256`.\n        if iszero(gt(0x100000000000000000000000000000000, prod1)) {\n            // Store the function selector of `FullMulDivFailed()`.\n            mstore(0x00, 0xae47f702)\n            // Revert with (offset, size).\n            revert(0x1c, 0x04)\n        }\n\n        // Divide [prod1 prod0] by 2^128.\n        result := or(shr(128, prod0), shl(128, prod1))\n    }\n}\n\n/// @dev Equivalent to `fullMulDivUp(x, x, 1 << 128)`\nfunction mulDiv128Up(uint256 x, uint256 y) pure returns (uint256 result) {\n    result = mulDiv128(x, y);\n    assembly (\"memory-safe\") {\n        if mulmod(x, y, 0x100000000000000000000000000000000) {\n            if iszero(add(result, 1)) {\n                // Store the function selector of `FullMulDivFailed()`.\n                mstore(0x00, 0xae47f702)\n                // Revert with (offset, size).\n                revert(0x1c, 0x04)\n            }\n            result := add(result, 1)\n        }\n    }\n}\n\n/// @dev Equivalent to `fullMulDiv(x, y, 1 << 224)`.\n/// NOTE: Does not check for overflow, so choose `x` and `y` carefully.\nfunction mulDiv224(uint256 x, uint256 y) pure returns (uint256 result) {\n    assembly (\"memory-safe\") {\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\n        // Least significant 256 bits of the product.\n        let prod0 := mul(x, y)\n        let mm := mulmod(x, y, not(0))\n        // Most significant 256 bits of the product.\n        let prod1 := sub(mm, add(prod0, lt(mm, prod0)))\n\n        // Divide [prod1 prod0] by 2^224.\n        result := or(shr(224, prod0), shl(32, prod1))\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"
      },
      "src/libraries/constants/Q.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nuint256 constant Q8 = 1 << 8;\n\nuint256 constant Q16 = 1 << 16;\n\nuint256 constant Q24 = 1 << 24;\n\nuint256 constant Q32 = 1 << 32;\n\nuint256 constant Q40 = 1 << 40;\n\nuint256 constant Q48 = 1 << 48;\n\nuint256 constant Q56 = 1 << 56;\n\nuint256 constant Q64 = 1 << 64;\n\nuint256 constant Q72 = 1 << 72;\n\nuint256 constant Q80 = 1 << 80;\n\nuint256 constant Q88 = 1 << 88;\n\nuint256 constant Q96 = 1 << 96;\n\nuint256 constant Q104 = 1 << 104;\n\nuint256 constant Q112 = 1 << 112;\n\nuint256 constant Q120 = 1 << 120;\n\nuint256 constant Q128 = 1 << 128;\n"
      },
      "lib/clones-with-immutable-args/src/ClonesWithImmutableArgs.sol": {
        "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity ^0.8.15;\n\nimport {Create2} from \"./Create2.sol\";\n\n/// @title ClonesWithImmutableArgs\n/// @author wighawag, zefram.eth, Saw-mon & Natalie, wminshew\n/// @notice Enables creating clone contracts with immutable args\nlibrary ClonesWithImmutableArgs {\n    // abi.encodeWithSignature(\"CreateFail()\")\n    uint256 private constant _CREATE_FAIL_ERROR_SIG =\n        0xebfef18800000000000000000000000000000000000000000000000000000000;\n\n    // abi.encodeWithSignature(\"IdentityPrecompileFailure()\")\n    uint256 private constant _IDENTITY_PRECOMPILE_ERROR_SIG =\n        0x3a008ffa00000000000000000000000000000000000000000000000000000000;\n\n    uint256 private constant _CUSTOM_ERROR_SIG_PTR = 0x0;\n\n    uint256 private constant _CUSTOM_ERROR_LENGTH = 0x4;\n\n    uint256 private constant _BOOTSTRAP_LENGTH = 0x3f; // 63 (43 instructions + 20 for implementation address)\n\n    /// @notice Creates a clone proxy of the implementation contract with immutable args\n    /// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length\n    /// @param implementation The implementation contract to clone\n    /// @param data Encoded immutable args\n    /// @return instance The address of the created clone\n    function clone(address implementation, bytes memory data) internal returns (address instance) {\n        (uint256 creationPtr, uint256 creationSize) = _getCreationCode(implementation, data);\n\n        assembly (\"memory-safe\") {\n            instance := create(0, creationPtr, creationSize)\n\n            // if the create failed, the instance address won't be set\n            if iszero(instance) {\n                mstore(_CUSTOM_ERROR_SIG_PTR, _CREATE_FAIL_ERROR_SIG)\n                revert(_CUSTOM_ERROR_SIG_PTR, _CUSTOM_ERROR_LENGTH)\n            }\n        }\n    }\n\n    /// @notice Creates a clone proxy of the implementation contract with immutable args\n    /// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length\n    /// @param implementation The implementation contract to clone\n    /// @param salt The salt for create2\n    /// @param data Encoded immutable args\n    /// @return instance The address of the created clone\n    function cloneDeterministic(\n        address implementation,\n        bytes32 salt,\n        bytes memory data\n    ) internal returns (address payable instance) {\n        (uint256 creationPtr, uint256 creationSize) = _getCreationCode(implementation, data);\n\n        assembly (\"memory-safe\") {\n            instance := create2(0, creationPtr, creationSize, salt)\n\n            // if the create failed, the instance address won't be set\n            if iszero(instance) {\n                mstore(_CUSTOM_ERROR_SIG_PTR, _CREATE_FAIL_ERROR_SIG)\n                revert(_CUSTOM_ERROR_SIG_PTR, _CUSTOM_ERROR_LENGTH)\n            }\n        }\n    }\n\n    /// @notice Predicts the address where a deterministic clone of implementation will be deployed\n    /// @param implementation The implementation contract to clone\n    /// @param salt The salt for create2\n    /// @param data Encoded immutable args\n    /// @return predicted The predicted address of the created clone exists\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        address deployer,\n        bytes memory data\n    ) internal view returns (address predicted) {\n        (uint256 creationPtr, uint256 creationSize) = _getCreationCode(implementation, data);\n\n        bytes32 bytecodeHash;\n        assembly (\"memory-safe\") {\n            bytecodeHash := keccak256(creationPtr, creationSize)\n        }\n\n        predicted = Create2.computeAddress(salt, bytecodeHash, deployer);\n    }\n\n    /// @notice Predicts the address where a deterministic clone of implementation will be deployed\n    /// @param implementation The implementation contract to clone\n    /// @param salt The salt for create2\n    /// @param data Encoded immutable args\n    /// @return predicted The predicted address of the created clone exists\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        bytes memory data\n    ) internal view returns (address predicted) {\n        predicted = predictDeterministicAddress(implementation, salt, address(this), data);\n    }\n\n    /// @notice Computes the creation code for a clone with immutable args\n    /// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length\n    /// @param implementation The implementation contract to clone\n    /// @param data Encoded immutable args\n    /// @return ptr The ptr to the clone's bytecode\n    /// @return creationSize The size of the clone to be created\n    function _getCreationCode(\n        address implementation,\n        bytes memory data\n    ) private view returns (uint256 ptr, uint256 creationSize) {\n        // unrealistic for memory ptr or data length to exceed 256 bits\n        assembly (\"memory-safe\") {\n            let extraLength := add(mload(data), 2) // +2 bytes for telling how much data there is appended to the call\n            creationSize := add(extraLength, _BOOTSTRAP_LENGTH)\n            let runSize := sub(creationSize, 0x0a)\n\n            // free memory pointer\n            ptr := mload(0x40)\n\n            // -------------------------------------------------------------------------------------------------------------\n            // CREATION (10 bytes)\n            // -------------------------------------------------------------------------------------------------------------\n\n            // 61 runtime  | PUSH2 runtime (r)     | r                       | –\n            // 3d          | RETURNDATASIZE        | 0 r                     | –\n            // 81          | DUP2                  | r 0 r                   | –\n            // 60 offset   | PUSH1 offset (o)      | o r 0 r                 | –\n            // 3d          | RETURNDATASIZE        | 0 o r 0 r               | –\n            // 39          | CODECOPY              | 0 r                     | [0 - runSize): runtime code\n            // f3          | RETURN                |                         | [0 - runSize): runtime code\n\n            // -------------------------------------------------------------------------------------------------------------\n            // RUNTIME (53 bytes + extraLength)\n            // -------------------------------------------------------------------------------------------------------------\n\n            // --- copy calldata to memmory ---\n            // 36          | CALLDATASIZE          | cds                     | –\n            // 3d          | RETURNDATASIZE        | 0 cds                   | –\n            // 3d          | RETURNDATASIZE        | 0 0 cds                 | –\n            // 37          | CALLDATACOPY          |                         | [0 - cds): calldata\n\n            // --- keep some values in stack ---\n            // 3d          | RETURNDATASIZE        | 0                       | [0 - cds): calldata\n            // 3d          | RETURNDATASIZE        | 0 0                     | [0 - cds): calldata\n            // 3d          | RETURNDATASIZE        | 0 0 0                   | [0 - cds): calldata\n            // 3d          | RETURNDATASIZE        | 0 0 0 0                 | [0 - cds): calldata\n            // 61 extra    | PUSH2 extra (e)       | e 0 0 0 0               | [0 - cds): calldata\n\n            // --- copy extra data to memory ---\n            // 80          | DUP1                  | e e 0 0 0 0             | [0 - cds): calldata\n            // 60 0x35     | PUSH1 0x35            | 0x35 e e 0 0 0 0        | [0 - cds): calldata\n            // 36          | CALLDATASIZE          | cds 0x35 e e 0 0 0 0    | [0 - cds): calldata\n            // 39          | CODECOPY              | e 0 0 0 0               | [0 - cds): calldata, [cds - cds + e): extraData\n\n            // --- delegate call to the implementation contract ---\n            // 36          | CALLDATASIZE          | cds e 0 0 0 0           | [0 - cds): calldata, [cds - cds + e): extraData\n            // 01          | ADD                   | cds+e 0 0 0 0           | [0 - cds): calldata, [cds - cds + e): extraData\n            // 3d          | RETURNDATASIZE        | 0 cds+e 0 0 0 0         | [0 - cds): calldata, [cds - cds + e): extraData\n            // 73 addr     | PUSH20 addr           | addr 0 cds+e 0 0 0 0    | [0 - cds): calldata, [cds - cds + e): extraData\n            // 5a          | GAS                   | gas addr 0 cds+e 0 0 0 0| [0 - cds): calldata, [cds - cds + e): extraData\n            // f4          | DELEGATECALL          | success 0 0             | [0 - cds): calldata, [cds - cds + e): extraData\n\n            // --- copy return data to memory ---\n            // 3d          | RETURNDATASIZE        | rds success 0 0         | [0 - cds): calldata, [cds - cds + e): extraData\n            // 3d          | RETURNDATASIZE        | rds rds success 0 0     | [0 - cds): calldata, [cds - cds + e): extraData\n            // 93          | SWAP4                 | 0 rds success 0 rds     | [0 - cds): calldata, [cds - cds + e): extraData\n            // 80          | DUP1                  | 0 0 rds success 0 rds   | [0 - cds): calldata, [cds - cds + e): extraData\n            // 3e          | RETURNDATACOPY        | success 0 rds           | [0 - rds): returndata, ... the rest might be dirty\n\n            // 60 0x33     | PUSH1 0x33            | 0x33 success 0 rds      | [0 - rds): returndata, ... the rest might be dirty\n            // 57          | JUMPI                 | 0 rds                   | [0 - rds): returndata, ... the rest might be dirty\n\n            // --- revert ---\n            // fd          | REVERT                |                         | [0 - rds): returndata, ... the rest might be dirty\n\n            // --- return ---\n            // 5b          | JUMPDEST              | 0 rds                   | [0 - rds): returndata, ... the rest might be dirty\n            // f3          | RETURN                |                         | [0 - rds): returndata, ... the rest might be dirty\n\n            mstore(\n                ptr,\n                or(\n                    // ⎬  ♠︎♠︎♠︎♠︎         ♣︎♣︎         ⎨           -              ♥︎♥︎♥︎♥︎-     ♦︎♦︎      -           >\n                    hex\"610000_3d_81_600a_3d_39_f3_36_3d_3d_37_3d_3d_3d_3d_610000_80_6035_36_39_36_01_3d_73\", // 30 bytes\n                    or(shl(0xe8, runSize), shl(0x58, extraLength)) // ♠︎=runSize, ♥︎=extraLength\n                )\n            )\n\n            mstore(add(ptr, 0x1e), shl(0x60, implementation)) // 20 bytes\n\n            //                        >     -                 ☼☼   -        |\n            mstore(add(ptr, 0x32), hex\"5a_f4_3d_3d_93_80_3e_6033_57_fd_5b_f3\") // 13 bytes\n\n            // -------------------------------------------------------------------------------------------------------------\n            // APPENDED DATA (Accessible from extcodecopy)\n            // (but also send as appended data to the delegatecall)\n            // -------------------------------------------------------------------------------------------------------------\n\n            extraLength := sub(extraLength, 2)\n\n            if iszero(\n                staticcall(\n                    gas(),\n                    0x04, // identity precompile\n                    add(data, 0x20), // copy source\n                    extraLength,\n                    add(ptr, _BOOTSTRAP_LENGTH), // copy destination\n                    extraLength\n                )\n            ) {\n                mstore(_CUSTOM_ERROR_SIG_PTR, _IDENTITY_PRECOMPILE_ERROR_SIG)\n                revert(_CUSTOM_ERROR_SIG_PTR, _CUSTOM_ERROR_LENGTH)\n            }\n\n            mstore(add(add(ptr, _BOOTSTRAP_LENGTH), extraLength), shl(0xf0, add(extraLength, 2)))\n        }\n    }\n}\n"
      },
      "src/RateModel.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib} from \"solmate/utils/FixedPointMathLib.sol\";\n\nimport {MAX_RATE, ONE} from \"./libraries/constants/Constants.sol\";\n\ninterface IRateModel {\n    /**\n     * @notice Specifies the percentage yield per second for a `lender`. Need not be a pure function\n     * of `utilization`. To convert to APY: `(1 + returnValue / 1e12) ** secondsPerYear - 1`\n     * @param utilization The `lender`'s total borrows divided by total assets, scaled up by 1e18\n     * @param lender The `Lender` to examine\n     * @return The percentage yield per second, scaled up by 1e12\n     */\n    function getYieldPerSecond(uint256 utilization, address lender) external view returns (uint256);\n}\n\n/// @title RateModel\n/// @author Aloe Labs, Inc.\n/// @dev \"Test everything; hold fast what is good.\" - 1 Thessalonians 5:21\ncontract RateModel is IRateModel {\n    uint256 private constant _A = 6.1010463348e20;\n\n    uint256 private constant _B = _A / 1e18;\n\n    /// @inheritdoc IRateModel\n    function getYieldPerSecond(uint256 utilization, address) external pure returns (uint256) {\n        unchecked {\n            return (utilization < 0.99e18) ? _A / (1e18 - utilization) - _B : 60400;\n        }\n    }\n}\n\nlibrary SafeRateLib {\n    using FixedPointMathLib for uint256;\n\n    function getAccrualFactor(IRateModel rateModel, uint256 utilization, uint256 dt) internal view returns (uint256) {\n        uint256 rate;\n\n        // Essentially `rate = rateModel.getYieldPerSecond(utilization, address(this)) ?? 0`, i.e. if the call\n        // fails, we set `rate = 0` instead of reverting. Solidity's try/catch could accomplish the same thing,\n        // but this is slightly more gas efficient.\n        bytes memory encodedCall = abi.encodeCall(IRateModel.getYieldPerSecond, (utilization, address(this)));\n        assembly (\"memory-safe\") {\n            let success := staticcall(100000, rateModel, add(encodedCall, 32), mload(encodedCall), 0, 32)\n            rate := mul(success, mload(0))\n        }\n\n        return _computeAccrualFactor(rate, dt);\n    }\n\n    function _computeAccrualFactor(uint256 rate, uint256 dt) private pure returns (uint256) {\n        if (rate > MAX_RATE) rate = MAX_RATE;\n        if (dt > 1 weeks) dt = 1 weeks;\n\n        unchecked {\n            return (ONE + rate).rpow(dt, ONE);\n        }\n    }\n}\n"
      },
      "lib/solmate/src/utils/FixedPointMathLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n    /*//////////////////////////////////////////////////////////////\n                    SIMPLIFIED FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    uint256 internal constant MAX_UINT256 = 2**256 - 1;\n\n    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n    }\n\n    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n    }\n\n    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n    }\n\n    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    LOW LEVEL FIXED POINT OPERATIONS\n    //////////////////////////////////////////////////////////////*/\n\n    function mulDivDown(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // Divide x * y by the denominator.\n            z := div(mul(x, y), denominator)\n        }\n    }\n\n    function mulDivUp(\n        uint256 x,\n        uint256 y,\n        uint256 denominator\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))\n            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {\n                revert(0, 0)\n            }\n\n            // If x * y modulo the denominator is strictly greater than 0,\n            // 1 is added to round up the division of x * y by the denominator.\n            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))\n        }\n    }\n\n    function rpow(\n        uint256 x,\n        uint256 n,\n        uint256 scalar\n    ) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            switch x\n            case 0 {\n                switch n\n                case 0 {\n                    // 0 ** 0 = 1\n                    z := scalar\n                }\n                default {\n                    // 0 ** n = 0\n                    z := 0\n                }\n            }\n            default {\n                switch mod(n, 2)\n                case 0 {\n                    // If n is even, store scalar in z for now.\n                    z := scalar\n                }\n                default {\n                    // If n is odd, store x in z for now.\n                    z := x\n                }\n\n                // Shifting right by 1 is like dividing by 2.\n                let half := shr(1, scalar)\n\n                for {\n                    // Shift n right by 1 before looping to halve it.\n                    n := shr(1, n)\n                } n {\n                    // Shift n right by 1 each iteration to halve it.\n                    n := shr(1, n)\n                } {\n                    // Revert immediately if x ** 2 would overflow.\n                    // Equivalent to iszero(eq(div(xx, x), x)) here.\n                    if shr(128, x) {\n                        revert(0, 0)\n                    }\n\n                    // Store x squared.\n                    let xx := mul(x, x)\n\n                    // Round to the nearest number.\n                    let xxRound := add(xx, half)\n\n                    // Revert if xx + half overflowed.\n                    if lt(xxRound, xx) {\n                        revert(0, 0)\n                    }\n\n                    // Set x to scaled xxRound.\n                    x := div(xxRound, scalar)\n\n                    // If n is even:\n                    if mod(n, 2) {\n                        // Compute z * x.\n                        let zx := mul(z, x)\n\n                        // If z * x overflowed:\n                        if iszero(eq(div(zx, x), z)) {\n                            // Revert if x is non-zero.\n                            if iszero(iszero(x)) {\n                                revert(0, 0)\n                            }\n                        }\n\n                        // Round to the nearest number.\n                        let zxRound := add(zx, half)\n\n                        // Revert if zx + half overflowed.\n                        if lt(zxRound, zx) {\n                            revert(0, 0)\n                        }\n\n                        // Return properly scaled zxRound.\n                        z := div(zxRound, scalar)\n                    }\n                }\n            }\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                        GENERAL NUMBER UTILITIES\n    //////////////////////////////////////////////////////////////*/\n\n    function sqrt(uint256 x) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let y := x // We start y at x, which will help us make our initial estimate.\n\n            z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n            // We check y >= 2^(k + 8) but shift right by k bits\n            // each branch to ensure that if x >= 256, then y >= 256.\n            if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n                y := shr(128, y)\n                z := shl(64, z)\n            }\n            if iszero(lt(y, 0x1000000000000000000)) {\n                y := shr(64, y)\n                z := shl(32, z)\n            }\n            if iszero(lt(y, 0x10000000000)) {\n                y := shr(32, y)\n                z := shl(16, z)\n            }\n            if iszero(lt(y, 0x1000000)) {\n                y := shr(16, y)\n                z := shl(8, z)\n            }\n\n            // Goal was to get z*z*y within a small factor of x. More iterations could\n            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n            // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n            // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n            // There is no overflow risk here since y < 2^136 after the first branch above.\n            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n            z := shr(1, add(z, div(x, z)))\n\n            // If x+1 is a perfect square, the Babylonian method cycles between\n            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n            z := sub(z, lt(div(x, z), z))\n        }\n    }\n\n    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Mod x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            z := mod(x, y)\n        }\n    }\n\n    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Divide x by y. Note this will return\n            // 0 instead of reverting if y is zero.\n            r := div(x, y)\n        }\n    }\n\n    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Add 1 to x * y if x % y > 0. Note this will\n            // return 0 instead of reverting if y is zero.\n            z := add(gt(mod(x, y), 0), div(x, y))\n        }\n    }\n}\n"
      },
      "lib/solmate/src/utils/SafeCastLib.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Safe unsigned integer casting library that reverts on overflow.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeCastLib.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)\nlibrary SafeCastLib {\n    function safeCastTo248(uint256 x) internal pure returns (uint248 y) {\n        require(x < 1 << 248);\n\n        y = uint248(x);\n    }\n\n    function safeCastTo240(uint256 x) internal pure returns (uint240 y) {\n        require(x < 1 << 240);\n\n        y = uint240(x);\n    }\n\n    function safeCastTo232(uint256 x) internal pure returns (uint232 y) {\n        require(x < 1 << 232);\n\n        y = uint232(x);\n    }\n\n    function safeCastTo224(uint256 x) internal pure returns (uint224 y) {\n        require(x < 1 << 224);\n\n        y = uint224(x);\n    }\n\n    function safeCastTo216(uint256 x) internal pure returns (uint216 y) {\n        require(x < 1 << 216);\n\n        y = uint216(x);\n    }\n\n    function safeCastTo208(uint256 x) internal pure returns (uint208 y) {\n        require(x < 1 << 208);\n\n        y = uint208(x);\n    }\n\n    function safeCastTo200(uint256 x) internal pure returns (uint200 y) {\n        require(x < 1 << 200);\n\n        y = uint200(x);\n    }\n\n    function safeCastTo192(uint256 x) internal pure returns (uint192 y) {\n        require(x < 1 << 192);\n\n        y = uint192(x);\n    }\n    \n    function safeCastTo184(uint256 x) internal pure returns (uint184 y) {\n        require(x < 1 << 184);\n\n        y = uint184(x);\n    }\n\n    function safeCastTo176(uint256 x) internal pure returns (uint176 y) {\n        require(x < 1 << 176);\n\n        y = uint176(x);\n    }\n\n    function safeCastTo168(uint256 x) internal pure returns (uint168 y) {\n        require(x < 1 << 168);\n\n        y = uint168(x);\n    }\n\n    function safeCastTo160(uint256 x) internal pure returns (uint160 y) {\n        require(x < 1 << 160);\n\n        y = uint160(x);\n    }\n\n    function safeCastTo152(uint256 x) internal pure returns (uint152 y) {\n        require(x < 1 << 152);\n\n        y = uint152(x);\n    }\n\n    function safeCastTo144(uint256 x) internal pure returns (uint144 y) {\n        require(x < 1 << 144);\n\n        y = uint144(x);\n    }\n\n    function safeCastTo136(uint256 x) internal pure returns (uint136 y) {\n        require(x < 1 << 136);\n\n        y = uint136(x);\n    }\n\n    function safeCastTo128(uint256 x) internal pure returns (uint128 y) {\n        require(x < 1 << 128);\n\n        y = uint128(x);\n    }\n\n    function safeCastTo120(uint256 x) internal pure returns (uint120 y) {\n        require(x < 1 << 120);\n\n        y = uint120(x);\n    }\n\n    function safeCastTo112(uint256 x) internal pure returns (uint112 y) {\n        require(x < 1 << 112);\n\n        y = uint112(x);\n    }\n\n    function safeCastTo104(uint256 x) internal pure returns (uint104 y) {\n        require(x < 1 << 104);\n\n        y = uint104(x);\n    }\n\n    function safeCastTo96(uint256 x) internal pure returns (uint96 y) {\n        require(x < 1 << 96);\n\n        y = uint96(x);\n    }\n\n    function safeCastTo88(uint256 x) internal pure returns (uint88 y) {\n        require(x < 1 << 88);\n\n        y = uint88(x);\n    }\n\n    function safeCastTo80(uint256 x) internal pure returns (uint80 y) {\n        require(x < 1 << 80);\n\n        y = uint80(x);\n    }\n\n    function safeCastTo72(uint256 x) internal pure returns (uint72 y) {\n        require(x < 1 << 72);\n\n        y = uint72(x);\n    }\n\n    function safeCastTo64(uint256 x) internal pure returns (uint64 y) {\n        require(x < 1 << 64);\n\n        y = uint64(x);\n    }\n\n    function safeCastTo56(uint256 x) internal pure returns (uint56 y) {\n        require(x < 1 << 56);\n\n        y = uint56(x);\n    }\n\n    function safeCastTo48(uint256 x) internal pure returns (uint48 y) {\n        require(x < 1 << 48);\n\n        y = uint48(x);\n    }\n\n    function safeCastTo40(uint256 x) internal pure returns (uint40 y) {\n        require(x < 1 << 40);\n\n        y = uint40(x);\n    }\n\n    function safeCastTo32(uint256 x) internal pure returns (uint32 y) {\n        require(x < 1 << 32);\n\n        y = uint32(x);\n    }\n\n    function safeCastTo24(uint256 x) internal pure returns (uint24 y) {\n        require(x < 1 << 24);\n\n        y = uint24(x);\n    }\n\n    function safeCastTo16(uint256 x) internal pure returns (uint16 y) {\n        require(x < 1 << 16);\n\n        y = uint16(x);\n    }\n\n    function safeCastTo8(uint256 x) internal pure returns (uint8 y) {\n        require(x < 1 << 8);\n\n        y = uint8(x);\n    }\n}\n"
      },
      "src/libraries/Rewards.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\n\n/// @title Rewards\n/// @notice Implements logic for staking rewards\n/// @author Aloe Labs, Inc.\n/// @author Inspired by [Yield Protocol](https://github.com/yieldprotocol/yield-utils-v2/blob/main/src/token/ERC20Rewards.sol)\nlibrary Rewards {\n    event RewardsRateSet(uint64 rate);\n\n    event RewardsClaimed(address indexed user, uint96 amount);\n\n    struct PoolState {\n        // Accumulated rewards per token, scaled up by 1e18\n        uint160 accumulated;\n        // Last time `accumulated` was updated\n        uint32 lastUpdated;\n        // The rewards rate, specified as [token units per second]\n        uint64 rate;\n    }\n\n    struct UserState {\n        // Rewards earned by the user up until the checkpoint\n        uint96 earned;\n        // `poolState.accumulated` the last time `userState` was updated\n        uint160 checkpoint;\n    }\n\n    struct Storage {\n        PoolState poolState;\n        mapping(address => UserState) userStates;\n    }\n\n    bytes32 private constant _REWARDS_SLOT = keccak256(\"aloe.ii.rewards\");\n\n    /**\n     * @notice Sets the pool's rewards rate. May be 0.\n     * @param store The rewards storage pointer\n     * @param accumulated Up-to-date `poolState.accumulated`, i.e. the output of `_accumulate`\n     * @param rate The rewards rate, specified as [token units per second]. Keep between 10^17 and 10^28\n     * token units per year for smooth operation -- between 0.1 and 10 billion tokens, assuming 18 decimals.\n     */\n    function setRate(Storage storage store, uint160 accumulated, uint64 rate) internal {\n        store.poolState = PoolState(accumulated, uint32(block.timestamp), rate);\n        emit RewardsRateSet(rate);\n    }\n\n    function claim(\n        Storage storage store,\n        uint160 accumulated,\n        address user,\n        uint256 balance\n    ) internal returns (uint96 earned) {\n        UserState memory userState = previewUserState(store, accumulated, user, balance);\n\n        earned = userState.earned;\n        userState.earned = 0;\n\n        store.userStates[user] = userState;\n        emit RewardsClaimed(user, earned);\n    }\n\n    /**\n     * @notice Ensures that changes in the pool's `totalSupply` don't mess up rewards accounting. Should\n     * be called anytime `totalSupply` changes.\n     * @dev Use `Rewards.load()` to easily obtain the first two arguments\n     * @param store The rewards storage pointer\n     * @param accumulated Up-to-date `poolState.accumulated`, i.e. the output of `_accumulate`\n     */\n    function updatePoolState(Storage storage store, uint160 accumulated) internal {\n        PoolState memory poolState = store.poolState;\n\n        poolState.accumulated = accumulated;\n        poolState.lastUpdated = uint32(block.timestamp);\n        // poolState.rate is unchanged\n\n        store.poolState = poolState;\n    }\n\n    /**\n     * @notice Tracks how much reward a `user` earned while holding a particular `balance`. Should be\n     * called anytime their balance changes.\n     * @dev Use `Rewards.load()` to easily obtain the first two arguments\n     * @param store The rewards storage pointer\n     * @param accumulated Up-to-date `poolState.accumulated`, i.e. the output of `_accumulate`\n     * @param user The user whose balance (# of shares) is about to change\n     * @param balance The user's balance (# of shares) -- before it changes\n     */\n    function updateUserState(Storage storage store, uint160 accumulated, address user, uint256 balance) internal {\n        store.userStates[user] = previewUserState(store, accumulated, user, balance);\n    }\n\n    function previewUserState(\n        Storage storage store,\n        uint160 accumulated,\n        address user,\n        uint256 balance\n    ) internal view returns (UserState memory userState) {\n        unchecked {\n            userState = store.userStates[user];\n\n            userState.earned += uint96((balance * (accumulated - userState.checkpoint)) / 1e18);\n            userState.checkpoint = accumulated;\n        }\n    }\n\n    function getRate() internal view returns (uint64) {\n        return _storage().poolState.rate;\n    }\n\n    /// @dev Returns arguments to be used in `updatePoolState` and `updateUserState`. No good semantic\n    /// meaning here, just a coincidence that both functions need this information.\n    function load(uint256 totalSupply) internal view returns (Storage storage store, uint160 accumulator) {\n        store = _storage();\n        accumulator = _accumulate(store.poolState, totalSupply);\n    }\n\n    /// @dev Accumulates rewards based on the current `rate` and time elapsed since last update\n    function _accumulate(PoolState memory poolState, uint256 totalSupply) private view returns (uint160) {\n        unchecked {\n            uint256 deltaT = block.timestamp - poolState.lastUpdated;\n            return poolState.accumulated + uint160(SoladyMath.rawDiv(1e18 * deltaT * poolState.rate, totalSupply));\n        }\n    }\n\n    /// @dev Diamond-pattern-style storage getter\n    function _storage() private pure returns (Storage storage store) {\n        bytes32 position = _REWARDS_SLOT;\n        assembly (\"memory-safe\") {\n            store.slot := position\n        }\n    }\n}\n"
      },
      "src/Ledger.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {ImmutableArgs} from \"clones-with-immutable-args/ImmutableArgs.sol\";\nimport {IERC165} from \"openzeppelin-contracts/contracts/interfaces/IERC165.sol\";\nimport {IERC2612} from \"openzeppelin-contracts/contracts/interfaces/IERC2612.sol\";\nimport {IERC4626} from \"openzeppelin-contracts/contracts/interfaces/IERC4626.sol\";\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\nimport {FixedPointMathLib} from \"solmate/utils/FixedPointMathLib.sol\";\nimport {ERC20} from \"solmate/tokens/ERC20.sol\";\n\nimport {BORROWS_SCALER, ONE} from \"./libraries/constants/Constants.sol\";\nimport {Q112} from \"./libraries/constants/Q.sol\";\nimport {Rewards} from \"./libraries/Rewards.sol\";\n\nimport {Factory} from \"./Factory.sol\";\nimport {IRateModel, SafeRateLib} from \"./RateModel.sol\";\n\ncontract Ledger {\n    using FixedPointMathLib for uint256;\n    using SafeRateLib for IRateModel;\n\n    struct Cache {\n        uint256 totalSupply;\n        uint256 lastBalance;\n        uint256 lastAccrualTime;\n        uint256 borrowBase;\n        uint256 borrowIndex;\n    }\n\n    Factory public immutable FACTORY;\n\n    address public immutable RESERVE;\n\n    /*//////////////////////////////////////////////////////////////\n                             LENDER STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    /// @dev Doesn't include reserve inflation. If you want that, use `stats()`\n    uint112 public totalSupply;\n\n    /// @dev Used in lieu of `asset.balanceOf` to prevent inflation attacks\n    uint112 public lastBalance;\n\n    /// @dev The last `block.timestamp` at which interest accrued\n    uint32 public lastAccrualTime;\n\n    /// @dev The principle of all outstanding loans as if they were taken out at `borrowIndex = ONE`\n    uint184 public borrowBase;\n\n    /// @dev Tracks all-time growth of borrow interest. Starts at `ONE` and increases monotonically over time\n    uint72 public borrowIndex;\n\n    /// @dev The principle of a given user's loan as if it was taken out at `borrowIndex = ONE`\n    mapping(address => uint256) public borrows;\n\n    /*//////////////////////////////////////////////////////////////\n                             ERC20 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    /// @dev Highest 32 bits are the referral code, next 112 are the principle, lowest 112 are the shares.\n    mapping(address => uint256) public balances;\n\n    mapping(address => mapping(address => uint256)) public allowance;\n\n    /*//////////////////////////////////////////////////////////////\n                            ERC2612 STORAGE\n    //////////////////////////////////////////////////////////////*/\n\n    mapping(address => uint256) public nonces;\n\n    /*//////////////////////////////////////////////////////////////\n                         GOVERNABLE PARAMETERS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev `rateModel.getYieldPerSecond` is given 100000 gas, and the output is clamped to `MAX_RATE`. If\n     * the call reverts, it's treated the same as if it returned 0.\n     */\n    IRateModel public rateModel;\n\n    /// @dev The portion of interest that accrues to the `RESERVE`. Expressed as a reciprocal, e.g. 16 → 6.25%\n    uint8 public reserveFactor;\n\n    /*//////////////////////////////////////////////////////////////\n                              CONSTRUCTOR\n    //////////////////////////////////////////////////////////////*/\n\n    constructor(address reserve) {\n        FACTORY = Factory(msg.sender);\n        RESERVE = reserve;\n    }\n\n    /// @notice Returns true if this contract implements the interface defined by `interfaceId`\n    function supportsInterface(bytes4 interfaceId) external pure returns (bool) {\n        return\n            interfaceId == type(IERC165).interfaceId ||\n            interfaceId == type(IERC2612).interfaceId ||\n            interfaceId == type(IERC4626).interfaceId;\n    }\n\n    /// @notice The name of the banknote.\n    function name() external view returns (string memory) {\n        return string.concat(\"Aloe \", asset().name(), unicode\" ⚭ [\", Ledger(peer()).asset().symbol(), \"]\");\n    }\n\n    /// @notice The symbol of the banknote.\n    function symbol() external view returns (string memory) {\n        return string.concat(asset().symbol(), \"+\");\n    }\n\n    /// @notice The number of decimals the banknote uses. Matches the underlying token.\n    function decimals() external view returns (uint8) {\n        return asset().decimals();\n    }\n\n    /// @notice The address of the underlying token.\n    function asset() public pure returns (ERC20) {\n        return ERC20(ImmutableArgs.addr());\n    }\n\n    /// @notice The address of the other `Lender` in the market\n    function peer() public view returns (address) {\n        return FACTORY.peer(address(this));\n    }\n\n    /// @notice The domain separator for EIP-2612\n    function DOMAIN_SEPARATOR() public view returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\"EIP712Domain(string version,uint256 chainId,address verifyingContract)\"),\n                    keccak256(\"1\"),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /**\n     * @notice Gets basic lending statistics as if `accrueInterest` were just called.\n     * @return The updated `borrowIndex`\n     * @return The sum of all banknote balances, in underlying units (i.e. `totalAssets`)\n     * @return The sum of all outstanding debts, in underlying units\n     * @return The sum of all banknote balances. Will differ from `totalSupply` due to reserves inflation\n     */\n    function stats() external view returns (uint72, uint256, uint256, uint256) {\n        (Cache memory cache, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n\n        unchecked {\n            return (uint72(cache.borrowIndex), inventory, inventory - cache.lastBalance, newTotalSupply);\n        }\n    }\n\n    /// @notice The rewards rate, specified as [token units per second]\n    function rewardsRate() external view returns (uint64 rate) {\n        rate = Rewards.getRate();\n    }\n\n    /// @notice All rewards earned by `account` that have not yet been paid out\n    function rewardsOf(address account) external view returns (uint96) {\n        (Rewards.Storage storage s, uint160 a) = Rewards.load(totalSupply);\n        return Rewards.previewUserState(s, a, account, balanceOf(account)).earned;\n    }\n\n    /// @notice The ID of the referrer associated with `account`'s deposit. If 0, they have no courier.\n    function courierOf(address account) external view returns (uint32) {\n        return uint32(balances[account] >> 224);\n    }\n\n    /// @notice The lending principle of `account`. Only tracked if they have a courier.\n    function principleOf(address account) external view returns (uint256) {\n        return (balances[account] >> 112) % Q112;\n    }\n\n    /// @notice The number of shares held by `account`\n    function balanceOf(address account) public view returns (uint256) {\n        return balances[account] % Q112;\n    }\n\n    /**\n     * @notice The amount of `asset` owed to `account` after accruing the latest interest, i.e.\n     * the value that `maxWithdraw` would return if outstanding borrows weren't a constraint.\n     * Fees owed to couriers are automatically subtracted from this value in real-time, but couriers\n     * themselves won't receive earnings until users `redeem` or `withdraw`.\n     * @dev Because of the fees, ∑underlyingBalances != totalAssets\n     */\n    function underlyingBalance(address account) external view returns (uint256) {\n        (, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n        return _convertToAssets(_nominalShares(account, inventory, newTotalSupply), inventory, newTotalSupply, false);\n    }\n\n    /**\n     * @notice The amount of `asset` owed to `account` before accruing the latest interest.\n     * See `underlyingBalance` for details.\n     * @dev An underestimate; more gas efficient than `underlyingBalance`\n     */\n    function underlyingBalanceStored(address account) external view returns (uint256) {\n        unchecked {\n            uint256 inventory = lastBalance + (uint256(borrowBase) * borrowIndex) / BORROWS_SCALER;\n            uint256 totalSupply_ = totalSupply;\n\n            return _convertToAssets(_nominalShares(account, inventory, totalSupply_), inventory, totalSupply_, false);\n        }\n    }\n\n    /**\n     * @notice The amount of `asset` owed by `account` after accruing the latest interest. If one calls\n     * `repay(borrowBalance(account), account)`, the `account` will be left with a borrow balance of 0.\n     */\n    function borrowBalance(address account) external view returns (uint256) {\n        uint256 b = borrows[account];\n\n        (Cache memory cache, , ) = _previewInterest(_getCache());\n        unchecked {\n            return b > 1 ? ((b - 1) * cache.borrowIndex).unsafeDivUp(BORROWS_SCALER) : 0;\n        }\n    }\n\n    /// @notice The amount of `asset` owed by `account` before accruing the latest interest.\n    function borrowBalanceStored(address account) external view returns (uint256) {\n        uint256 b = borrows[account];\n\n        unchecked {\n            return b > 1 ? ((b - 1) * borrowIndex).unsafeDivUp(BORROWS_SCALER) : 0;\n        }\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                           ERC4626 ACCOUNTING\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice The total amount of `asset` under management\n     * @dev `convertToShares(totalAssets()) != totalSupply()` due to reserves inflation. If you need\n     * the up-to-date supply, use `stats()`\n     */\n    function totalAssets() external view returns (uint256) {\n        (, uint256 inventory, ) = _previewInterest(_getCache());\n        return inventory;\n    }\n\n    function convertToShares(uint256 assets) public view returns (uint256) {\n        (, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n        return _convertToShares(assets, inventory, newTotalSupply, /* roundUp: */ false);\n    }\n\n    function convertToAssets(uint256 shares) public view returns (uint256) {\n        (, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n        return _convertToAssets(shares, inventory, newTotalSupply, /* roundUp: */ false);\n    }\n\n    function previewDeposit(uint256 assets) public view returns (uint256) {\n        return convertToShares(assets);\n    }\n\n    function previewMint(uint256 shares) public view returns (uint256) {\n        (, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n        return _convertToAssets(shares, inventory, newTotalSupply, /* roundUp: */ true);\n    }\n\n    function previewRedeem(uint256 shares) public view returns (uint256) {\n        return convertToAssets(shares);\n    }\n\n    function previewWithdraw(uint256 assets) public view returns (uint256) {\n        (, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n        return _convertToShares(assets, inventory, newTotalSupply, /* roundUp: */ true);\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                    ERC4626 DEPOSIT/WITHDRAWAL LIMITS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @notice Returns a conservative estimate of the maximum amount of `asset()` that can be deposited into the\n     * Vault for `receiver`, through a deposit call.\n     * @dev Should return the *precise* maximum. In this case that'd be on the order of 2^112 with constraints\n     * coming from both `lastBalance` and `totalSupply`, which changes during interest accrual. Instead of doing\n     * complicated math, we provide a constant conservative estimate of 2^96.\n     * @return The maximum amount of `asset()` that can be deposited\n     */\n    function maxDeposit(address) external pure returns (uint256) {\n        return 1 << 96;\n    }\n\n    /**\n     * @notice Returns a conservative estimate of the maximum number of Vault shares that can be minted for `receiver`,\n     * through a mint call.\n     * @dev Should return the *precise* maximum. In this case that'd be on the order of 2^112 with constraints\n     * coming from both `lastBalance` and `totalSupply`, which changes during interest accrual. Instead of doing\n     * complicated math, we provide a constant conservative estimate of 2^96.\n     * @return The maximum number of Vault shares that can be minted\n     */\n    function maxMint(address) external pure returns (uint256) {\n        return 1 << 96;\n    }\n\n    /**\n     * @notice Returns the maximum number of Vault shares that can be redeemed in the Vault by `owner`, through a\n     * redeem call.\n     * @param owner The address that would burn Vault shares when redeeming\n     * @return The maximum number of Vault shares that can be redeemed\n     */\n    function maxRedeem(address owner) public view returns (uint256) {\n        (Cache memory cache, uint256 inventory, uint256 newTotalSupply) = _previewInterest(_getCache());\n\n        uint256 a = _nominalShares(owner, inventory, newTotalSupply);\n        uint256 b = _convertToShares(cache.lastBalance, inventory, newTotalSupply, false);\n\n        return a < b ? a : b;\n    }\n\n    /**\n     * @notice Returns the maximum amount of `asset()` that can be withdrawn from the Vault by `owner`, through a\n     * withdraw call.\n     * @param owner The address that would burn Vault shares when withdrawing\n     * @return The maximum amount of `asset()` that can be withdrawn\n     */\n    function maxWithdraw(address owner) external view returns (uint256) {\n        return convertToAssets(maxRedeem(owner));\n    }\n\n    /*//////////////////////////////////////////////////////////////\n                                 HELPERS\n    //////////////////////////////////////////////////////////////*/\n\n    /**\n     * @dev Accrues interest up to the current `block.timestamp`. Updates and returns `cache`, but doesn't write\n     * anything to storage.\n     */\n    function _previewInterest(Cache memory cache) internal view returns (Cache memory, uint256, uint256) {\n        unchecked {\n            uint256 oldBorrows = (cache.borrowBase * cache.borrowIndex) / BORROWS_SCALER;\n            uint256 oldInventory = cache.lastBalance + oldBorrows;\n\n            if (cache.lastAccrualTime == block.timestamp || oldBorrows == 0) {\n                return (cache, oldInventory, cache.totalSupply);\n            }\n\n            // sload `reserveFactor` and `rateModel` at the same time since they're in the same slot\n            uint8 rf = reserveFactor;\n            uint256 accrualFactor = rateModel.getAccrualFactor({\n                utilization: (1e18 * oldBorrows) / oldInventory,\n                dt: block.timestamp - cache.lastAccrualTime\n            });\n\n            cache.borrowIndex = SoladyMath.min((cache.borrowIndex * accrualFactor) / ONE, type(uint72).max);\n            cache.lastAccrualTime = 0; // 0 indicates `borrowIndex` was updated\n\n            uint256 newInventory = cache.lastBalance + (cache.borrowBase * cache.borrowIndex) / BORROWS_SCALER;\n            uint256 newTotalSupply = SoladyMath.min(\n                SoladyMath.fullMulDiv(\n                    cache.totalSupply,\n                    newInventory,\n                    newInventory - (newInventory - oldInventory) / rf\n                ),\n                type(uint112).max\n            );\n            return (cache, newInventory, newTotalSupply);\n        }\n    }\n\n    function _convertToShares(\n        uint256 assets,\n        uint256 inventory,\n        uint256 totalSupply_,\n        bool roundUp\n    ) internal pure returns (uint256) {\n        if (totalSupply_ == 0) return assets;\n        return roundUp ? assets.mulDivUp(totalSupply_, inventory) : assets.mulDivDown(totalSupply_, inventory);\n    }\n\n    function _convertToAssets(\n        uint256 shares,\n        uint256 inventory,\n        uint256 totalSupply_,\n        bool roundUp\n    ) internal pure returns (uint256) {\n        if (totalSupply_ == 0) return shares;\n        return roundUp ? shares.mulDivUp(inventory, totalSupply_) : shares.mulDivDown(inventory, totalSupply_);\n    }\n\n    /// @dev The `account`'s balance, minus any shares earned by their courier\n    function _nominalShares(\n        address account,\n        uint256 inventory,\n        uint256 totalSupply_\n    ) private view returns (uint256 balance) {\n        unchecked {\n            uint256 data = balances[account];\n            balance = data % Q112;\n\n            uint32 id = uint32(data >> 224);\n            if (id != 0) {\n                uint256 principleAssets = (data >> 112) % Q112;\n                uint256 principleShares = _convertToShares(principleAssets, inventory, totalSupply_, true);\n\n                if (balance > principleShares) {\n                    (, uint16 cut) = FACTORY.couriers(id);\n\n                    uint256 fee = ((balance - principleShares) * cut) / 10_000;\n                    balance -= fee;\n                }\n            }\n        }\n    }\n\n    function _getCache() internal view returns (Cache memory) {\n        return Cache(totalSupply, lastBalance, lastAccrualTime, borrowBase, borrowIndex);\n    }\n}\n"
      },
      "src/libraries/Oracle.sol": {
        "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\nimport {IUniswapV3Pool} from \"v3-core/contracts/interfaces/IUniswapV3Pool.sol\";\n\nimport {UNISWAP_AVG_WINDOW} from \"./constants/Constants.sol\";\nimport {Q16} from \"./constants/Q.sol\";\nimport {TickMath} from \"./TickMath.sol\";\n\n/// @title Oracle\n/// @notice Provides functions to integrate with V3 pool oracle\n/// @author Aloe Labs, Inc.\n/// @author Modified from [Uniswap](https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/OracleLibrary.sol)\nlibrary Oracle {\n    /**\n     * @notice Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool\n     * @param pool Address of the pool that we want to observe\n     * @param seed The indices of `pool.observations` where we start our search for the 30-minute-old (lowest 16 bits)\n     * and 60-minute-old (next 16 bits) observations. Determine these off-chain to make this method more efficient\n     * than Uniswap's binary search. If any of the highest 8 bits are set, we fallback to onchain binary search.\n     * @return metric If the price was manipulated at any point in the past `UNISWAP_AVG_WINDOW` seconds, then at\n     * some point in that period, this value will spike. It may still be high now, or (if the attacker is smart and\n     * well-financed) it may have returned to nominal.\n     * @return sqrtMeanPriceX96 sqrt(TWAP) over the past `UNISWAP_AVG_WINDOW` seconds\n     */\n    function consult(IUniswapV3Pool pool, uint40 seed) internal view returns (uint56 metric, uint160 sqrtMeanPriceX96) {\n        unchecked {\n            int56[] memory tickCumulatives = new int56[](3);\n\n            if ((seed >> 32) > 0) {\n                uint32[] memory secondsAgos = new uint32[](3);\n                secondsAgos[0] = UNISWAP_AVG_WINDOW * 2;\n                secondsAgos[1] = UNISWAP_AVG_WINDOW;\n                secondsAgos[2] = 0;\n                (tickCumulatives, ) = pool.observe(secondsAgos);\n            } else {\n                (, int24 currentTick, uint16 observationIndex, uint16 observationCardinality, , , ) = pool.slot0();\n                {\n                    (, , , bool initialized) = pool.observations((observationIndex + 1) % observationCardinality);\n                    if (!initialized) observationCardinality = observationIndex + 1;\n                }\n\n                (tickCumulatives[0], ) = observe(\n                    pool,\n                    uint32(block.timestamp - UNISWAP_AVG_WINDOW * 2),\n                    seed >> 16,\n                    currentTick,\n                    observationIndex,\n                    observationCardinality\n                );\n                (tickCumulatives[1], ) = observe(\n                    pool,\n                    uint32(block.timestamp - UNISWAP_AVG_WINDOW),\n                    seed % Q16,\n                    currentTick,\n                    observationIndex,\n                    observationCardinality\n                );\n                (tickCumulatives[2], ) = observe(\n                    pool,\n                    uint32(block.timestamp),\n                    observationIndex,\n                    currentTick,\n                    observationIndex,\n                    observationCardinality\n                );\n            }\n\n            // Compute arithmetic mean tick over `UNISWAP_AVG_WINDOW`, always rounding down to -inf\n            int256 delta = tickCumulatives[2] - tickCumulatives[1];\n            int256 meanTick0ToW = delta / int32(UNISWAP_AVG_WINDOW);\n            assembly (\"memory-safe\") {\n                // Equivalent: if (delta < 0 && (delta % UNISWAP_AVG_WINDOW != 0)) meanTick0ToW--;\n                meanTick0ToW := sub(meanTick0ToW, and(slt(delta, 0), iszero(iszero(smod(delta, UNISWAP_AVG_WINDOW)))))\n            }\n            sqrtMeanPriceX96 = TickMath.getSqrtRatioAtTick(int24(meanTick0ToW));\n\n            // Compute arithmetic mean tick over the interval [-2w, 0)\n            int256 meanTick0To2W = (tickCumulatives[2] - tickCumulatives[0]) / int32(UNISWAP_AVG_WINDOW * 2);\n            // Compute arithmetic mean tick over the interval [-2w, -w]\n            int256 meanTickWTo2W = (tickCumulatives[1] - tickCumulatives[0]) / int32(UNISWAP_AVG_WINDOW);\n            //                                         i                 i-2w                       i-w               i-2w\n            //        meanTick0To2W - meanTickWTo2W = (∑ tick_n * dt_n - ∑ tick_n * dt_n) / (2T) - (∑ tick_n * dt_n - ∑ tick_n * dt_n) / T\n            //                                         n=0               n=0                        n=0               n=0\n            //\n            //                                        i                   i-w\n            // 2T * (meanTick0To2W - meanTickWTo2W) = ∑ tick_n * dt_n  - 2∑ tick_n * dt_n\n            //                                        n=i-2w              n=i-2w\n            //\n            //                                        i                   i-w\n            //                                      = ∑ tick_n * dt_n  -  ∑ tick_n * dt_n\n            //                                        n=i-w               n=i-2w\n            //\n            // Thus far all values have been \"true\". We now assume that some manipulated value `manip_n` is added to each `tick_n`\n            //\n            //                                        i                               i-w\n            //                                      = ∑ (tick_n + manip_n) * dt_n  -  ∑ (tick_n + manip_n) * dt_n\n            //                                        n=i-w                           n=i-2w\n            //\n            //                                        i                   i-w                 i                    i-w\n            //                                      = ∑ tick_n * dt_n  -  ∑ tick_n * dt_n  +  ∑ manip_n * dt_n  -  ∑ manip_n * dt_n\n            //                                        n=i-w               n=i-2w              n=i-w                n=i-2w\n            //\n            //        meanTick0To2W - meanTickWTo2W = (meanTick0ToW_true - meanTickWTo2W_true) / 2  +  (sumManip0ToW - sumManipWTo2W) / (2T)\n            //\n            // For short time periods and reasonable market conditions, (meanTick0ToW_true - meanTickWTo2W_true) ≈ 0\n            //\n            //                                      ≈ (sumManip0ToW - sumManipWTo2W) / (2T)\n            //\n            // The TWAP we care about (see a few lines down) is measured over the interval [-w, 0). The result we've\n            // just derived contains `sumManip0ToW`, which is the sum of all manipulation in that same interval. As\n            // such, we use it as a metric for detecting manipulation. NOTE: If an attacker manipulates things to\n            // the same extent in the prior interval [-2w, -w), the metric will be 0. To guard against this, we must\n            // to watch the metric over the entire window. Even though it may be 0 *now*, it will have risen past a\n            // threshold at *some point* in the past `UNISWAP_AVG_WINDOW` seconds.\n            metric = uint56(SoladyMath.dist(meanTick0To2W, meanTickWTo2W));\n        }\n    }\n\n    /**\n     * @notice Searches for oracle observations nearest to the `target` time. If `target` lies between two existing\n     * observations, linearly interpolate between them. If `target` is newer than the most recent observation,\n     * we interpolate between the most recent one and a hypothetical one taken at the current block.\n     * @dev As long as `target <= block.timestamp`, return values should match what you'd get from Uniswap.\n     * @custom:example ```solidity\n     *   uint32[] memory secondsAgos = new uint32[](1);\n     *   secondsAgos[0] = block.timestamp - target;\n     *   (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) = pool.observe(\n     *     secondsAgos\n     *   );\n     * ```\n     * @param pool The Uniswap pool to examine\n     * @param target The timestamp of the desired observation\n     * @param seed The index of `pool.observations` where we start our search. Can be determined off-chain to make\n     * this method more efficient than Uniswap's binary search.\n     * @param tick The current tick (from `pool.slot0()`)\n     * @param observationIndex The current observation index (from `pool.slot0()`)\n     * @param observationCardinality The current observation cardinality. Should be determined as follows:\n     * ```solidity\n     *   (, , uint16 observationIndex, uint16 observationCardinality, , , ) = pool.slot0();\n     *   (, , , bool initialized) = pool.observations((observationIndex + 1) % observationCardinality);\n     *   if (!initialized) observationCardinality = observationIndex + 1;\n     * ```\n     * NOTE: If you fail to account for the `!initialized` case, and `target` comes before the oldest observation,\n     * this may return incorrect data instead of reverting with \"OLD\".\n     * @return The tick * time elapsed since `pool` was first initialized\n     * @return The time elapsed / max(1, liquidity) since `pool` was first initialized\n     */\n    function observe(\n        IUniswapV3Pool pool,\n        uint32 target,\n        uint256 seed,\n        int24 tick,\n        uint16 observationIndex,\n        uint16 observationCardinality\n    ) internal view returns (int56, uint160) {\n        unchecked {\n            seed %= observationCardinality;\n            (uint32 timeL, int56 tickCumL, uint160 liqCumL, ) = pool.observations(seed);\n\n            for (uint256 i = 0; i < observationCardinality; i++) {\n                if (timeL == target) {\n                    return (tickCumL, liqCumL);\n                }\n\n                if (timeL < target && seed == observationIndex) {\n                    uint56 delta = target - timeL;\n                    uint128 liquidity = pool.liquidity();\n                    return (\n                        tickCumL + tick * int56(delta),\n                        liqCumL + (uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)\n                    );\n                }\n\n                seed = (seed + 1) % observationCardinality;\n                (uint32 timeR, int56 tickCumR, uint160 liqCumR, ) = pool.observations(seed);\n\n                if (timeL < target && target < timeR) {\n                    uint56 delta = target - timeL;\n                    uint56 denom = timeR - timeL;\n                    // Uniswap divides before multiplying, so we do too\n                    return (\n                        tickCumL + ((tickCumR - tickCumL) / int56(denom)) * int56(delta),\n                        liqCumL + uint160((uint256(liqCumR - liqCumL) * delta) / denom)\n                    );\n                }\n\n                (timeL, tickCumL, liqCumL) = (timeR, tickCumR, liqCumR);\n            }\n\n            revert(\"OLD\");\n        }\n    }\n\n    /**\n     * @notice Given a pool, returns the number of seconds ago of the oldest stored observation\n     * @param pool Address of Uniswap V3 pool that we want to observe\n     * @param observationIndex The observation index from pool.slot0()\n     * @param observationCardinality The observationCardinality from pool.slot0()\n     * @dev `(, , uint16 observationIndex, uint16 observationCardinality, , , ) = pool.slot0();`\n     * @return secondsAgo The number of seconds ago that the oldest observation was stored\n     */\n    function getMaxSecondsAgo(\n        IUniswapV3Pool pool,\n        uint16 observationIndex,\n        uint16 observationCardinality\n    ) internal view returns (uint32 secondsAgo) {\n        require(observationCardinality != 0, \"NI\");\n\n        unchecked {\n            (uint32 observationTimestamp, , , bool initialized) = pool.observations(\n                (observationIndex + 1) % observationCardinality\n            );\n\n            // The next index might not be initialized if the cardinality is in the process of increasing\n            // In this case the oldest observation is always in index 0\n            if (!initialized) {\n                (observationTimestamp, , , ) = pool.observations(0);\n            }\n\n            secondsAgo = uint32(block.timestamp) - observationTimestamp;\n        }\n    }\n}\n"
      },
      "src/libraries/Volatility.sol": {
        "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity 0.8.23;\n\nimport {FixedPointMathLib as SoladyMath} from \"solady/utils/FixedPointMathLib.sol\";\n\n/// @title Volatility\n/// @notice Provides functions that use Uniswap v3 to compute price volatility\n/// @author Aloe Labs, Inc.\nlibrary Volatility {\n    using SoladyMath for uint256;\n\n    struct PoolMetadata {\n        // the overall fee minus the protocol fee for token0, times 1e6\n        uint24 gamma0;\n        // the overall fee minus the protocol fee for token1, times 1e6\n        uint24 gamma1;\n        // the pool tick spacing\n        int24 tickSpacing;\n    }\n\n    struct FeeGrowthGlobals {\n        // the fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n        uint256 feeGrowthGlobal0X128;\n        // the fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n        uint256 feeGrowthGlobal1X128;\n        // the block timestamp at which feeGrowthGlobal0X128 and feeGrowthGlobal1X128 were last updated\n        uint32 timestamp;\n    }\n\n    uint256 private constant _Q224Div1e18 = (uint256(1 << 224) * 1e6) / 1e24; // solhint-disable const-name-snakecase\n    uint256 private constant _Q128Div1e18 = (uint256(1 << 128) * 1e6) / 1e24; // solhint-disable const-name-snakecase\n\n    /**\n     * @notice Estimates implied volatility using\n     * [this math](https://lambert-guillaume.medium.com/on-chain-volatility-and-uniswap-v3-d031b98143d1).\n     * @dev The return value can fit in uint128 if necessary\n     * @param metadata The pool's metadata (may be cached)\n     * @param sqrtMeanPriceX96 sqrt(TWAP) over some period. Likely from `Oracle.consult`\n     * @param a The pool's cumulative feeGrowthGlobals some time in the past\n     * @param b The pool's cumulative feeGrowthGlobals as of the current block\n     * @param scale The timescale (in seconds) in which IV should be reported, e.g. hourly, daily, annualized\n     * @return An estimate of the implied volatility scaled by 1e12\n     */\n    function estimate(\n        PoolMetadata memory metadata,\n        uint160 sqrtMeanPriceX96,\n        FeeGrowthGlobals memory a,\n        FeeGrowthGlobals memory b,\n        uint32 scale\n    ) internal pure returns (uint256) {\n        unchecked {\n            // Return early to avoid division by 0\n            if (b.timestamp - a.timestamp == 0) return 0;\n\n            // Goal:  IV = 2γ √(volume / valueOfLiquidity)\n            //\n            //  γ = √(γ₀γ₁)\n            //  volume ≈ ((P · fgg0 / γ₀) + (fgg1 / γ₁)) · liquidity\n            //  valueOfLiquidity = (tickSpacing · liquidity · √P) / 20000\n            //\n            //        IV = 2 √( 20000 · γ₀γ₁ · ((P · fgg0 / γ₀) + (fgg1 / γ₁)) / √P / tickSpacing )\n            //           = 2 √( 20000 ·        ((P · fgg0 · γ₁) + (fgg1 · γ₀)) / √P / tickSpacing )\n            //           = 2 √( 20000 ·        (fgg0 · γ₁ · √P  +  fgg1 · γ₀ / √P)  / tickSpacing )\n\n            // Calculate average [fees per unit of liquidity] for this time period\n            uint256 fgg0X128 = b.feeGrowthGlobal0X128 - a.feeGrowthGlobal0X128;\n            uint256 fgg1X128 = b.feeGrowthGlobal1X128 - a.feeGrowthGlobal1X128;\n\n            // Start math.\n            // Also remove Q128 and instead scale by 1e24 (gammas have 1e6, and we pull 1e18 out of the denominator).\n            uint256 fgg0Gamma1MulP = fgg0X128.fullMulDiv(uint256(metadata.gamma1) * sqrtMeanPriceX96, _Q224Div1e18);\n            uint256 fgg1Gamma0DivP = fgg1X128.fullMulDiv(\n                uint256(metadata.gamma0) << 96,\n                sqrtMeanPriceX96 * _Q128Div1e18\n            );\n\n            // Make sure numerator won't overflow in the next step\n            uint256 inner = (fgg0Gamma1MulP + fgg1Gamma0DivP).min(uint256(1 << 224) / 20_000);\n\n            // Finish math and adjust to specified timescale\n            return\n                2 *\n                SoladyMath.sqrt(\n                    (20_000 * inner * scale) / (b.timestamp - a.timestamp) / uint256(int256(metadata.tickSpacing))\n                );\n        }\n    }\n}\n"
      },
      "lib/clones-with-immutable-args/src/Create2.sol": {
        "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.15;\n\n/**\n * @author OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.8.0/contracts/utils/Create2.sol)\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40) // Get free memory pointer\n\n            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |\n            // | salt              |                                      BBBBBBBBBBBBB...BB                   |\n            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |\n            // | 0xFF              |            FF                                                             |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n            mstore(add(ptr, 0x40), bytecodeHash)\n            mstore(add(ptr, 0x20), salt)\n            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n            mstore8(start, 0xff)\n            addr := keccak256(start, 85)\n        }\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/introspection/IERC165.sol\";\n"
      },
      "lib/openzeppelin-contracts/contracts/interfaces/IERC2612.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC2612.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/extensions/IERC20Permit.sol\";\n\ninterface IERC2612 is IERC20Permit {}\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/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/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "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/IERC20Metadata.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "forge-std/=lib/forge-std/src/",
        "clones-with-immutable-args/=lib/clones-with-immutable-args/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/",
        "solady/=lib/solady/src/",
        "solmate/=lib/solmate/src/",
        "v3-core/=lib/v3-core/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 100000000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": true,
      "libraries": {}
    }
  }}