// File: src/MaxApyVault.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

import {BaseVault, StrategyData, IERC20, Math, SafeTransferLib, IStrategy} from "./base/BaseVault.sol";

/*KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
KKKKK0OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO0KKKKKKK
KK0dcclllllllllllllllllllllllllllllccccccccccccccccccclx0KKK
KOc,dKNWWWWWWWWWWWWWWWWWWWWWWWWWWWWNNNNNNNNNNNNNNNNNXOl';xKK
Kd'oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMX; ,kK
Ko'xMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .dK
Ko'dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
Kd'oWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KO:,xXWWWWWWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKOl,',;;,,,,,,;;,,,,,,,;;cxXMMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKOoc;;;;;;;;;;;;;;;;;;;,.cXMMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKKKKK00O00K0:,0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKKKklcccccld;,0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKKKkl;ckXNXOc. '0MMMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKKKkc;l0WMMMMMX; .oKNMMMMMMMMMMMMMMMMMMMMMMNc .oK
KKKKKKKKKKKKkc;l0WMMMMMMMWd.  .,lddddddxONMMMMMMMMMMMMNc .oK
KKKKKKKKKKkc;l0WMMMMMMMMMMWOl::;'.  .....:0WMMMMMMMMMMNc .oK
KKKKKKK0xc;o0WMMMMMMMMMMMMMMMMMWNk'.;xkko'lNMMMMMMMMMMNc .oK
KKKKK0x:;oKWMMMMMMMMMMMMMMMMMMMMMWd..lKKk,lNMMMMMMMMMMNc .oK
KKK0x:;oKWMMMMMMMMMMMMMMMMMMMMMMWO,  c0Kk,lNMMMMMMMMMMNc .oK
KKx:;dKWMMMMMMMMMMMMMMMMMMMMMWN0c.  ;kKKk,lNMMMMMMMMMMNc .oK
Kx,:KWMMMMMMMMMMMMMMMMMMMMMW0c,.  'oOKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMMMMMW0c.   'oOKKKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMMMW0c.  ':oOKKKKKKKk,lNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMMMW0l.  'oOKKKKKKKKKKk,cNMMMMMMMMMMNc .oK
Ko'xMMMMMMMMMMMMMMMW0l.  'oOKKKKKKKKKKKKk,lNMMMMMMMMMMNc .oK
Ko'dWMMMMMMMMMMMMW0l.  'oOKKKKKKKKKKKKKKk,cNMMMMMMMMMMX: .oK
KO:,xXNWWWWWWWWNOl.  'oOKKKKKKKKKKKKKKKK0c,xNMMMMMMMMNd. .dK
KKOl''',,,,,,,,..  'oOKKKKKKKKKKKKKKKKKKKOl,,ccccccc:'  .c0K
KKKKOoc:;;;;;;;;:ldOKKKKKKKKKKKKKKKKKKKKKKKkl;'......',cx0KK
KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK0OOOOOOO0KKK*/

/// @title MaxApy Vault Contract
/// @notice A vault contract deploying `underlyingAsset` to strategies that earn yield and report gains/losses to the vault
/// @author Forked and adapted from YVaults (https://github.com/yearn/yearn-vaults/blob/efb47d8a84fcb13ceebd3ceb11b126b323bcc05d/contracts/Vault.vy)
contract MaxApyVault is BaseVault {
    using SafeTransferLib for address;

    ////////////////////////////////////////////////////////////////
    ///                     CONSTRUCTOR                          ///
    ////////////////////////////////////////////////////////////////
    /// @dev Create the Vault
    /// @param _underlyingAsset The vault's underlying asset that will be deposited by users
    /// @param _name The ERC20 token name for the vault's shares token
    /// @param _symbol The ERC20 token symbol for the vault's shares token
    constructor(IERC20 _underlyingAsset, string memory _name, string memory _symbol, address _treasury)
        BaseVault(_underlyingAsset, _name, _symbol)
    {
        performanceFee = 1000; // 10% of reported yield (per Strategy)
        managementFee = 200; // 2% of reported yield (per Strategy)
        depositLimit = type(uint256).max;
        lastReport = block.timestamp;
        lockedProfitDegradation = (DEGRADATION_COEFFICIENT * 46) / 10 ** 6; // 6 hours in blocks
        treasury = _treasury;
    }

    ////////////////////////////////////////////////////////////////
    ///                 DEPOSIT/WITHDRAWAL LOGIC                 ///
    ////////////////////////////////////////////////////////////////

    /// @notice Deposits `amount` of `underlyingAsset`, issuing shares to `recipient`. If the Vault is in Emergency Shutdown,
    /// deposits will not be accepted and this call will fail.
    /// @dev Measuring quantity of shares to issue is based on the total outstanding debt that this contract
    /// has ("expected value") instead of the total balance sheet it has ("estimated value"). This has important
    /// security considerations, and is done intentionally. If this value were measured against external systems, it
    /// could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able
    /// to claim by redeeming their shares.
    /// @param amount The quantity of tokens to deposit
    /// @param recipient The address to issue the shares in this Vault to
    function deposit(uint256 amount, address recipient) external noEmergencyShutdown nonReentrant returns (uint256) {
        uint256 totalIdle_;
        assembly ("memory-safe") {
            // if recipient == address(0)
            if iszero(shl(96, recipient)) {
                // throw the `InvalidZeroAddress` error
                mstore(0x00, 0xf6b2911f)
                revert(0x1c, 0x04)
            }
            // if amount == 0
            if iszero(amount) {
                // throw the `InvalidZeroAmount` error
                mstore(0x00, 0xdd484e70)
                revert(0x1c, 0x04)
            }

            // Get totalAssets, same as calling _totalAssets() but caching totalIdle
            totalIdle_ := sload(totalIdle.slot)
            let totalAssets_ := add(totalIdle_, sload(totalDebt.slot))
            if lt(totalAssets_, totalIdle_) { revert(0, 0) }

            // check if totalAssets + amount overflows
            let total := add(totalAssets_, amount)
            if lt(total, totalAssets_) { revert(0, 0) }
            // if totalAssets + amount > depositLimit
            if gt(total, sload(depositLimit.slot)) {
                // throw the `VaultDepositLimitExceeded` error
                mstore(0x00, 0x0c11966b)
                revert(0x1c, 0x04)
            }
        }

        /// Issue new shares (needs to be done before taking deposit to be accurate and not modify `_totalAssets()`)
        // Inline _issueSharesForAmount(recipient, amount) saves 50 gas
        uint256 vaultTotalSupply = totalSupply();
        uint256 shares = amount;
        /// By default minting 1:1 shares

        if (vaultTotalSupply != 0) {
            /// Mint amount of tokens based on what the Vault is managing overall
            shares = (amount * vaultTotalSupply) / _freeFunds();
        }

        assembly ("memory-safe") {
            // if shares == 0
            if iszero(shares) {
                // Throw the `InvalidZeroShares` error
                mstore(0x00, 0x5a870a25)
                revert(0x1c, 0x04)
            }
        }

        _mint(recipient, shares);

        address(underlyingAsset).safeTransferFrom(msg.sender, address(this), amount);

        assembly ("memory-safe") {
            sstore(totalIdle.slot, add(totalIdle_, amount))
            // Emit the `Deposit` event
            mstore(0x00, shares)
            mstore(0x20, amount)
            log2(0x00, 0x40, _DEPOSIT_EVENT_SIGNATURE, recipient)
        }

        return shares;
    }

    /// @notice Withdraws the calling account's tokens from this Vault, redeeming
    /// amount `shares` for the corresponding amount of tokens
    /// @dev Measuring quantity of shares to issue is based on the total outstanding debt that this contract
    /// has ("expected value") instead of the total balance sheet it has ("estimated value"). This has important
    /// security considerations, and is done intentionally. If this value were measured against external systems, it
    /// could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able
    /// to claim by redeeming their shares
    /// @param shares How many shares to try and redeem for tokens
    /// @param recipient The address to issue the shares in this Vault to
    /// @param maxLoss The maximum acceptable loss to sustain on withdrawal. Up to loss specified amount of shares may be
    /// burnt to cover losses on withdrawal
    function withdraw(uint256 shares, address recipient, uint256 maxLoss) external nonReentrant returns (uint256) {
        assembly ("memory-safe") {
            // if maxLoss > MAX_BPS
            if gt(maxLoss, MAX_BPS) {
                // throw the `InvalidMaxLoss` error
                mstore(0x00, 0xef374dc7)
                revert(0x1c, 0x04)
            }

            // if shares == 0
            if iszero(shares) {
                // throw the `InvalidZeroShares` error
                mstore(0x00, 0x5a870a25)
                revert(0x1c, 0x04)
            }

            // if (shares == type(uint256).max) shares = balanceOf(msg.sender);
            if eq(shares, not(0)) {
                // compute `balanceOf(msg.sender)` and store it in `shares`
                mstore(0x0c, 0x87a211a2) // `_BALANCE_SLOT_SEED`
                mstore(0x00, caller())
                shares := sload(keccak256(0x0c, 0x20))
            }
        }

        // Cache underlying asset
        IERC20 underlying = underlyingAsset;

        uint256 valueToWithdraw = _shareValue(shares);
        uint256 vaultBalance = totalIdle;

        // Check if value to withdraw exceeds vault balance
        if (valueToWithdraw > vaultBalance) {
            // Vault balance is not enough to cover withdrawal. We need to perform forced withdrawals
            // from strategies until requested value amount is covered.
            // During forced withdrawal, a Strategy may realize a loss, which is reported back to the
            // Vault. This will affect the withdrawer, affecting the amount of tokens they will
            // receive in exchange for their shares.

            uint256 totalLoss;

            // Iterate over strategies
            for (uint256 i; i < MAXIMUM_STRATEGIES;) {
                address strategy = withdrawalQueue[i];

                // Check if we have exhausted the queue
                if (strategy == address(0)) break;

                // Check if the vault balance is finally enough to cover the requested withdrawal
                if (vaultBalance >= valueToWithdraw) break;

                uint256 slotStrategies2;
                // Compute remaining amount to withdraw considering the current balance of the vault
                uint256 amountNeeded;
                assembly ("memory-safe") {
                    // amountNeeded = valueToWithdraw - vaultBalance;
                    amountNeeded := sub(valueToWithdraw, vaultBalance)

                    // cache slot strategies[strategy].strategyTotalDebt
                    mstore(0x00, strategy)
                    mstore(0x20, strategies.slot)
                    slotStrategies2 := add(keccak256(0x00, 0x40), 2)

                    // compute strategies[strategy].strategyTotalDebt
                    let strategyTotalDebt := shr(128, shl(128, sload(slotStrategies2)))

                    // Don't withdraw more than the debt loaned to the strategy so that the strategy can still continue
                    // to work based on the profits it has.

                    // amountNeeded = Math.min(amountNeeded, strategyTotalDebt)
                    amountNeeded :=
                        xor(amountNeeded, mul(xor(amountNeeded, strategyTotalDebt), lt(strategyTotalDebt, amountNeeded)))
                }

                // Try the next strategy if the current strategy has no debt to be withdrawn
                if (amountNeeded == 0) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                // Withdraw from strategy. Compute amount withdrawn
                // considering the difference between balances pre/post withdrawal
                uint256 preBalance = underlying.balanceOf(address(this));
                uint256 loss = IStrategy(strategy).withdraw(amountNeeded);

                uint256 withdrawn = underlying.balanceOf(address(this)) - preBalance;

                // Increase cached vault balance to track the newly withdrawn amount
                vaultBalance += withdrawn;

                // If loss has been realised, withdrawer will incur it, affecting to the amount
                // of value they will receive in exchange for their shares
                if (loss != 0) {
                    valueToWithdraw -= loss;
                    totalLoss += loss;
                    _reportLoss(strategy, loss);
                }

                assembly ("memory-safe") {
                    // Reduce debts by the amount withdrawn
                    //totalDebt -= withdrawn;
                    let totalDebt_ := sload(totalDebt.slot)
                    if gt(withdrawn, totalDebt_) { revert(0, 0) }
                    sstore(totalDebt.slot, sub(totalDebt_, withdrawn))

                    // compute strategies[strategy].strategyTotalDebt
                    let slotContent := sload(slotStrategies2)
                    let strategyTotalDebt := sub(shr(128, shl(128, slotContent)), withdrawn)
                    // strategies[strategy].strategyTotalDebt -= uint128(withdrawn);
                    sstore(slotStrategies2, or(shl(128, shr(128, slotContent)), strategyTotalDebt))
                    // Emit the `WithdrawFromStrategy` event
                    mstore(0x00, strategyTotalDebt)
                    mstore(0x20, loss)
                    log2(0x00, 0x40, _WITHDRAW_FROM_STRATEGY_EVENT_SIGNATURE, strategy)
                }

                unchecked {
                    ++i;
                }
            }

            // Update total idle with the actual vault balance that considers the total withdrawn amount
            totalIdle = vaultBalance;

            // We have withdrawn everything possible out of the withdrawal queue but we still don't
            // have enough to fully pay the user back. Adjust the total amount we've freed up through
            // forced withdrawals
            if (valueToWithdraw > vaultBalance) {
                valueToWithdraw = vaultBalance;
                // Burn number of shares that corresponds to what Vault has on-hand,
                // including the losses incurred during withdrawals
                shares = _sharesForAmount(valueToWithdraw + totalLoss);
            }

            assembly ("memory-safe") {
                let sum := add(valueToWithdraw, totalLoss)
                if lt(sum, valueToWithdraw) {
                    // throw the `Overflow` error
                    revert(0, 0)
                }
                // Ensure max loss allowed has not been reached
                // if (totalLoss > (maxLoss * (valueToWithdraw + totalLoss)) / MAX_BPS)
                if gt(totalLoss, div(mul(maxLoss, sum), MAX_BPS)) {
                    // no need to check overflow here maxLoss is capped at MAX_BPS
                    // throw the `MaxLossReached` error
                    mstore(0x00, 0x9ec5941d)
                    revert(0x1c, 0x04)
                }
            }
        }

        // Burn shares
        _burn(msg.sender, shares);

        // Reduce value withdrawn from vault total idle
        totalIdle -= valueToWithdraw;

        // Transfer underlying to `recipient`
        address(underlying).safeTransfer(recipient, valueToWithdraw);

        assembly ("memory-safe") {
            // Emit the `Withdraw` event
            mstore(0x00, shares)
            mstore(0x20, valueToWithdraw)
            log2(0x00, 0x40, _WITHDRAW_EVENT_SIGNATURE, recipient)
        }

        return valueToWithdraw;
    }

    ////////////////////////////////////////////////////////////////
    ///                      REPORT LOGIC                        ///
    ////////////////////////////////////////////////////////////////

    /// @notice  Reports the amount of assets the calling Strategy has free (usually in terms of ROI).
    /// The performance fee is determined here, off of the strategy's profits (if any), and sent to governance.
    /// The strategist's fee is also determined here (off of profits), to be handled according to the strategist on the next harvest.
    /// @dev For approved strategies, this is the most efficient behavior. The Strategy reports back what it has free, then
    /// Vault "decides" whether to take some back or give it more.
    /// Note that the most it can take is `gain + debtPayment`, and the most it can give is all of the
    /// remaining reserves. Anything outside of those bounds is abnormal behavior
    /// @param gain Amount Strategy has realized as a gain on its investment since its last report, and is free
    /// to be given back to Vault as earnings
    /// @param loss Amount Strategy has realized as a loss on its investment since its last report, and should be
    /// accounted for on the Vault's balance sheet. The loss will reduce the debtRatio for the strategy and vault.
    /// The next time the strategy will harvest, it will pay back the debt in an attempt to adjust to the new debt limit.
    /// @param debtPayment Amount Strategy has made available to cover outstanding debt
    /// @return debt Amount of debt outstanding (if totalDebt > debtLimit or emergency shutdown).
    function report(uint128 gain, uint128 loss, uint128 debtPayment)
        external
        checkRoles(STRATEGY_ROLE)
        returns (uint256)
    {
        // Cache underlying asset
        IERC20 underlying = underlyingAsset;
        // Cache strategy balance
        uint256 senderBalance = underlying.balanceOf(msg.sender);

        assembly ("memory-safe") {
            // Ensure strategy reporting actually has enough funds to cover `gain` and `debtPayment`
            let sum := add(gain, debtPayment)
            if lt(sum, gain) {
                // throw the `Overflow` error
                revert(0, 0)
            }
            // if (underlying.balanceOf(msg.sender) < gain + debtPayment)
            if lt(senderBalance, sum) {
                // throw the `InvalidReportedGainAndDebtPayment` error
                mstore(0x00, 0x746feeec)
                revert(0x1c, 0x04)
            }
        }

        // If strategy suffered a loss, report it
        if (loss > 0) {
            _reportLoss(msg.sender, loss);
        }

        // Assess both management fee and performance fee, and issue both as shares of the vault
        uint256 totalFees = _assessFees(msg.sender, gain);

        // Set gain returns as realized gains for the vault
        strategies[msg.sender].strategyTotalGain += gain;

        // Compute the line of credit the Vault is able to offer the Strategy (if any)
        uint256 credit = _creditAvailable(msg.sender);

        // Compute excess of debt the Strategy wants to transfer back to the Vault (if any)
        uint256 debt = _debtOutstanding(msg.sender);

        // Adjust excess of reported debt payment by the debt outstanding computed
        debtPayment = uint128(Math.min(uint256(debtPayment), debt));

        if (debtPayment != 0) {
            strategies[msg.sender].strategyTotalDebt -= debtPayment;
            totalDebt -= debtPayment;
            debt -= debtPayment;
        }

        // Update the actual debt based on the full credit we are extending to the Strategy
        if (credit != 0) {
            strategies[msg.sender].strategyTotalDebt += uint128(credit);
            totalDebt += credit;
        }

        // Give/take corresponding amount to/from Strategy, based on the difference between the reported gains
        // and the debt needed to be paid off (if any)
        uint256 totalReportedAmount = gain + debtPayment;

        unchecked {
            if (credit > totalReportedAmount) {
                // Credit is greater than the amount reported by the strategy, send funds **to** strategy
                totalIdle -= (credit - totalReportedAmount);
                address(underlying).safeTransfer(msg.sender, credit - totalReportedAmount);
            } else if (totalReportedAmount > credit) {
                // Amount reported by the strategy is greater than the credit, take funds **from** strategy
                totalIdle += (totalReportedAmount - credit);
                address(underlying).safeTransferFrom(msg.sender, address(this), totalReportedAmount - credit);
            }

            // else don't do anything (credit and reported amounts are balanced, hence no transfers need to be executed)
        }

        // Profit is locked and gradually released per block
        uint256 lockedProfitBeforeLoss = _calculateLockedProfit() + gain - totalFees;

        if (lockedProfitBeforeLoss > 0) {
            lockedProfit = lockedProfitBeforeLoss - loss;
        } else {
            lockedProfit = 0;
        }

        // Update reporting time
        strategies[msg.sender].strategyLastReport = uint48(block.timestamp);
        lastReport = block.timestamp;

        emit StrategyReported(
            msg.sender,
            gain,
            loss,
            debtPayment,
            strategies[msg.sender].strategyTotalGain,
            strategies[msg.sender].strategyTotalLoss,
            strategies[msg.sender].strategyTotalDebt,
            credit,
            strategies[msg.sender].strategyDebtRatio
        );

        if (strategies[msg.sender].strategyDebtRatio == 0 || emergencyShutdown) {
            // Take every last penny the Strategy has (Emergency Exit/revokeStrategy)
            return IStrategy(msg.sender).estimatedTotalAssets();
        }

        // Otherwise, just return what we have as debt outstanding
        return debt;
    }

    ////////////////////////////////////////////////////////////////
    ///                STRATEGIES CONFIGURATION                  ///
    ////////////////////////////////////////////////////////////////

    /// @notice Adds a new strategy
    /// @dev The Strategy will be appended to `withdrawalQueue`, and `_organizeWithdrawalQueue` will reorganize the queue order
    /// @param newStrategy The new strategy to add
    /// @param strategyDebtRatio The percentage of the total assets in the vault that the `newStrategy` has access to
    /// @param strategyMaxDebtPerHarvest Lower limit on the increase of debt since last harvest
    /// @param strategyMinDebtPerHarvest Upper limit on the increase of debt since last harvest
    /// @param strategyPerformanceFee The fee the strategist will receive based on this Vault's performance
    function addStrategy(
        address newStrategy,
        uint256 strategyDebtRatio,
        uint256 strategyMaxDebtPerHarvest,
        uint256 strategyMinDebtPerHarvest,
        uint256 strategyPerformanceFee
    ) external checkRoles(ADMIN_ROLE) noEmergencyShutdown {
        uint256 slot; // Slot where strategies[newStrategy] slot will be stored

        assembly ("memory-safe") {
            // General checks

            // if (withdrawalQueue[MAXIMUM_STRATEGIES - 1] != address(0))
            if sload(add(withdrawalQueue.slot, sub(MAXIMUM_STRATEGIES, 1))) {
                // throw `QueueIsFull()` error
                mstore(0x00, 0xa3d0cff3)
                revert(0x1c, 0x04)
            }

            // Strategy checks
            // if (newStrategy == address(0))
            if iszero(newStrategy) {
                // throw `InvalidZeroAddress()` error
                mstore(0x00, 0xf6b2911f)
                revert(0x1c, 0x04)
            }

            // Compute strategies[newStrategy] slot
            mstore(0x00, newStrategy)
            mstore(0x20, strategies.slot)
            slot := keccak256(0x00, 0x40)

            // if (strategies[newStrategy].strategyActivation != 0)
            if shr(208, shl(176, sload(slot))) {
                // throw `StrategyAlreadyActive()` error
                mstore(0x00, 0xc976754d)
                revert(0x1c, 0x04)
            }
        }
        if (IStrategy(newStrategy).vault() != address(this)) {
            assembly ("memory-safe") {
                // throw `InvalidStrategyVault()` error
                mstore(0x00, 0xac4e0773)
                revert(0x1c, 0x04)
            }
        }
        if (IStrategy(newStrategy).underlyingAsset() != address(underlyingAsset)) {
            assembly ("memory-safe") {
                // throw `InvalidStrategyUnderlying()` error
                mstore(0x00, 0xf083d3f1)
                revert(0x1c, 0x04)
            }
        }

        if (IStrategy(newStrategy).strategist() == address(0)) {
            assembly ("memory-safe") {
                // throw `StrategyMustHaveStrategist()` error
                mstore(0x00, 0xeb8bf8b6)
                revert(0x1c, 0x04)
            }
        }

        uint256 debtRatio_;
        assembly ("memory-safe") {
            debtRatio_ := sload(debtRatio.slot)
            // Compute debtRatio + strategyDebtRatio
            let sum := add(debtRatio_, strategyDebtRatio)
            if lt(sum, strategyDebtRatio) {
                // throw the `Overflow` error
                revert(0, 0)
            }

            // if (debtRatio + strategyDebtRatio > MAX_BPS)
            if gt(sum, MAX_BPS) {
                // throw the `InvalidDebtRatio` error
                mstore(0x00, 0x79facb0d)
                revert(0x1c, 0x04)
            }

            // if (strategyMinDebtPerHarvest > strategyMaxDebtPerHarvest)
            if gt(strategyMinDebtPerHarvest, strategyMaxDebtPerHarvest) {
                // throw the `InvalidMinDebtPerHarvest` error
                mstore(0x00, 0x5f3bd953)
                revert(0x1c, 0x04)
            }

            // if (strategyPerformanceFee > 5000)
            if gt(strategyPerformanceFee, 5000) {
                // throw the `InvalidPerformanceFee` error
                mstore(0x00, 0xf14508d0)
                revert(0x1c, 0x04)
            }

            // Add strategy to strategies mapping
            // Strategy struct
            // StrategyData({
            //     strategyPerformanceFee: uint16(strategyPerformanceFee),
            //     strategyDebtRatio: uint16(strategyDebtRatio),
            //     strategyActivation: uint48(block.timestamp),
            //     strategyLastReport: uint48(block.timestamp),
            //     strategyMaxDebtPerHarvest: uint128(strategyMaxDebtPerHarvest),
            //     strategyMinDebtPerHarvest: uint128(strategyMinDebtPerHarvest),
            //     strategyTotalDebt: 0,
            //     strategyTotalGain: 0,
            //     strategyTotalLoss: 0
            // });

            // Using yul saves 5k gas, bitmasks are used to create the `StrategyData` struct above.
            // Slot 0 and slot 1 will be updated. Slot 2 is not updated since it stores `strategyTotalDebt`
            // and `strategyTotalLoss`, which will remain with a value of 0 upon strategy addition.

            // Store data for slot 0 in strategies[newStrategy]
            sstore(
                slot,
                or(
                    shl(128, strategyMaxDebtPerHarvest),
                    or(
                        shl(80, and(0xffffffffffff, timestamp())), // Set `strategyLastReport` to `block.timestamp`
                        or(
                            shl(32, and(0xffffffffffff, timestamp())), // Set `strategyActivation` to `block.timestamp`
                            or(shl(16, and(0xffff, strategyPerformanceFee)), and(0xffff, strategyDebtRatio))
                        )
                    )
                )
            )

            // Store data for slot 1 in strategies[newStrategy]
            sstore(add(slot, 1), shr(128, shl(128, strategyMinDebtPerHarvest)))
        }

        // Grant `STRATEGY_ROLE` to strategy
        _grantRoles(newStrategy, STRATEGY_ROLE);

        assembly {
            // Update vault parameters
            // debtRatio += strategyDebtRatio;
            sstore(debtRatio.slot, add(debtRatio_, strategyDebtRatio))
            // Add strategy to withdrawal queue
            // withdrawalQueue[MAXIMUM_STRATEGIES - 1] = newStrategy;
            sstore(add(withdrawalQueue.slot, sub(MAXIMUM_STRATEGIES, 1)), newStrategy)
        }

        _organizeWithdrawalQueue();

        assembly ("memory-safe") {
            // Emit the `StrategyAdded` event
            mstore(0x00, strategyDebtRatio)
            mstore(0x20, strategyMaxDebtPerHarvest)
            mstore(0x40, strategyMinDebtPerHarvest)
            mstore(0x60, strategyPerformanceFee)
            log2(0x00, 0x80, _STRATEGY_ADDED_EVENT_SIGNATURE, newStrategy)
        }
    }

    /// @notice Removes a strategy from the queue
    /// @dev  We don't do this with `revokeStrategy` because it should still be possible to withdraw from the Strategy if it's unwinding.
    /// @param strategy The strategy to remove
    function removeStrategy(address strategy) external checkRoles(ADMIN_ROLE) noEmergencyShutdown {
        address[MAXIMUM_STRATEGIES] memory cachedWithdrawalQueue = withdrawalQueue;
        for (uint256 i; i < MAXIMUM_STRATEGIES;) {
            if (cachedWithdrawalQueue[i] == strategy) {
                // The strategy was found and can be removed
                withdrawalQueue[i] = address(0);

                _removeRoles(strategy, STRATEGY_ROLE);

                // Update withdrawal queue
                _organizeWithdrawalQueue();

                // Emit the `StrategyRemoved` event
                assembly {
                    log2(0x00, 0x00, _STRATEGY_REMOVED_EVENT_SIGNATURE, strategy)
                }
                return;
            }

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits
    /// @dev This function should only be used in the scenario where the Strategy is being retired but no migration
    /// of the positions is possible, or in the extreme scenario that the Strategy needs to be put into "Emergency Exit"
    /// mode in order for it to exit as quickly as possible. The latter scenario could be for any reason that is considered
    /// "critical" that the Strategy exits its position as fast as possible, such as a sudden change in market
    /// conditions leading to losses, or an imminent failure in an external dependency.
    /// @param strategy The strategy to revoke
    function revokeStrategy(address strategy) external checkRoles(ADMIN_ROLE) {
        uint256 cachedStrategyDebtRatio = strategies[strategy].strategyDebtRatio; // Saves an SLOAD if strategy is != addr(0)
        assembly ("memory-safe") {
            // if (strategies[strategy].strategyActivation == 0)
            if iszero(cachedStrategyDebtRatio) {
                // throw `StrategyDebtRatioAlreadyZero()` error
                mstore(0x00, 0xe3a1d5ed)
                revert(0x1c, 0x04)
            }
        }
        // Remove `STRATEGY_ROLE` from strategy
        _removeRoles(strategy, STRATEGY_ROLE);

        // Revoke the strategy
        _revokeStrategy(strategy, cachedStrategyDebtRatio);
    }

    /// @notice Updates a given strategy configured data
    /// @param strategy The strategy to change the data to
    /// @param newDebtRatio The new percentage of the total assets in the vault that `strategy` has access to
    /// @param newMaxDebtPerHarvest New lower limit on the increase of debt since last harvest
    /// @param newMinDebtPerHarvest New upper limit on the increase of debt since last harvest
    /// @param newPerformanceFee New fee the strategist will receive based on this Vault's performance
    function updateStrategyData(
        address strategy,
        uint256 newDebtRatio,
        uint256 newMaxDebtPerHarvest,
        uint256 newMinDebtPerHarvest,
        uint256 newPerformanceFee
    ) external checkRoles(ADMIN_ROLE) {
        uint256 slot; // Slot where strategies[strategy] slot will be stored
        uint256 slotContent; // Used to store strategies[strategy] slot content

        assembly ("memory-safe") {
            // Compute strategies[newStrategy] slot
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)
            slot := keccak256(0x00, 0x40)

            // Load strategies[newStrategy] data into `slotContent`
            slotContent := sload(slot)
            // if (strategyData.strategyActivation == 0)
            if iszero(shr(208, shl(176, slotContent))) {
                // throw `StrategyNotActive()` error
                mstore(0x00, 0xdc974a98)
                revert(0x1c, 0x04)
            }
        }
        if (IStrategy(strategy).emergencyExit() == 2) {
            assembly ("memory-safe") {
                // throw `StrategyInEmergencyExitMode()` error
                mstore(0x00, 0x57c7c24f)
                revert(0x1c, 0x04)
            }
        }
        assembly ("memory-safe") {
            // if (newMinDebtPerHarvest > newMaxDebtPerHarvest)
            if gt(newMinDebtPerHarvest, newMaxDebtPerHarvest) {
                // throw the `InvalidMinDebtPerHarvest` error
                mstore(0x00, 0x5f3bd953)
                revert(0x1c, 0x04)
            }

            // if (strategyPerformanceFee > 5000)
            if gt(newPerformanceFee, 5000) {
                // throw the `InvalidPerformanceFee` error
                mstore(0x00, 0xf14508d0)
                revert(0x1c, 0x04)
            }
        }

        uint256 strategyDebtRatio_;
        assembly {
            // Compute strategies[newStrategy].strategyDebtRatio
            strategyDebtRatio_ := shr(240, shl(240, slotContent))
        }

        uint256 debtRatio_;
        unchecked {
            // Update `debtRatio` storage as well as cache `debtRatio` final value result in `debtRatio_`
            // Underflowing will make maxbps check fail later
            debtRatio_ = debtRatio -= strategyDebtRatio_;
        }

        assembly ("memory-safe") {
            let sum := add(debtRatio_, newDebtRatio)
            if lt(sum, debtRatio_) {
                // throw the `Overflow` error
                revert(0, 0)
            }
            // if (debtRatio_ + newDebtRatio > MAX_BPS)
            if gt(sum, MAX_BPS) {
                // throw the `InvalidDebtRatio` error
                mstore(0x00, 0x79facb0d)
                revert(0x1c, 0x04)
            }
        }

        unchecked {
            // Add new debt ratio to current `debtRatio`
            debtRatio = debtRatio_ + newDebtRatio;
        }

        assembly ("memory-safe") {
            // Update strategies[strategy] with new updated data: debtRatio, maxDebtPerHarvest, minDebtPerHarvest, performanceFee
            // Slot 0 and slot 1 will be updated with the new values. Slot 2 is not updated since it stores `strategyTotalDebt`
            // and `strategyTotalLoss`, which are not updated in `updateStrategyData()`.

            // Store data for slot 0 in strategies[strategy]
            sstore(
                slot,
                or(
                    // Obtain old values in slot
                    and(shl(32, 0xffffffffffffffffffffffff), slotContent), // Extract previously stored `strategyActivation` and `strategyLastReport`
                    // Build new values to store
                    or(
                        shl(128, newMaxDebtPerHarvest),
                        or(shl(16, and(0xffff, newPerformanceFee)), and(0xffff, newDebtRatio))
                    )
                )
            )
            // Store data for slot 1 in strategies[strategy]
            sstore(
                add(slot, 1),
                or(
                    // Obtain old values in slot
                    shl(128, shr(128, sload(add(slot, 1)))), // Extract previously stored `strategyTotalGain`
                    // Build new values to store
                    shr(128, shl(128, newMinDebtPerHarvest))
                )
            )

            // Emit the `StrategyUpdated` event
            mstore(0x00, newDebtRatio)
            mstore(0x20, newMaxDebtPerHarvest)
            mstore(0x40, newMinDebtPerHarvest)
            mstore(0x60, newPerformanceFee)
            log2(0x00, 0x80, _STRATEGY_UPDATED_EVENT_SIGNATURE, strategy)
        }
    }

    ////////////////////////////////////////////////////////////////
    ///                   VAULT CONFIGURATION                    ///
    ////////////////////////////////////////////////////////////////

    /// @notice Updates the withdrawalQueue to match the addresses and order specified by `queue`
    /// @dev There can be fewer strategies than the maximum, as well as fewer than the total number
    /// of strategies active in the vault.
    /// Note This is order sensitive, specify the addresses in the order in which funds should be
    /// withdrawn (so `queue`[0] is the first Strategy withdrawn from, `queue`[1] is the second, etc.),
    /// and add address(0) only when strategies to be added have occupied first queue positions.
    /// This means that the least impactful Strategy (the Strategy that will have its core positions
    /// impacted the least by having funds removed) should be at `queue`[0], then the next least
    /// impactful at `queue`[1], and so on.
    /// @param queue The array of addresses to use as the new withdrawal queue. **This is order sensitive**.
    function setWithdrawalQueue(address[MAXIMUM_STRATEGIES] calldata queue) external checkRoles(ADMIN_ROLE) {
        address prevStrategy;
        // Check queue order is correct
        for (uint256 i; i < MAXIMUM_STRATEGIES;) {
            assembly ("memory-safe") {
                let strategy := calldataload(add(4, mul(i, 0x20)))
                // if (prevStrategy == address(0) && queue[i] != address(0) && i != 0)
                if and(gt(strategy, 0), and(iszero(prevStrategy), gt(i, 0))) {
                    // throw the `InvalidQueueOrder` error
                    mstore(0x00, 0xefb91db4)
                    revert(0x1c, 0x04)
                }

                // Store data necessary to compute strategies[newStrategy] slot
                mstore(0x00, strategy)
                mstore(0x20, strategies.slot)

                // if (strategy != address(0) && strategies[strategy].strategyActivation == 0)
                if and(iszero(shr(208, shl(176, sload(keccak256(0x00, 0x40))))), gt(strategy, 0)) {
                    // throw the `StrategyNotActive` error
                    mstore(0x00, 0xdc974a98)
                    revert(0x1c, 0x04)
                }
                prevStrategy := strategy
            }

            unchecked {
                ++i;
            }
        }
        withdrawalQueue = queue;
        emit WithdrawalQueueUpdated(queue);
    }

    /// @notice Used to change the value of `performanceFee`
    /// @dev Should set this value below the maximum strategist performance fee
    /// @param _performanceFee The new performance fee to use
    function setPerformanceFee(uint256 _performanceFee) external checkRoles(ADMIN_ROLE) {
        assembly ("memory-safe") {
            // if (strategyPerformanceFee > 5000)
            if gt(_performanceFee, 5000) {
                // throw the `InvalidPerformanceFee` error
                mstore(0x00, 0xf14508d0)
                revert(0x1c, 0x04)
            }
        }
        performanceFee = _performanceFee;
        assembly ("memory-safe") {
            // Emit the `PerformanceFeeUpdated` event
            mstore(0x00, _performanceFee)
            log1(0x00, 0x20, _PERFORMANCE_FEE_UPDATED_EVENT_SIGNATURE)
        }
    }

    /// @notice Used to change the value of `managementFee`
    /// @param _managementFee The new performance fee to use
    function setManagementFee(uint256 _managementFee) external checkRoles(ADMIN_ROLE) {
        assembly ("memory-safe") {
            // if (_managementFee > MAX_BPS)
            if gt(_managementFee, MAX_BPS) {
                // throw the `InvalidManagementFee` error
                mstore(0x00, 0x8e9b51ff)
                revert(0x1c, 0x04)
            }
        }
        managementFee = _managementFee;
        assembly {
            // Emit the `ManagementFeeUpdated` event
            mstore(0x00, _managementFee)
            log1(0x00, 0x20, _MANAGEMENT_FEE_UPDATED_EVENT_SIGNATURE)
        }
    }

    /// @notice Used to change the value of `lockedProfitDegradation`
    /// @param _lockedProfitDegradation The rate of degradation in percent per second scaled to 1e18
    function setLockedProfitDegradation(uint256 _lockedProfitDegradation) external checkRoles(ADMIN_ROLE) {
        assembly ("memory-safe") {
            // if (_lockedProfitDegradation > DEGRADATION_COEFFICIENT)
            if gt(_lockedProfitDegradation, DEGRADATION_COEFFICIENT) {
                // throw the `InvalidLockedProfitDegradation` error
                mstore(0x00, 0xd5fccc67)
                revert(0x1c, 0x04)
            }
        }

        lockedProfitDegradation = _lockedProfitDegradation;

        assembly ("memory-safe") {
            // Emit the `LockedProfitDegradationUpdated` event
            mstore(0x00, _lockedProfitDegradation)
            log1(0x00, 0x20, _LOCKED_PROFIT_DEGRADATION_UPDATED_EVENT_SIGNATURE)
        }
    }

    /// @notice Changes the maximum amount of tokens that can be deposited in this Vault
    /// @dev This is not how much may be deposited by a single depositor,
    /// but the maximum amount that may be deposited across all depositors
    /// @param _depositLimit The new deposit limit to use
    function setDepositLimit(uint256 _depositLimit) external checkRoles(ADMIN_ROLE) {
        depositLimit = _depositLimit;
        assembly ("memory-safe") {
            // Emit the `DepositLimitUpdated` event
            mstore(0x00, _depositLimit)
            log1(0x00, 0x20, _DEPOSIT_LIMIT_UPDATED_EVENT_SIGNATURE)
        }
    }

    /// @notice Activates or deactivates Vault mode where all Strategies go into full withdrawal.
    /// During Emergency Shutdown:
    /// 1. No users may deposit into the Vault (but may withdraw as usual)
    /// 2. No new Strategies may be added
    /// 3. Each Strategy must pay back their debt as quickly as reasonable to minimally affect their position
    /// @param _emergencyShutdown If true, the Vault goes into Emergency Shutdown. If false, the Vault goes back into normal operation
    function setEmergencyShutdown(bool _emergencyShutdown) external checkRoles(EMERGENCY_ADMIN_ROLE) {
        emergencyShutdown = _emergencyShutdown;
        assembly ("memory-safe") {
            // Emit the `EmergencyShutdownUpdated` event
            mstore(0x00, _emergencyShutdown)
            log1(0x00, 0x20, _EMERGENCY_SHUTDOWN_UPDATED_EVENT_SIGNATURE)
        }
    }

    /// @notice Updates the treasury address
    /// @param _treasury The new treasury address
    function setTreasury(address _treasury) external checkRoles(ADMIN_ROLE) {
        treasury = _treasury;
        assembly ("memory-safe") {
            // Emit the `TreasuryUpdated` event
            mstore(0x00, _treasury)
            log1(0x00, 0x20, _TREASURY_UPDATED_EVENT_SIGNATURE)
        }
    }

    ////////////////////////////////////////////////////////////////
    ///                    VIEW FUNCTIONS                        ///
    ////////////////////////////////////////////////////////////////

    /// @notice Returns the total quantity of all assets under control of this Vault,
    /// whether they're loaned out to a Strategy, or currently held in the Vault
    /// @return The total assets under control of this Vault
    function totalAssets() public view returns (uint256) {
        return _totalAssets();
    }

    /// @notice Determines the amount of underlying corresponding to `shares` amount of shares
    /// @dev Measuring quantity of shares to issue is based on the total outstanding debt that this contract
    /// has ("expected value") instead of the total balance sheet (balanceOf) it has ("estimated value"). This has important
    /// security considerations, and is done intentionally. If this value were measured against external systems, it
    /// could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able
    /// to claim by redeeming their shares.
    /// @param shares The amount of shares to compute the equivalent underlying for
    /// @return the value of underlying computed given the `shares` amount of shares given as input
    function shareValue(uint256 shares) public view returns (uint256) {
        return _shareValue(shares);
    }

    /// @notice Determines how many shares `amount` of underlying asset would receive
    /// @param amount The amount to compute the equivalent shares for
    /// @return shares the shares computed given the amount
    function sharesForAmount(uint256 amount) public view returns (uint256 shares) {
        return _sharesForAmount(amount);
    }

    /// @notice Amount of tokens in Vault a Strategy has access to as a credit line.
    /// This will check the Strategy's debt limit, as well as the tokens available in the
    /// Vault, and determine the maximum amount of tokens (if any) the Strategy may draw on
    /// @param strategy The strategy to check
    /// @return The quantity of tokens available for the Strategy to draw on
    function creditAvailable(address strategy) external view returns (uint256) {
        return _creditAvailable(strategy);
    }

    /// @notice Determines if `strategy` is past its debt limit and if any tokens should be withdrawn to the Vault
    /// @param strategy The Strategy to check
    /// @return The quantity of tokens to withdraw
    function debtOutstanding(address strategy) external view returns (uint256) {
        return _debtOutstanding(strategy);
    }

    /// @notice returns stratetegyTotalDebt, saves gas, no need to return the whole struct
    /// @param strategy The Strategy to check
    /// @return strategyTotalDebt The strategy's total debt
    function getStratetegyTotalDebt(address strategy) external view returns (uint256 strategyTotalDebt) {
        assembly ("memory-safe") {
            // Store data necessary to compute strategies[newStrategy] slot
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)

            // Obtain strategies[strategy].strategyTotalDebt, stored in struct's slot 2
            strategyTotalDebt := shr(128, shl(128, sload(add(keccak256(0x00, 0x40), 2))))
        }
    }
}

// File: src/base/BaseVault.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

import {StrategyData} from "../helpers/VaultTypes.sol";
import {ERC20} from "../lib/ERC20.sol";
import {ReentrancyGuard} from "../lib/ReentrancyGuard.sol";
import {IStrategy} from "../interfaces/IStrategy.sol";

import {OwnableRoles} from "solady/auth/OwnableRoles.sol";
import {IERC20} from "openzeppelin/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "openzeppelin/token/ERC20/extensions/IERC20Metadata.sol";
import {FixedPointMathLib as Math} from "solady/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

/// @title MaxApy Base Vault Contract
/// @notice Stores data and executes generic logic for MaxApy vaults
/// @author MaxApy
contract BaseVault is ERC20, OwnableRoles, ReentrancyGuard {
    using SafeTransferLib for address;

    ////////////////////////////////////////////////////////////////
    ///                         CONSTANTS                        ///
    ////////////////////////////////////////////////////////////////

    uint256 public constant MAXIMUM_STRATEGIES = 20;
    uint256 public constant MAX_BPS = 10_000;
    uint256 public constant DEGRADATION_COEFFICIENT = 1e18;
    uint256 public constant SECS_PER_YEAR = 31_556_952;
    /// 365.2425 days

    /// Roles
    uint256 public constant ADMIN_ROLE = _ROLE_0;
    uint256 public constant EMERGENCY_ADMIN_ROLE = _ROLE_1;
    uint256 public constant STRATEGY_ROLE = _ROLE_2;

    ////////////////////////////////////////////////////////////////
    ///                         ERRORS                           ///
    ////////////////////////////////////////////////////////////////
    error QueueIsFull();
    error VaultInEmergencyShutdownMode();
    error StrategyInEmergencyExitMode();
    error InvalidZeroAddress();
    error StrategyAlreadyActive();
    error StrategyNotActive();
    error InvalidStrategyVault();
    error InvalidStrategyUnderlying();
    error InvalidDebtRatio();
    error InvalidMinDebtPerHarvest();
    error InvalidPerformanceFee();
    error InvalidManagementFee();
    error InvalidLockedProfitDegradation();
    error StrategyDebtRatioAlreadyZero();
    error InvalidQueueOrder();
    error VaultDepositLimitExceeded();
    error InvalidZeroAmount();
    error InvalidZeroShares();
    error InvalidMaxLoss();
    error MaxLossReached();
    error LossGreaterThanStrategyTotalDebt();
    error InvalidReportedGainAndDebtPayment();
    error FeesAlreadyAssesed();

    ////////////////////////////////////////////////////////////////
    ///                         EVENTS                           ///
    ////////////////////////////////////////////////////////////////

    /// @notice Emitted when a strategy is newly added to the protocol
    event StrategyAdded(
        address indexed newStrategy,
        uint16 strategyDebtRatio,
        uint128 strategyMaxDebtPerHarvest,
        uint128 strategyMinDebtPerHarvest,
        uint16 strategyPerformanceFee
    );

    /// @notice Emitted when a strategy is removed from the protocol
    event StrategyAdded(address indexed strategy);

    /// @notice Emitted when a vault's emergency shutdown state is switched
    event EmergencyShutdownUpdated(bool emergencyShutdown);

    /// @notice Emitted when a strategy is revoked from the vault
    event StrategyRevoked(address indexed strategy);

    /// @notice Emitted when a strategy parameters are updated
    event StrategyUpdated(
        address indexed strategy,
        uint16 newDebtRatio,
        uint128 newMaxDebtPerHarvest,
        uint128 newMinDebtPerHarvest,
        uint16 newPerformanceFee
    );

    /// @notice Emitted when the withdrawal queue is updated
    event WithdrawalQueueUpdated(address[MAXIMUM_STRATEGIES] withdrawalQueue);

    /// @notice Emitted when the vault's performance fee is updated
    event PerformanceFeeUpdated(uint16 newPerformanceFee);

    /// @notice Emitted when the vault's management fee is updated
    event ManagementFeeUpdated(uint256 newManagementFee);

    /// @notice Emitted the vault's locked profit degradation is updated
    event LockedProfitDegradationUpdated(uint256 newLockedProfitDegradation);

    /// @notice Emitted when the vault's deposit limit is updated
    event DepositLimitUpdated(uint256 newDepositLimit);

    /// @notice Emitted when the vault's treasury addresss is updated
    event TreasuryUpdated(address treasury);

    /// @notice Emitted on vault deposits
    event Deposit(address indexed recipient, uint256 shares, uint256 amount);

    /// @notice Emitted on vault withdrawals
    event Withdraw(address indexed recipient, uint256 shares, uint256 amount);

    /// @notice Emitted on withdrawal strategy withdrawals
    event WithdrawFromStrategy(address indexed strategy, uint128 strategyTotalDebt, uint128 loss);

    /// @notice Emitted after assessing protocol fees
    event FeesReported(uint256 managementFee, uint16 performanceFee, uint256 strategistFee, uint256 duration);

    /// @notice Emitted after a strategy reports to the vault
    event StrategyReported(
        address indexed strategy,
        uint256 gain,
        uint256 loss,
        uint256 debtPayment,
        uint128 strategyTotalGain,
        uint128 strategyTotalLoss,
        uint128 strategyTotalDebt,
        uint256 credit,
        uint16 strategyDebtRatio
    );

    // EVENT SIGNATURES

    uint256 internal constant _STRATEGY_ADDED_EVENT_SIGNATURE =
        0x66277e61c003f7703009ad857a4c4900f9cd3ee44535afe5905f98d53922e0f4;

    uint256 internal constant _STRATEGY_REMOVED_EVENT_SIGNATURE =
        0x3f008fd510eae7a9e7bee13513d7b83bef8003d488b5a3d0b0da4de71d6846f1;

    uint256 internal constant _EMERGENCY_SHUTDOWN_UPDATED_EVENT_SIGNATURE =
        0xa63137c77816d51f856c11ffb11e84757ac9db0ce2569f94edd04c91fe2250a1;

    uint256 internal constant _STRATEGY_REVOKED_EVENT_SIGNATURE =
        0x4201c688d84c01154d321afa0c72f1bffe9eef53005c9de9d035074e71e9b32a;

    uint256 internal constant _STRATEGY_UPDATED_EVENT_SIGNATURE =
        0x102a33a8369310733322056f2c0f753209cd77c65b1ce5775c2d6f181e38778f;

    uint256 internal constant _WITHDRAWAL_QUEUE_UPDATED_EVENT_SIGNATURE =
        0x92fa0b6a2861480bf8c9977f0f9fe1d95c535ba23cbf234f2716fc765aec3be8;

    uint256 internal constant _PERFORMANCE_FEE_UPDATED_EVENT_SIGNATURE =
        0x0632b4ddf7c06e7e3bc19b7ce92862c7de91b312a392142116fb574a06a47cfd;

    uint256 internal constant _MANAGEMENT_FEE_UPDATED_EVENT_SIGNATURE =
        0x2147e2bc8c39e67f74b1a9e08896ea1485442096765942206af1f4bc8bcde917;

    uint256 internal constant _LOCKED_PROFIT_DEGRADATION_UPDATED_EVENT_SIGNATURE =
        0x056863905a721211fc4dda1d688efc8f120b4b689d2e41da8249cf6eff200691;

    uint256 internal constant _DEPOSIT_LIMIT_UPDATED_EVENT_SIGNATURE =
        0xc512617347fd848ec9d7347c99c10e4fa7059132c92d0445930a7fb0c8252ff5;

    uint256 internal constant _TREASURY_UPDATED_EVENT_SIGNATURE =
        0x7dae230f18360d76a040c81f050aa14eb9d6dc7901b20fc5d855e2a20fe814d1;

    uint256 internal constant _DEPOSIT_EVENT_SIGNATURE =
        0x90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a15;

    uint256 internal constant _WITHDRAW_EVENT_SIGNATURE =
        0xf279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b568;

    uint256 internal constant _WITHDRAW_FROM_STRATEGY_EVENT_SIGNATURE =
        0x8c1171ccd065c6769e1540f65c3c0874e5f7173ccdff7ca293238e69d000bf20;

    uint256 internal constant _FEES_REPORTED_EVENT_SIGNATURE =
        0x25bf703141a84375d04ea08a0c4a21c7406f300f133e12aef555607b4f3ff238;

    uint256 internal constant _STRATEGY_REPORTED_EVENT_SIGNATURE =
        0xc2d7e1173e37528dce423c72b129fa1ad2c5d51e50974c64fe13f1928eb27f89;

    ////////////////////////////////////////////////////////////////
    ///               VAULT GLOBAL STATE VARIABLES               ///
    ////////////////////////////////////////////////////////////////

    /// @notice The vault underlying asset
    IERC20 public underlyingAsset;

    /// @notice Vault state stating if vault is in emergency shutdown mode
    bool public emergencyShutdown;
    /// @notice Limit for totalAssets the Vault can hold
    uint256 public depositLimit;
    /// @notice Debt ratio for the Vault across all strategies (in BPS, <= 10k)
    uint256 public debtRatio;
    /// @notice Amount of tokens that are in the vault
    uint256 public totalIdle;
    /// @notice Amount of tokens that all strategies have borrowed
    uint256 public totalDebt;
    /// @notice block.timestamp of last report
    uint256 public lastReport;
    /// @notice How much profit is locked and cant be withdrawn
    uint256 public lockedProfit;
    /// @notice Rate per block of degradation. DEGRADATION_COEFFICIENT is 100% per block
    uint256 public lockedProfitDegradation;
    /// @notice Rewards address where performance and management fees are sent to
    address public treasury;

    /// @notice Record of all the strategies that are allowed to receive assets from the vault
    mapping(address => StrategyData) public strategies;
    /// @notice Ordering that `withdraw` uses to determine which strategies to pull funds from
    address[MAXIMUM_STRATEGIES] public withdrawalQueue;

    /// @notice Fee minted to the treasury and deducted from yield earned every time the vault harvests a strategy
    uint256 public performanceFee;
    /// @notice Flat rate taken from vault yield over a year
    uint256 public managementFee;

    ////////////////////////////////////////////////////////////////
    ///                         MODIFIERS                        ///
    ////////////////////////////////////////////////////////////////

    modifier checkRoles(uint256 roles) {
        _checkRoles(roles);
        _;
    }

    modifier noEmergencyShutdown() {
        assembly ("memory-safe") {
            // if emergencyShutdown == true
            if shr(160, sload(emergencyShutdown.slot)) {
                // throw the `VaultInEmergencyShutdownMode` error
                mstore(0x00, 0x04aca5db)
                revert(0x1c, 0x04)
            }
        }
        _;
    }

    ////////////////////////////////////////////////////////////////
    ///                     CONSTRUCTOR                          ///
    ////////////////////////////////////////////////////////////////
    constructor(IERC20 _underlyingAsset, string memory _name, string memory _symbol)
        ERC20(_name, _symbol, IERC20Metadata(address(_underlyingAsset)).decimals())
    {
        _initializeOwner(msg.sender);
        _grantRoles(msg.sender, ADMIN_ROLE);
        underlyingAsset = _underlyingAsset;
    }

    ////////////////////////////////////////////////////////////////
    ///                    INTERNAL FUNCTIONS                    ///
    ////////////////////////////////////////////////////////////////

    /// @notice Reports a strategy loss, adjusting the corresponding vault and strategy parameters
    /// to minimize trust in the strategy
    /// @param strategy The strategy reporting the loss
    /// @param loss The amount of loss to report
    function _reportLoss(address strategy, uint256 loss) internal {
        // Strategy data
        uint128 strategyTotalDebt;
        uint16 strategyDebtRatio;

        // Vault data
        uint256 totalDebt_;
        uint256 debtRatio_;

        // Slot data
        uint256 strategiesSlot;
        uint256 slot0Content;
        uint256 slot2Content;

        assembly ("memory-safe") {
            // Get strategies slot
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)
            strategiesSlot := keccak256(0x00, 0x40)
            // Obtain strategy slot 0 data
            slot0Content := sload(strategiesSlot)
            // Obtain strategy slot 2 data
            slot2Content := sload(add(strategiesSlot, 2))

            // Cache strategy data
            strategyDebtRatio := shr(240, shl(240, slot0Content))
            strategyTotalDebt := shr(128, shl(128, slot2Content))

            // Ensure loss reported is not greater than strategy total debt
            // if loss > strategyData.strategyTotalDebt
            if gt(loss, strategyTotalDebt) {
                // throw the `LossGreaterThanStrategyTotalDebt` error
                mstore(0x00, 0xd5436ad8)
                revert(0x1c, 0x04)
            }

            // Obtain vault debtRatio
            debtRatio_ := sload(debtRatio.slot)
            // Obtain vault totalDebt
            totalDebt_ := sload(totalDebt.slot)
        }

        // Reduce trust in this strategy by the amount of loss, lowering the corresponding strategy debt ratio
        uint256 ratioChange = Math.min((loss * debtRatio_) / totalDebt_, strategyDebtRatio);

        assembly {
            // Overflow checks
            if gt(ratioChange, debtRatio_) {
                // throw `Overflwow` error
                revert(0, 0)
            }
            if gt(loss, totalDebt_) {
                // throw `Overflow` error
                revert(0, 0)
            }
            if gt(ratioChange, strategyDebtRatio) {
                // throw `Overflow` error
                revert(0, 0)
            }

            // Update vault data
            // debtRatio -= ratioChange;
            // totalDebt -= loss;
            sstore(debtRatio.slot, sub(debtRatio_, ratioChange)) // debtRatio -= ratioChange
            sstore(totalDebt.slot, sub(totalDebt_, loss)) // totalDebt -= loss

            // Update strategy debt ratio
            // strategies[strategy].strategyDebtRatio -= ratioChange
            sstore(
                strategiesSlot,
                or(
                    shr(240, shl(240, sub(strategyDebtRatio, ratioChange))), // Compute strategies[strategy].strategyDebtRatio - ratioChange
                    shl(16, shr(16, slot0Content)) // Obtain previous slot data, removing `strategyDebtRatio`
                )
            )

            // Adjust final strategy parameters by the loss
            let strategyTotalLoss := shr(128, slot2Content)
            // strategyTotalLoss += loss
            strategyTotalLoss := add(strategyTotalLoss, loss)

            if lt(strategyTotalLoss, loss) {
                // throw `Overflow` error
                revert(0, 0)
            }

            // Pack strategyTotalLoss and strategyTotalDebt into slot2Content
            slot2Content :=
                or(
                    shl(128, strategyTotalLoss),
                    shr(128, shl(128, sub(strategyTotalDebt, loss))) // Compute strategies[strategy].strategyTotalDebt -= loss;
                )

            // Update strategy total loss and total debt, store in slot 2
            sstore(add(strategiesSlot, 2), slot2Content)
        }
    }

    /// @notice Issues new shares to cover performance, management and strategist fees
    /// @param strategy The strategy reporting the gain
    /// @param gain The amount of gain to extract fees from
    /// @return the total fees (performance + management + strategist) extracted from the gain
    function _assessFees(address strategy, uint256 gain) internal returns (uint256) {
        bool success;
        uint256 slot0Content;
        assembly ("memory-safe") {
            // Get strategies[strategy] slot
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)
            // Get strategies[strategy] data
            slot0Content := sload(keccak256(0x00, 0x40))

            // If strategy was just added or no gains were reported, return 0 as fees
            // if (strategyData.strategyActivation == block.timestamp || gain == 0)
            if or(eq(shr(208, shl(176, slot0Content)), timestamp()), eq(gain, 0)) { success := 1 }
        }
        if (success) {
            return 0;
        }

        // Stack variables to cache
        uint256 duration;
        uint256 strategyPerformanceFee;
        uint256 computedManagementFee;
        uint256 computedStrategistFee;
        uint256 computedPerformanceFee;
        uint256 totalFee;

        assembly ("memory-safe") {
            // duration = block.timestamp - strategyData.strategyLastReport;
            duration := sub(timestamp(), shr(208, shl(128, slot0Content)))

            // if duration == 0
            if iszero(duration) {
                // throw the `FeesAlreadyAssesed` error
                mstore(0x00, 0x17de0c6e)
                revert(0x1c, 0x04)
            }

            // Cache strategy performance fee
            strategyPerformanceFee := shr(240, shl(224, slot0Content))

            // Load vault fees
            let managementFee_ := sload(managementFee.slot)
            let performanceFee_ := sload(performanceFee.slot)

            // Overflow check equivalent to require(managementFee_ == 0 || gain <= type(uint256).max / managementFee_)
            if iszero(iszero(mul(managementFee_, gt(gain, div(not(0), managementFee_))))) { revert(0, 0) }

            // Compute vault management fee
            // computedManagementFee = (gain * managementFee) / MAX_BPS
            computedManagementFee := div(mul(gain, managementFee_), MAX_BPS)

            // Overflow check equivalent to require(strategyPerformanceFee == 0 || gain <= type(uint256).max / strategyPerformanceFee)
            if iszero(iszero(mul(strategyPerformanceFee, gt(gain, div(not(0), strategyPerformanceFee))))) {
                revert(0, 0)
            }

            // Compute strategist fee
            // computedStrategistFee = (gain * strategyData.strategyPerformanceFee) / MAX_BPS;
            computedStrategistFee := div(mul(gain, strategyPerformanceFee), MAX_BPS)

            // Overflow check equivalent to require(performanceFee_ == 0 || gain <= type(uint256).max / performanceFee_)
            if iszero(iszero(mul(performanceFee_, gt(gain, div(not(0), performanceFee_))))) { revert(0, 0) }

            // Compute vault performance fee
            // computedPerformanceFee = (gain * performanceFee) / MAX_BPS;
            computedPerformanceFee := div(mul(gain, performanceFee_), MAX_BPS)

            // totalFee = computedManagementFee + computedStrategistFee + computedPerformanceFee
            totalFee := add(add(computedManagementFee, computedStrategistFee), computedPerformanceFee)

            // Ensure total fee is not greater than the gain, set total fee to become the actual gain otherwise
            // if totalFee > gain
            if gt(totalFee, gain) {
                // totalFee = gain
                totalFee := gain
            }
        }

        // Only transfer shares if there are actual shares to transfer
        if (totalFee != 0) {
            // Compute corresponding shares and mint rewards to vault
            uint256 reward = _issueSharesForAmount(address(this), totalFee);

            // Transfer corresponding rewards in shares to strategist
            if (computedStrategistFee != 0) {
                uint256 strategistReward;
                assembly {
                    // Overflow check equivalent to require(reward == 0 || computedStrategistFee <= type(uint256).max / reward)
                    // No need to check for totalFee == 0 since it is checked in the if clause above
                    if iszero(iszero(mul(reward, gt(computedStrategistFee, div(not(0), reward))))) { revert(0, 0) }

                    // Compute strategist reward
                    // strategistReward = (computedStrategistFee * reward) / totalFee;
                    strategistReward := div(mul(computedStrategistFee, reward), totalFee)
                }
                // Transfer corresponding reward to strategist
                address(this).safeTransfer(IStrategy(strategy).strategist(), strategistReward);
            }

            // Treasury earns remaining shares (performance fee + management fee + any dust leftover from flooring math above)
            uint256 cachedBalance = balanceOf(address(this));
            if (cachedBalance != 0) {
                address(this).safeTransfer(treasury, cachedBalance);
            }
        }

        assembly ("memory-safe") {
            // Emit the `FeesReported` event
            let m := mload(0x40)
            mstore(0x00, computedManagementFee)
            mstore(0x20, computedPerformanceFee)
            mstore(0x40, computedStrategistFee)
            mstore(0x60, duration)
            log1(0x00, 0x80, _FEES_REPORTED_EVENT_SIGNATURE)
            mstore(0x40, m)
            mstore(0x60, 0)
        }

        return totalFee;
    }

    /// @notice Amount of tokens in Vault a Strategy has access to as a credit line.
    /// This will check the Strategy's debt limit, as well as the tokens available in the
    /// Vault, and determine the maximum amount of tokens (if any) the Strategy may draw on
    /// @param strategy The strategy to check
    /// @return The quantity of tokens available for the Strategy to draw on
    function _creditAvailable(address strategy) internal view returns (uint256) {
        if (emergencyShutdown) return 0;

        // Compute necessary data regarding current state of the vault
        uint256 vaultTotalAssets = _totalAssets();
        uint256 vaultDebtLimit = _computeDebtLimit(debtRatio, vaultTotalAssets);
        uint256 vaultTotalDebt = totalDebt;

        // Stack variables to cache
        bool success;
        uint256 slot;
        uint256 slot0Content;
        uint256 strategyTotalDebt;
        uint256 strategyDebtLimit;
        assembly ("memory-safe") {
            // Compute slot of strategies[strategy]
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)
            slot := keccak256(0x00, 0x40)
            // Load strategies[strategy].strategyTotalDebt
            strategyTotalDebt := shr(128, shl(128, sload(add(slot, 2))))

            // Load slot 0 content
            slot0Content := sload(slot)

            // Extract strategies[strategy].strategyDebtRatio
            let strategyDebtRatio := shr(240, shl(240, slot0Content))

            // Overflow check equivalent to require(vaultTotalAssets == 0 || strategyDebtRatio <= type(uint256).max / vaultTotalAssets)
            if iszero(iszero(mul(vaultTotalAssets, gt(strategyDebtRatio, div(not(0), vaultTotalAssets))))) {
                revert(0, 0)
            }

            // Compute necessary data regarding current state of the strategy

            // strategyDebtLimit = (strategies[strategy].strategyDebtRatio * vaultTotalAssets) / MAX_BPS;
            strategyDebtLimit := div(mul(strategyDebtRatio, vaultTotalAssets), MAX_BPS)

            // If strategy current debt is already greater than the configured debt limit for that strategy,
            // or if the vault's current debt is already greater than the configured debt limit for that vault,
            // no credit should be given to the strategy
            // if strategies[strategy].strategyTotalDebt > strategyDebtLimit || vaultTotalDebt > vaultDebtLimit
            if or(gt(strategyTotalDebt, strategyDebtLimit), gt(vaultTotalDebt, vaultDebtLimit)) { success := 1 }
        }
        if (success) return 0;

        // Adjust by the vault debt limit left
        uint256 available;
        unchecked {
            available = Math.min(strategyDebtLimit - strategyTotalDebt, vaultDebtLimit - vaultTotalDebt);
        }

        // Adjust by the idle amount of underlying the vault has
        available = Math.min(available, totalIdle);

        assembly {
            // Adjust by min and max borrow limits per harvest

            // if (available < strategies[strategy].strategyMinDebtPerHarvest) return 0;
            if lt(available, shr(128, shl(128, sload(add(slot, 1))))) { success := 1 }
        }
        if (success) return 0;

        // Obtain strategies[strategy].strategyMaxDebtPerHarvest from the previously loaded slot0Content, this saves one SLOAD
        uint256 strategyMaxDebtPerHarvest;
        assembly {
            strategyMaxDebtPerHarvest := shr(128, slot0Content)
        }
        return Math.min(available, strategyMaxDebtPerHarvest);
    }

    /// @notice Performs the debt limit calculation
    /// @param _debtRatio The debt ratio to use for computation
    /// @param totalAssets The amount of assets
    /// @return debtLimit The limit amount of assets allowed for the strategy, given the current debt ratio and total assets
    function _computeDebtLimit(uint256 _debtRatio, uint256 totalAssets) internal pure returns (uint256 debtLimit) {
        assembly {
            // Overflow check equivalent to require(totalAssets == 0 || _debtRatio <= type(uint256).max / totalAssets)
            if iszero(iszero(mul(totalAssets, gt(_debtRatio, div(not(0), totalAssets))))) { revert(0, 0) }
            // _debtRatio * totalAssets / MAX_BPS
            debtLimit := div(mul(_debtRatio, totalAssets), MAX_BPS)
        }
    }

    /// @notice Determines if `strategy` is past its debt limit and if any tokens should be withdrawn to the Vault
    /// @param strategy The Strategy to check
    /// @return debtOutstanding The quantity of tokens to withdraw
    function _debtOutstanding(address strategy) internal view returns (uint256 debtOutstanding) {
        uint256 strategyTotalDebt;
        uint256 strategyDebtRatio;
        assembly ("memory-safe") {
            // Get strategies[strategy] slot
            mstore(0x00, strategy)
            mstore(0x20, strategies.slot)
            let slot := keccak256(0x00, 0x40)
            // Obtain strategies[strategy].strategyTotalDebt from slot 2
            strategyTotalDebt := shr(128, shl(128, sload(add(slot, 2))))
            // Obtain strategies[strategy].strategyDebtRatio from slot 0
            strategyDebtRatio := shr(240, shl(240, sload(slot)))
        }
        // If debt ratio configured in vault is zero or emergency shutdown, any amount of debt in the strategy should be returned
        if (debtRatio == 0 || emergencyShutdown) return strategyTotalDebt;

        uint256 strategyDebtLimit = _computeDebtLimit(strategyDebtRatio, _totalAssets());

        // There will not be debt outstanding if strategy total debt is smaller or equal to the current debt limit
        if (strategyDebtLimit >= strategyTotalDebt) {
            return 0;
        }
        unchecked {
            debtOutstanding = strategyTotalDebt - strategyDebtLimit;
        }
    }

    /// @notice Reorganize `withdrawalQueue` based on premise that if there is an
    /// empty value between two actual values, then the empty value should be
    /// replaced by the later value.
    /// @dev Relative ordering of non-zero values is maintained.
    function _organizeWithdrawalQueue() internal {
        uint256 offset;
        for (uint256 i; i < MAXIMUM_STRATEGIES;) {
            address strategy = withdrawalQueue[i];
            if (strategy == address(0)) {
                unchecked {
                    ++offset;
                }
            } else if (offset > 0) {
                withdrawalQueue[i - offset] = strategy;
                withdrawalQueue[i] = address(0);
            }

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Revoke a Strategy, setting its debt limit to 0 and preventing any future deposits
    /// @param strategy The strategy to revoke
    /// @param strategy The strategy debt ratio
    function _revokeStrategy(address strategy, uint256 strategyDebtRatio) internal {
        debtRatio -= strategyDebtRatio;
        strategies[strategy].strategyDebtRatio = 0;
        assembly {
            log2(0x00, 0x00, _STRATEGY_REVOKED_EVENT_SIGNATURE, strategy)
        }
    }

    /// @notice Issues `amount` Vault shares to `to`
    /// @dev Shares must be issued prior to taking on new collateral, or calculation will be wrong.
    /// This means that only *trusted* tokens (with no capability for exploitative behavior) can be used
    /// @param to The shares recipient
    /// @param amount The amount considered to compute the shares
    /// @return shares The amount of shares computed from the amount
    function _issueSharesForAmount(address to, uint256 amount) internal returns (uint256 shares) {
        uint256 vaultTotalSupply = totalSupply();

        // By default, 1:1 shares are minted
        shares = amount;

        if (vaultTotalSupply != 0) {
            // Mint amount of tokens based on what the Vault is managing overall
            shares = (amount * vaultTotalSupply) / _freeFunds();
        }

        assembly ("memory-safe") {
            // if shares == 0
            if iszero(shares) {
                // Throw the `InvalidZeroShares` error
                mstore(0x00, 0x5a870a25)
                revert(0x1c, 0x04)
            }
        }

        _mint(to, shares);
    }

    ////////////////////////////////////////////////////////////////
    ///                INTERNAL VIEW FUNCTIONS                   ///
    ////////////////////////////////////////////////////////////////

    /// @notice Calculates the free funds available considering the locked profit
    /// @return The amount of free funds available
    function _freeFunds() internal view returns (uint256) {
        return _totalAssets() - _calculateLockedProfit();
    }

    /// @notice Returns the total quantity of all assets under control of this Vault,
    /// whether they're loaned out to a Strategy, or currently held in the Vault
    /// @return totalAssets The total assets under control of this Vault
    function _totalAssets() internal view returns (uint256 totalAssets) {
        assembly {
            let totalDebt_ := sload(totalDebt.slot)
            totalAssets := add(sload(totalIdle.slot), totalDebt_)

            // Perform overflow check
            if lt(totalAssets, totalDebt_) { revert(0, 0) }
        }
    }

    /// @notice Calculates how much profit is locked and cant be withdrawn
    /// @return calculatedLockedProfit The total assets locked
    function _calculateLockedProfit() internal view returns (uint256 calculatedLockedProfit) {
        assembly {
            // No need to check for underflow, since block.timestamp is always greater or equal than lastReport
            let difference := sub(timestamp(), sload(lastReport.slot)) // difference = block.timestamp - lastReport
            let lockedProfitDegradation_ := sload(lockedProfitDegradation.slot)

            // Overflow check equivalent to require(lockedProfitDegradation_ == 0 || difference <= type(uint256).max / lockedProfitDegradation_)
            if iszero(iszero(mul(lockedProfitDegradation_, gt(difference, div(not(0), lockedProfitDegradation_))))) {
                revert(0, 0)
            }

            // lockedFundsRatio = (block.timestamp - lastReport) * lockedProfitDegradation
            let lockedFundsRatio := mul(difference, lockedProfitDegradation_)

            if lt(lockedFundsRatio, DEGRADATION_COEFFICIENT) {
                let vaultLockedProfit := sload(lockedProfit.slot)
                // Overflow check equivalent to require(vaultLockedProfit == 0 || lockedFundsRatio <= type(uint256).max / vaultLockedProfit)
                if iszero(iszero(mul(vaultLockedProfit, gt(lockedFundsRatio, div(not(0), vaultLockedProfit))))) {
                    revert(0, 0)
                }
                // ((lockedFundsRatio * vaultLockedProfit) / DEGRADATION_COEFFICIENT
                let degradation := div(mul(lockedFundsRatio, vaultLockedProfit), DEGRADATION_COEFFICIENT)
                // Overflow check
                if gt(degradation, vaultLockedProfit) { revert(0, 0) }
                // calculatedLockedProfit = vaultLockedProfit - ((lockedFundsRatio * vaultLockedProfit) / DEGRADATION_COEFFICIENT);
                calculatedLockedProfit := sub(vaultLockedProfit, degradation)
            }
        }
    }

    /// @notice Determines the amount of underlying corresponding to `shares` amount of shares
    /// @dev Measuring quantity of shares to issue is based on the total outstanding debt that this contract
    /// has ("expected value") instead of the total balance sheet (balanceOf) it has ("estimated value"). This has important
    /// security considerations, and is done intentionally. If this value were measured against external systems, it
    /// could be purposely manipulated by an attacker to withdraw more assets than they otherwise should be able
    /// to claim by redeeming their shares.
    /// @param shares The amount of shares to compute the equivalent underlying for
    /// @return shareValue the value of underlying computed given the `shares` amount of shares given as input
    function _shareValue(uint256 shares) internal view returns (uint256 shareValue) {
        uint256 totalSupply_ = totalSupply();
        // Return price = 1:1 if vault is empty
        if (totalSupply_ == 0) return shares;
        uint256 freeFunds = _freeFunds();
        assembly {
            // Overflow check equivalent to require(freeFunds == 0 || shares <= type(uint256).max / freeFunds)
            if iszero(iszero(mul(freeFunds, gt(shares, div(not(0), freeFunds))))) { revert(0, 0) }
            // shares * freeFunds / totalSupply_
            shareValue := div(mul(shares, freeFunds), totalSupply_)
        }
    }

    /// @notice Determines how many shares `amount` of underlying asset would receive
    /// @param amount The amount to compute the equivalent shares for
    /// @return shares the shares computed given the amount
    function _sharesForAmount(uint256 amount) internal view returns (uint256 shares) {
        uint256 freeFunds = _freeFunds();
        assembly {
            //if (freeFunds != 0) return (amount * totalSupply()) / freeFunds;
            if gt(freeFunds, 0) {
                let totalSupply_ := sload(0x05345cdf77eb68f44c) // load data from `_TOTAL_SUPPLY_SLOT`

                // Overflow check equivalent to require(totalSupply_ == 0 || amount <= type(uint256).max / totalSupply_)
                if iszero(iszero(mul(totalSupply_, gt(amount, div(not(0), totalSupply_))))) { revert(0, 0) }
                // amount * totalSupply() / freeFunds
                shares := div(mul(amount, totalSupply_), freeFunds)
            }
        }
    }
}

// File: src/helpers/VaultTypes.sol



pragma solidity ^0.8.19;

/// @notice Stores all data from a single strategy
/// @dev Packed in two slots
struct StrategyData {
    /// Slot 0
    /// @notice Maximum percentage available to be lent to strategies(in BPS)
    /// @dev in BPS. uint16 is enough to cover the max BPS value of 10_000
    uint16 strategyDebtRatio;
    /// @notice The performance fee
    /// @dev in BPS. uint16 is enough to cover the max BPS value of 10_000
    uint16 strategyPerformanceFee;
    /// @notice Timestamp when the strategy was added.
    /// @dev Overflowing July 21, 2554
    uint48 strategyActivation;
    /// @notice block.timestamp of the last time a report occured
    /// @dev Overflowing July 21, 2554
    uint48 strategyLastReport;
    /// @notice Upper limit on the increase of debt since last harvest
    /// @dev max debt per harvest to be set to a maximum value of 4,722,366,482,869,645,213,695
    uint128 strategyMaxDebtPerHarvest;
    /// Slot 1
    /// @notice Lower limit on the increase of debt since last harvest
    /// @dev min debt per harvest to be set to a maximum value of 16,777,215
    uint128 strategyMinDebtPerHarvest;
    /// @notice Total returns that Strategy has realized for Vault
    /// @dev max strategy total gain of 79,228,162,514,264,337,593,543,950,335
    uint128 strategyTotalGain;
    /// Slot 2
    /// @notice Total outstanding debt that Strategy has
    /// @dev max total debt of 79,228,162,514,264,337,593,543,950,335
    uint128 strategyTotalDebt;
    /// @notice Total losses that Strategy has realized for Vault
    /// @dev max strategy total loss of 79,228,162,514,264,337,593,543,950,335
    uint128 strategyTotalLoss;
}

// File: src/lib/ERC20.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.

library StringPacker { // This library is used to pack and unpack strings into bytes32. This is used to store the name and symbol of the token in the contract.
    function pack(string memory unpacked) internal pure returns (bytes32 packed) {
        require(bytes(unpacked).length < 32);
        assembly {
            packed := mload(add(unpacked, 31))
        }
    }

    function unpack(bytes32 packed) internal pure returns (string memory unpacked) {
        uint256 l = uint256(packed >> 248);
        require(l < 32);
        unpacked = string(new bytes (l));
        assembly {
            mstore(add(unpacked, 31), packed) // Potentially writes into unallocated memory, which is fine
        }
    }
}

abstract contract ERC20 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The total supply has overflowed.
    error TotalSupplyOverflow();

    /// @dev The allowance has overflowed.
    error AllowanceOverflow();

    /// @dev The allowance has underflowed.
    error AllowanceUnderflow();

    /// @dev Insufficient balance.
    error InsufficientBalance();

    /// @dev Insufficient allowance.
    error InsufficientAllowance();

    /// @dev The permit is invalid.
    error InvalidPermit();

    /// @dev The permit has expired.
    error PermitExpired();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
    event Transfer(address indexed from, address indexed to, uint256 amount);

    /// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
    uint256 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
    uint256 private constant _APPROVAL_EVENT_SIGNATURE =
        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The storage slot for the total supply.
    uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;

    /// @dev The balance slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _BALANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let balanceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;

    /// @dev The allowance slot of (`owner`, `spender`) is given by:
    /// ```
    ///     mstore(0x20, spender)
    ///     mstore(0x0c, _ALLOWANCE_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let allowanceSlot := keccak256(0x0c, 0x34)
    /// ```
    uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;

    /// @dev The nonce slot of `owner` is given by:
    /// ```
    ///     mstore(0x0c, _NONCES_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let nonceSlot := keccak256(0x0c, 0x20)
    /// ```
    uint256 private constant _NONCES_SLOT_SEED = 0x38377508;

    ////////////////////////////////////////////////////////////////
    ///                     METADATA STORAGE                     ///
    ////////////////////////////////////////////////////////////////

    bytes32 private immutable name_; // added immutable variables to name, symbol, decimals

    bytes32 private immutable symbol_;

    uint256 public immutable decimals;

    constructor(string memory _name, string memory _symbol, uint8 _decimals) {
        name_ = StringPacker.pack(_name);
        symbol_ = StringPacker.pack(_symbol);
        decimals = _decimals;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ERC20 METADATA                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the name of the token.
    function name() public view returns (string memory) {
        return StringPacker.unpack(name_);
    }

    /// @dev Returns the symbol of the token.
    function symbol() public view returns (string memory) {
        return StringPacker.unpack(symbol_);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           ERC20                            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the amount of tokens in existence.
    function totalSupply() public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_TOTAL_SUPPLY_SLOT)
        }
    }

    /// @dev Returns the amount of tokens owned by `owner`.
    function balanceOf(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
    function allowance(address owner, address spender) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x34))
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
    ///
    /// Emits a {Approval} event.
    function approve(address spender, uint256 amount) public virtual returns (bool) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Atomically increases the allowance granted to `spender` by the caller.
    ///
    /// Emits a {Approval} event.
    function increaseAllowance(address spender, uint256 difference) public virtual returns (bool) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowanceBefore := sload(allowanceSlot)
            // Add to the allowance.
            let allowanceAfter := add(allowanceBefore, difference)
            // Revert upon overflow.
            if lt(allowanceAfter, allowanceBefore) {
                mstore(0x00, 0xf9067066) // `AllowanceOverflow()`.
                revert(0x1c, 0x04)
            }
            // Store the updated allowance.
            sstore(allowanceSlot, allowanceAfter)
            // Emit the {Approval} event.
            mstore(0x00, allowanceAfter)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Atomically decreases the allowance granted to `spender` by the caller.
    ///
    /// Emits a {Approval} event.
    function decreaseAllowance(address spender, uint256 difference) public virtual returns (bool) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, caller())
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowanceBefore := sload(allowanceSlot)
            // Revert if will underflow.
            if lt(allowanceBefore, difference) {
                mstore(0x00, 0x8301ab38) // `AllowanceUnderflow()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated allowance.
            let allowanceAfter := sub(allowanceBefore, difference)
            sstore(allowanceSlot, allowanceAfter)
            // Emit the {Approval} event.
            mstore(0x00, allowanceAfter)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
        }
        return true;
    }

    /// @dev Transfer `amount` tokens from the caller to `to`.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    ///
    /// Emits a {Transfer} event.
    function transfer(address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(msg.sender, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, caller())
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(msg.sender, to, amount);
        return true;
    }

    /// @dev Transfers `amount` tokens from `from` to `to`.
    ///
    /// Note: Does not update the allowance if it is the maximum uint256 value.
    ///
    /// Requirements:
    /// - `from` must at least have `amount`.
    /// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
    ///
    /// Emits a {Transfer} event.
    function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the allowance slot and load its value.
            mstore(0x20, caller())
            mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if iszero(eq(allowance_, not(0))) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
        return true;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL MINT FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Mints `amount` tokens to `to`, increasing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _mint(address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(address(0), to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
            let totalSupplyAfter := add(totalSupplyBefore, amount)
            // Revert if the total supply overflows.
            if lt(totalSupplyAfter, totalSupplyBefore) {
                mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
                revert(0x1c, 0x04)
            }
            // Store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(address(0), to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  INTERNAL BURN FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Burns `amount` tokens from `from`, reducing the total supply.
    ///
    /// Emits a {Transfer} event.
    function _burn(address from, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, address(0), amount);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the balance slot and load its value.
            mstore(0x0c, _BALANCE_SLOT_SEED)
            mstore(0x00, from)
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Subtract and store the updated total supply.
            sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
            // Emit the {Transfer} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
        }
        _afterTokenTransfer(from, address(0), amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL TRANSFER FUNCTIONS                 */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Moves `amount` of tokens from `from` to `to`.
    function _transfer(address from, address to, uint256 amount) internal virtual {
        _beforeTokenTransfer(from, to, amount);
        /// @solidity memory-safe-assembly
        assembly {
            let from_ := shl(96, from)
            // Compute the balance slot and load its value.
            mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
            let fromBalanceSlot := keccak256(0x0c, 0x20)
            let fromBalance := sload(fromBalanceSlot)
            // Revert if insufficient balance.
            if gt(amount, fromBalance) {
                mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
                revert(0x1c, 0x04)
            }
            // Subtract and store the updated balance.
            sstore(fromBalanceSlot, sub(fromBalance, amount))
            // Compute the balance slot of `to`.
            mstore(0x00, to)
            let toBalanceSlot := keccak256(0x0c, 0x20)
            // Add and store the updated balance of `to`.
            // Will not overflow because the sum of all user balances
            // cannot exceed the maximum uint256 value.
            sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
            // Emit the {Transfer} event.
            mstore(0x20, amount)
            log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
        }
        _afterTokenTransfer(from, to, amount);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                INTERNAL ALLOWANCE FUNCTIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the allowance slot and load its value.
            mstore(0x20, spender)
            mstore(0x0c, _ALLOWANCE_SLOT_SEED)
            mstore(0x00, owner)
            let allowanceSlot := keccak256(0x0c, 0x34)
            let allowance_ := sload(allowanceSlot)
            // If the allowance is not the maximum uint256 value.
            if iszero(eq(allowance_, not(0))) {
                // Revert if the amount to be transferred exceeds the allowance.
                if gt(amount, allowance_) {
                    mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
                    revert(0x1c, 0x04)
                }
                // Subtract and store the updated allowance.
                sstore(allowanceSlot, sub(allowance_, amount))
            }
        }
    }

    /// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
    ///
    /// Emits a {Approval} event.
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let owner_ := shl(96, owner)
            // Compute the allowance slot and store the amount.
            mstore(0x20, spender)
            mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
            sstore(keccak256(0x0c, 0x34), amount)
            // Emit the {Approval} event.
            mstore(0x00, amount)
            log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     HOOKS TO OVERRIDE                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Hook that is called before any transfer of tokens.
    /// This includes minting and burning.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /// @dev Hook that is called after any transfer of tokens.
    /// This includes minting and burning.
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

// File: src/lib/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.19;

//Efficient Solidity & assembly version of ReentrancyGuard
abstract contract ReentrancyGuard {
    error ReentrantCall();
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.

    uint256 private _status = 1;

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        assembly {
            if eq(sload(_status.slot), 2) {
                mstore(0x00, 0x37ed32e8) // ReentrantCall() selector
                revert(0x1c, 0x04)
            }
            sstore(_status.slot, 0x02)
        }
        _;
        assembly {
            sstore(_status.slot, 0x01)
        }
    }
}

// File: src/interfaces/IStrategy.sol



// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

import {StrategyData} from "../helpers/VaultTypes.sol";

interface IStrategy {
    /// Roles
    function grantRoles(address user, uint256 roles) external payable;

    function revokeRoles(address user, uint256 roles) external payable;

    function renounceRoles(uint256 roles) external payable;

    function harvest(uint256 minExpectedBalance, uint256 minOutputAfterInvestment) external;

    function setEmergencyExit(uint256 _emergencyExit) external;

    function setStrategist(address _newStrategist) external;

    function vault() external returns (address);

    function underlyingAsset() external returns (address);

    function emergencyExit() external returns (uint256);

    function withdraw(uint256 amountNeeded) external returns (uint256);

    function delegatedAssets() external view returns (uint256);

    function estimatedTotalAssets() external view returns (uint256);

    function strategist() external view returns (address);

    function strategyName() external view returns (bytes32);

    function isActive() external view returns (bool);

    /// View roles
    function hasAnyRole(address user, uint256 roles) external view returns (bool result);

    function hasAllRoles(address user, uint256 roles) external view returns (bool result);

    function rolesOf(address user) external view returns (uint256 roles);

    function rolesFromOrdinals(uint8[] memory ordinals) external pure returns (uint256 roles);

    function ordinalsFromRoles(uint256 roles) external pure returns (uint8[] memory ordinals);
}

// File: lib/solady/src/auth/OwnableRoles.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {Ownable} from "./Ownable.sol";

/// @notice Simple single owner and multiroles authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
/// @dev While the ownable portion follows [EIP-173](https://eips.ethereum.org/EIPS/eip-173)
/// for compatibility, the nomenclature for the 2-step ownership handover and roles
/// may be unique to this codebase.
abstract contract OwnableRoles is Ownable { 
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The `user`'s roles is updated to `roles`.
    /// Each bit of `roles` represents whether the role is set.
    event RolesUpdated(address indexed user, uint256 indexed roles);

    /// @dev `keccak256(bytes("RolesUpdated(address,uint256)"))`.
    uint256 private constant _ROLES_UPDATED_EVENT_SIGNATURE =
        0x715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe26;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The role slot of `user` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _ROLE_SLOT_SEED))
    ///     let roleSlot := keccak256(0x00, 0x20)
    /// ```
    /// This automatically ignores the upper bits of the `user` in case
    /// they are not clean, as well as keep the `keccak256` under 32-bytes.
    ///
    /// Note: This is equal to `_OWNER_SLOT_NOT` in for gas efficiency.
    uint256 private constant _ROLE_SLOT_SEED = 0x8b78c6d8;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Grants the roles directly without authorization guard.
    /// Each bit of `roles` represents the role to turn on.
    function _grantRoles(address user, uint256 roles) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            let roleSlot := keccak256(0x0c, 0x20)
            // Load the current value and `or` it with `roles`.
            roles := or(sload(roleSlot), roles)
            // Store the new value.
            sstore(roleSlot, roles)
            // Emit the {RolesUpdated} event.
            log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), roles)
        }
    }

    /// @dev Removes the roles directly without authorization guard.
    /// Each bit of `roles` represents the role to turn off.
    function _removeRoles(address user, uint256 roles) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            let roleSlot := keccak256(0x0c, 0x20)
            // Load the current value.
            let currentRoles := sload(roleSlot)
            // Use `and` to compute the intersection of `currentRoles` and `roles`,
            // `xor` it with `currentRoles` to flip the bits in the intersection.
            roles := xor(currentRoles, and(currentRoles, roles))
            // Then, store the new value.
            sstore(roleSlot, roles)
            // Emit the {RolesUpdated} event.
            log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), roles)
        }
    }

    /// @dev Throws if the sender does not have any of the `roles`.
    function _checkRoles(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, caller())
            // Load the stored value, and if the `and` intersection
            // of the value and `roles` is zero, revert.
            if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Throws if the sender is not the owner,
    /// and does not have any of the `roles`.
    /// Checks for ownership first, then lazily checks for roles.
    function _checkOwnerOrRoles(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner.
            // Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
            if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
                // Compute the role slot.
                mstore(0x0c, _ROLE_SLOT_SEED)
                mstore(0x00, caller())
                // Load the stored value, and if the `and` intersection
                // of the value and `roles` is zero, revert.
                if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Throws if the sender does not have any of the `roles`,
    /// and is not the owner.
    /// Checks for roles first, then lazily checks for ownership.
    function _checkRolesOrOwner(uint256 roles) internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, caller())
            // Load the stored value, and if the `and` intersection
            // of the value and `roles` is zero, revert.
            if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
                // If the caller is not the stored owner.
                // Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
                if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
                    mstore(0x00, 0x82b42900) // `Unauthorized()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to grant `user` `roles`.
    /// If the `user` already has a role, then it will be an no-op for the role.
    function grantRoles(address user, uint256 roles) public payable virtual onlyOwner {
        _grantRoles(user, roles);
    }

    /// @dev Allows the owner to remove `user` `roles`.
    /// If the `user` does not have a role, then it will be an no-op for the role.
    function revokeRoles(address user, uint256 roles) public payable virtual onlyOwner {
        _removeRoles(user, roles);
    }

    /// @dev Allow the caller to remove their own roles.
    /// If the caller does not have a role, then it will be an no-op for the role.
    function renounceRoles(uint256 roles) public payable virtual {
        _removeRoles(msg.sender, roles);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns whether `user` has any of `roles`.
    function hasAnyRole(address user, uint256 roles) public view virtual returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            // Load the stored value, and set the result to whether the
            // `and` intersection of the value and `roles` is not zero.
            result := iszero(iszero(and(sload(keccak256(0x0c, 0x20)), roles)))
        }
    }

    /// @dev Returns whether `user` has all of `roles`.
    function hasAllRoles(address user, uint256 roles) public view virtual returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            // Whether the stored value is contains all the set bits in `roles`.
            result := eq(and(sload(keccak256(0x0c, 0x20)), roles), roles)
        }
    }

    /// @dev Returns the roles of `user`.
    function rolesOf(address user) public view virtual returns (uint256 roles) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the role slot.
            mstore(0x0c, _ROLE_SLOT_SEED)
            mstore(0x00, user)
            // Load the stored value.
            roles := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Convenience function to return a `roles` bitmap from an array of `ordinals`.
    /// This is meant for frontends like Etherscan, and is therefore not fully optimized.
    /// Not recommended to be called on-chain.
    function rolesFromOrdinals(uint8[] memory ordinals) public pure returns (uint256 roles) {
        /// @solidity memory-safe-assembly
        assembly {
            for { let i := shl(5, mload(ordinals)) } i { i := sub(i, 0x20) } {
                // We don't need to mask the values of `ordinals`, as Solidity
                // cleans dirty upper bits when storing variables into memory.
                roles := or(shl(mload(add(ordinals, i)), 1), roles)
            }
        }
    }

    /// @dev Convenience function to return an array of `ordinals` from the `roles` bitmap.
    /// This is meant for frontends like Etherscan, and is therefore not fully optimized.
    /// Not recommended to be called on-chain.
    function ordinalsFromRoles(uint256 roles) public pure returns (uint8[] memory ordinals) {
        /// @solidity memory-safe-assembly
        assembly {
            // Grab the pointer to the free memory.
            ordinals := mload(0x40)
            let ptr := add(ordinals, 0x20)
            let o := 0
            // The absence of lookup tables, De Bruijn, etc., here is intentional for
            // smaller bytecode, as this function is not meant to be called on-chain.
            for { let t := roles } 1 {} {
                mstore(ptr, o)
                // `shr` 5 is equivalent to multiplying by 0x20.
                // Push back into the ordinals array if the bit is set.
                ptr := add(ptr, shl(5, and(t, 1)))
                o := add(o, 1)
                t := shr(o, roles)
                if iszero(t) { break }
            }
            // Store the length of `ordinals`.
            mstore(ordinals, shr(5, sub(ptr, add(ordinals, 0x20))))
            // Allocate the memory.
            mstore(0x40, ptr)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by an account with `roles`.
    modifier onlyRoles(uint256 roles) virtual {
        _checkRoles(roles);
        _;
    }

    /// @dev Marks a function as only callable by the owner or by an account
    /// with `roles`. Checks for ownership first, then lazily checks for roles.
    modifier onlyOwnerOrRoles(uint256 roles) virtual {
        _checkOwnerOrRoles(roles);
        _;
    }

    /// @dev Marks a function as only callable by an account with `roles`
    /// or the owner. Checks for roles first, then lazily checks for ownership.
    modifier onlyRolesOrOwner(uint256 roles) virtual {
        _checkRolesOrOwner(roles);
        _;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ROLE CONSTANTS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // IYKYK

    uint256 internal constant _ROLE_0 = 1 << 0;
    uint256 internal constant _ROLE_1 = 1 << 1;
    uint256 internal constant _ROLE_2 = 1 << 2;
    uint256 internal constant _ROLE_3 = 1 << 3;
    uint256 internal constant _ROLE_4 = 1 << 4;
    uint256 internal constant _ROLE_5 = 1 << 5;
    uint256 internal constant _ROLE_6 = 1 << 6;
    uint256 internal constant _ROLE_7 = 1 << 7;
    uint256 internal constant _ROLE_8 = 1 << 8;
    uint256 internal constant _ROLE_9 = 1 << 9;
    uint256 internal constant _ROLE_10 = 1 << 10;
    uint256 internal constant _ROLE_11 = 1 << 11;
    uint256 internal constant _ROLE_12 = 1 << 12;
    uint256 internal constant _ROLE_13 = 1 << 13;
    uint256 internal constant _ROLE_14 = 1 << 14;
    uint256 internal constant _ROLE_15 = 1 << 15;
    uint256 internal constant _ROLE_16 = 1 << 16;
    uint256 internal constant _ROLE_17 = 1 << 17;
    uint256 internal constant _ROLE_18 = 1 << 18;
    uint256 internal constant _ROLE_19 = 1 << 19;
    uint256 internal constant _ROLE_20 = 1 << 20;
    uint256 internal constant _ROLE_21 = 1 << 21;
    uint256 internal constant _ROLE_22 = 1 << 22;
    uint256 internal constant _ROLE_23 = 1 << 23;
    uint256 internal constant _ROLE_24 = 1 << 24;
    uint256 internal constant _ROLE_25 = 1 << 25;
    uint256 internal constant _ROLE_26 = 1 << 26;
    uint256 internal constant _ROLE_27 = 1 << 27;
    uint256 internal constant _ROLE_28 = 1 << 28;
    uint256 internal constant _ROLE_29 = 1 << 29;
    uint256 internal constant _ROLE_30 = 1 << 30;
    uint256 internal constant _ROLE_31 = 1 << 31;
    uint256 internal constant _ROLE_32 = 1 << 32;
    uint256 internal constant _ROLE_33 = 1 << 33;
    uint256 internal constant _ROLE_34 = 1 << 34;
    uint256 internal constant _ROLE_35 = 1 << 35;
    uint256 internal constant _ROLE_36 = 1 << 36;
    uint256 internal constant _ROLE_37 = 1 << 37;
    uint256 internal constant _ROLE_38 = 1 << 38;
    uint256 internal constant _ROLE_39 = 1 << 39;
    uint256 internal constant _ROLE_40 = 1 << 40;
    uint256 internal constant _ROLE_41 = 1 << 41;
    uint256 internal constant _ROLE_42 = 1 << 42;
    uint256 internal constant _ROLE_43 = 1 << 43;
    uint256 internal constant _ROLE_44 = 1 << 44;
    uint256 internal constant _ROLE_45 = 1 << 45;
    uint256 internal constant _ROLE_46 = 1 << 46;
    uint256 internal constant _ROLE_47 = 1 << 47;
    uint256 internal constant _ROLE_48 = 1 << 48;
    uint256 internal constant _ROLE_49 = 1 << 49;
    uint256 internal constant _ROLE_50 = 1 << 50;
    uint256 internal constant _ROLE_51 = 1 << 51;
    uint256 internal constant _ROLE_52 = 1 << 52;
    uint256 internal constant _ROLE_53 = 1 << 53;
    uint256 internal constant _ROLE_54 = 1 << 54;
    uint256 internal constant _ROLE_55 = 1 << 55;
    uint256 internal constant _ROLE_56 = 1 << 56;
    uint256 internal constant _ROLE_57 = 1 << 57;
    uint256 internal constant _ROLE_58 = 1 << 58;
    uint256 internal constant _ROLE_59 = 1 << 59;
    uint256 internal constant _ROLE_60 = 1 << 60;
    uint256 internal constant _ROLE_61 = 1 << 61;
    uint256 internal constant _ROLE_62 = 1 << 62;
    uint256 internal constant _ROLE_63 = 1 << 63;
    uint256 internal constant _ROLE_64 = 1 << 64;
    uint256 internal constant _ROLE_65 = 1 << 65;
    uint256 internal constant _ROLE_66 = 1 << 66;
    uint256 internal constant _ROLE_67 = 1 << 67;
    uint256 internal constant _ROLE_68 = 1 << 68;
    uint256 internal constant _ROLE_69 = 1 << 69;
    uint256 internal constant _ROLE_70 = 1 << 70;
    uint256 internal constant _ROLE_71 = 1 << 71;
    uint256 internal constant _ROLE_72 = 1 << 72;
    uint256 internal constant _ROLE_73 = 1 << 73;
    uint256 internal constant _ROLE_74 = 1 << 74;
    uint256 internal constant _ROLE_75 = 1 << 75;
    uint256 internal constant _ROLE_76 = 1 << 76;
    uint256 internal constant _ROLE_77 = 1 << 77;
    uint256 internal constant _ROLE_78 = 1 << 78;
    uint256 internal constant _ROLE_79 = 1 << 79;
    uint256 internal constant _ROLE_80 = 1 << 80;
    uint256 internal constant _ROLE_81 = 1 << 81;
    uint256 internal constant _ROLE_82 = 1 << 82;
    uint256 internal constant _ROLE_83 = 1 << 83;
    uint256 internal constant _ROLE_84 = 1 << 84;
    uint256 internal constant _ROLE_85 = 1 << 85;
    uint256 internal constant _ROLE_86 = 1 << 86;
    uint256 internal constant _ROLE_87 = 1 << 87;
    uint256 internal constant _ROLE_88 = 1 << 88;
    uint256 internal constant _ROLE_89 = 1 << 89;
    uint256 internal constant _ROLE_90 = 1 << 90;
    uint256 internal constant _ROLE_91 = 1 << 91;
    uint256 internal constant _ROLE_92 = 1 << 92;
    uint256 internal constant _ROLE_93 = 1 << 93;
    uint256 internal constant _ROLE_94 = 1 << 94;
    uint256 internal constant _ROLE_95 = 1 << 95;
    uint256 internal constant _ROLE_96 = 1 << 96;
    uint256 internal constant _ROLE_97 = 1 << 97;
    uint256 internal constant _ROLE_98 = 1 << 98;
    uint256 internal constant _ROLE_99 = 1 << 99;
    uint256 internal constant _ROLE_100 = 1 << 100;
    uint256 internal constant _ROLE_101 = 1 << 101;
    uint256 internal constant _ROLE_102 = 1 << 102;
    uint256 internal constant _ROLE_103 = 1 << 103;
    uint256 internal constant _ROLE_104 = 1 << 104;
    uint256 internal constant _ROLE_105 = 1 << 105;
    uint256 internal constant _ROLE_106 = 1 << 106;
    uint256 internal constant _ROLE_107 = 1 << 107;
    uint256 internal constant _ROLE_108 = 1 << 108;
    uint256 internal constant _ROLE_109 = 1 << 109;
    uint256 internal constant _ROLE_110 = 1 << 110;
    uint256 internal constant _ROLE_111 = 1 << 111;
    uint256 internal constant _ROLE_112 = 1 << 112;
    uint256 internal constant _ROLE_113 = 1 << 113;
    uint256 internal constant _ROLE_114 = 1 << 114;
    uint256 internal constant _ROLE_115 = 1 << 115;
    uint256 internal constant _ROLE_116 = 1 << 116;
    uint256 internal constant _ROLE_117 = 1 << 117;
    uint256 internal constant _ROLE_118 = 1 << 118;
    uint256 internal constant _ROLE_119 = 1 << 119;
    uint256 internal constant _ROLE_120 = 1 << 120;
    uint256 internal constant _ROLE_121 = 1 << 121;
    uint256 internal constant _ROLE_122 = 1 << 122;
    uint256 internal constant _ROLE_123 = 1 << 123;
    uint256 internal constant _ROLE_124 = 1 << 124;
    uint256 internal constant _ROLE_125 = 1 << 125;
    uint256 internal constant _ROLE_126 = 1 << 126;
    uint256 internal constant _ROLE_127 = 1 << 127;
    uint256 internal constant _ROLE_128 = 1 << 128;
    uint256 internal constant _ROLE_129 = 1 << 129;
    uint256 internal constant _ROLE_130 = 1 << 130;
    uint256 internal constant _ROLE_131 = 1 << 131;
    uint256 internal constant _ROLE_132 = 1 << 132;
    uint256 internal constant _ROLE_133 = 1 << 133;
    uint256 internal constant _ROLE_134 = 1 << 134;
    uint256 internal constant _ROLE_135 = 1 << 135;
    uint256 internal constant _ROLE_136 = 1 << 136;
    uint256 internal constant _ROLE_137 = 1 << 137;
    uint256 internal constant _ROLE_138 = 1 << 138;
    uint256 internal constant _ROLE_139 = 1 << 139;
    uint256 internal constant _ROLE_140 = 1 << 140;
    uint256 internal constant _ROLE_141 = 1 << 141;
    uint256 internal constant _ROLE_142 = 1 << 142;
    uint256 internal constant _ROLE_143 = 1 << 143;
    uint256 internal constant _ROLE_144 = 1 << 144;
    uint256 internal constant _ROLE_145 = 1 << 145;
    uint256 internal constant _ROLE_146 = 1 << 146;
    uint256 internal constant _ROLE_147 = 1 << 147;
    uint256 internal constant _ROLE_148 = 1 << 148;
    uint256 internal constant _ROLE_149 = 1 << 149;
    uint256 internal constant _ROLE_150 = 1 << 150;
    uint256 internal constant _ROLE_151 = 1 << 151;
    uint256 internal constant _ROLE_152 = 1 << 152;
    uint256 internal constant _ROLE_153 = 1 << 153;
    uint256 internal constant _ROLE_154 = 1 << 154;
    uint256 internal constant _ROLE_155 = 1 << 155;
    uint256 internal constant _ROLE_156 = 1 << 156;
    uint256 internal constant _ROLE_157 = 1 << 157;
    uint256 internal constant _ROLE_158 = 1 << 158;
    uint256 internal constant _ROLE_159 = 1 << 159;
    uint256 internal constant _ROLE_160 = 1 << 160;
    uint256 internal constant _ROLE_161 = 1 << 161;
    uint256 internal constant _ROLE_162 = 1 << 162;
    uint256 internal constant _ROLE_163 = 1 << 163;
    uint256 internal constant _ROLE_164 = 1 << 164;
    uint256 internal constant _ROLE_165 = 1 << 165;
    uint256 internal constant _ROLE_166 = 1 << 166;
    uint256 internal constant _ROLE_167 = 1 << 167;
    uint256 internal constant _ROLE_168 = 1 << 168;
    uint256 internal constant _ROLE_169 = 1 << 169;
    uint256 internal constant _ROLE_170 = 1 << 170;
    uint256 internal constant _ROLE_171 = 1 << 171;
    uint256 internal constant _ROLE_172 = 1 << 172;
    uint256 internal constant _ROLE_173 = 1 << 173;
    uint256 internal constant _ROLE_174 = 1 << 174;
    uint256 internal constant _ROLE_175 = 1 << 175;
    uint256 internal constant _ROLE_176 = 1 << 176;
    uint256 internal constant _ROLE_177 = 1 << 177;
    uint256 internal constant _ROLE_178 = 1 << 178;
    uint256 internal constant _ROLE_179 = 1 << 179;
    uint256 internal constant _ROLE_180 = 1 << 180;
    uint256 internal constant _ROLE_181 = 1 << 181;
    uint256 internal constant _ROLE_182 = 1 << 182;
    uint256 internal constant _ROLE_183 = 1 << 183;
    uint256 internal constant _ROLE_184 = 1 << 184;
    uint256 internal constant _ROLE_185 = 1 << 185;
    uint256 internal constant _ROLE_186 = 1 << 186;
    uint256 internal constant _ROLE_187 = 1 << 187;
    uint256 internal constant _ROLE_188 = 1 << 188;
    uint256 internal constant _ROLE_189 = 1 << 189;
    uint256 internal constant _ROLE_190 = 1 << 190;
    uint256 internal constant _ROLE_191 = 1 << 191;
    uint256 internal constant _ROLE_192 = 1 << 192;
    uint256 internal constant _ROLE_193 = 1 << 193;
    uint256 internal constant _ROLE_194 = 1 << 194;
    uint256 internal constant _ROLE_195 = 1 << 195;
    uint256 internal constant _ROLE_196 = 1 << 196;
    uint256 internal constant _ROLE_197 = 1 << 197;
    uint256 internal constant _ROLE_198 = 1 << 198;
    uint256 internal constant _ROLE_199 = 1 << 199;
    uint256 internal constant _ROLE_200 = 1 << 200;
    uint256 internal constant _ROLE_201 = 1 << 201;
    uint256 internal constant _ROLE_202 = 1 << 202;
    uint256 internal constant _ROLE_203 = 1 << 203;
    uint256 internal constant _ROLE_204 = 1 << 204;
    uint256 internal constant _ROLE_205 = 1 << 205;
    uint256 internal constant _ROLE_206 = 1 << 206;
    uint256 internal constant _ROLE_207 = 1 << 207;
    uint256 internal constant _ROLE_208 = 1 << 208;
    uint256 internal constant _ROLE_209 = 1 << 209;
    uint256 internal constant _ROLE_210 = 1 << 210;
    uint256 internal constant _ROLE_211 = 1 << 211;
    uint256 internal constant _ROLE_212 = 1 << 212;
    uint256 internal constant _ROLE_213 = 1 << 213;
    uint256 internal constant _ROLE_214 = 1 << 214;
    uint256 internal constant _ROLE_215 = 1 << 215;
    uint256 internal constant _ROLE_216 = 1 << 216;
    uint256 internal constant _ROLE_217 = 1 << 217;
    uint256 internal constant _ROLE_218 = 1 << 218;
    uint256 internal constant _ROLE_219 = 1 << 219;
    uint256 internal constant _ROLE_220 = 1 << 220;
    uint256 internal constant _ROLE_221 = 1 << 221;
    uint256 internal constant _ROLE_222 = 1 << 222;
    uint256 internal constant _ROLE_223 = 1 << 223;
    uint256 internal constant _ROLE_224 = 1 << 224;
    uint256 internal constant _ROLE_225 = 1 << 225;
    uint256 internal constant _ROLE_226 = 1 << 226;
    uint256 internal constant _ROLE_227 = 1 << 227;
    uint256 internal constant _ROLE_228 = 1 << 228;
    uint256 internal constant _ROLE_229 = 1 << 229;
    uint256 internal constant _ROLE_230 = 1 << 230;
    uint256 internal constant _ROLE_231 = 1 << 231;
    uint256 internal constant _ROLE_232 = 1 << 232;
    uint256 internal constant _ROLE_233 = 1 << 233;
    uint256 internal constant _ROLE_234 = 1 << 234;
    uint256 internal constant _ROLE_235 = 1 << 235;
    uint256 internal constant _ROLE_236 = 1 << 236;
    uint256 internal constant _ROLE_237 = 1 << 237;
    uint256 internal constant _ROLE_238 = 1 << 238;
    uint256 internal constant _ROLE_239 = 1 << 239;
    uint256 internal constant _ROLE_240 = 1 << 240;
    uint256 internal constant _ROLE_241 = 1 << 241;
    uint256 internal constant _ROLE_242 = 1 << 242;
    uint256 internal constant _ROLE_243 = 1 << 243;
    uint256 internal constant _ROLE_244 = 1 << 244;
    uint256 internal constant _ROLE_245 = 1 << 245;
    uint256 internal constant _ROLE_246 = 1 << 246;
    uint256 internal constant _ROLE_247 = 1 << 247;
    uint256 internal constant _ROLE_248 = 1 << 248;
    uint256 internal constant _ROLE_249 = 1 << 249;
    uint256 internal constant _ROLE_250 = 1 << 250;
    uint256 internal constant _ROLE_251 = 1 << 251;
    uint256 internal constant _ROLE_252 = 1 << 252;
    uint256 internal constant _ROLE_253 = 1 << 253;
    uint256 internal constant _ROLE_254 = 1 << 254;
    uint256 internal constant _ROLE_255 = 1 << 255;
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: lib/solady/src/utils/FixedPointMathLib.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, either due to a
    /// multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The multiply-divide operation failed, either due to a
    /// multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The output is undefined, as the input is zero.
    error Log2Undefined();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                // Store the function selector of `MulWadFailed()`.
                mstore(0x00, 0xbac65e5b)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if mul(y, gt(x, div(not(0), y))) {
                // Store the function selector of `MulWadFailed()`.
                mstore(0x00, 0xbac65e5b)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                // Store the function selector of `DivWadFailed()`.
                mstore(0x00, 0x7c5f487d)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
            if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
                // Store the function selector of `DivWadFailed()`.
                mstore(0x00, 0x7c5f487d)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is < 0.5 we return zero. This happens when
            // x <= floor(log(0.5e18) * 1e18) ~ -42e18
            if (x <= -42139678854452767551) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
                // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
                if iszero(slt(x, 135305999368893231589)) {
                    // Store the function selector of `ExpOverflow()`.
                    mstore(0x00, 0xa37bfec9)
                    // Revert with (offset, size).
                    revert(0x1c, 0x04)
                }
            }

            // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // k is in the range [-61, 195].

            // Evaluate using a (6, 7)-term rational approximation.
            // p is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave p in 2**192 basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already 2**96 too large.
                r := sdiv(p, q)
            }

            // r should be in the range (0.09, 0.25) * 2**96.

            // We now need to multiply r by:
            // * the scale factor s = ~6.031367120.
            // * the 2**k factor from the range reduction.
            // * the 1e18 / 2**96 factor for base conversion.
            // We do this all at once, with an intermediate result in 2**213
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    function lnWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            /// @solidity memory-safe-assembly
            assembly {
                if iszero(sgt(x, 0)) {
                    // Store the function selector of `LnWadUndefined()`.
                    mstore(0x00, 0x1615e638)
                    // Revert with (offset, size).
                    revert(0x1c, 0x04)
                }
            }

            // We want to convert x from 10**18 fixed point to 2**96 fixed point.
            // We do this by multiplying by 2**96 / 10**18. But since
            // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
            // and add ln(2**96 / 10**18) at the end.

            // Compute k = log2(x) - 96.
            int256 k;
            /// @solidity memory-safe-assembly
            assembly {
                let v := x
                k := shl(7, lt(0xffffffffffffffffffffffffffffffff, v))
                k := or(k, shl(6, lt(0xffffffffffffffff, shr(k, v))))
                k := or(k, shl(5, lt(0xffffffff, shr(k, v))))

                // For the remaining 32 bits, use a De Bruijn lookup.
                // See: https://graphics.stanford.edu/~seander/bithacks.html
                v := shr(k, v)
                v := or(v, shr(1, v))
                v := or(v, shr(2, v))
                v := or(v, shr(4, v))
                v := or(v, shr(8, v))
                v := or(v, shr(16, v))

                // forgefmt: disable-next-item
                k := sub(or(k, byte(shr(251, mul(v, shl(224, 0x07c4acdd))),
                    0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f)), 96)
            }

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x <<= uint256(159 - k);
            x = int256(uint256(x) >> 159);

            // Evaluate using a (8, 8)-term rational approximation.
            // p is made monic, we will multiply by a scale factor later.
            int256 p = x + 3273285459638523848632254066296;
            p = ((p * x) >> 96) + 24828157081833163892658089445524;
            p = ((p * x) >> 96) + 43456485725739037958740375743393;
            p = ((p * x) >> 96) - 11111509109440967052023855526967;
            p = ((p * x) >> 96) - 45023709667254063763336534515857;
            p = ((p * x) >> 96) - 14706773417378608786704636184526;
            p = p * x - (795164235651350426258249787498 << 96);

            // We leave p in 2**192 basis so we don't need to scale it back up for the division.
            // q is monic by convention.
            int256 q = x + 5573035233440673466300451813936;
            q = ((q * x) >> 96) + 71694874799317883764090561454958;
            q = ((q * x) >> 96) + 283447036172924575727196451306956;
            q = ((q * x) >> 96) + 401686690394027663651624208769553;
            q = ((q * x) >> 96) + 204048457590392012362485061816622;
            q = ((q * x) >> 96) + 31853899698501571402653359427138;
            q = ((q * x) >> 96) + 909429971244387300277376558375;
            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial is known not to have zeros in the domain.
                // No scaling required because p is already 2**96 too large.
                r := sdiv(p, q)
            }

            // r is in the range (0, 0.125) * 2**96

            // Finalization, we need to:
            // * multiply by the scale factor s = 5.549…
            // * add ln(2**96 / 10**18)
            // * add k * ln(2)
            // * multiply by 10**18 / 2**96 = 5**18 >> 78

            // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
            r *= 1677202110996718588342820967067443963516166;
            // add ln(2) * k * 5e18 * 2**192
            r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
            // add ln(2**96 / 10**18) * 5e18 * 2**192
            r += 600920179829731861736702779321621459595472258049074101567377883020018308;
            // base conversion: mul 2**18 / 2**192
            r >>= 174;
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Calculates `floor(a * b / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            for {} 1 {} {
                // 512-bit multiply `[prod1 prod0] = x * y`.
                // Compute the product mod `2**256` and mod `2**256 - 1`
                // then use the Chinese Remainder Theorem to reconstruct
                // the 512 bit result. The result is stored in two 256
                // variables such that `product = prod1 * 2**256 + prod0`.

                // Least significant 256 bits of the product.
                let prod0 := mul(x, y)
                let mm := mulmod(x, y, not(0))
                // Most significant 256 bits of the product.
                let prod1 := sub(mm, add(prod0, lt(mm, prod0)))

                // Handle non-overflow cases, 256 by 256 division.
                if iszero(prod1) {
                    if iszero(d) {
                        // Store the function selector of `FullMulDivFailed()`.
                        mstore(0x00, 0xae47f702)
                        // Revert with (offset, size).
                        revert(0x1c, 0x04)
                    }
                    result := div(prod0, d)
                    break       
                }

                // Make sure the result is less than `2**256`.
                // Also prevents `d == 0`.
                if iszero(gt(d, prod1)) {
                    // Store the function selector of `FullMulDivFailed()`.
                    mstore(0x00, 0xae47f702)
                    // Revert with (offset, size).
                    revert(0x1c, 0x04)
                }

                ///////////////////////////////////////////////
                // 512 by 256 division.
                ///////////////////////////////////////////////

                // Make division exact by subtracting the remainder from `[prod1 prod0]`.
                // Compute remainder using mulmod.
                let remainder := mulmod(x, y, d)
                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
                // Factor powers of two out of `d`.
                // Compute largest power of two divisor of `d`.
                // Always greater or equal to 1.
                let twos := and(d, sub(0, d))
                // Divide d by power of two.
                d := div(d, twos)
                // Divide [prod1 prod0] by the factors of two.
                prod0 := div(prod0, twos)
                // Shift in bits from `prod1` into `prod0`. For this we need
                // to flip `twos` such that it is `2**256 / twos`.
                // If `twos` is zero, then it becomes one.
                prod0 := or(prod0, mul(prod1, add(div(sub(0, twos), twos), 1)))
                // Invert `d mod 2**256`
                // Now that `d` is an odd number, it has an inverse
                // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                // Compute the inverse by starting with a seed that is correct
                // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                let inv := xor(mul(3, d), 2)
                // Now use Newton-Raphson iteration to improve the precision.
                // Thanks to Hensel's lifting lemma, this also works in modular
                // arithmetic, doubling the correct bits in each step.
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                result := mul(prod0, mul(inv, sub(2, mul(d, inv)))) // inverse mod 2**256
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 result) {
        result = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                if iszero(add(result, 1)) {
                    // Store the function selector of `FullMulDivFailed()`.
                    mstore(0x00, 0xae47f702)
                    // Revert with (offset, size).
                    revert(0x1c, 0x04)
                }
                result := add(result, 1)
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                // Store the function selector of `MulDivFailed()`.
                mstore(0x00, 0xad251c27)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := div(mul(x, y), d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {
                // Store the function selector of `MulDivFailed()`.
                mstore(0x00, 0xad251c27)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                // Store the function selector of `DivFailed()`.
                mstore(0x00, 0x65244e4e)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns the square root of `x`.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`.
            // We check `y >= 2**(k + 8)` but shift right by `k` bits
            // each branch to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))

            z := shl(add(div(r, 3), lt(0xf, shr(r, x))), 0xff)
            z := div(z, byte(mod(r, 3), shl(232, 0x7f624b)))

            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)

            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 58)) {
                // Store the function selector of `FactorialOverflow()`.
                mstore(0x00, 0xaba0f2a2)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            for { result := 1 } x {} {
                result := mul(result, x)
                x := sub(x, 1)
            }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(x) {
                // Store the function selector of `Log2Undefined()`.
                mstore(0x00, 0x5be3aa5c)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))

            // For the remaining 32 bits, use a De Bruijn lookup.
            // See: https://graphics.stanford.edu/~seander/bithacks.html
            x := shr(r, x)
            x := or(x, shr(1, x))
            x := or(x, shr(2, x))
            x := or(x, shr(4, x))
            x := or(x, shr(8, x))
            x := or(x, shr(16, x))

            // forgefmt: disable-next-item
            r := or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
                0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        unchecked {
            uint256 isNotPo2;
            assembly {
                isNotPo2 := iszero(iszero(and(x, sub(x, 1))))
            }
            return log2(x) + isNotPo2;
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (((x & 1) + (y & 1)) >> 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let mask := sub(0, shr(255, x))
            z := xor(mask, add(mask, x))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let a := sub(y, x)
            z := xor(a, mul(xor(a, sub(x, y)), sgt(x, y)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        z = min(max(x, minValue), maxValue);
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        z = min(max(x, minValue), maxValue);
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

// File: lib/solady/src/utils/SafeTransferLib.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Caution! This library won't check that a token has code, responsibility is delegated to the caller.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH
    /// that disallows any storage writes.
    uint256 internal constant _GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    /// Multiply by a small constant (e.g. 2), if needed.
    uint256 internal constant _GAS_STIPEND_NO_GRIEF = 100000;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` (in wei) ETH to `to`.
    /// Reverts upon failure.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // For better gas estimation.
                    if iszero(gt(gas(), 1000000)) { revert(0, 0) }
                }
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a gas stipend
    /// equal to `_GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default
    /// for 99% of cases and can be overriden with the three-argument version of this
    /// function if necessary.
    ///
    /// If sending via the normal procedure fails, force sends the ETH by
    /// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
    ///
    /// Reverts if the current contract has insufficient balance.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        // Manually inlined because the compiler doesn't inline functions with branches.
        /// @solidity memory-safe-assembly
        assembly {
            // If insufficient balance, revert.
            if lt(selfbalance(), amount) {
                // Store the function selector of `ETHTransferFailed()`.
                mstore(0x00, 0xb12d13eb)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Transfer the ETH and check if it succeeded or not.
            if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                // We can directly use `SELFDESTRUCT` in the contract creation.
                // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
                if iszero(create(amount, 0x0b, 0x16)) {
                    // For better gas estimation.
                    if iszero(gt(gas(), 1000000)) { revert(0, 0) }
                }
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    /// The `gasStipend` can be set to a low enough value to prevent
    /// storage writes or gas griefing.
    ///
    /// Simply use `gasleft()` for `gasStipend` if you don't need a gas stipend.
    ///
    /// Note: Does NOT revert upon failure.
    /// Returns whether the transfer of ETH is successful instead.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and check if it succeeded or not.
            success := call(gasStipend, to, amount, 0, 0, 0, 0)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x0c, 0x23b872dd000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.

            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x0c, 0x70a08231000000000000000000000000)
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Store the function selector of `transferFrom(address,address,uint256)`.
            mstore(0x00, 0x23b872dd)
            // The `amount` argument is already written to the memory word at 0x6c.
            amount := mload(0x60)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFromFailed()`.
                mstore(0x00, 0x7939f424)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            mstore(0x14, to) // Store the `to` argument.
            // The `amount` argument is already written to the memory word at 0x34.
            amount := mload(0x34)
            // Store the function selector of `transfer(address,uint256)`.
            mstore(0x00, 0xa9059cbb000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `TransferFailed()`.
                mstore(0x00, 0x90b8ec18)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // Store the function selector of `approve(address,uint256)`.
            mstore(0x00, 0x095ea7b3000000000000000000000000)

            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    // Set success to whether the call reverted, if not we check it either
                    // returned exactly 1 (can't just be non-zero data), or had no return data.
                    or(eq(mload(0x00), 1), iszero(returndatasize())),
                    call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                )
            ) {
                // Store the function selector of `ApproveFailed()`.
                mstore(0x00, 0x3e3f8f73)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
            // Restore the part of the free memory pointer that was overwritten.
            mstore(0x34, 0)
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            // Store the function selector of `balanceOf(address)`.
            mstore(0x00, 0x70a08231000000000000000000000000)
            amount :=
                mul(
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }
}

// File: lib/solady/src/auth/Ownable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
/// @dev While the ownable portion follows [EIP-173](https://eips.ethereum.org/EIPS/eip-173)
/// for compatibility, the nomenclature for the 2-step ownership handover
/// may be unique to this codebase.
abstract contract Ownable { 
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The owner slot is given by: `not(_OWNER_SLOT_NOT)`.
    /// It is intentionally choosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    uint256 private constant _OWNER_SLOT_NOT = 0x8b78c6d8;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Clean the upper 96 bits.
            newOwner := shr(96, shl(96, newOwner))
            // Store the new value.
            sstore(not(_OWNER_SLOT_NOT), newOwner)
            // Emit the {OwnershipTransferred} event.
            log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let ownerSlot := not(_OWNER_SLOT_NOT)
            // Clean the upper 96 bits.
            newOwner := shr(96, shl(96, newOwner))
            // Emit the {OwnershipTransferred} event.
            log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
            // Store the new value.
            sstore(ownerSlot, newOwner)
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(not(_OWNER_SLOT_NOT)))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will be automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(not(_OWNER_SLOT_NOT))
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    function ownershipHandoverValidFor() public view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}