Skip to content
Verified contractPartialGPL-3.0-only

Validation

Address0x8df125dc481b6b42e03c0977398cd3b6ead88a5e
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.34

 

Same code

3 more contracts

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
License
GPL-3.0-only
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,443,534
Creation transaction
0x21bba0686d…08ad3dcfa2
Main copy (most transactions)
0xe61a70f7…e193f72e

23 files

lib/core-v1/contracts/libraries/Validation.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';

import {
    DEPOSIT_L,
    DEPOSIT_X,
    DEPOSIT_Y,
    BORROW_L,
    BORROW_X,
    BORROW_Y
} from 'contracts/interfaces/tokens/ITokenController.sol';

import {
    Q72,
    Q128,
    LTVMAX_IN_MAG2,
    ALLOWED_LIQUIDITY_LEVERAGE,
    MAG2,
    MINIMUM_LIQUIDITY
} from 'contracts/libraries/constants.sol';
import {Convert} from 'contracts/libraries/Convert.sol';
import {TickMath} from 'contracts/libraries/TickMath.sol';
import {QuadraticSwapFees} from 'contracts/libraries/QuadraticSwapFees.sol';

library Validation {
    uint256 internal constant MAX_BORROW_PERCENTAGE = 90;

    struct InputParams {
        uint256[6] userAssets;
        int16 minTick;
        int16 maxTick;
        uint256 sqrtPriceMinInQ72;
        uint256 sqrtPriceMaxInQ72;
        uint256 activeLiquidityAssets;
        uint256 reservesXAssets;
        uint256 reservesYAssets;
        bool hasBorrow;
    }

    struct CheckLtvParams {
        uint256 netDepositedXinLAssets;
        uint256 netDepositedYinLAssets;
        uint256 netBorrowedXinLAssets;
        uint256 netBorrowedYinLAssets;
    }

    struct VerifyMaxBorrowParams {
        uint256 depositedAssets;
        uint256 borrowedAssets;
        uint256 reserve;
        uint256 totalDepositedLAssets;
        uint256 totalBorrowedLAssets;
    }

    error InsufficientLiquidity();
    error AmmalgamCannotBorrowAgainstSameCollateral();
    error AmmalgamMaxBorrowReached();
    error AmmalgamDepositIsNotStrictlyBigger();
    error AmmalgamLTV();
    error AmmalgamMaxSlippage();
    error AmmalgamTooMuchLeverage();
    error AmmalgamTransferAmtExceedsBalance();

    /**
     * @notice Get the input parameters for the validation
     * @dev hasBorrow is set to true here, because we assume that the caller has verified there is
     *      a borrowed asset
     * @param userAssets The user assets of the pool
     * @param activeLiquidityAssets The current active liquidity assets of the pool
     * @param reserveXAssets The reserve of the X asset
     * @param reserveYAssets The reserve of the Y asset
     * @param externalLiquidity The external liquidity of the pool
     * @param minTick The min tick of the pool
     * @param maxTick The max tick of the pool
     * @return inputParams The input parameters for the validation
     */
    function getInputParams(
        uint256[6] memory userAssets,
        uint256 activeLiquidityAssets,
        uint256 reserveXAssets,
        uint256 reserveYAssets,
        uint256 externalLiquidity,
        int16 minTick,
        int16 maxTick
    ) internal pure returns (Validation.InputParams memory inputParams) {
        inputParams = Validation.InputParams({
            userAssets: userAssets,
            minTick: minTick,
            maxTick: maxTick,
            sqrtPriceMinInQ72: TickMath.getSqrtPriceAtTick(minTick),
            sqrtPriceMaxInQ72: TickMath.getSqrtPriceAtTick(maxTick),
            activeLiquidityAssets: activeLiquidityAssets + externalLiquidity,
            reservesXAssets: reserveXAssets,
            reservesYAssets: reserveYAssets,
            hasBorrow: true
        });
    }

    /**
     * @notice Get the check LTV parameters for needed for `validateLTVAndLeverage()`
     * @dev the sqrt prices are in the input params, but by passing them we allow for the ability
     *      to switch them as needed in liquidation and other cases.
     * @param userAssets User asset array
     * @param sqrtPriceMinInQ72 The minimum sqrt price in Q72
     * @param sqrtPriceMaxInQ72 The maximum sqrt price in Q72
     */
    function getCheckLtvParams(
        uint256[6] memory userAssets,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72
    ) internal pure returns (CheckLtvParams memory checkLtvParams) {
        (checkLtvParams.netBorrowedXinLAssets, checkLtvParams.netBorrowedYinLAssets) =
            getBorrowedInL(userAssets, sqrtPriceMinInQ72, sqrtPriceMaxInQ72);
        (checkLtvParams.netDepositedXinLAssets, checkLtvParams.netDepositedYinLAssets) =
            getDepositsInL(userAssets, sqrtPriceMinInQ72, sqrtPriceMaxInQ72);
    }

    /**
     * @notice Verifies that debt is backed by liquidity from an independent provider and
     *   that users do not borrow the same underlying assets they supply as collateral.
     * @param userAssets The account's assets by token type.
     * @param activeLiquidityAssets The pair's active liquidity assets.
     */
    function validateBalanceAndLiqAndNotSameAssetsSuppliedAndBorrowed(
        uint256[6] memory userAssets,
        uint256 activeLiquidityAssets
    ) internal pure {
        if (activeLiquidityAssets < userAssets[DEPOSIT_L] + MINIMUM_LIQUIDITY) revert InsufficientLiquidity();

        verifyNotSameAssetsSuppliedAndBorrowed(
            userAssets[DEPOSIT_X], userAssets[DEPOSIT_Y], userAssets[BORROW_X], userAssets[BORROW_Y]
        );
    }

    function validateLTVAndLeverage(
        CheckLtvParams memory checkLtvParams,
        uint256 activeLiquidityAssets
    ) internal pure {
        checkLtv(checkLtvParams, activeLiquidityAssets);
        checkLeverage(checkLtvParams);
    }

    /**
     * Added TokenType and uint256s for amount, balance from, and balance to
     * to enable to pass a value for the current balance of a token to avoid one
     * check of a balance that can be done from within a token.
     */
    function validateSolvency(
        uint256[6] memory userAssets,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72,
        uint256 activeLiquidityAssets
    ) external pure {
        validateBalanceAndLiqAndNotSameAssetsSuppliedAndBorrowed(userAssets, activeLiquidityAssets);
        CheckLtvParams memory checkLtvParams = getCheckLtvParams(userAssets, sqrtPriceMinInQ72, sqrtPriceMaxInQ72);
        validateLTVAndLeverage(checkLtvParams, activeLiquidityAssets - userAssets[DEPOSIT_L]);
    }

    function verifyNotSameAssetsSuppliedAndBorrowed(
        uint256 depositedXAssets,
        uint256 depositedYAssets,
        uint256 borrowedXAssets,
        uint256 borrowedYAssets
    ) internal pure {
        if ((borrowedXAssets > 0 && depositedXAssets > 0) || (borrowedYAssets > 0 && depositedYAssets > 0)) {
            revert AmmalgamCannotBorrowAgainstSameCollateral();
        }
    }

    function verifyMaxBorrow(
        VerifyMaxBorrowParams memory params
    ) internal pure {
        unchecked {
            uint256 scaledBorrowedLiquidityAssets = Convert.mulDiv(
                params.reserve,
                params.totalBorrowedLAssets,
                params.totalDepositedLAssets - params.totalBorrowedLAssets,
                false
            );

            if (
                Convert.mulDiv(params.reserve + scaledBorrowedLiquidityAssets, MAX_BORROW_PERCENTAGE, MAG2, false)
                    + params.depositedAssets < scaledBorrowedLiquidityAssets + params.borrowedAssets
            ) {
                revert AmmalgamMaxBorrowReached();
            }
        }
    }

    function getDepositsInL(
        uint256[6] memory userAssets,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72
    ) private pure returns (uint256 netDepositedXinLAssets, uint256 netDepositedYinLAssets) {
        netDepositedXinLAssets = netDepositedYinLAssets = userAssets[DEPOSIT_L];

        if (0 < userAssets[DEPOSIT_X]) {
            netDepositedXinLAssets += Validation.convertXToL(
                userAssets[DEPOSIT_X],
                sqrtPriceMaxInQ72, // max tick is applied on X for deposit
                false
            );
        }
        if (0 < userAssets[DEPOSIT_Y]) {
            netDepositedYinLAssets += Validation.convertYToL(
                userAssets[DEPOSIT_Y],
                sqrtPriceMinInQ72, // min tick is applied on Y for deposit
                false
            );
        }
    }

    function getBorrowedInL(
        uint256[6] memory userAssets,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72
    ) private pure returns (uint256 netBorrowedXinLAssets, uint256 netBorrowedYinLAssets) {
        netBorrowedXinLAssets = netBorrowedYinLAssets = userAssets[BORROW_L];

        if (userAssets[BORROW_X] > 0) {
            netBorrowedXinLAssets += convertXToL(
                userAssets[BORROW_X],
                sqrtPriceMinInQ72, // min tick is applied on X for borrow
                true
            );
        }
        if (userAssets[BORROW_Y] > 0) {
            netBorrowedYinLAssets += convertYToL(
                userAssets[BORROW_Y],
                sqrtPriceMaxInQ72, // max tick is applied on Y for borrow
                true
            );
        }
    }

    /**
     * Convert X assets to L assets: L = x / sqrt(p)
     * amountLAssets = amountInXAssets * Q72 / sqrtPriceInXInQ72
     */
    function convertXToL(
        uint256 amountInXAssets,
        uint256 sqrtPriceInXInQ72,
        bool roundUp
    ) internal pure returns (uint256 amountLAssets) {
        if (amountInXAssets == 0) return 0;
        amountLAssets = Convert.mulDiv(amountInXAssets, Q72, sqrtPriceInXInQ72, roundUp);
    }

    /**
     * Convert L assets to X assets: x = L * sqrt(p)
     * amountXAssets = amount * sqrtPriceQ72 / Q72
     */
    function convertLToX(
        uint256 amount,
        uint256 sqrtPriceQ72,
        bool roundUp
    ) internal pure returns (uint256 amountXAssets) {
        if (amount == 0) return 0;
        amountXAssets = Convert.mulDiv(amount, sqrtPriceQ72, Q72, roundUp);
    }

    /**
     * Convert Y assets to L assets: L = y * sqrt(p)
     * amountLAssets = amountInYAssets * sqrtPriceInXInQ72 / Q72
     */
    function convertYToL(
        uint256 amountInYAssets,
        uint256 sqrtPriceInXInQ72,
        bool roundUp
    ) internal pure returns (uint256 amountInLAssets) {
        if (amountInYAssets == 0) return 0;
        amountInLAssets = Convert.mulDiv(amountInYAssets, sqrtPriceInXInQ72, Q72, roundUp);
    }

    /**
     * Convert L assets to Y assets: y = L / sqrt(p)
     * amountYAssets = amount * Q72 / sqrtPriceQ72
     */
    function convertLToY(
        uint256 amount,
        uint256 sqrtPriceQ72,
        bool roundUp
    ) internal pure returns (uint256 amountYAssets) {
        if (amount == 0) return 0;
        amountYAssets = Convert.mulDiv(amount, Q72, sqrtPriceQ72, roundUp);
    }

    function calcDebtAndCollateral(
        CheckLtvParams memory checkLtvParams
    ) internal pure returns (uint256 debtLiquidityAssets, uint256 collateralLiquidityAssets, bool netDebtX) {
        bool xDepositIsStrictlyBigger = checkLtvParams.netDepositedXinLAssets > checkLtvParams.netBorrowedXinLAssets;
        bool yDepositIsStrictlyBigger = checkLtvParams.netDepositedYinLAssets > checkLtvParams.netBorrowedYinLAssets;

        if (!xDepositIsStrictlyBigger && !yDepositIsStrictlyBigger) {
            unchecked {
                debtLiquidityAssets = checkLtvParams.netBorrowedXinLAssets - checkLtvParams.netDepositedXinLAssets
                    + (checkLtvParams.netBorrowedYinLAssets - checkLtvParams.netDepositedYinLAssets);
            }
        } else if (!xDepositIsStrictlyBigger) {
            unchecked {
                debtLiquidityAssets = checkLtvParams.netBorrowedXinLAssets - checkLtvParams.netDepositedXinLAssets;
                collateralLiquidityAssets = checkLtvParams.netDepositedYinLAssets - checkLtvParams.netBorrowedYinLAssets;
            }
            netDebtX = true;
        } else if (!yDepositIsStrictlyBigger) {
            unchecked {
                debtLiquidityAssets = checkLtvParams.netBorrowedYinLAssets - checkLtvParams.netDepositedYinLAssets;
                collateralLiquidityAssets = checkLtvParams.netDepositedXinLAssets - checkLtvParams.netBorrowedXinLAssets;
            }
        }
    }

    function checkLtv(
        CheckLtvParams memory checkLtvParams,
        uint256 activeLiquidityAssets
    ) private pure returns (uint256 debtLiquidityAssets, uint256 collateralLiquidityAssets) {
        if (checkLtvParams.netBorrowedXinLAssets == 0 && checkLtvParams.netBorrowedYinLAssets == 0) return (0, 0);

        (debtLiquidityAssets, collateralLiquidityAssets,) = calcDebtAndCollateral(checkLtvParams);
        if (collateralLiquidityAssets == 0 && debtLiquidityAssets > 0) {
            revert AmmalgamDepositIsNotStrictlyBigger();
        }

        // Exclude current user liquidity as liquidator may sell collateral after liquidation in
        // which case the slippage would not included deposited L.
        // underflow has been checked at 'Ammalgam: Insufficient liquidity'.
        unchecked {
            debtLiquidityAssets = increaseForSlippage(debtLiquidityAssets, activeLiquidityAssets);

            if (collateralLiquidityAssets * LTVMAX_IN_MAG2 < debtLiquidityAssets * MAG2) revert AmmalgamLTV();
        }
    }

    /**
     * @notice Increases an L-denominated debt amount by the constant-product slippage needed
     *   to buy that debt against the pool's active liquidity.
     *
     *   Let `D` be `debtLiquidityAssets` and `L` be `activeLiquidityAssets`. The function
     *   reverts when `D >= L`; otherwise it returns:
     *
     *   ```math
     *   D_{in}=\left\lceil\frac{L\cdot D}{L-D}\right\rceil
     *   ```
     *
     *   This is the amount of L assets that must enter the pool to remove `D` L assets
     *   of debt from the opposite reserve under the constant-product approximation.
     *
     * @param debtLiquidityAssets The amount of debt with units of L that will need to be purchased in case of liquidation.
     * @param activeLiquidityAssets The amount of liquidity in the pool available to swap against.
     */
    function increaseForSlippage(
        uint256 debtLiquidityAssets,
        uint256 activeLiquidityAssets
    ) internal pure returns (uint256) {
        if (debtLiquidityAssets >= activeLiquidityAssets) {
            revert AmmalgamMaxSlippage();
        }
        return Math.ceilDiv(activeLiquidityAssets * debtLiquidityAssets, (activeLiquidityAssets - debtLiquidityAssets));
    }

    function checkLeverage(
        CheckLtvParams memory checkLtvParams
    ) private pure {
        unchecked {
            uint256 totalNetDeposits = checkLtvParams.netDepositedXinLAssets + checkLtvParams.netDepositedYinLAssets;
            uint256 totalNetDebts = checkLtvParams.netBorrowedXinLAssets + checkLtvParams.netBorrowedYinLAssets;

            if (totalNetDebts > 0) {
                if (
                    totalNetDeposits < totalNetDebts
                        || (totalNetDeposits - totalNetDebts) * ALLOWED_LIQUIDITY_LEVERAGE < totalNetDeposits
                ) {
                    revert AmmalgamTooMuchLeverage();
                }
            }
        }
    }
}

lib/core-v1/contracts/interfaces/ISaturationAndGeometricTWAPState.sol

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

import {Liquidation} from 'contracts/libraries/Liquidation.sol';
import {Saturation} from 'contracts/libraries/Saturation.sol';
import {Validation} from 'contracts/libraries/Validation.sol';
import {GeometricTWAP} from 'contracts/libraries/GeometricTWAP.sol';

interface ISaturationAndGeometricTWAPState {
    // errors

    error PairAlreadyExists();
    error PairDoesNotExist();
    error InvalidUserConfiguration();

    /**
     * @notice Exposes the public getter for the configured mid-term interval (in seconds)
     */
    function midTermIntervalConfig() external view returns (uint24);

    /**
     * @notice Exposes the public getter for the configured long-term interval (in seconds)
     */
    function longTermIntervalConfig() external view returns (uint24);

    /**
     * @notice  initializes the sat (allocating storage for all nodes) and twap structs
     */
    function init(uint256 reserveX, uint256 reserveY) external;

    // saturation external functions

    function setNewPositionSaturation(address pair, uint256 maxDesiredSaturationInMAG2) external;

    /**
     * @notice  get the details of a specific to the tree and leaf in the saturation state.
     * @param   pairAddress  the pair for which the tree is being queried
     * @param   netDebtX  whether to query the netDebtX or netDebtY side of the tree
     * @param   leaf  the leaf index to query, you can use zero if you don't need the leaf details
     * @return  saturation  the saturation details for the specified leaf
     * @return  currentPenaltyInBorrowLSharesPerSatInQ72  the current penalty per sat in borrowL
     *    shares for the specified leaf
     * @return  totalSatInLAssets  the total saturation in L assets for the specified tree
     * @return  highestSetLeaf  the highest set leaf index for the specified tree
     * @return  tranches  the list of tranches set in the specified leaf
     */
    function getTreeLeafDetails(
        address pairAddress,
        bool netDebtX,
        uint256 leaf
    )
        external
        view
        returns (
            Saturation.SaturationPair memory saturation,
            uint256 currentPenaltyInBorrowLSharesPerSatInQ72,
            uint128 totalSatInLAssets,
            uint16 highestSetLeaf,
            uint16[] memory tranches
        );

    function getTrancheDetails(
        address pairAddress,
        bool netDebtX,
        int16 tranche
    ) external view returns (uint16 leaf, Saturation.SaturationPair memory saturation);

    function getAccount(
        address pairAddress,
        bool netX,
        address accountAddress
    ) external view returns (Saturation.Account memory);

    /**
     * @notice Check if an account exists in either netX or netY saturation tree
     * @param pairAddress The address of the pair
     * @param accountAddress The address of the account to check
     * @return exists True if the account exists in either tree
     */
    function accountExistsInSaturation(
        address pairAddress,
        address accountAddress
    ) external view returns (bool exists);

    /**
     * @notice  update the borrow position of an account and potentially check (and revert) if the
     *   resulting sat is too high
     * @param   inputParams  contains the position and pair params, like account borrows/deposits,
     *   current price and active liquidity
     * @param   account  for which is position is being updated
     * @param   skipMinOrMaxTickCheck  whether to skip the min/max tick check during validation
     */
    function update(Validation.InputParams memory inputParams, address account, bool skipMinOrMaxTickCheck) external;

    /**
     * @notice  accrue penalties since last accrual based on all over saturated positions
     *
     * @param   externalLiquidity  Swap liquidity outside this pool
     * @param   duration  since last accrual of penalties
     * @param   allAssetsDepositL  allAsset[DEPOSIT_L]
     * @param   allAssetsBorrowL  allAsset[BORROW_L]
     * @param   allSharesBorrowL  allShares[BORROW_L]
     * @param   fragileLiquidityAssets  fragile liquidity removed from active liquidity so the penalty
     * threshold reads the same liquidity we use to measure risk capacity in update()
     */
    function accruePenalties(
        address account,
        uint256 externalLiquidity,
        uint256 duration,
        uint256 allAssetsDepositL,
        uint256 allAssetsBorrowL,
        uint256 allSharesBorrowL,
        uint256 fragileLiquidityAssets
    ) external returns (uint112 penaltyInBorrowLShares, uint112 accountPenaltyInBorrowLShares);

    /**
     * @notice Calculate the ratio by which the saturation has changed for `account`.
     * @param inputParams The params containing the position of `account`.
     * @param liqSqrtPriceInXInQ72 The liquidation sqrt price for netX in Q72; pass 0 if not applicable.
     * @param liqSqrtPriceInYInQ72 The liquidation sqrt price for netY in Q72; pass 0 if not applicable.
     * @param pairAddress The address of the pair
     * @param account The account for which we are calculating the saturation change ratio.
     * @return ratioBips The ratio representing the change in saturation for account.
     */
    function calcSatChangeRatioBips(
        Validation.InputParams memory inputParams,
        uint256 liqSqrtPriceInXInQ72,
        uint256 liqSqrtPriceInYInQ72,
        address pairAddress,
        address account
    ) external view returns (uint256 ratioBips);

    // price extremes external functions

    /**
     * @notice Record a price extreme observation for the calling pair.
     */
    function recordPriceExtreme(
        uint256 priceQ128
    ) external;

    // twap external functions

    /**
     * @notice Configures the interval of long-term observations.
     * @dev This function is used to set the long-term interval between observations for the long-term buffer.
     * @param pairAddress The address of the pair for which the long-term interval is being configured.
     * @param longTermIntervalConfigFactor The desired duration for each long-term period.
     *      The size is set as a factor of the mid-term interval to ensure a sufficient buffer, requiring
     *      at least 16 * 12 = 192 seconds per period, resulting in a total of ~25 minutes (192 * 8 = 1536 seconds)
     *      for the long-term buffer.
     */
    function configLongTermInterval(address pairAddress, uint24 longTermIntervalConfigFactor) external;

    /**
     * @notice Records a new observation tick value and updates the observation data.
     * @dev This function is used to record new observation data for the contract. It ensures that
     *      the provided tick value is stored appropriately in both mid-term and long-term
     *      observations, updates interval counters, and handles tick cumulative values based
     *      on the current interval configuration. Ensures that this function is called in
     *      chronological order, with increasing timestamps. Returns in case the
     *      provided block timestamp is less than or equal to the last recorded timestamp.
     * @param newTick The new tick value to be recorded, representing the most recent update of
     *      reserveXAssets and reserveYAssets.
     * @param timeElapsed The time elapsed since the last observation.
     */
    function recordObservation(int16 newTick, uint32 timeElapsed) external returns (bool);

    /**
     * @notice Gets the min and max range of tick values from the stored oracle observations.
     * @dev This function calculates the minimum and maximum tick values among three observed ticks:
     *          long-term tick, mid-term tick, and current tick.
     * @param pair The address of the pair for which the tick range is being queried.
     * @param reserveXAssets The current pair reserves of asset X.
     * @param reserveYAssets The current pair reserves of asset Y.
     * @param includeLongTermTick Boolean value indicating whether to include the long-term tick in the range.
     * @return minTick The minimum tick value among the three observed ticks.
     * @return maxTick The maximum tick value among the three observed ticks.
     */
    function getTickRange(
        address pair,
        uint256 reserveXAssets,
        uint256 reserveYAssets,
        bool includeLongTermTick
    ) external view returns (int16, int16);

    /**
     * @notice Gets the tick value representing the TWAP since the last
     *         lending update and checkpoints the current lending cumulative sum
     *         as `self.lendingCumulativeSum` and the current block timestamp as `self.lastLendingTimestamp`.
     * @dev See `getLendingStateTick` for implementation details which was
     *      separated to allow view access without any state updates.
     * @param timeElapsedSinceUpdate The time elapsed since the last price update.
     * @param timeElapsedSinceLendingUpdate The time elapsed since the last lending update.
     * @return lendingStateTick The tick value representing the TWAP since the last lending update.
     */
    function getLendingStateTickAndCheckpoint(
        uint32 timeElapsedSinceUpdate,
        uint32 timeElapsedSinceLendingUpdate
    ) external returns (int16, uint256);

    /**
     * @dev Retrieves the mid-term tick value based on the stored observations.
     * @return midTermTick The mid-term tick value.
     */
    function getObservedMidTermTick() external view returns (int16 midTermTick);

    /**
     * @notice Gets the tick value representing the TWAP since the last lending update.
     * @param newTick The current tick value.
     * @param timeElapsedSinceUpdate The time elapsed since the last price update.
     * @param timeElapsedSinceLendingUpdate The time elapsed since the last lending update.
     * @return lendingStateTick The tick value representing the TWAP since the last lending update.
     * @return currentCumulativeSum The current cumulative sum for the last updated timestamp.
     */
    function getLendingStateTick(
        int56 newTick,
        uint32 timeElapsedSinceUpdate,
        uint32 timeElapsedSinceLendingUpdate
    ) external view returns (int16, uint256);

    function getObservations(
        address pair
    ) external view returns (GeometricTWAP.Observations memory);
}

lib/core-v1/contracts/interfaces/tokens/IAmmalgamERC20.sol

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

import {IERC20} from '@openzeppelin/contracts/interfaces/IERC20.sol';
import {IERC20Metadata} from '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import {IERC20Permit} from '@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol';

/**
 * @title IAmmalgamERC20
 * @dev This interface extends IERC20, IERC20Metadata, and IERC20Permit, and defines mint and burn functions.
 */
interface IAmmalgamERC20 is IERC20, IERC20Metadata, IERC20Permit {
    /**
     * @dev Emitted when tokens are minted
     * @param to Address where minted tokens are sent
     * @param assets The amount of token assets being minted
     * @param shares The amount of token shares being minted
     */
    event Mint(address indexed sender, address indexed to, uint256 assets, uint256 shares);

    /**
     * @dev Emitted when tokens are burned
     * @param sender Supplies Ammalgam Liquidity token into the pair contract and receives the minted assets in exchange
     * @param to Address where burned tokens are sent
     * @param assets The amount of token assets being burned
     * @param shares The amount of token shares being burned
     */
    event Burn(address indexed sender, address indexed to, uint256 assets, uint256 shares);

    /**
     * @dev Emitted on a borrow of tokens
     * @param sender The address initiating the borrowing action
     * @param to The address receiving the borrowed tokens
     * @param assets The amount of the borrowed token assets
     * @param shares The amount of token shares being borrowed
     */
    event Borrow(address indexed sender, address indexed to, uint256 assets, uint256 shares);

    /**
     * @dev Emitted on a repayment of tokens
     * @param sender The address initiating the repayment action
     * @param onBehalfOf The address of the account on whose behalf tokens are repaid
     * @param assets The address of the repaid token
     * @param shares The amount of tokens being repaid
     */
    event Repay(address indexed sender, address indexed onBehalfOf, uint256 assets, uint256 shares);

    /**
     * @dev Emitted on a liquidity borrow
     * @param sender The address initiating the borrowing action
     * @param to Address where the borrowed liquidity is sent
     * @param assets The amount of the borrowed liquidity token
     * @param shares The amount of token shares being borrowed
     */
    event BorrowLiquidity(address indexed sender, address indexed to, uint256 assets, uint256 shares);

    /**
     * @dev Emitted on a liquidity repayment
     * @param sender Supplies borrowed liquidity into the pair contract and the corresponding Ammalgam Debt tokens will be destroyed
     * @param onBehalfOf Address for whom the repayment is made
     * @param assets The amount of liquidity assets being repaid
     * @param shares The amount of liquidity shares being repaid
     */
    event RepayLiquidity(address indexed sender, address indexed onBehalfOf, uint256 assets, uint256 shares);

    /**
     * @notice Creates `amount` tokens and assigns them to `to` address, increasing the total supply.
     * @dev Emits a IERC20.Transfer event with `from` set to the zero address.
     * @param to The account to deliver the tokens to.
     * @param assets The quantity of assets represented by the shares.
     * @param shares The amount of shares to mint.
     */
    function ownerMint(address sender, address to, uint256 assets, uint256 shares) external;

    /**
     * @notice Destroys `amount` tokens from `from` address, reducing the total supply.
     * @dev Emits a IERC20.Transfer event with `to` set to the zero address.
     * @param receiver For debt tokens, this is the account whose debt is being reduced. For deposit tokens,
     *      this is the account receiving the underlying assets.
     * @param assets The quantity of assets represented by the shares.
     * @param shares The amount of shares to be burned.
     */
    function ownerBurn(address sender, address receiver, uint256 assets, uint256 shares) external;

    /**
     * @notice Transfers `amount` tokens from the `from` address to the `to` address.
     * @param from The account to deduct the tokens from.
     * @param to The account to deliver the tokens to.
     * @param amount The amount of tokens to be transferred.
     */
    function ownerTransfer(address from, address to, uint256 amount) external;
}

lib/core-v1/contracts/interfaces/tokens/ITokenController.sol

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

import {IERC20} from '@openzeppelin/contracts/interfaces/IERC20.sol';

import {IAmmalgamERC20} from 'contracts/interfaces/tokens/IAmmalgamERC20.sol';
import {ISaturationAndGeometricTWAPState} from 'contracts/interfaces/ISaturationAndGeometricTWAPState.sol';

uint256 constant DEPOSIT_L = 0;
uint256 constant DEPOSIT_X = 1;
uint256 constant DEPOSIT_Y = 2;
uint256 constant BORROW_L = 3;
uint256 constant BORROW_X = 4;
uint256 constant BORROW_Y = 5;
uint256 constant FIRST_DEBT_TOKEN = 3;
uint256 constant TOKEN_COUNT = 6;

bool constant ROUNDING_UP = true;

/**
 * @title ITokenController Interface
 * @notice The interface of a ERC20 facade for multiple token types with functionality similar to ERC1155.
 * @dev The TokenController provides support to the AmmalgamPair contract for token management.
 */
interface ITokenController {
    /**
     * @notice Reverts when fragile liquidity exceeds active liquidity available for risk checks.
     */
    error FragileLiquidityExceedsActiveLiquidity();

    /**
     * @dev Emitted when reserves are synchronized
     * @param reserveXAssets The updated reserve for token X
     * @param reserveYAssets The updated reserve for token Y
     */
    event Sync(uint256 reserveXAssets, uint256 reserveYAssets);

    /**
     * @dev Emitted when external liquidity is updated
     * @param externalLiquidity The updated value for external liquidity
     */
    event UpdateExternalLiquidity(uint112 externalLiquidity);

    /**
     * @dev Emitted when bad debt is burned
     * @param borrower The address of the borrower
     * @param tokenType The type of token being burned
     * @param badDebtAssets The amount of bad debt assets being burned
     * @param badDebtShares The amount of bad debt shares being burned
     */
    event BurnBadDebt(
        address indexed borrower, uint256 indexed tokenType, uint256 badDebtAssets, uint256 badDebtShares
    );

    /**
     * @dev Emitted when Interest gets accrued
     * @param reserveXAssets The amount reserve X assets in the pool after interest accrual
     * @param reserveYAssets The amount reserve Y assets in the pool after interest accrual
     * @param depositXAssets The amount of total `DEPOSIT_X` assets in the pool after interest accrual
     * @param depositYAssets The amount of total `DEPOSIT_Y` assets in the pool after interest accrual
     * @param borrowLAssets The amount of total `BORROW_L` assets in the pool after interest accrual
     * @param borrowXAssets The amount of total `BORROW_X` assets in the pool after interest accrual
     * @param borrowYAssets The amount of total `BORROW_Y` assets in the pool after interest accrual
     */
    event InterestAccrued(
        uint256 reserveXAssets,
        uint256 reserveYAssets,
        uint112 depositXAssets,
        uint112 depositYAssets,
        uint112 borrowLAssets,
        uint112 borrowXAssets,
        uint112 borrowYAssets
    );

    /**
     * @notice Get the underlying tokens for the AmmalgamERC20Controller.
     * @return The addresses of the underlying tokens.
     */
    function underlyingTokens() external view returns (IERC20, IERC20);

    /**
     * @notice Fetches the current reserves and the last update timestamp.
     * @return reserveXAssets The raw reserveX or reserveX plus unaccrued interest.
     * @return reserveYAssets The raw reserveY or reserveY plus unaccrued interest.
     * @return lastTimestamp The timestamp of the last operation.
     */
    function getReserves()
        external
        view
        returns (uint112 reserveXAssets, uint112 reserveYAssets, uint32 lastTimestamp);

    function externalLiquidity() external view returns (uint112);

    function fragileLiquidityShares() external view returns (uint112);

    /**
     * @notice Updates the external liquidity value.
     * @dev This function sets the external liquidity to a new value and emits an event with the new value. It can only be called by the fee setter.
     * @param _externalLiquidity The new external liquidity value.
     */
    function updateExternalLiquidity(
        uint112 _externalLiquidity
    ) external;

    /**
     * @notice Returns the reference reserves for the block, these represent a snapshot of the
     *   reserves at the start of the block weighted for mints, burns, borrow and repayment of
     *   liquidity. These amounts are critical to calculating the correct fees for any swap.
     * @return referenceReserveX The reference reserve for asset X.
     * @return referenceReserveY The reference reserve for asset Y.
     */
    function referenceReserves() external view returns (uint112 referenceReserveX, uint112 referenceReserveY);

    /**
     * @notice Return the IAmmalgamERC20 token corresponding to the token type
     * @param tokenType The type of token for which the scaler is being computed.
     *                  Can be one of BORROW_X, DEPOSIT_X, BORROW_Y, DEPOSIT_Y, BORROW_L, or DEPOSIT_L.
     * @return The IAmmalgamERC20 token
     */
    function tokens(
        uint256 tokenType
    ) external view returns (IAmmalgamERC20);

    /**
     *  @notice Computes current total assets and shares.
     *
     * @dev Behavior depends on the `withInterest` flag:
     *       1. If `withInterest` is `false`: Returns stored values (`allAssets`, `allShares`) without adjustments.
     *      2. If `withInterest` is `true`:
     *         - First calls `computeAssetsState()` to recalculate assets and shares (accounts for elapsed time, interest, and lending state).
     *         - Converts protocol fees to shares for DEPOSIT_L/X/Y and adds them to `_allShares`.
     *         - Adds protocol fees to DEPOSIT_L/X/Y in `_allAssets` (updated after shares to avoid double-counting).
     *      3. If `computeAssetsState()` detects no elapsed lending time, it returns stored values without recalculation.
     *
     * @param withInterest Toggle to enable/disable interest accrual, reserve adjustments, and protocol fee application.
     *
     * @return _allAssets Array of six `uint128` values: Total assets for each of the 6 Amalgam token types.
     *         If `withInterest` is `true`, includes protocol fees for DEPOSIT_L/X/Y.
     * @return _allShares Array of six `uint112` values: Total shares for each of the 6 Amalgam token types.
     *         If `withInterest` is `true`, includes shares converted from protocol fees for DEPOSIT_L/X/Y.
     */
    function totalAssetsAndShares(
        bool withInterest
    ) external view returns (uint112[6] memory _allAssets, uint112[6] memory _allShares);
}

lib/core-v1/contracts/libraries/Convert.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';

import {Q56, Q72, MAG2, BUFFER, BUFFER_NUMERATOR} from 'contracts/libraries/constants.sol';
import {ROUNDING_UP} from 'contracts/interfaces/tokens/ITokenController.sol';

library Convert {
    function toLiquidityAssets(
        uint256 liquidityShares,
        uint256 reservesAssets,
        uint256 activeLiquidityAssets,
        uint256 depositLiquidityAssets,
        uint256 depositLiquidityShares
    ) internal pure returns (uint256) {
        // This calculation is derived from the original formula:
        // amountAssets = amountShares * (depositLiquidityAssets / depositLiquidityShares) * reservesAssets / activeLiquidityAssets.
        return Convert.mulDiv(
            Convert.mulDiv(liquidityShares, reservesAssets, activeLiquidityAssets, false),
            depositLiquidityAssets,
            depositLiquidityShares,
            false
        );
    }

    function toAssets(
        uint256 shares,
        uint256 totalAssets,
        uint256 totalShares,
        bool roundingUp
    ) internal pure returns (uint256 _assets) {
        if (totalShares == 0) {
            return shares; // If no shares, assets are equal to shares.
        }
        return mulDiv(shares, totalAssets, totalShares, roundingUp);
    }

    function toShares(
        uint256 assets,
        uint256 totalAssets,
        uint256 totalShares,
        bool roundingUp
    ) internal pure returns (uint256 _shares) {
        if (totalAssets == 0) {
            return assets; // If no assets, shares are equal to assets.
        }
        return mulDiv(assets, totalShares, totalAssets, roundingUp);
    }

    function mulDiv(uint256 x, uint256 y, uint256 z, bool roundingUp) internal pure returns (uint256 result) {
        result = x * y;
        result = roundingUp ? Math.ceilDiv(result, z) : result / z;
    }

    /**
     * @notice helper method to calculate balance adjustment for missing assets
     * @dev In the depleted case the adjusted reserve is `(reserve - missing) * bufferNumerator`,
     *      matching the `BUFFER_NUMERATOR` scaling applied by `calculateBalanceAfterFees` so the
     *      K comparison stays division-free.
     *      For updateObservation, different scaled `buffer` and `bufferNumerator` values
     *      are supplied so the adjusted reserve reflects observation-specific logic.
     * @param reserve the starting reserve
     * @param missing the missing assets, zero if deposits > borrows of X or Y
     * @param buffer  Scaling factor applied to the reserve for the depletion comparison.
     * @param bufferNumerator  Scaling factor applied to the missing amount for the comparison
     *                         and for computing the depleted-case adjusted reserve.
     * @return reserveAdjustment The adjusted reserve value used for swap or updateObservation
     *                           depends on the buffer, bufferNumerator to be passed in.
     */
    function calculateReserveAdjustmentsForMissingAssets(
        uint256 reserve,
        uint256 missing,
        uint256 buffer,
        uint256 bufferNumerator
    ) internal pure returns (uint256 reserveAdjustment) {
        reserveAdjustment = reserve * buffer < missing * bufferNumerator
            ? (reserve - missing) * bufferNumerator // depleted case
            : reserve; // not depleted case
    }

    /**
     * @notice Depletion-adjusted active liquidity, `sqrt` of the adjusted-reserve product using the
     *  swap K-check buffer. Shared by interest accrual and `TokenController.calculateActiveLiquidityAssets`
     *  so every active-liquidity reader uses one basis.
     * @param reserveXAssets reserve X used for the active-liquidity calculation.
     * @param reserveYAssets reserve Y used for the active-liquidity calculation.
     * @param missingXAssets missing X assets, zero if deposits > borrows of X.
     * @param missingYAssets missing Y assets, zero if deposits > borrows of Y.
     * @return The depletion-adjusted active liquidity.
     */
    function depletionAdjustedActiveLiquidity(
        uint256 reserveXAssets,
        uint256 reserveYAssets,
        uint256 missingXAssets,
        uint256 missingYAssets
    ) internal pure returns (uint256) {
        return Math.sqrt(
            calculateReserveAdjustmentsForMissingAssets(reserveXAssets, missingXAssets, BUFFER, BUFFER_NUMERATOR)
                * calculateReserveAdjustmentsForMissingAssets(reserveYAssets, missingYAssets, BUFFER, BUFFER_NUMERATOR)
        );
    }
}

lib/core-v1/contracts/libraries/GeometricTWAP.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';

import {Convert} from 'contracts/libraries/Convert.sol';
import {TickMath} from 'contracts/libraries/TickMath.sol';
import {DEFAULT_TICK_DELTA_FACTOR, MAX_TICK_DELTA, Q32} from 'contracts/libraries/constants.sol';

/**
 * @title GeometricTWAP: Library for Geometric TWAP calculation and observations.
 */
library GeometricTWAP {
    uint256 internal constant MID_TERM_ARRAY_LENGTH = 51;
    uint256 internal constant LONG_TERM_ARRAY_LENGTH = 9;
    uint256 internal constant LOG_BASE_OF_ROOT_TWO = 178;
    uint256 internal constant MID_TERM_ARRAY_LAST_INDEX = MID_TERM_ARRAY_LENGTH - 1;
    uint256 internal constant LONG_TERM_ARRAY_LAST_INDEX = LONG_TERM_ARRAY_LENGTH - 1;
    /**
     * @notice Minimum long-term interval factor is used to verify the long-term interval
     *      is at least 14 times the mid-term interval. This ensures that the long term
     *      interval is required to be at least 14 times the mid-term interval, this is
     *      ```math
     *      \left \lceil \frac{2 * MID\_TERM\_ARRAY\_LAST\_INDEX}{LONG\_TERM\_ARRAY\_LAST\_INDEX} \right \rceil.
     *      ```
     */
    uint256 internal constant MINIMUM_LONG_TERM_INTERVAL_FACTOR = 14;

    /**
     * @notice Struct for storing observations related to the Geometric TWAP calculation.
     * @dev This struct holds various data points used in the Time-Weighted Average Price (TWAP)
     *      calculation.
     * @member midTermIndex: The index representing the total duration observed for the
     *      short-term period. Its initial value is 0.
     * @member longTermIndex: The index representing the total duration observed for the
     *      long-term period. Its initial value is 0.
     * @member lastTick: The latest recorded tick, bounded to avoid outliers.
     * @member midTermIntervalConfig: The configurable interval for each period of the mid-term buffer.
     * @member longTermIntervalConfig: The time required to pass before the long term twap is updated.
     * @member lendingCumulativeSum: The cumulative sum of mid-term values for lending state.
     * @member midTermTimeInterval: An array tracking timestamp at which each mid-term observation is recorded.
     * @member longTermTimeInterval: An array tracking timestamp at which each long-term observation is recorded.
     * @member midTerm: An array of mid-term observations. Each element stores cumulative tick value.
     *      The array size is 51 for it observes 50 price changes for last 10 minutes (12 * 50 = 600 seconds).
     * @member longTerm: An array of long-term observations. Each element stores cumulative tick
     *      value of a buffer. The buffer size is configured by `longTermIntervalConfig`. The term is
     *      observed every `longTermIntervalConfig` duration.
     */
    struct Observations {
        bool isMidTermBufferInitialized;
        bool isLongTermBufferInitialized;
        uint8 midTermIndex;
        uint8 longTermIndex;
        int16 lastTick;
        uint24 midTermIntervalConfig;
        uint24 longTermIntervalConfig;
        int56 lendingCumulativeSum;
        int56[MID_TERM_ARRAY_LENGTH] midTermCumulativeSum;
        int56[LONG_TERM_ARRAY_LENGTH] longTermCumulativeSum;
        uint32[MID_TERM_ARRAY_LENGTH] midTermTimeInterval;
        uint32[LONG_TERM_ARRAY_LENGTH] longTermTimeInterval;
    }

    error InvalidIntervalConfig();

    /**
     * @notice Initializes the observation struct with the specified interval configurations.
     * @dev This function sets the initial values for the mid-term and long-term interval configurations.
     *
     *      This forces the time to to go through the long term is twice as long as it takes to go
     *      through the mid-term interval.
     * @param self The storage reference to the Observations struct.
     * @param midTermTimePerUpdate The time required to pass before the mid-term twap is updated.
     * @param longTermTimePerUpdate The time required to pass before the long-term twap is updated.
     */
    function initializeObservationStruct(
        Observations storage self,
        uint24 midTermTimePerUpdate,
        uint24 longTermTimePerUpdate
    ) internal {
        if (
            midTermTimePerUpdate == 0
                || longTermTimePerUpdate < MINIMUM_LONG_TERM_INTERVAL_FACTOR * midTermTimePerUpdate
        ) {
            revert InvalidIntervalConfig();
        }
        self.midTermIntervalConfig = midTermTimePerUpdate;
        self.longTermIntervalConfig = longTermTimePerUpdate;
    }

    function addObservationAndSetLendingState(Observations storage self, int16 firstTick) internal {
        // Update the mid-term & long-term states with first tick value.
        setObservationData(self, firstTick, 0, 0, true);
    }

    /**
     * @notice Configures the interval of long-term observations.
     * @dev This function is used to set the long-term interval between observations for the long-term buffer.
     * @param self The storage reference to the Observations struct.
     * @param longTermTimePerUpdate the time required to pass before the long term twap is update.
     */
    function configLongTermInterval(Observations storage self, uint24 longTermTimePerUpdate) internal {
        uint256 midTermIntervalConfig = self.midTermIntervalConfig;
        if (
            longTermTimePerUpdate < MINIMUM_LONG_TERM_INTERVAL_FACTOR * midTermIntervalConfig
                || midTermIntervalConfig == 0 // make sure the library is initialized
        ) {
            revert InvalidIntervalConfig();
        }
        self.longTermIntervalConfig = longTermTimePerUpdate;
    }

    /**
     * @notice Records a new observation tick value and updates the observation data.
     * @dev This function is used to record new observation data for the contract. It ensures that
     *      the provided tick value is stored appropriately in both mid-term and long-term
     *      observations, updates interval counters, and handles tick cumulative values based
     *      on the current interval configuration. Ensures that this function is called in
     *      chronological order, with increasing timestamps. Returns in case the
     *      provided block timestamp is less than or equal to the last recorded timestamp.
     * @param self The storage structure containing observation data.
     * @param newTick The new tick value to be recorded, representing the most recent update of
     *      reserveXAssets and reserveYAssets.
     * @param timeElapsed The time elapsed since the last observation.
     * @return updated A boolean indicating whether the observation was updated.
     */
    function recordObservation(
        Observations storage self,
        int16 newTick,
        uint32 timeElapsed
    ) internal returns (bool updated) {
        // Record observation only if the time elapsed is greater than the configured mid-term interval.
        if (timeElapsed >= self.midTermIntervalConfig) {
            uint256 currentMidTermIndex = self.midTermIndex;

            newTick = boundTick(self, newTick);

            // Update state for mid-term range observations.
            int56 currentCumulativeTick = getMidTermAtLastIndex(self, currentMidTermIndex);
            unchecked {
                currentCumulativeTick += int56(newTick) * int56(uint56(timeElapsed));
            }

            setObservationData(self, newTick, currentCumulativeTick, currentMidTermIndex, false);
            updated = true;
        }
    }

    /**
     * @notice Gets the min and max range of tick values from the stored oracle observations.
     * @dev This function calculates the minimum and maximum tick values among three observed ticks:
     *          long-term tick, mid-term tick, and current tick.
     * @param self The observation struct where stored oracle array containing the tick observations.
     * @param currentTick The current (most recent) tick based on the current reserves.
     * @return minTick The minimum tick value among the three observed ticks.
     * @return maxTick The maximum tick value among the three observed ticks.
     */
    function getTickRange(Observations storage self, int16 currentTick) internal view returns (int16, int16) {
        bool isLongTermBufferInitialized = self.isLongTermBufferInitialized;
        (int16 longTermTick, int16 midTermTick, int16 blockTick) = getObservedTicks(self, isLongTermBufferInitialized);
        uint256 factor = getLongTermBufferFactor(self, isLongTermBufferInitialized);
        return getTickRangeInternal(longTermTick, midTermTick, blockTick, currentTick, factor);
    }

    /**
     * @notice Gets the min and max range of tick values from the stored oracle observations.
     * @dev This function calculates the minimum and maximum tick values among the mid-term tick and current tick.
     * @param self The observation struct where stored oracle array containing the tick observations.
     * @return minTick The minimum tick value.
     * @return maxTick The maximum tick value.
     */
    function getTickRangeWithoutLongTerm(
        Observations storage self
    ) internal view returns (int16 minTick, int16 maxTick) {
        int16 midTermTick = getObservedMidTermTick(self);
        int16 blockTick = self.lastTick;

        // we do not include the current tick to avoid manipulation to increase liquidation payout.
        (minTick, maxTick) = getMinAndMaxOfThree(midTermTick, blockTick, blockTick);
        maxTick += 1;
    }

    /**
     * @dev Retrieves the long-term, mid-term, and current tick values based on the stored observations.
     * @dev visibility is only `internal` for testing purposes
     * @param self The observation struct.
     * @param isLongTermBufferInitialized Boolean value which represents whether long-term buffer is filled or not.
     * @return The long-term, mid-term, and last tick values.
     */
    function getObservedTicks(
        Observations storage self,
        bool isLongTermBufferInitialized
    ) internal view returns (int16, int16, int16) {
        return (getObservedLongTermTick(self, isLongTermBufferInitialized), getObservedMidTermTick(self), self.lastTick);
    }

    /**
     * @dev Retrieves the mid-term tick value based on the stored observations.
     * @param self The observation struct.
     * @return midTermTick The mid-term tick value.
     */
    function getObservedMidTermTick(
        Observations storage self
    ) internal view returns (int16 midTermTick) {
        uint256 currentMidTermIndex = self.midTermIndex; // gas savings
        uint256 lastMidTermInterval = getLastIndex(currentMidTermIndex, MID_TERM_ARRAY_LAST_INDEX);
        bool isMidTermBufferInitialized = self.isMidTermBufferInitialized;

        if (!isMidTermBufferInitialized && lastMidTermInterval == 0) {
            midTermTick = self.lastTick;
        } else {
            unchecked {
                // Timestamp can overflow after 136 years, this is safe as long as
                // there is an update every 2.67 years on average for a cycle through
                // the mid-term array.
                midTermTick = calculateTickAverage(
                    self.midTermCumulativeSum[lastMidTermInterval],
                    (isMidTermBufferInitialized ? self.midTermCumulativeSum[currentMidTermIndex] : int56(0)),
                    uint256(
                        self.midTermTimeInterval[lastMidTermInterval]
                            - (
                                isMidTermBufferInitialized
                                    ? self.midTermTimeInterval[currentMidTermIndex]
                                    : self.midTermTimeInterval[0]
                            )
                    )
                );
            }
        }
    }

    /**
     * @dev Retrieves the long-term tick value based on the stored observations.
     * @param self The observation struct.
     * @param isLongTermBufferInitialized Boolean value which represents whether long-term buffer is filled or not.
     * @return longTermTick The long-term tick value.
     */
    function getObservedLongTermTick(
        Observations storage self,
        bool isLongTermBufferInitialized
    ) private view returns (int16 longTermTick) {
        uint256 currentLongTermIndex = self.longTermIndex;
        uint256 lastLongTermInterval = getLastIndex(currentLongTermIndex, LONG_TERM_ARRAY_LAST_INDEX);

        if (!isLongTermBufferInitialized && lastLongTermInterval == 0) {
            longTermTick = self.lastTick;
        } else {
            unchecked {
                // we allow the timestamp to overflow every 136 years.
                longTermTick = calculateTickAverage(
                    self.longTermCumulativeSum[lastLongTermInterval],
                    isLongTermBufferInitialized ? self.longTermCumulativeSum[currentLongTermIndex] : int56(0),
                    uint256(
                        self.longTermTimeInterval[lastLongTermInterval]
                            - (
                                isLongTermBufferInitialized
                                    ? self.longTermTimeInterval[currentLongTermIndex]
                                    : self.longTermTimeInterval[0]
                            )
                    )
                );
            }
        }
    }

    // visibility is only `internal` for testing purposes
    function getTickRangeInternal(
        int16 longTermTick,
        int16 midTermTick,
        int16 blockTick,
        int16 currentTick,
        uint256 factor
    ) internal pure returns (int16 minTick, int16 maxTick) {
        (minTick, maxTick) = getMinAndMaxOfFour(longTermTick, midTermTick, blockTick, currentTick);

        // `minTick` & `maxTick` bound check to be within the range of `MIN_TICK` and `MAX_TICK`.
        unchecked {
            // 0 <= delta <= MAX_TICK-MIN_TICK
            uint256 delta = uint256(int256(maxTick) - minTick);

            int256 buffer = int256(
                delta
                    + Convert.mulDiv(
                        LOG_BASE_OF_ROOT_TWO, LONG_TERM_ARRAY_LAST_INDEX - factor, LONG_TERM_ARRAY_LAST_INDEX, false
                    )
            );

            // `minTick` & `maxTick` bound check to be within the range of `MIN_TICK` and `MAX_TICK`.
            // safe from under flow
            minTick =
                int256(blockTick) - buffer > int256(TickMath.MIN_TICK) ? int16(blockTick - buffer) : TickMath.MIN_TICK;
            maxTick = int256(blockTick) + buffer + 1 < int256(TickMath.MAX_TICK)
                ? int16(blockTick + buffer + 1)
                : TickMath.MAX_TICK;
        }
    }

    function getMinAndMaxOfFour(int16 a, int16 b, int16 c, int16 d) private pure returns (int16 min, int16 max) {
        (min, max) = getMinAndMaxOfThree(b, c, d);
        (min, max) = getMinAndMaxOfThree(a, min, max);
    }

    function getMinAndMaxOfThree(int16 a, int16 b, int16 c) private pure returns (int16 min, int16 max) {
        (min, max) = c < b ? (c, b) : (b, c);
        if (a < min) {
            min = a;
        } else if (max < a) {
            max = a;
        }
    }

    function getMidTermAtLastIndex(Observations storage self, uint256 index) private view returns (int56) {
        return self.midTermCumulativeSum[getLastIndex(index, MID_TERM_ARRAY_LAST_INDEX)];
    }

    function getLastIndex(uint256 index, uint256 lastIndex) private pure returns (uint256) {
        unchecked {
            return index == 0 ? lastIndex : index - 1;
        }
    }

    function getNextIndex(uint256 currentIndex, uint256 indexLength) private pure returns (uint8) {
        unchecked {
            return uint8((currentIndex + 1) % indexLength);
        }
    }

    /**
     * @notice Gets the tick value representing the TWAP since the last
     *         lending update and checkpoints the current lending cumulative sum
     *         as `self.lendingCumulativeSum` and the current block timestamp as `self.lastLendingTimestamp`.
     * @dev See `getLendingStateTick` for implementation details which was
     *      separated to allow view access without any state updates.
     * @param self Observations storage struct
     * @param timeElapsedSinceUpdate The time elapsed since the last price update.
     * @param timeElapsedSinceLendingUpdate The time elapsed since the last lending update.
     * @return lendingStateTick The tick value representing the TWAP since the last lending update.
     */
    function getLendingStateTickAndCheckpoint(
        Observations storage self,
        uint32 timeElapsedSinceUpdate,
        uint32 timeElapsedSinceLendingUpdate
    ) internal returns (int16) {
        (int16 lendingStateTick, int56 currentCumulativeSum) =
            getLendingStateTick(self, 0, timeElapsedSinceUpdate, timeElapsedSinceLendingUpdate, false);

        self.lendingCumulativeSum = currentCumulativeSum;
        return lendingStateTick;
    }

    /**
     * @notice Gets the tick value representing the TWAP since the last lending update.
     * @param self Observations storage struct
     * @param newTick The current tick value.
     * @param timeElapsedSinceUpdate The time elapsed since the last price update.
     * @param timeElapsedSinceLendingUpdate The time elapsed since the last lending update.
     * @return lendingStateTick The tick value representing the TWAP since the last lending update.
     * @return currentCumulativeSum The current cumulative sum for the last updated timestamp.
     */
    function getLendingStateTick(
        Observations storage self,
        int56 newTick,
        uint32 timeElapsedSinceUpdate,
        uint32 timeElapsedSinceLendingUpdate,
        bool tickAvailable
    ) internal view returns (int16, int56) {
        uint24 midTermIntervalConfig = self.midTermIntervalConfig; // gas savings
        int56 currentCumulativeSum = getMidTermAtLastIndex(self, self.midTermIndex);

        if (tickAvailable && timeElapsedSinceUpdate >= midTermIntervalConfig) {
            unchecked {
                // add currentTimeStamp * tick to cumulativeSum
                currentCumulativeSum += int56(boundTick(self, int16(newTick))) * int56(uint56(timeElapsedSinceUpdate));
            }
        }

        return (
            (timeElapsedSinceLendingUpdate < midTermIntervalConfig)
                ? self.lastTick
                : calculateTickAverage(currentCumulativeSum, self.lendingCumulativeSum, timeElapsedSinceLendingUpdate),
            currentCumulativeSum
        );
    }

    /**
     * @notice Updates the observation data with the new tick value and current timestamp.
     * @dev This function updates both mid-term and long-term observation states based on the provided
     *      new tick value and the current timestamp. It also updates the last recorded observation state.
     * @param self The storage reference to the Observations struct.
     * @param newTick The new tick value to be recorded.
     * @param currentCumulativeTick The current cumulative tick sum.
     */
    function setObservationData(
        Observations storage self,
        int16 newTick,
        int56 currentCumulativeTick,
        uint256 currentMidTermIndex,
        bool firstUpdate
    ) private {
        uint32 currentTimestamp = getCurrentTimestamp();
        // Update the mid-term interval state.
        self.midTermCumulativeSum[currentMidTermIndex] = currentCumulativeTick;
        self.midTermTimeInterval[currentMidTermIndex] = currentTimestamp;

        // set storage and memory to save gas.
        uint256 nextIndex = self.midTermIndex = getNextIndex(currentMidTermIndex, MID_TERM_ARRAY_LENGTH);

        if (!self.isMidTermBufferInitialized && nextIndex == 0) {
            self.isMidTermBufferInitialized = true;
        }

        {
            // Check if long-term interval should be updated.
            uint24 currentLongTermConfig = self.longTermIntervalConfig;

            uint32 duration;
            unchecked {
                duration = currentTimestamp
                    - self.longTermTimeInterval[getLastIndex(self.longTermIndex, LONG_TERM_ARRAY_LAST_INDEX)];
            }
            if (duration >= currentLongTermConfig || firstUpdate) {
                uint256 currentLongTermIndex = self.longTermIndex;

                // Update the long-term interval state.
                self.longTermCumulativeSum[currentLongTermIndex] = currentCumulativeTick;
                self.longTermTimeInterval[currentLongTermIndex] = currentTimestamp;
                // set to storage and memory to save gas.
                nextIndex = self.longTermIndex = getNextIndex(currentLongTermIndex, LONG_TERM_ARRAY_LENGTH);

                if (!self.isLongTermBufferInitialized && nextIndex == 0) {
                    self.isLongTermBufferInitialized = true;
                }
            }
        }

        // update last recorded observation state.
        self.lastTick = newTick;
    }

    /**
     * @notice Computes the tick average based on the cumulative sum and duration.
     * @param currentCumulativeSum The current cumulative sum of mid-term/long-term values.
     * @param previousCumulativeSum The previous cumulative sum recorded for mid-term/long-term.
     * @param bufferLength If the mid-term/long-term buffer is fully recorded, then the buffer length
     *         equals the duration passed between the first and last recorded ticks, else it's same as
     *         the mid-term/long-term buffer.
     * @return tick The computed tick average for mid-term/long-term.
     */
    function calculateTickAverage(
        int56 currentCumulativeSum,
        int56 previousCumulativeSum,
        uint256 bufferLength
    ) private pure returns (int16 tick) {
        unchecked {
            // under flows desired
            tick = int16((currentCumulativeSum - previousCumulativeSum) / int256(bufferLength));
        }
    }

    /**
     * @dev Gets the long-term buffer factor based on the available data in long-term array.
     * @param self The observation struct where stored oracle array containing the tick observations.
     * @param isLongTermBufferInitialized Boolean value which represents whether long-term buffer is filled or not.
     * @return factor The amount of information we have in the long-term array.
     */
    function getLongTermBufferFactor(
        Observations storage self,
        bool isLongTermBufferInitialized
    ) private view returns (uint256 factor) {
        /**
         * Factor, `F` is the amount of information we have in the long-term array.
         * It's represented by the last filled index count in the long-term array.
         */
        factor = LONG_TERM_ARRAY_LAST_INDEX;
        if (!isLongTermBufferInitialized) {
            factor = self.longTermIndex - 1;
        }
    }

    /**
     * @notice Adjusts the new tick value to ensure it stays within valid bounds. When we have less data, the outlier
     *         factor is greater to allow for more flexibility to find the true price.
     * @dev The function ensures that `newTick` stays within the bounds
     *      determined by `lastTick` and a dynamically calculated factor.
     * @param self The storage reference to `Observations`, which holds historical tick data.
     * @param newTick The proposed new tick value to be adjusted within valid bounds.
     * @return The adjusted tick value constrained within the allowable range.
     */
    function boundTick(Observations storage self, int16 newTick) internal view returns (int16) {
        int256 outlierFactor = DEFAULT_TICK_DELTA_FACTOR;

        bool isLongTermBufferInitialized = self.isLongTermBufferInitialized;

        if (!isLongTermBufferInitialized) {
            outlierFactor =
                int256(LONG_TERM_ARRAY_LAST_INDEX - getLongTermBufferFactor(self, isLongTermBufferInitialized));
        }
        int16 lastTick = self.lastTick;
        unchecked {
            int256 maxTickDelta = outlierFactor * MAX_TICK_DELTA;
            int256 minTickBound = lastTick - maxTickDelta;
            int256 maxTickBound = lastTick + maxTickDelta;

            if (newTick > maxTickBound) {
                newTick = int16(maxTickBound);
            } else if (newTick < minTickBound) {
                newTick = int16(minTickBound);
            }
        }

        return newTick;
    }

    /**
     * @dev Returns the current block timestamp casted to uint32.
     * @return The current block timestamp as a uint32 value.
     */
    function getCurrentTimestamp() internal view returns (uint32) {
        unchecked {
            // slither-disable-next-line weak-prng
            return uint32(block.timestamp % Q32);
        }
    }

    /**
     * @dev Average the mid-term tick and the new tick, rounding towards the `midTermTick`.
     * @param midTermTick The midterm tick value
     * @param newTick The new tick value
     * @return The calculated average tick value
     */
    function calculateTickAverageTowardsMidTerm(int256 midTermTick, int256 newTick) internal pure returns (int16) {
        int256 sum = midTermTick + newTick;

        // If sum is even, the average is an integer
        // If sum is odd, the average is a half-integer, so round towards `midTermTick`
        return int16(sum % 2 == 0 ? sum / 2 : midTermTick > newTick ? (sum + 1) / 2 : (sum - 1) / 2);
    }
}

lib/core-v1/contracts/libraries/Interest.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {MathLib, WAD} from '@morpho-org/morpho-blue/src/libraries/MathLib.sol';

import {TickMath} from 'contracts/libraries/TickMath.sol';

import {
    ITokenController,
    DEPOSIT_L,
    DEPOSIT_X,
    DEPOSIT_Y,
    BORROW_L,
    BORROW_X,
    BORROW_Y,
    FIRST_DEBT_TOKEN,
    TOKEN_COUNT,
    ROUNDING_UP
} from 'contracts/interfaces/tokens/ITokenController.sol';
import {
    B_IN_Q72,
    Q72,
    Q128,
    LIQUIDITY_INTEREST_RATE_MAGNIFICATION,
    MAX_SATURATION_PERCENT_IN_WAD,
    MAX_UTILIZATION_PERCENT_IN_WAD,
    SECONDS_IN_YEAR
} from 'contracts/libraries/constants.sol';
import {Convert} from 'contracts/libraries/Convert.sol';

/**
 * @title Interest Library
 * @notice This library is used for calculating and accruing interest.
 * @dev many calculations are unchecked because we asset values are stored as uint112. We also limit
 *      the max amount amount of interest to ensure that it can not overflow when added to the
 *      current assets.
 *
 */
library Interest {
    using MathLib for uint256;
    using MathLib for uint112;

    struct AccrueInterestParams {
        uint256 duration;
        int16 lendingStateTick;
        uint112[6] shares;
        uint256 satPercentageInWads;
        uint256 reserveXAssets;
        uint256 reserveYAssets;
    }

    uint256 internal constant OPTIMAL_UTILIZATION = 0.8e18; //  80%
    uint256 internal constant DANGER_UTILIZATION = 0.925e18; // 92.5%
    uint256 internal constant SLOPE1 = 0.1e18;
    uint256 internal constant SLOPE2 = 2e18;
    uint256 internal constant SLOPE3 = 20e18;
    uint256 internal constant BASE_OPTIMAL_UTILIZATION = 0.08e18; // 8%
    uint256 internal constant BASE_DANGER_UTILIZATION = 0.33e18; // 33%

    uint256 internal constant LENDING_FEE_RATE = 10;
    uint256 private constant MAX_UINT112 = type(uint112).max;
    uint256 private constant LAST_DEPOSIT = 2; // FIRST_DEBT_TOKEN - 1;

    uint256 private constant NO_RESERVES_FOR_L = 0;

    /**
     * @dev Maximum percentage for the penalty saturation allowed.
     * This is used to prevent excessive penalties in case of high utilization.
     */
    uint256 private constant PENALTY_SATURATION_PERCENT_IN_WAD = 0.85e18; // 85%

    /**
     * @dev `MAX_SATURATION_PERCENT_IN_WAD` - `PENALTY_SATURATION_PERCENT_IN_WAD`
     */
    uint256 private constant SATURATION_PENALTY_BUFFER_IN_WAD = 0.1e18;

    function accrueInterestAndUpdateReservesWithAssets(
        uint112[6] storage assets,
        AccrueInterestParams memory accrueInterestParams
    ) external returns (uint256 interestXForLP, uint256 interestYForLP, uint256[3] memory protocolFeeAssets) {
        if (accrueInterestParams.duration > 0) {
            uint112[6] memory newAssets;
            (newAssets, interestXForLP, interestYForLP, protocolFeeAssets) =
                accrueInterestWithAssets(assets, accrueInterestParams);
            for (uint256 i = DEPOSIT_X; i < TOKEN_COUNT; i++) {
                assets[i] = newAssets[i];
            }
            emit ITokenController.InterestAccrued(
                accrueInterestParams.reserveXAssets + interestXForLP,
                accrueInterestParams.reserveYAssets + interestYForLP,
                newAssets[DEPOSIT_X],
                newAssets[DEPOSIT_Y],
                newAssets[BORROW_L],
                newAssets[BORROW_X],
                newAssets[BORROW_Y]
            );
        }
    }

    /**
     * @notice we approximate the reserves based on an average tick value since the last lending
     *         state update.
     * @dev this will never return values greater than uint112 max when used correctly. The reserve
     *      values are underestimated due to a tick being an approximate price. We use a smaller
     *      value when multiplying and a larger when dividing to ensure that we do not overflow.
     * @param activeLiquidityAssets active L where $\sqrt{reserveX\cdot reserveY}=L$
     * @param lendingStateTick Average tick value since last lending state update.
     * @return reserveXAssets approximate average reserve since last lending state update.
     * @return reserveYAssets approximate average reserve since last lending state update.
     */
    function getReservesAtTick(
        uint256 activeLiquidityAssets,
        int16 lendingStateTick
    ) internal pure returns (uint256 reserveXAssets, uint256 reserveYAssets) {
        // calculate reserves at lending state tick
        uint256 sqrtPriceAtLendingStateTickMinInQ72 = TickMath.getSqrtPriceAtTick(lendingStateTick);
        uint256 sqrtPriceAtLendingStateTickMaxInQ72 =
            Convert.mulDiv(sqrtPriceAtLendingStateTickMinInQ72, B_IN_Q72, Q72, true);

        unchecked {
            // x = L * sqrt(p)
            reserveXAssets = Convert.mulDiv(activeLiquidityAssets, sqrtPriceAtLendingStateTickMinInQ72, Q72, false);

            // y = L / sqrt(p)
            reserveYAssets = Convert.mulDiv(activeLiquidityAssets, Q72, sqrtPriceAtLendingStateTickMaxInQ72, false);
        }

        return (Math.max(reserveXAssets, 1), Math.max(reserveYAssets, 1));
    }

    /**
     * @notice Reserve tokens borrowed out beyond the single-sided deposit, i.e. `max(borrow, deposit) - deposit`.
     * @param startingAssets Asset balances indexed by token type.
     * @return missingXAssets Reserve X borrowed beyond the X deposit.
     * @return missingYAssets Reserve Y borrowed beyond the Y deposit.
     */
    function missingAssetsInReserve(
        uint112[6] memory startingAssets
    ) private pure returns (uint256 missingXAssets, uint256 missingYAssets) {
        missingXAssets = Math.max(startingAssets[BORROW_X], startingAssets[DEPOSIT_X]) - startingAssets[DEPOSIT_X];
        missingYAssets = Math.max(startingAssets[BORROW_Y], startingAssets[DEPOSIT_Y]) - startingAssets[DEPOSIT_Y];
    }

    function getUtilizationsInWads(
        uint112[6] memory startingAssets,
        uint256 reservesXAssets,
        uint256 reservesYAssets,
        uint256 satPercentageInWads
    ) internal pure returns (uint256[3] memory utilizationInWads) {
        uint256 missingAssetsXInL;
        uint256 missingAssetsYInL;

        unchecked {
            // Calculate missing assets in a block scope to reduce stack depth
            {
                uint256 activeLiquidity = startingAssets[DEPOSIT_L] - startingAssets[BORROW_L];
                (uint256 missingXAssets, uint256 missingYAssets) = missingAssetsInReserve(startingAssets);

                // overflow not possible on multiplication, and underflow caught by conditions
                if (missingXAssets > 0) {
                    missingAssetsXInL = Math.ceilDiv(missingXAssets * activeLiquidity, reservesXAssets);
                }
                if (missingYAssets > 0) {
                    missingAssetsYInL = Math.ceilDiv(missingYAssets * activeLiquidity, reservesYAssets);
                }
            }

            // Calculate utilizations in separate block scope
            {
                utilizationInWads = [
                    mutateUtilizationForSaturation(
                        getUtilizationInWads(
                            startingAssets[BORROW_L] + Math.max(missingAssetsXInL, missingAssetsYInL),
                            startingAssets[DEPOSIT_L]
                        ),
                        satPercentageInWads
                    ),
                    getUtilizationInWads(startingAssets[BORROW_X], startingAssets[DEPOSIT_X] + reservesXAssets),
                    getUtilizationInWads(startingAssets[BORROW_Y], startingAssets[DEPOSIT_Y] + reservesYAssets)
                ];
            }
        }
    }

    function accrueInterestWithAssets(
        uint112[6] memory assets,
        AccrueInterestParams memory params
    )
        public
        pure
        returns (
            uint112[6] memory newAssets,
            uint256 interestXPortionForLP,
            uint256 interestYPortionForLP,
            uint256[3] memory protocolFeeAssets
        )
    {
        uint112[6] memory startingAssets = assets;
        uint256[3] memory interestAssetSet;
        {
            uint256 activeLiquidityAssets;
            {
                (uint256 missingXAssets, uint256 missingYAssets) = missingAssetsInReserve(startingAssets);
                activeLiquidityAssets = Convert.depletionAdjustedActiveLiquidity(
                    params.reserveXAssets, params.reserveYAssets, missingXAssets, missingYAssets
                );
            }

            startingAssets[DEPOSIT_L] = uint112(activeLiquidityAssets + startingAssets[BORROW_L]);

            (uint256 averageReservesX, uint256 averageReservesY) =
                getReservesAtTick(activeLiquidityAssets, params.lendingStateTick);

            {
                uint256[3] memory utilizationsInWads = getUtilizationsInWads(
                    startingAssets, averageReservesX, averageReservesY, params.satPercentageInWads
                );

                // for loop overhead not worth it for three loops.
                interestAssetSet = [
                    // Magnify interest on liquidity by 5x what x and y rates for the same utilization.
                    LIQUIDITY_INTEREST_RATE_MAGNIFICATION
                        * computeInterestAssets(
                            params.duration,
                            utilizationsInWads[DEPOSIT_L],
                            NO_RESERVES_FOR_L,
                            startingAssets[BORROW_L],
                            startingAssets[DEPOSIT_L]
                        ),
                    computeInterestAssets(
                        params.duration,
                        utilizationsInWads[DEPOSIT_X],
                        params.reserveXAssets,
                        startingAssets[BORROW_X],
                        startingAssets[DEPOSIT_X]
                    ),
                    computeInterestAssets(
                        params.duration,
                        utilizationsInWads[DEPOSIT_Y],
                        params.reserveYAssets,
                        startingAssets[BORROW_Y],
                        startingAssets[DEPOSIT_Y]
                    )
                ];
            }

            unchecked {
                protocolFeeAssets = [
                    Convert.mulDiv(interestAssetSet[DEPOSIT_L], LENDING_FEE_RATE, 100, ROUNDING_UP),
                    Convert.mulDiv(interestAssetSet[DEPOSIT_X], LENDING_FEE_RATE, 100, ROUNDING_UP),
                    Convert.mulDiv(interestAssetSet[DEPOSIT_Y], LENDING_FEE_RATE, 100, ROUNDING_UP)
                ];

                interestAssetSet = [
                    interestAssetSet[DEPOSIT_L] - protocolFeeAssets[DEPOSIT_L],
                    interestAssetSet[DEPOSIT_X] - protocolFeeAssets[DEPOSIT_X],
                    interestAssetSet[DEPOSIT_Y] - protocolFeeAssets[DEPOSIT_Y]
                ];

                interestXPortionForLP = Convert.mulDiv(
                    interestAssetSet[DEPOSIT_X], averageReservesX, startingAssets[DEPOSIT_X] + averageReservesX, false
                );
                interestYPortionForLP = Convert.mulDiv(
                    interestAssetSet[DEPOSIT_Y], averageReservesY, startingAssets[DEPOSIT_Y] + averageReservesY, false
                );
            }
        }

        // Skip DEPOSIT_L in the loop - it will be calculated after based on new reserves and BORROW_L
        for (uint256 i = DEPOSIT_X; i < TOKEN_COUNT; i++) {
            uint256 interestPortionForLP;
            uint256 protocolFees;
            uint256 shortArrayIndex = i % FIRST_DEBT_TOKEN;

            if (i == DEPOSIT_X) {
                interestPortionForLP = interestXPortionForLP;
            } else if (i == DEPOSIT_Y) {
                interestPortionForLP = interestYPortionForLP;
            } else if (i > LAST_DEPOSIT) {
                // add protocol fees to all borrows.
                protocolFees = protocolFeeAssets[shortArrayIndex];
            }
            newAssets[i] = addInterestToAssets(
                startingAssets[i],
                interestAssetSet[shortArrayIndex]
                // Back out lp interest being attributed to reserves
                - interestPortionForLP
                // add protocol fees to all borrows.
                + protocolFees
            );
        }

        // Calculate DEPOSIT_L last from the depletion adjusted active liquidity assets.
        // newReserves include LP interest portions that will be added to reserves.
        uint256 newReserveX = params.reserveXAssets + interestXPortionForLP;
        uint256 newReserveY = params.reserveYAssets + interestYPortionForLP;
        {
            uint256 depositXWithFees = uint256(newAssets[DEPOSIT_X]) + protocolFeeAssets[DEPOSIT_X];
            uint256 depositYWithFees = uint256(newAssets[DEPOSIT_Y]) + protocolFeeAssets[DEPOSIT_Y];
            uint256 missingXAssets = Math.max(uint256(newAssets[BORROW_X]), depositXWithFees) - depositXWithFees;
            uint256 missingYAssets = Math.max(uint256(newAssets[BORROW_Y]), depositYWithFees) - depositYWithFees;

            newAssets[DEPOSIT_L] = uint112(
                Convert.depletionAdjustedActiveLiquidity(newReserveX, newReserveY, missingXAssets, missingYAssets)
                    + newAssets[BORROW_L]
            );
        }
    }

    function getUtilizationInWads(
        uint256 totalBorrowedAssets,
        uint256 totalDepositedAssets
    ) internal pure returns (uint256 utilization) {
        if (totalDepositedAssets > 0) {
            // assets are both 112 and will not overflow.
            unchecked {
                // assets are uint112, cant overflow.
                utilization = Math.ceilDiv(totalBorrowedAssets * WAD, totalDepositedAssets);
            }
        }
    }

    /**
     * @notice Adjusts utilization based on saturation to calculate interest penalties
     * @dev When saturation exceeds `PENALTY_SATURATION_PERCENT_IN_WAD`, utilization is increased
     *      to apply higher interest rates as a penalty for high saturation
     * @param utilization Current utilization of `L`, `X`, or `Y` assets
     * @param maxSatInWads Saturation utilization
     * @return The adjusted utilization value
     */
    function mutateUtilizationForSaturation(
        uint256 utilization,
        uint256 maxSatInWads
    ) internal pure returns (uint256) {
        // Early return, if saturation is above or below defined threshold, or utilization is greater than max utilization.
        if (utilization >= MAX_UTILIZATION_PERCENT_IN_WAD || maxSatInWads <= PENALTY_SATURATION_PERCENT_IN_WAD) {
            return utilization;
        } else if (maxSatInWads >= MAX_SATURATION_PERCENT_IN_WAD) {
            return MAX_UTILIZATION_PERCENT_IN_WAD;
        }

        // Calculate adjustment based on formula:
        // min(max((maxSatInWads - MAX_SATURATION_PERCENT) * (MAX_UTILIZATION - utilization) /
        //     (MAX_SATURATION_PERCENT - PENALTY_SATURATION_PERCENT) + MAX_UTILIZATION, utilization), MAX_UTILIZATION)
        uint256 adjustedUtilization = MAX_UTILIZATION_PERCENT_IN_WAD
            - Convert.mulDiv(
                MAX_SATURATION_PERCENT_IN_WAD - maxSatInWads,
                MAX_UTILIZATION_PERCENT_IN_WAD - utilization,
                SATURATION_PENALTY_BUFFER_IN_WAD,
                false
            );

        return Math.min(Math.max(adjustedUtilization, utilization), MAX_UTILIZATION_PERCENT_IN_WAD);
    }

    function computeInterestAssets(
        uint256 duration,
        uint256 utilization,
        uint256 reserveAssets,
        uint256 borrowedAssets,
        uint256 depositedAssets
    ) internal pure returns (uint256) {
        uint256 baseRateInWads = getAnnualInterestRatePerSecondInWads(utilization);

        return computeInterestAssetsGivenRate(
            duration, borrowedAssets, Math.max(depositedAssets, reserveAssets), baseRateInWads
        );
    }

    function computeInterestAssetsGivenRate(
        uint256 duration,
        uint256 borrowedAssets,
        uint256 maxDepositedOrReserveAssets,
        uint256 rateInWads
    ) internal pure returns (uint256) {
        // max amount of interest that can accrue is uint112 max to prevent overflows
        // this means that once an asset hits the max, interest will no longer accrue.
        unchecked {
            return Math.min(
                Convert.mulDiv(MathLib.wTaylorCompounded(rateInWads, duration), borrowedAssets, WAD, false),
                type(uint112).max - Math.max(maxDepositedOrReserveAssets, borrowedAssets)
            );
        }
    }

    function addInterestToAssets(uint256 prevAssets, uint256 interest) internal pure returns (uint112) {
        // safe down cast because interest <= type(uint112).max - max(depositedAssets, borrowedAssets) due to the check in computeInterestAssetsGivenRate
        unchecked {
            return uint112(prevAssets + interest);
        }
    }

    /**
     * @notice Gets the annual interest rate for a given utilization
     * @dev Same as getAnnualInterestRatePerSecondInWads but without dividing by SECONDS_IN_YEAR
     * @param utilizationInWads The utilization rate in WADs
     * @return interestRate The annual interest rate in WADs
     */
    function getAnnualInterestRatePerSecondInWads(
        uint256 utilizationInWads
    ) internal pure returns (uint256 interestRate) {
        if (utilizationInWads <= OPTIMAL_UTILIZATION) {
            interestRate = utilizationInWads.wMulDown(SLOPE1);
        } else if (utilizationInWads <= DANGER_UTILIZATION) {
            interestRate = (utilizationInWads - OPTIMAL_UTILIZATION).wMulDown(SLOPE2) + BASE_OPTIMAL_UTILIZATION;
        } else {
            interestRate = (utilizationInWads - DANGER_UTILIZATION).wMulDown(SLOPE3) + BASE_DANGER_UTILIZATION;
        }
        interestRate /= SECONDS_IN_YEAR;
    }
}

lib/core-v1/contracts/libraries/Liquidation.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';

import {
    BIPS,
    MAG1,
    MAG2,
    ALLOWED_LIQUIDITY_LEVERAGE,
    ALLOWED_LIQUIDITY_LEVERAGE_MINUS_ONE
} from 'contracts/libraries/constants.sol';
import {Convert} from 'contracts/libraries/Convert.sol';
import {PartialLiquidations} from 'contracts/libraries/PartialLiquidations.sol';
import {Saturation} from 'contracts/libraries/Saturation.sol';
import {TickMath} from 'contracts/libraries/TickMath.sol';
import {Validation} from 'contracts/libraries/Validation.sol';
import {ISaturationAndGeometricTWAPState} from 'contracts/interfaces/ISaturationAndGeometricTWAPState.sol';
import {
    DEPOSIT_L,
    DEPOSIT_X,
    DEPOSIT_Y,
    BORROW_L,
    BORROW_X,
    BORROW_Y
} from 'contracts/interfaces/tokens/ITokenController.sol';
import {ROUNDING_UP} from 'contracts/interfaces/tokens/ITokenController.sol';

library Liquidation {
    // constants

    uint256 internal constant START_NEGATIVE_PREMIUM_LTV_BIPS = 6000; // == 0.6
    uint256 private constant START_PREMIUM_LTV_BIPS = 7500; // == 0.75
    uint256 private constant NEGATIVE_PREMIUM_SLOPE_IN_BIPS = 66_667; // 20/3
    uint256 private constant NEGATIVE_PREMIUM_INTERCEPT_IN_BIPS = 40_000; // == -4 (subtracted since stored positively)
    uint256 private constant POSITIVE_PREMIUM_SLOPE_IN_BIPS = 7408; // == 20/27
    uint256 private constant POSITIVE_PREMIUM_INTERCEPT_IN_BIPS = 4444; // == 4/9

    /**
     * @notice This factor brings a leveraged position just below the leverage liquidation threshold
     */
    uint256 internal constant LEVERAGE_LIQUIDATION_BREAK_EVEN_FACTOR_MAG2 = 10; // 0.1 MAG2 version

    /**
     * @notice Leverage liquidation factor derived from max allowed leverage scaled by the break-even factor
     */
    uint256 internal constant LEVERAGE_LIQUIDATION_FACTOR =
        ALLOWED_LIQUIDITY_LEVERAGE * MAG2 / LEVERAGE_LIQUIDATION_BREAK_EVEN_FACTOR_MAG2;
    uint256 internal constant MAX_PREMIUM_IN_BIPS = 11_111; // == 10 * BIPS / 9

    uint256 internal constant HARD = 0;
    uint256 internal constant SATURATION = 1;
    uint256 internal constant LEVERAGE = 2;

    // errors

    error LiquidationPremiumTooHigh();
    error LiquidationZeroPremium();
    error NotEnoughRepaidForLiquidation();
    error TooMuchDepositToTransferForLeverageLiquidation();
    error LiquidationMutation();

    function verifyHardLiquidation(
        ISaturationAndGeometricTWAPState saturationState,
        address pairAddress,
        Validation.InputParams memory inputParams,
        uint256[6] memory proposedLiquidation,
        uint256 fragileLiquidityAssets,
        address borrower
    ) external view returns (uint256[6] memory partialLiquidation, bool badDebt) {
        {
            (uint256 netRepaidLAssets, uint256 netSeizedLAssets, bool netDebtX) = calculateNetDebtAndSeizedDeposits(
                proposedLiquidation, inputParams.sqrtPriceMinInQ72, inputParams.sqrtPriceMaxInQ72
            );

            Saturation.Account memory account = saturationState.getAccount(pairAddress, netDebtX, borrower);

            partialLiquidation = PartialLiquidations.calculatePartialLiquidation(
                account.satPairPerTranche,
                account.lastTranche,
                inputParams.userAssets,
                inputParams.activeLiquidityAssets - fragileLiquidityAssets,
                netRepaidLAssets,
                netSeizedLAssets,
                netDebtX
            );
        }

        uint256 maxAllowedPremiumBips = calcHardMaxPremiumInBips(
            partialLiquidation,
            inputParams.activeLiquidityAssets,
            inputParams.sqrtPriceMinInQ72,
            inputParams.sqrtPriceMaxInQ72
        );

        // Premium exceeds max before bad debt and all assets seized.
        badDebt = maxAllowedPremiumBips > MAX_PREMIUM_IN_BIPS
            && (
                partialLiquidation[DEPOSIT_L] == inputParams.userAssets[DEPOSIT_L]
                    && partialLiquidation[DEPOSIT_X] == inputParams.userAssets[DEPOSIT_X]
                    && partialLiquidation[DEPOSIT_Y] == inputParams.userAssets[DEPOSIT_Y]
            );

        if (!badDebt) {
            // Not bad debt.
            // Debt repaid must be equal to or greater than the partial liquidation amount.
            // Deposits seized will be less than or equal the partial liquidation amount.
            // Verifies the repaid amount of each asset to cover the partial liquidation.
            if (
                proposedLiquidation[BORROW_L] < partialLiquidation[BORROW_L]
                    || proposedLiquidation[BORROW_X] < partialLiquidation[BORROW_X]
                    || proposedLiquidation[BORROW_Y] < partialLiquidation[BORROW_Y]
            ) {
                revert NotEnoughRepaidForLiquidation();
            }
            // Verified that proposed deposits do not exceed partial liquidation allowance.
            if (
                proposedLiquidation[DEPOSIT_L] > partialLiquidation[DEPOSIT_L]
                    || proposedLiquidation[DEPOSIT_X] > partialLiquidation[DEPOSIT_X]
                    || proposedLiquidation[DEPOSIT_Y] > partialLiquidation[DEPOSIT_Y]
            ) {
                revert LiquidationMutation();
            }
            // keep the repaid amounts from the partial liquidation and use the proposed deposits.
            partialLiquidation[DEPOSIT_L] = proposedLiquidation[DEPOSIT_L];
            partialLiquidation[DEPOSIT_X] = proposedLiquidation[DEPOSIT_X];
            partialLiquidation[DEPOSIT_Y] = proposedLiquidation[DEPOSIT_Y];
        } else {
            // potential bad debt case.
            // Debt repaid will be less than the partial liquidation amount, deposits will be equal
            // to the partial liquidation amount.
            // Verify that liquidator does not mutate by not seizing enough of one asset and more
            // of another.
            // Do not allow a liquidator to skip any borrow leg held by the borrower.
            // Bad debt burns the borrower's full token balance after this validation.
            if (
                (
                    proposedLiquidation[BORROW_L] > partialLiquidation[BORROW_L]
                        || proposedLiquidation[BORROW_X] > partialLiquidation[BORROW_X]
                        || proposedLiquidation[BORROW_Y] > partialLiquidation[BORROW_Y]
                ) || (proposedLiquidation[BORROW_L] == 0 && partialLiquidation[BORROW_L] > 0)
                    || (proposedLiquidation[BORROW_X] == 0 && partialLiquidation[BORROW_X] > 0)
                    || (proposedLiquidation[BORROW_Y] == 0 && partialLiquidation[BORROW_Y] > 0)
            ) {
                revert LiquidationMutation();
            }
            // keep the deposit amount from the partial liquidation and use the proposed repaid amounts.
            partialLiquidation[BORROW_L] = proposedLiquidation[BORROW_L];
            partialLiquidation[BORROW_X] = proposedLiquidation[BORROW_X];
            partialLiquidation[BORROW_Y] = proposedLiquidation[BORROW_Y];
        }

        (uint256 netDebtRepaidInLAssets, uint256 netDepositsSeizedInLAssets,) = calculateNetDebtAndSeizedDeposits(
            partialLiquidation, inputParams.sqrtPriceMinInQ72, inputParams.sqrtPriceMaxInQ72
        );

        checkHardPremiums(netDebtRepaidInLAssets, netDepositsSeizedInLAssets, maxAllowedPremiumBips);
    }

    function checkHardPremiums(
        uint256 repaidDebtInL,
        uint256 seizedCollateralValueInL,
        uint256 maxAllowedPremiumBips
    ) internal pure {
        uint256 premiumInBips = calcHardPremiumInBips(repaidDebtInL, seizedCollateralValueInL);

        if (maxAllowedPremiumBips < premiumInBips) revert LiquidationPremiumTooHigh();
    }

    function calculateNetDebtAndSeizedDeposits(
        uint256[6] memory proposedLiquidation,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72
    ) internal pure returns (uint256 netDebtInLAssets, uint256 netCollateralInLAssets, bool netDebtX) {
        // swap min and max
        Validation.CheckLtvParams memory checkLtvParams =
            Validation.getCheckLtvParams(proposedLiquidation, sqrtPriceMaxInQ72, sqrtPriceMinInQ72);
        (netDebtInLAssets, netCollateralInLAssets, netDebtX) = Validation.calcDebtAndCollateral(checkLtvParams);
    }

    function checkSaturationPremiums(
        ISaturationAndGeometricTWAPState saturationAndGeometricTWAPState,
        Validation.InputParams memory inputParams,
        address borrower
    ) external view returns (uint256 seizeLAssets, uint256 seizeXAssets, uint256 seizeYAssets) {
        uint256 premiumInBips = calcSaturationMaxPremiumInBips(saturationAndGeometricTWAPState, inputParams, borrower);

        if (premiumInBips == 0) {
            revert LiquidationZeroPremium();
        }

        (seizeLAssets, seizeXAssets, seizeYAssets) = calcSaturationSeizedAssets(
            inputParams.userAssets[DEPOSIT_L],
            inputParams.userAssets[DEPOSIT_X],
            inputParams.userAssets[DEPOSIT_Y],
            premiumInBips
        );
    }

    /**
     * @notice Calculate weighted leverage liquidation repayments and seized deposits.
     * @dev The first three return indices are seized deposits, the last three are required
     *   repayments, and all values are in each token's native units. The formula for the premium
     *   is calculated with the average net borrow of X and Y $$B$$ and the net deposit of X and Y
     *   $$D$$ and a scaler $$S$$ that sets the pace at which the premium increased, in code we
     *   call this `LEVERAGE_LIQUIDATION_BREAK_EVEN_FACTOR_MAG2`, and allowed leverage $$AL$$,
     *   `ALLOWED_LIQUIDITY_LEVERAGE`:
     *   ```math
     *   premium = \begin{cases}
     *     S \left(
     *       \frac{B}{D}
     *       - \frac{AL - 1}{AL}
     *     \right)
     *     \text { if } \frac{B}{D} >
     *       \frac{AL - 1}{AL} \\
     *     0 \text { otherwise }
     *   \end{cases}
     *   ```
     *
     *   This can be visualized [here](https://www.desmos.com/calculator/1cd55f1yhz).
     *
     *   The premium is a percentage of the total deposit. If the premium is low enough, then we
     *   we attempt to deleverage the position such that the premium and closed part of the
     *   position leaves it under the leveraged threshold. If this is not possible, then all of the
     *   users deposit will be transferred to the liquidator and there will be bad debt.
     *
     *   Note that the de leveraging relies on the min and max tick to be equal, so the result may
     *   not be a valid amount of leverage using a min and max price as is done in the Validation
     *   library.
     *
     * @param inputParams The params representing the position of the borrower.
     * @return leveragedLiquidationParams Array indexed by DEPOSIT_L, DEPOSIT_X, DEPOSIT_Y,
     *   BORROW_L, BORROW_X, BORROW_Y.
     * @return badDebt Whether the leverage liquidation leaves bad debt to burn.
     */
    function liquidateLeverageCalcDeltaAndPremium(
        Validation.InputParams memory inputParams
    ) external pure returns (uint256[6] memory leveragedLiquidationParams, bool badDebt) {
        uint256 netDepositInLAssets;
        uint256 netBorrowInLAssets;

        // we use the averageSqrtPrice for conversion between L and X/Y assets
        uint256 averageSqrtPrice = Math.sqrt(inputParams.sqrtPriceMinInQ72 * inputParams.sqrtPriceMaxInQ72);

        // overestimates borrow and underestimates deposit as we do in validation
        Validation.CheckLtvParams memory checkLtvParams =
            Validation.getCheckLtvParams(inputParams.userAssets, averageSqrtPrice, averageSqrtPrice);

        {
            // We average the two since both are in L assets.
            netDepositInLAssets = (checkLtvParams.netDepositedXinLAssets + checkLtvParams.netDepositedYinLAssets) / 2;
            netBorrowInLAssets = (checkLtvParams.netBorrowedXinLAssets + checkLtvParams.netBorrowedYinLAssets) / 2;
        }

        if (
            // guarantee that premium > 0;
            ALLOWED_LIQUIDITY_LEVERAGE * netBorrowInLAssets
                > ALLOWED_LIQUIDITY_LEVERAGE_MINUS_ONE * netDepositInLAssets + LEVERAGE_LIQUIDATION_FACTOR
        ) {
            uint256 premiumValueInLAssets = (
                ALLOWED_LIQUIDITY_LEVERAGE * netBorrowInLAssets
                    - ALLOWED_LIQUIDITY_LEVERAGE_MINUS_ONE * netDepositInLAssets
            ) / LEVERAGE_LIQUIDATION_FACTOR;

            uint256 totalRepayInLAssets;
            uint256 remainingDepositAfterPremium;
            if (netDepositInLAssets < premiumValueInLAssets) {
                // extreme, unlikely, case when the premium is greater than all deposits
                premiumValueInLAssets = netDepositInLAssets;
            } else {
                // start close assets as the remaining deposits after premium.
                remainingDepositAfterPremium = netDepositInLAssets - premiumValueInLAssets;
            }

            if (netBorrowInLAssets < remainingDepositAfterPremium) {
                // the position can be de leveraged to meet leverage requirements.
                totalRepayInLAssets = remainingDepositAfterPremium
                    - ALLOWED_LIQUIDITY_LEVERAGE * (remainingDepositAfterPremium - netBorrowInLAssets);
            } else {
                totalRepayInLAssets = remainingDepositAfterPremium;
                badDebt = true;
            }

            uint256 totalSeizedInLAssets = totalRepayInLAssets + premiumValueInLAssets;

            leveragedLiquidationParams[DEPOSIT_L] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[DEPOSIT_L], totalSeizedInLAssets, netDepositInLAssets, !ROUNDING_UP
            );
            leveragedLiquidationParams[DEPOSIT_X] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[DEPOSIT_X], totalSeizedInLAssets, netDepositInLAssets, !ROUNDING_UP
            );
            leveragedLiquidationParams[DEPOSIT_Y] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[DEPOSIT_Y], totalSeizedInLAssets, netDepositInLAssets, !ROUNDING_UP
            );
            leveragedLiquidationParams[BORROW_L] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[BORROW_L], totalRepayInLAssets, netBorrowInLAssets, ROUNDING_UP
            );
            leveragedLiquidationParams[BORROW_X] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[BORROW_X], totalRepayInLAssets, netBorrowInLAssets, ROUNDING_UP
            );
            leveragedLiquidationParams[BORROW_Y] = calculateLeverageLiquidationAsset(
                inputParams.userAssets[BORROW_Y], totalRepayInLAssets, netBorrowInLAssets, ROUNDING_UP
            );
        } else {
            revert LiquidationZeroPremium();
        }
    }

    /**
     * @notice Calculate the amount of an asset to be liquidated in a leverage liquidation.
     * @dev we use the min so amounts don't exceed balances
     * @param userAsset The amount of the asset held by the user.
     * @param totalShareLAsset The portion getting seized or repaid in L assets, or fraction of the total borrowed l or deposited l respectively.
     * @param totalLAsset The total borrowed l or deposited l respectively.
     * @param rounding Whether to round up the result, we round up for the borrow legs to make sure enough is repaid to cover the seized deposits.
     */
    function calculateLeverageLiquidationAsset(
        uint256 userAsset,
        uint256 totalShareLAsset,
        uint256 totalLAsset,
        bool rounding
    ) internal pure returns (uint256) {
        return Math.min(
            userAsset,
            Math.mulDiv(userAsset, totalShareLAsset, totalLAsset, rounding ? Math.Rounding.Ceil : Math.Rounding.Floor)
        );
    }

    /**
     * @notice Calculate the maximum premium the liquidator may receive given the LTV of the borrower.
     * @dev We min the result to favor the borrower.
     * @return maxPremiumInBips The max premium allowed to be received by the liquidator.
     */
    function calcHardMaxPremiumInBips(
        uint256[6] memory validatedLiquidation,
        uint256 activeLiquidityAssets,
        uint256 sqrtPriceMinInQ72,
        uint256 sqrtPriceMaxInQ72
    ) internal pure returns (uint256 maxPremiumInBips) {
        // Calculate max premium before repay, swap min and max
        Validation.CheckLtvParams memory checkLtvParams =
            Validation.getCheckLtvParams(validatedLiquidation, sqrtPriceMaxInQ72, sqrtPriceMinInQ72);

        (uint256 netDebtInLAssets, uint256 netCollateralInLAssets,) = Validation.calcDebtAndCollateral(checkLtvParams);

        netDebtInLAssets = Validation.increaseForSlippage(netDebtInLAssets, activeLiquidityAssets);

        maxPremiumInBips = convertLtvToPremium(
            0 < netCollateralInLAssets ? Convert.mulDiv(netDebtInLAssets, BIPS, netCollateralInLAssets, false) : 0
        );
    }

    /**
     * @notice Calculate the premium being afforded to the liquidator given the repay and depositToTransfer amounts.
     * @dev We use prices to maximize the `premiumInBips` to favor the borrower
     * @param repaidDebtInL The amount of debt being repaid in L assets.
     * @param seizedCollateralValueInL The value of the collateral being seized in L assets.
     * @return premiumInBips The premium being received by the liquidator.
     */
    function calcHardPremiumInBips(
        uint256 repaidDebtInL,
        uint256 seizedCollateralValueInL
    ) internal pure returns (uint256 premiumInBips) {
        // If nothing is being or can be liquidated, premium is infinite, we will revert
        if (repaidDebtInL == 0) {
            return type(uint256).max;
        }

        // Calculate premium in bips
        unchecked {
            premiumInBips = Convert.mulDiv(seizedCollateralValueInL, BIPS, repaidDebtInL, ROUNDING_UP);
        }
    }

    /**
     * @notice Calculates the maximum premium the liquidator should receive based on borrower LTV.
     *   `ltvBips` and the returned premium are both denominated in bips. Let `l` be
     *   `ltvBips`, `a` and `b` be the two LTV thresholds, `m` be a slope, and `c` be an
     *   intercept. The negative-premium segment uses `m_-` and `c_-`; the positive-premium
     *   segment uses `m_+` and `c_+`.
     *
     *   ```math
     *   P(l)=
     *   \begin{cases}
     *     0
     *       & l \le a \\
     *     \left\lfloor\frac{m_{-}\cdot l}{BIPS}\right\rfloor-c_{-}
     *       & a < l < b \\
     *     \left\lfloor\frac{m_{+}\cdot l}{BIPS}\right\rfloor+c_{+}
     *       & b \le l
     *   \end{cases}
     *   ```
     * @dev internal for testing only
     * @param ltvBips LTV of the borrower.
     * @return maxPremiumInBips The maximum premium for the liquidator.
     */
    function convertLtvToPremium(
        uint256 ltvBips
    ) internal pure returns (uint256 maxPremiumInBips) {
        if (ltvBips > START_NEGATIVE_PREMIUM_LTV_BIPS) {
            if (ltvBips < START_PREMIUM_LTV_BIPS) {
                // negative premium <=> maxPremiumInBips < 1
                // linear function going thru (START_NEGATIVE_PREMIUM_LTV_BIPS, 0) and (START_PREMIUM_LTV_BIPS, 1)
                maxPremiumInBips = Convert.mulDiv(NEGATIVE_PREMIUM_SLOPE_IN_BIPS, ltvBips, BIPS, false)
                    - NEGATIVE_PREMIUM_INTERCEPT_IN_BIPS;
            } else {
                // positive premium <=> 1 <= maxPremiumInBips
                // linear function going thru (START_PREMIUM_LTV_BIPS, 1) and (0.9, 1/0.9)
                maxPremiumInBips = Convert.mulDiv(POSITIVE_PREMIUM_SLOPE_IN_BIPS, ltvBips, BIPS, false)
                    + POSITIVE_PREMIUM_INTERCEPT_IN_BIPS;
            }
        }
    }

    // saturation liquidation

    function calcSaturationSeizedAssets(
        uint256 depositedLAssets,
        uint256 depositedXAssets,
        uint256 depositedYAssets,
        uint256 premiumInBips
    ) internal pure returns (uint256 seizedLAssets, uint256 seizedXAssets, uint256 seizedYAssets) {
        seizedLAssets = depositedLAssets * premiumInBips / BIPS;
        seizedXAssets = depositedXAssets * premiumInBips / BIPS;
        seizedYAssets = depositedYAssets * premiumInBips / BIPS;
    }

    /**
     * @notice Calculate the max premium the saturation liquidator can receive given position of
     *         `account`.
     * @param saturationAndGeometricTWAPState The contract containing the saturation state.
     * @param inputParams The params containing the position of `account`.
     * @param account The account of the borrower.
     * @return maxPremiumBips The max premium for the liquidator.
     */
    function calcSaturationMaxPremiumInBips(
        ISaturationAndGeometricTWAPState saturationAndGeometricTWAPState,
        Validation.InputParams memory inputParams,
        address account
    ) internal view returns (uint256 maxPremiumBips) {
        // calculate ratio of new sat vs old sat
        (uint256 netXLiqSqrtPriceInXInQ72, uint256 netYLiqSqrtPriceInXInQ72) =
            Saturation.calcLiqSqrtPriceQ72(inputParams.userAssets);

        // use max of netX vs netY
        uint256 ratioBips;
        if (0 < netXLiqSqrtPriceInXInQ72 || 0 < netYLiqSqrtPriceInXInQ72) {
            ratioBips = saturationAndGeometricTWAPState.calcSatChangeRatioBips(
                inputParams, netXLiqSqrtPriceInXInQ72, netYLiqSqrtPriceInXInQ72, address(this), account
            );
        }

        // if the saturation has decreased, no saturation liquidation (maxPremium == 0)
        if (ratioBips < BIPS) return 0;

        // calculate premium
        unchecked {
            maxPremiumBips = (ratioBips - BIPS) / MAG1;
        }
    }
}

lib/core-v1/contracts/libraries/PartialLiquidations.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';

import {
    BIPS,
    EXPECTED_SATURATION_LTV_MAG2,
    MAG2,
    MAX_SATURATION_RATIO_IN_MAG2,
    TRANCHE_B_IN_Q72,
    TRANCHE_B_MINUS_ONE_IN_Q72,
    Q72,
    Q144
} from 'contracts/libraries/constants.sol';
import {ISaturationAndGeometricTWAPState} from 'contracts/interfaces/ISaturationAndGeometricTWAPState.sol';
import {
    DEPOSIT_L,
    DEPOSIT_X,
    DEPOSIT_Y,
    BORROW_L,
    BORROW_X,
    BORROW_Y
} from 'contracts/interfaces/tokens/ITokenController.sol';
import {Convert} from 'contracts/libraries/Convert.sol';
import {Saturation} from 'contracts/libraries/Saturation.sol';
import {TickMath} from 'contracts/libraries/TickMath.sol';
import {Validation} from 'contracts/libraries/Validation.sol';

/**
 * @title PartialLiquidations
 * @notice We allow liquidations to happen in parts when the position is spread across more than
 *   one tranche. These partial liquidations allow the liquidator to specify how many tranches they
 *   are liquidating based on how much they are repaying. Smaller slices start with the tranche range
 *   closest to the current price and move outward, so the slice reaches expected LTV before the full
 *   position on the same debt side does. In most cases, one tranche will be liquidated at one time,
 *   but in some cases, a sliver of liquidity in the first tranche may not be worth the cost to
 *   liquidate until it and the next tranche have become profitable to liquidate.
 *
 *   Once we determine the number of tranches to liquidate, we build the liquidated slice from the
 *   debt side first. L uses a weight because both deposit and borrow L can be included together;
 *   the opposing side is then solved directly so the slice lands on the expected liquidation LTV.
 *
 *   A partial liquidation splits the signed position into the liquidated slice and the remaining
 *   position:
 *
 *  ```math
 *   P_0=P_\Delta+P_1,
 *   \qquad
 *   P_0=[L_0,X_0,Y_0],
 *   \qquad
 *   P_\Delta=[L_\Delta,X_\Delta,Y_\Delta]
 *   ```
 *
 *   The slice must preserve component signs, must not exceed the original component magnitudes, and
 *   must have exact expected liquidation LTV at the slice square-root price `s_delta`. The whole
 *   position and the remaining position do not need to have the same LTV as the liquidated slice.
 *
 *   Signed components are net deposits minus borrows:
 *
 *   ```math
 *   \begin{align}
 *     L_0 &= depositL - borrowL \\
 *     X_0 &= depositX - borrowX \\
 *     Y_0 &= depositY - borrowY
 *   \end{align}
 *   ```
 *
 *   The slice is constructed from the debt-side component first. Throughout this library, `s` is
 *   a square-root price, not a price. At square-root price `s`, X is measured in L as `X / s` and
 *   Y is measured in L as `Y * s`.
 *
 *   Let `k` be the unscaled expected liquidation LTV:
 *
 *   ```math
 *   k=EXPECTED\_SATURATION\_LTV
 *   ```
 *
 *   In code, `k` is represented by `EXPECTED_SATURATION_LTV_MAG2 / MAG2`.
 *
 *   In signed slice notation, repaid debt components are negative and seized collateral components
 *   are positive. For net debt X, the exact-LTV slice condition is:
 *
 *   ```math
 *   k=\dfrac{-X_\Delta/s_\Delta-L_\Delta}{L_\Delta+Y_\Delta s_\Delta}
 *   ```
 *
 *   The net debt Y equations are symmetric:
 *
 *   ```math
 *   k=\dfrac{-Y_\Delta s_\Delta-L_\Delta}{L_\Delta+X_\Delta/s_\Delta}
 *   ```
 *
 */
library PartialLiquidations {
    int256 internal constant MAG2_INT = int256(MAG2);

    struct LoopMemoryState {
        uint256 satArrayLength;
        uint256 partialSatInLAssets;
        uint256 includedTranches;
        uint256 partialSatLimit;
    }

    /**
     * @notice Calculates the partial liquidation slice for the tranches covered by the repayment.
     * @dev Returns the full user asset array when every tranche is included. Returns the zero array
     *   when no L-denominated debt is repaid. The tranche count is chosen from absolute
     *   `satInLAssets`, while the slice geometry uses the corresponding relative saturation values.
     * @param satPairPerTranche Saturation entries for the borrower, ordered from the end of
     *   liquidation toward the start of liquidation.
     * @param lastTranche Last tranche occupied by the borrower in the liquidation direction.
     * @param userAssets Borrower assets in `[depositL, depositX, depositY, borrowL, borrowX, borrowY]` order.
     * @param activeLiquidityAssets Active liquidity used to scale tranche saturation.
     * @param netRepaidLAssets Net debt repaid by the liquidator, denominated in L.
     * @param netSeizedLAssets Net collateral seized by the liquidator, denominated in L.
     * @param netDebtX Whether the liquidation repays net X debt. If false, it repays net Y debt.
     * @return liquidation Component-bounded asset amounts to remove from the borrower.
     */
    function calculatePartialLiquidation(
        Saturation.SaturationPair[] memory satPairPerTranche,
        int16 lastTranche,
        uint256[6] memory userAssets,
        uint256 activeLiquidityAssets,
        uint256 netRepaidLAssets,
        uint256 netSeizedLAssets,
        bool netDebtX
    ) internal pure returns (uint256[6] memory liquidation) {
        if (netRepaidLAssets > 0) {
            uint256 partialSaturation;
            uint256 totalSaturation;
            uint256 remainingTranches;

            {
                LoopMemoryState memory loopMem = LoopMemoryState({
                    satArrayLength: satPairPerTranche.length,
                    partialSatInLAssets: 0,
                    includedTranches: 0,
                    partialSatLimit: Math.max(netRepaidLAssets, netSeizedLAssets * EXPECTED_SATURATION_LTV_MAG2 / MAG2)
                });

                uint256 bFactor = Q72;

                for (uint256 i = loopMem.satArrayLength; i > 0; --i) {
                    Saturation.SaturationPair memory borrowerTranche = satPairPerTranche[i - 1];
                    uint256 satInRelativeLAssets = borrowerTranche.satRelativeToL * Q72 / bFactor;
                    bFactor = bFactor * TRANCHE_B_IN_Q72 / Q72;

                    if (loopMem.partialSatLimit > loopMem.partialSatInLAssets) {
                        loopMem.includedTranches++;
                        partialSaturation += satInRelativeLAssets;
                    }
                    totalSaturation += satInRelativeLAssets;

                    // measure saturation
                    loopMem.partialSatInLAssets += borrowerTranche.satInLAssets;
                }

                if (loopMem.includedTranches == loopMem.satArrayLength) {
                    return userAssets;
                }
                remainingTranches = loopMem.satArrayLength - loopMem.includedTranches;
            }
            int16 adjTick = int16(uint16(remainingTranches));
            uint256 sqrtPriceQ72 = TickMath.getSqrtPriceAtTick(
                (netDebtX ? lastTranche + adjTick : lastTranche + 1 - adjTick) * int16(Saturation.TICKS_PER_TRANCHE)
            );

            liquidation = calcMutation(
                userAssets, sqrtPriceQ72, partialSaturation, totalSaturation, activeLiquidityAssets, netDebtX
            );
        }
    }

    // helpers

    /**
     * @notice Builds a liquidation slice from raw tranche-boundary and saturation inputs.
     *   It derives the target square-root price and asset weights from the same saturation window,
     *   applies L through a shared weight, then solves the deposit-side delta directly from the
     *   exact-LTV equation.
     *
     *   The target slice square-root price is the selected tranche boundary moved by the start
     *   weight from the same saturation walk:
     *
     *   ```math
     *   s_\Delta=b^T\sqrt{w_s}
     *   ```
     *
     *   In signed notation, the debt-side slice then fixes one raw borrow amount:
     *
     *   ```math
     *   X_\Delta=-borrowX\cdot w_X
     *     \qquad \text{for net debt X}
     *   ```
     *
     *   ```math
     *   Y_\Delta=-borrowY\cdot w_Y
     *     \qquad \text{for net debt Y}
     *   ```
     *
     *   L is selected next. The remaining side is solved last from the exact-LTV equation and may be
     *   either collateral seized or same-side borrow repaid, depending on the sign of the solved
     *   delta.
     * @param userAssets Borrower assets in `[depositL, depositX, depositY, borrowL, borrowX, borrowY]` order.
     * @param trancheBoundarySqrtPriceQ72 Boundary sqrt price for the tranche adjacent to the included slice.
     * @param partialSaturation Relative saturation included in the partial liquidation.
     * @param totalSaturation Total relative borrower saturation across all tranches.
     * @param activeLiquidityAssets Active liquidity used to scale tranche saturation.
     * @param netDebtX Whether the debt side is X. If false, the debt side is Y.
     * @return liquidation Component-bounded asset amounts to remove from the borrower.
     */
    function calcMutation(
        uint256[6] memory userAssets,
        uint256 trancheBoundarySqrtPriceQ72,
        uint256 partialSaturation,
        uint256 totalSaturation,
        uint256 activeLiquidityAssets,
        bool netDebtX
    ) internal pure returns (uint256[6] memory liquidation) {
        uint256 debtSideWeightQ72;
        uint256 targetLiquidationSqrtPriceQ72;
        {
            uint256 sqrtStartWeightQ72 = calcSqrtStartWeightQ72(partialSaturation, activeLiquidityAssets, netDebtX);

            uint256 sqrtEndWeightQ72 =
                calcSqrtEndWeightQ72(partialSaturation, totalSaturation, activeLiquidityAssets, netDebtX);

            debtSideWeightQ72 = calcDebtSideWeightQ72(sqrtStartWeightQ72, sqrtEndWeightQ72, netDebtX);

            targetLiquidationSqrtPriceQ72 = trancheBoundarySqrtPriceQ72 * sqrtStartWeightQ72 / Q72;
        }

        uint256 debtSideDelta = Convert.mulDiv(userAssets[netDebtX ? BORROW_X : BORROW_Y], debtSideWeightQ72, Q72, true);

        int256 lDelta;
        {
            uint256 lWeightQ72 =
                calcLWeightQ72(userAssets, debtSideWeightQ72, debtSideDelta, targetLiquidationSqrtPriceQ72, netDebtX);

            lDelta = applyLMutation(liquidation, userAssets, lWeightQ72);
        }

        {
            int256 remainingSideDelta =
                calcRemainingSideDelta(debtSideDelta, lDelta, targetLiquidationSqrtPriceQ72, netDebtX);

            if (netDebtX) {
                liquidation[BORROW_X] = debtSideDelta;
                applyRemainingSideDelta(liquidation, userAssets, remainingSideDelta, DEPOSIT_Y, BORROW_Y);
            } else {
                liquidation[BORROW_Y] = debtSideDelta;
                applyRemainingSideDelta(liquidation, userAssets, remainingSideDelta, DEPOSIT_X, BORROW_X);
            }
        }
    }

    /**
     * @notice Applies the L weight to both L legs and returns the resulting signed L delta.
     *   The raw L legs are both included at the same weight:
     *
     *   ```math
     *   depositL_{\Delta}=depositL\cdot w_L,\qquad borrowL_{\Delta}=borrowL\cdot w_L
     *   ```
     *
     *   The signed L contribution is:
     *
     *   ```math
     *   L_{\Delta}=depositL_{\Delta}-borrowL_{\Delta}
     *   ```
     * @param liquidation Liquidation array being built.
     * @param userAssets Borrower assets in `[depositL, depositX, depositY, borrowL, borrowX, borrowY]` order.
     * @param lWeightQ72 Q72 weight to apply to deposit L and borrow L.
     * @return lDelta Signed L contribution of the liquidated slice.
     */
    function applyLMutation(
        uint256[6] memory liquidation,
        uint256[6] memory userAssets,
        uint256 lWeightQ72
    ) private pure returns (int256 lDelta) {
        liquidation[DEPOSIT_L] = Convert.mulDiv(userAssets[DEPOSIT_L], lWeightQ72, Q72, false);
        liquidation[BORROW_L] = Convert.mulDiv(userAssets[BORROW_L], lWeightQ72, Q72, true);

        lDelta = int256(liquidation[DEPOSIT_L]) - int256(liquidation[BORROW_L]);
    }

    /**
     * @notice Calculates the saturation-derived weight for the debt-side borrow asset.
     *   The selected debt-side weight is:
     *
     *   ```math
     *   w_{debt}=
     *   \begin{cases}
     *     w_X & \text{if net debt X} \\
     *     w_Y & \text{if net debt Y}
     *   \end{cases}
     *   ```
     * @param sqrtStartWeightQ72 Start sqrt weight of the included saturation window.
     * @param sqrtEndWeightQ72 End sqrt weight of the included saturation window.
     * @param netDebtX Whether the debt side is X. If false, the debt side is Y.
     * @return debtSideWeightQ72 Q72 weight applied to the debt-side borrow amount.
     */
    function calcDebtSideWeightQ72(
        uint256 sqrtStartWeightQ72,
        uint256 sqrtEndWeightQ72,
        bool netDebtX
    ) private pure returns (uint256 debtSideWeightQ72) {
        uint256 xWeightQ72 = calcXWeightQ72(sqrtStartWeightQ72, sqrtEndWeightQ72);
        debtSideWeightQ72 = netDebtX ? xWeightQ72 : calcYWeightQ72(xWeightQ72, sqrtEndWeightQ72);
    }

    /**
     * @notice Applies the signed remaining-side delta to the matching deposit or borrow leg.
     *   Positive deltas seize remaining-side collateral. Negative deltas repay borrow on that side.
     *   Partial borrow repayment is valid as long as it is not greater than the starting borrow.
     *
     *   ```math
     *   R_\Delta>0 \Rightarrow deposit_\Delta=\min(R_\Delta, deposit)
     *   ```
     *
     *   ```math
     *   R_\Delta<0 \Rightarrow borrow_\Delta=\min(-R_\Delta, borrow)
     *   ```
     * @param liquidation Liquidation array being built.
     * @param userAssets Borrower assets in `[depositL, depositX, depositY, borrowL, borrowX, borrowY]` order.
     * @param remainingSideDelta Signed amount for the side opposite the fixed debt-side borrow.
     * @param depositIndex Deposit token index for the remaining side.
     * @param borrowIndex Borrow token index for the remaining side.
     */
    function applyRemainingSideDelta(
        uint256[6] memory liquidation,
        uint256[6] memory userAssets,
        int256 remainingSideDelta,
        uint256 depositIndex,
        uint256 borrowIndex
    ) private pure {
        if (remainingSideDelta > 0) {
            liquidation[depositIndex] = Math.min(uint256(remainingSideDelta), userAssets[depositIndex]);
        } else if (remainingSideDelta < 0) {
            liquidation[borrowIndex] = Math.min(uint256(-remainingSideDelta), userAssets[borrowIndex]);
        }
    }

    /**
     * @notice Solves the signed remaining-side delta for the fixed debt-side repayment.
     *   The returned delta is positive when the slice must seize deposit-side collateral and
     *   negative when it must repay borrow on that side to land on expected LTV.
     *
     *   For net debt X, define the fixed X-side debt value in L-units:
     *
     *   ```math
     *   debtSideValueInL=-\frac{X_\Delta}{s_\Delta}=\frac{borrowX_\Delta}{s_\Delta}
     *   ```
     *
     *   Then:
     *
     *   ```math
     *   Y_\Delta=\dfrac{debtSideValueInL-(1+k)L_\Delta}{ks_\Delta}
     *   ```
     *
     *   For net debt Y, define the fixed Y-side debt value in L-units:
     *
     *   ```math
     *   debtSideValueInL=-Y_\Delta s_\Delta=borrowY_\Delta s_\Delta
     *   ```
     *
     *   Then:
     *
     *   ```math
     *   X_\Delta=\dfrac{s_\Delta(debtSideValueInL-(1+k)L_\Delta)}{k}
     *   ```
     * @param borrowDelta Final debt-side borrow amount repaid by the liquidation.
     * @param lDelta Signed L contribution already included in the liquidation.
     * @param sqrtPriceQ72 Target liquidation sqrt price for the slice.
     * @param netDebtX Whether the debt side is X. If false, the debt side is Y.
     * @return remainingSideDelta Signed delta for the remaining side.
     */
    function calcRemainingSideDelta(
        uint256 borrowDelta,
        int256 lDelta,
        uint256 sqrtPriceQ72,
        bool netDebtX
    ) private pure returns (int256 remainingSideDelta) {
        uint256 debtSideValueInL = netDebtX
            ? Convert.mulDiv(borrowDelta, Q72, sqrtPriceQ72, false)
            : Convert.mulDiv(borrowDelta, sqrtPriceQ72, Q72, false);

        int256 numerator =
            int256(debtSideValueInL) * MAG2_INT - lDelta * int256(Saturation.EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2);
        uint256 mulFactor = netDebtX ? Q72 : sqrtPriceQ72;
        uint256 denominator = EXPECTED_SATURATION_LTV_MAG2 * (netDebtX ? sqrtPriceQ72 : Q72);
        remainingSideDelta = numerator >= 0
            ? int256(Convert.mulDiv(uint256(numerator), mulFactor, denominator, false))
            : -int256(Convert.mulDiv(uint256(-numerator), mulFactor, denominator, true));
    }

    /**
     * @notice Calculates the partial liquidation weight for asset X.
     *   In unscaled terms, `sqrtStartWeightQ72` is $\sqrt{w_s}$ and
     *   `sqrtEndWeightQ72` is $\sqrt{w_e}$. The branch matches which side of
     *   one the saturation window starts on:
     *
     *   ```math
     *   w_X =
     *   \begin{cases}
     *     \dfrac{\sqrt{w_s}-1}{\sqrt{w_s}-\sqrt{w_e}} & \text{if } \sqrt{w_s}>1 \\
     *     \dfrac{1-\sqrt{w_s}}{\sqrt{w_e}-\sqrt{w_s}} & \text{otherwise}
     *   \end{cases}
     *   ```
     * @param sqrtStartWeightQ72 Q72 start sqrt weight for the included saturation window.
     * @param sqrtEndWeightQ72 Q72 end sqrt weight for the included saturation window.
     * @return xWeightQ72 Q72 weight for asset X.
     */
    function calcXWeightQ72(
        uint256 sqrtStartWeightQ72,
        uint256 sqrtEndWeightQ72
    ) private pure returns (uint256 xWeightQ72) {
        if (sqrtStartWeightQ72 > Q72) {
            xWeightQ72 = (sqrtStartWeightQ72 - Q72) * Q72 / (sqrtStartWeightQ72 - sqrtEndWeightQ72);
        } else {
            xWeightQ72 = (Q72 - sqrtStartWeightQ72) * Q72 / (sqrtEndWeightQ72 - sqrtStartWeightQ72);
        }
    }

    /**
     * @notice Calculates the partial liquidation weight for asset Y.
     *   Formula for `w_Y`:
     *  ```math
     *  \begin{equation}
     *    w_Y = \sqrt{w_e} \cdot w_X
     *  \end{equation}
     *  ```
     * @param weightXQ72 Q72 weight for asset X.
     * @param sqrtEndWeightQ72 Q72 end sqrt weight for the included saturation window.
     * @return yWeightQ72 Q72 weight for asset Y.
     */
    function calcYWeightQ72(uint256 weightXQ72, uint256 sqrtEndWeightQ72) private pure returns (uint256 yWeightQ72) {
        yWeightQ72 = sqrtEndWeightQ72 * weightXQ72 / Q72;
    }

    /**
     * @notice Calculates the partial liquidation weight for asset L from the debt-side slice.
     *   Net-zero L is omitted. Net-borrow L uses the debt-side weight. Net-deposit L
     *   chooses the lower feasible L endpoint implied by the fixed debt-side repayment.
     *
     *   For net-borrow L:
     *
     *   ```math
     *   L_\Delta=L_0\cdot w_{debt}
     *   ```
     *
     *   For net-deposit L, L is the free collateral-side variable:
     *
     *   ```math
     *   0 \le L_\Delta \le L_0
     *   ```
     *
     *   Let `debtSideValueInL` be the fixed debt-side value and `remainingCollateralInL` be the
     *   remaining positive deposit-side collateral, both in L-units:
     *
     *   ```math
     *   debtSideValueInL=
     *   \begin{cases}
     *     \dfrac{borrowX_\Delta}{s_\Delta} & \text{if net debt X} \\
     *     borrowY_\Delta s_\Delta & \text{if net debt Y}
     *   \end{cases}
     *   ```
     *
     *   ```math
     *   remainingCollateralInL=
     *   \begin{cases}
     *     (depositY-borrowY)s_\Delta & \text{if net debt X and } depositY>borrowY \\
     *     \dfrac{depositX-borrowX}{s_\Delta} & \text{if net debt Y and } depositX>borrowX \\
     *     0 & \text{otherwise}
     *   \end{cases}
     *   ```
     *
     *   Exact LTV gives the lower feasible endpoint. Only positive remaining-side collateral changes
     *   that endpoint; zero or net-borrow remaining-side value uses the same lower bound:
     *
     *   ```math
     *   L_\Delta=\max\left(0,\frac{debtSideValueInL-k\cdot remainingCollateralInL}{1+k}\right)
     *     \qquad \text{when } remainingCollateralInL>0
     *   ```
     *
     *   ```math
     *   L_\Delta=\frac{debtSideValueInL}{1+k}
     *     \qquad \text{when } remainingCollateralInL=0
     *   ```
     * @param userAssets Borrower assets in `[depositL, depositX, depositY, borrowL, borrowX, borrowY]` order.
     * @param debtSideWeightQ72 Q72 weight applied to the debt-side borrow amount.
     * @param debtSideDelta Final debt-side borrow amount repaid by the liquidation.
     * @param targetLiquidationSqrtPriceQ72 Target liquidation sqrt price for the slice.
     * @param netDebtX Whether the debt side is X. If false, the debt side is Y.
     * @return lWeightQ72 Q72 weight applied to deposit L and borrow L.
     */
    function calcLWeightQ72(
        uint256[6] memory userAssets,
        uint256 debtSideWeightQ72,
        uint256 debtSideDelta,
        uint256 targetLiquidationSqrtPriceQ72,
        bool netDebtX
    ) private pure returns (uint256 lWeightQ72) {
        int256 netL = int256(userAssets[DEPOSIT_L]) - int256(userAssets[BORROW_L]);

        if (netL == 0) {
            lWeightQ72 = 0;
        } else if (netL < 0) {
            lWeightQ72 = debtSideWeightQ72;
        } else {
            uint256 debtSideAssetsInL = netDebtX
                ? Convert.mulDiv(debtSideDelta, Q72, targetLiquidationSqrtPriceQ72, false)
                : Convert.mulDiv(debtSideDelta, targetLiquidationSqrtPriceQ72, Q72, false);

            uint256 remainingSideAssets;
            if (netDebtX) {
                if (userAssets[DEPOSIT_Y] > userAssets[BORROW_Y]) {
                    remainingSideAssets = userAssets[DEPOSIT_Y] - userAssets[BORROW_Y];
                }
            } else {
                if (userAssets[DEPOSIT_X] > userAssets[BORROW_X]) {
                    remainingSideAssets = userAssets[DEPOSIT_X] - userAssets[BORROW_X];
                }
            }

            uint256 denominator = Saturation.EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2;
            uint256 lower;
            if (remainingSideAssets > 0) {
                uint256 remainingSideAssetsInL = netDebtX
                    ? Convert.mulDiv(remainingSideAssets, targetLiquidationSqrtPriceQ72, Q72, false)
                    : Convert.mulDiv(remainingSideAssets, Q72, targetLiquidationSqrtPriceQ72, false);

                uint256 debtSideComponent = debtSideAssetsInL * MAG2;

                uint256 remainingSideComponent = EXPECTED_SATURATION_LTV_MAG2 * remainingSideAssetsInL;

                lower = debtSideComponent > remainingSideComponent
                    ? (debtSideComponent - remainingSideComponent) / denominator
                    : 0;
            } else {
                lower = debtSideAssetsInL * MAG2 / denominator;
            }

            uint256 netLAbs = uint256(netL);
            lWeightQ72 = lower < netLAbs ? Convert.mulDiv(lower, Q72, netLAbs, true) : Q72;
        }
    }

    /**
     * @notice Calculates the start sqrt weight for the included saturation window.
     *   The saturation is normalized by the active liquidity scaled by the maximum allowed
     *   saturation ratio. Define:
     *
     *   ```math
     *   r_{max}=\frac{MAX\_SATURATION\_RATIO\_IN\_MAG2}{MAG2}
     *   ```
     *
     *   We round up the sqrt to avoid `sqrtStartWeightQ72 == Q72`, which would return `0` from `calcXWeightQ72`.
     *
     *   Normalize the included saturation by active liquidity:
     *
     *   ```math
     *   a_s=\frac{sat}{r_{max}L}
     *   ```
     *
     *   The underlying non-sqrt start weight is:
     *
     *   ```math
     *   \begin{equation}
     *     w_s = \begin{cases}
     *       1+a_s(B-1)
     *         & \text{ if net debt of X } \\
     *       \frac{1}{1+a_s(B-1)}
     *         & \text{ if net debt of Y}
     *     \end{cases}
     *   \end{equation}
     *   ```
     * @param partialSaturation Saturation included in the partial liquidation.
     * @param activeLiquidityAssets Active liquidity used to scale tranche saturation.
     * @param netDebtX Whether the debt side is X. If false, the reciprocal weight is used.
     * @return sqrtStartWeightQ72 Q72 start sqrt weight, adjusted for the debt side.
     */
    function calcSqrtStartWeightQ72(
        uint256 partialSaturation,
        uint256 activeLiquidityAssets,
        bool netDebtX
    ) internal pure returns (uint256 sqrtStartWeightQ72) {
        sqrtStartWeightQ72 = Math.sqrt(
            Q72
                * (
                    Q72
                        + Convert.mulDiv(
                            (TRANCHE_B_MINUS_ONE_IN_Q72) * MAG2,
                            partialSaturation,
                            activeLiquidityAssets * MAX_SATURATION_RATIO_IN_MAG2,
                            true
                        )
                ),
            Math.Rounding.Ceil
        );

        sqrtStartWeightQ72 = weightInNumeratorOrDenominator(sqrtStartWeightQ72, netDebtX);
    }

    /**
     * @notice Calculates the end sqrt weight for the included saturation window.
     *   Normalize the remaining saturation by active liquidity:
     *
     *   ```math
     *   r_{max}=\frac{MAX\_SATURATION\_RATIO\_IN\_MAG2}{MAG2},
     *   \qquad
     *   a_e=\frac{sat_{total}-sat}{r_{max}L}
     *   ```
     *
     *   The underlying non-sqrt end weight is:
     *
     *   ```math
     *   \begin{equation}
     *     w_e = \begin{cases}
     *       1-a_e(B-1)
     *         & \text{ if net debt of X } \\
     *       \frac{1}{1-a_e(B-1)}
     *         & \text{ if net debt of Y}
     *     \end{cases}
     *   \end{equation}
     *   ```
     * @param partialSaturation Saturation included in the partial liquidation.
     * @param totalSaturation Total borrower saturation across all tranches.
     * @param activeLiquidityAssets Active liquidity used to scale tranche saturation.
     * @param netDebtX Whether the debt side is X. If false, the reciprocal weight is used.
     * @return sqrtEndWeightQ72 Q72 end sqrt weight, adjusted for the debt side.
     */
    function calcSqrtEndWeightQ72(
        uint256 partialSaturation,
        uint256 totalSaturation,
        uint256 activeLiquidityAssets,
        bool netDebtX
    ) private pure returns (uint256 sqrtEndWeightQ72) {
        sqrtEndWeightQ72 = Math.sqrt(
            Q72
                * (
                    Q72
                        - Convert.mulDiv(
                            totalSaturation - partialSaturation,
                            (TRANCHE_B_MINUS_ONE_IN_Q72) * MAG2,
                            activeLiquidityAssets * MAX_SATURATION_RATIO_IN_MAG2,
                            false
                        )
                )
        );

        sqrtEndWeightQ72 = weightInNumeratorOrDenominator(sqrtEndWeightQ72, netDebtX);
    }

    /**
     * @notice Adjusts a sqrt weight into numerator form for X debt or denominator form for Y debt.
     *   Net debt Y walks the same tranche geometry in inverted square-root-price space:
     *
     *   ```math
     *   \sqrt{w}\mapsto\frac{1}{\sqrt{w}}
     *   ```
     * @param sqrtWeight Q72 sqrt weight before debt-side orientation.
     * @param netDebtX Whether the debt side is X. If false, the reciprocal weight is returned.
     * @return adjustedSqrtWeight Q72 sqrt weight oriented for the debt side.
     */
    function weightInNumeratorOrDenominator(
        uint256 sqrtWeight,
        bool netDebtX
    ) private pure returns (uint256 adjustedSqrtWeight) {
        adjustedSqrtWeight = netDebtX ? sqrtWeight : Q144 / sqrtWeight;
    }
}

lib/core-v1/contracts/libraries/QuadraticSwapFees.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {Convert} from 'contracts/libraries/Convert.sol';

/**
 * @title QuadraticSwapFees
 * @author Will
 * @notice A library to calculate fees that grow with respect to price deviation from a reference point.
 *   This library relies on a reference reserve from the start of the block to determine what the overall
 *   growth in price has been in the current block.
 *
 * Fee Model Overview:
 *   The fee structure uses two distinct models depending on the magnitude of price deviation:
 *
 *   1. Quadratic Fee Model (for moderate price changes):
 *      - Used when price deviation is relatively small
 *      - Fee grows proportionally to the square of the price movement
 *      - This creates a smooth, incentive-aligned fee curve that discourages large single swaps
 *        while keeping fees reasonable for normal market activity
 *      - Key property: If one swap would pay fee `F`, splitting it into two equal swaps would pay
 *        two fees that sum to approximately `F`
 *
 *   2. Linear Fee Model (for extreme price changes):
 *      - Used when price deviation exceeds the quadratic threshold
 *      - Fee grows linearly beyond the threshold point, capping at `MAX_QUADRATIC_FEE_PERCENT`
 *      - This prevents fees from becoming prohibitively expensive for very large swaps while
 *        still maintaining strong economic disincentives against massive price manipulations
 *      - The linear growth provides a more predictable fee structure for extreme market conditions
 *
 * Why Two Models?
 *   - Quadratic fees alone would become so high that the invariant curve property of being monotonic, leading
 *     larger swaps amounts in would eventually lead to less assets out than smaller swaps in.
 *   - Linear fees alone wouldn't provide enough protection against price manipulation for moderate swaps
 *
 * Price Movement Behavior:
 *   - If the price moves away from the reference, and then back toward it, the fee is minimal until
 *     the price again crosses the starting reference price
 *   - Only the net price deviation from the start-of-block reference is charged
 */
library QuadraticSwapFees {
    /**
     * @notice Minimum fee is one tenth of a basis point.
     */
    uint256 public constant MIN_FEE_Q64 = 0x1999999999999999;

    /**
     * @notice 10000 bips per 100 percent in Q64.
     */
    uint256 public constant BIPS_Q64 = 0x27100000000000000000;

    /**
     * @notice Max percent fee growing at a quadratic rate. After this the growths slows down.
     */
    uint256 internal constant MAX_QUADRATIC_FEE_PERCENT = 40;

    /**
     * @notice A scaler that controls how fast the fee grows, at 20, 9x price change will be
     *   a 40% fee.
     */
    uint256 internal constant N = 20;

    /**
     * @notice A reserve multiplier used to determine the boundary at which we switch from quadratic to linear fee.
     */
    uint256 private constant RESERVE_MULTIPLIER = 2;

    /**
     * @notice the $$\sqrt{price}$$ at which we switch from quadratic fee to a more linear fee.
     *   ```math
     *     \frac{MAX\_QUADRATIC\_FEE\_PERCENT + 2\cdot N}{N}
     *   ```
     */
    uint256 private constant LINEAR_START_REFERENCE_SCALER = 4;

    /**
     * @notice the fee at `LINEAR_START_REFERENCE_SCALER` in bips
     */
    uint256 private constant MAX_QUADRATIC_FEE_PERCENT_BIPS = 4000;

    /**
     * @notice $$N \cdot 100 \cdot Q64$$ or `N` times bips in one percent in Q64
     */
    uint256 private constant N_TIMES_BIPS_Q64_PER_PERCENT = 0x7d00000000000000000;

    /**
     * @notice 2 times Q64 or Q65
     */
    uint256 private constant TWO_Q64 = 0x20000000000000000;

    /**
     * @notice `MAX_QUADRATIC_FEE_PERCENT` in Q64, $$MAX\_QUADRATIC\_FEE\_PERCENT \cdot Q64$$
     */
    uint256 private constant MAX_QUADRATIC_FEE_Q64 = 0x280000000000000000;

    /**
     * @notice Computes the swap fee based on the `input` amount and the pool's
     *   `currentReserve` and `referenceReserve` for the input asset.
     *
     * Control flow by scenario:
     *   - `currentReserve >= referenceReserve` (price already at/away from reference):
     *     - If `input + RESERVE_MULTIPLIER * currentReserve < referenceReserve * LINEAR_START_REFERENCE_SCALER`:
     *       Use the quadratic fee model (closer to reference, pre-threshold).
     *     - Otherwise:
     *       Use the linear fee model (farther from reference, post-threshold).
     *   - `currentReserve < referenceReserve` (price at/moving back toward the start-of-block reference):
     *     - If `input + currentReserve <= referenceReserve`:
     *       Does not cross the reference. Only the global minimum fee will apply at the end.
     *     - If `input + currentReserve > referenceReserve`:
     *       Crosses the reference. The portion beyond the reference (`pastBy`) is charged using
     *       either the quadratic or linear model depending on `pastBy`:
     *         - `pastBy > RESERVE_MULTIPLIER * referenceReserve` → use linear fee model
     *         - otherwise → use quadratic fee model
     *       The resulting fee for the beyond-reference portion is then weighted by `pastBy / input`.
     *
     *   ```math
     *     \begin{equation*}
     *       f_\phi(X_{in}) =
     *         \begin{cases}
     *           n \cdot \frac{2(X_{0}-X_{R})+X_{in}}{X_{R}}
     *             &\text{if } X_0 \ge X_R \text{ \& } X_{in} + 2 X_{0} \le X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\
     *
     *           M_Q \left( 2 - X_R \frac{M_Q}{n\left( X_{in} + 2 (X_0 - X_R) \right)} \right)
     *             &\text {if } X_0 \ge X_R \text{ \& } X_{in} + 2X_{0} \ge X_{R}\left(\frac{M_Q+\ 2n}{n}\right) \\
     *
     *           \frac{n \cdot \left( \frac{pastBy^2}{X_R} \right)}{X_{in}}
     *             &\text{ if } X_0 + X_{in} \gt X_R \text{ \& } X_{in} + 2 X_{0} \le X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\
     *
     *           \frac{M_Q \left( 2 - X_R \frac{M_Q}{n \cdot pastBy} \right) \cdot pastBy}{X_{in}}
     *             &\text{ if } X_0 + X_{in} \gt X_R \text{ \& } X_{in} + 2 X_{0} \ge X_{R}\left(\frac{M_Q +\ 2n}{n}\right) \\
     *
     *           MinBips &\text{ otherwise } X_0 + X_{in} \le  X_R \\
     *         \end{cases}
     *     \end{equation*}
     *   ```
     *
     *   where:
     *   - `X_in` is the `input` amount
     *   - `X_0` is the `currentReserve`
     *   - `X_R` is the `referenceReserve`
     *   - `M_Q` is `MAX_QUADRATIC_FEE_PERCENT`
     *   - `n` is `N`
     *   - `pastBy` is the amount by which the price has moved past the `referenceReserve`
     *   - `MinBips` is `MIN_FEE_Q64`
     *
     * @param input The input amount of the asset (units of the asset).
     * @param currentReserve The current reserve of the input asset in the pool.
     * @param referenceReserve The start-of-block reference reserve for the input asset.
     * @return fee The swap fee in Q64 bips.
     */
    function calculateSwapFeeBipsQ64(
        uint256 input,
        uint256 currentReserve,
        uint256 referenceReserve
    ) internal pure returns (uint256 fee) {
        if (input == 0) return 0;

        /**
         * @dev All arithmetic operations within this `unchecked` block are safe from overflow/underflow.
         *
         * 1. `input + currentReserve` cannot overflow:
         *    - The caller `AmmalgamPair` verifies reserves via `updateReserves(reserveAssets + amountIn)`
         *    - Reserves are casted using `SafeCast` to `uint112` before being stored,
         *      so `input + currentReserve <= type(uint112).max`
         *
         * 2. a) `LINEAR_START_REFERENCE_SCALER * referenceReserve` cannot overflow:
         *    b) `RESERVE_MULTIPLIER * referenceReserve` cannot overflow:
         *       - `referenceReserve` is bounded by `uint112`
         *
         * 3. `currentReserveAfterSwap + currentReserve` cannot overflow:
         *    - `currentReserveAfterSwap = input + currentReserve` is bounded by `uint112`
         *    - `currentReserve` is bounded by `uint112`
         */
        unchecked {
            uint256 currentReserveAfterSwap = input + currentReserve;
            if (currentReserve >= referenceReserve) {
                if (currentReserveAfterSwap + currentReserve > referenceReserve * LINEAR_START_REFERENCE_SCALER) {
                    fee = calculateLinearFeeBipsQ64(input, currentReserve, referenceReserve);
                } else {
                    fee = calculateQuadraticFeeBipsQ64(input, currentReserve, referenceReserve);
                }
            } else {
                if (currentReserveAfterSwap > referenceReserve) {
                    uint256 pastBy = currentReserveAfterSwap - referenceReserve;

                    // similar inequality as above but treating `currentReserve == referenceReserve`
                    if (pastBy > RESERVE_MULTIPLIER * referenceReserve) {
                        fee = calculateLinearFeeBipsQ64(pastBy, referenceReserve, referenceReserve);
                    } else {
                        fee = calculateQuadraticFeeBipsQ64(pastBy, referenceReserve, referenceReserve);
                    }

                    // We weight the fee based on how far past the reference reserve
                    fee = Convert.mulDiv(fee, pastBy, input, false);
                }
            }
        }

        fee = Math.max(fee, MIN_FEE_Q64);
    }

    /**
     * @notice Calculates the quadratic fee in Q64 bips.
     * @dev The quadratic fee model charges fees proportional to the square of price movement.
     * Refer to `calculateSwapFeeBipsQ64` NatSpec for the quadratic fee formula.
     *
     * @param input The input amount of the asset (units of the asset).
     * @param currentReserve The current reserve of the input asset in the pool.
     * @param referenceReserve The start-of-block reference reserve for the input asset.
     * @return fee The quadratic fee in Q64 bips.
     */
    function calculateQuadraticFeeBipsQ64(
        uint256 input,
        uint256 currentReserve,
        uint256 referenceReserve
    ) private pure returns (uint256 fee) {
        fee = Convert.mulDiv(
            N_TIMES_BIPS_Q64_PER_PERCENT,
            input + RESERVE_MULTIPLIER * (currentReserve - referenceReserve),
            referenceReserve,
            false
        );
    }

    /**
     * @notice Calculates the linear fee in Q64 bips.
     * @dev The linear fee model charges fees that grow linearly (not quadratically) for extreme price deviations.
     * Refer to `calculateSwapFeeBipsQ64` NatSpec for the linear fee formula.
     *
     * @param input The input amount of the asset (units of the asset).
     * @param currentReserve The current reserve of the input asset in the pool.
     * @param referenceReserve The start-of-block reference reserve for the input asset.
     * @return fee The linear fee in Q64 bips.
     */
    function calculateLinearFeeBipsQ64(
        uint256 input,
        uint256 currentReserve,
        uint256 referenceReserve
    ) private pure returns (uint256 fee) {
        fee = MAX_QUADRATIC_FEE_PERCENT_BIPS
            * (
                TWO_Q64
                    - Convert.mulDiv(
                        referenceReserve,
                        MAX_QUADRATIC_FEE_Q64,
                        N * (input + RESERVE_MULTIPLIER * (currentReserve - referenceReserve)),
                        false
                    )
            );
    }
}

lib/core-v1/contracts/libraries/Saturation.sol

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

import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {SafeCast} from '@openzeppelin/contracts/utils/math/SafeCast.sol';
import {BitLib} from '@mangrovedao/mangrove-core/lib/core/BitLib.sol';
import {MathLib, WAD} from '@morpho-org/morpho-blue/src/libraries/MathLib.sol';

import {Convert} from 'contracts/libraries/Convert.sol';
import {Uint16Set} from 'contracts/libraries/Uint16Set.sol';
import {TickMath} from 'contracts/libraries/TickMath.sol';
import {
    B_IN_Q72,
    BIPS,
    EXPECTED_SATURATION_LTV_MAG2,
    MAG1,
    MAG2,
    MAG4,
    MAG6,
    MAX_SATURATION_RATIO_IN_MAG2,
    MINIMUM_LIQUIDITY,
    Q16,
    Q32,
    Q56,
    Q72,
    Q88,
    Q112,
    Q128,
    Q144,
    Q200,
    TRANCHE_B_IN_Q72,
    TRANCHE_B_MINUS_ONE_IN_Q72,
    SAT_PERCENTAGE_DELTA_DEFAULT_WAD,
    SAT_PERCENTAGE_DELTA_4_WAD,
    SAT_PERCENTAGE_DELTA_5_WAD,
    SAT_PERCENTAGE_DELTA_6_WAD,
    SAT_PERCENTAGE_DELTA_7_WAD,
    ZERO_ADDRESS,
    MAX_SATURATION_PERCENT_IN_WAD,
    MAX_UTILIZATION_PERCENT_IN_WAD,
    LIQUIDITY_INTEREST_RATE_MAGNIFICATION,
    SECONDS_IN_YEAR
} from 'contracts/libraries/constants.sol';
import {Liquidation} from 'contracts/libraries/Liquidation.sol';
import {Validation} from 'contracts/libraries/Validation.sol';
import {
    DEPOSIT_L,
    DEPOSIT_X,
    DEPOSIT_Y,
    BORROW_L,
    BORROW_X,
    BORROW_Y,
    ROUNDING_UP
} from 'contracts/interfaces/tokens/ITokenController.sol';
import {Interest} from 'contracts/libraries/Interest.sol';

/**
 * @title   A lib to maintain the saturation of all the positions
 * @author  [email protected]
 * @author  Will [email protected]
 * @notice  Saturation, or sat, is defined as the net borrow. In theory, we would want to divide net
 *  borrow by the total liquidity; in practice, we keep the net borrow only in the tree. The unit
 *  of sat is relative to active liquidity assets, or the amount of L deposited less the amount
 *  borrowed.
 *
 *  When we determine how much a swap moves the price, or square root price, we can define our
 *  equation using ticks, or tranches (25 ticks), where for some base $b$, the square root price
 *  is $b^t$ for some tick $t$. Alternatively for a larger base $B = b^{25}$ we can define the
 *  square root price as $B^T$ for some tranche $T$. Using the square root price, we can define the
 *  amount of x or y in each tranche as:
 *  ```math
 *  \begin{align*}
 *    x =  L \cdot B^{T_0} - L \cdot B^{T_1} \\
 *    y = \frac{L}{ B^{T_1}} - \frac{L}{B^{T_0}}
 *  \end{align*}
 *  ```
 *  where liquidity is $L = \sqrt{reserveX \cdot reserveY}$. If we want to know how much debt of x
 *  or y can be liquidated within one tick, we can solve these equations for L and then the amount
 *  of x and y are considered the debt we would like to see if it could be liquidated in one tick.
 *  If saturation with respect to our starting $L$ is smaller, that amount of debt can be
 *  liquidated in one swap in the given ticks. Otherwise it is too big and can not. Note that we
 *  assume $$t_1 \text{ and } t_0 \in \mathbb{Z}$$ and $$t_0 + 1 = t_1$$. Then our definition of
 *  saturation relative to L is as follows,
 *
 *  ```math
 *    \begin{equation}
 *      saturationRelativeToL =
 *        \begin{cases}
 *          \frac{ debtX }{ b^{ t_1 } } \left( \frac{ b }{ b - 1 } \right) \\
 *          debtY \cdot b^{ t_0 } \cdot \left( \frac{ b }{ b - 1 } \right)
 *        \end{cases}
 *    \end{equation}
 *   ```
 *  Saturation is kept in a tree, starting with a root, levels and leafs. We keep 2 trees, one for
 *  net X borrows, another for net Y borrows. The price is always the price of Y in units of X.
 *  Mostly, the code works with the sqrt of price. A net X borrow refers to a position that if
 *  liquidated would cause the price to become smaller; the opposite for net Y positions. Ticks are
 *  along the price dimension and int16. Tranches are 25 ticks, stored as int16.
 *
 *  Leafs (uint16) split the sat, which is uint112, into intervals. From left to right, the leafs
 *  of the tree cover the sat space in increasing order. Each account with a position has a price
 *  at which its LTV would reach LTVMAX, which is its liquidation (=liq) price.
 *
 *  To place a debt into the appropriate tranche, we think of each debt and its respective
 *  collateral as a series of sums, where each item in the series fits in one tranche. Using
 *  formulas above, we determine the number of ticks a debt would cross if liquidated. This is
 *  considered the span of the liquidation. Using this value we then determine the start and end
 *  points of the liquidation, where the start would be closer to the prices, on the right of the
 *  end for net debt of x and on the left of the end for net debt of Y.
 *
 *  Once we have the liquidation start, end, and span, we begin to place the debt, one tranche at a
 *  time moving towards the price. In this process we compare the prior recorded saturation and
 *  allow the insertion up to some max, set at 90% or the configuration set by the user.
 *
 *  A Tranche contains multiple accounts and thus a total sat. The tranche's sat assigns it to a
 *  leaf. Each leaf can contain multiple tranches and thus has a total actual sat whilst
 *  representing a specific sat per tranche range. Leafs and thus tranches and thus accounts above
 *  a certain sat threshold are considered over saturated. These accounts are penalized for being
 *  in an over saturated tranche. Each account, tranche and leaf has a total penalty that needs to
 *  be repaid to close the position fully. Sat is distributed over multiple tranches, in case a
 *  single tranche does not have enough available sat left. Sat is kept cumulatively in the tree,
 *  meaning a node contains the sum of the sat of its parents. Updating a sat at the  bottom of the
 *  tree requires updating all parents. Penalty is kept as a path sum, in uints of LAssets, meaning
 *  the penalty of an account is the sum of the penalties of all its parents. Updating the penalty
 *  for a range of leafs only requires updating the appropriate parent. Position (=pos) refers to
 *  the relative index of a child within its parent. Index refers to the index of a node in within
 *  its level
 *
 *  The formula for allocating saturation is derived from,
 *  ```math
 *  \begin{align*}
 *    X = L \cdot \left( b^{t_e} - b^{t_s} \right) \\
 *    Y = L \cdot \left( \frac{1}{b^{t_s}} - \frac{1}{b^{t_e}} \right)
 *  \end{align*}
 *  ```
 *
 *  for the start and end of liquidation $$t_s$$ and $$t_e$$ respectively. When we consider our
 *  buckets of `TICKS_PER_TRANCHE` we can rewrite this as a series where each boundary of each
 *  tranche $$T_i$$ where $$T_0 = t_e \bmod \mathrm{TICKS\_PER\_TRANCHE}$$ for a net debt of X and
 *  $$T_0 = (-t_e) \bmod \mathrm{TICKS\_PER\_TRANCHE}$$ for a net debt of Y and
 *  $$T_i = T_{i-1} + \mathrm{TICKS\_PER\_TRANCHE}$$ for each subsequent tranche and
 *  $$B= b^{\mathrm{TICKS\_PER\_TRANCHE}}$$. Thus we can rewrite the equations as:
 *
 *  ```math
 *  \begin{align*}
 *    X &=
 *      L \left(b^{T_1} - b^{t_e} \right)
 *      + L \left( b^{T_2} - b^{T_1}\right)
 *      + ...
 *      + L \left( b^{T_n} - b^{T_{n-1}}\right)
 *      + L \left(b^{t_s}-b^{T_n}  \right)
 *    \\
 *
 *    \Large\frac{X}{b^{t_e}(B-1)} &=
 *      \Large L \left(
 *        \frac{B \cdot b^{t_e-T_0} - 1}{B-1}
 *        + \frac{ \sum_{i=1}^{n-1} B^{i} }{ b^{t_e-T_0} }
 *        + \frac{B^{n} \left(
 *  \frac{b^{t_s}}{B^{n} \cdot  b^{T_0}}-1 \right) }{ b^{t_e-T_0}(B-1)}
 *        \right)
 *  \end{align*}
 *  ```
 *
 *  We then define the left side of this equation as total saturation $T_{sat}$ or newSaturation as
 *  we call it in the parameter passed in. Saturation is relative to the saturation in one tranche.
 *  The right side of the equation defines the saturation in each tranche $s_i$, starting at the
 *  furthest point from the tranche and moving forward.
 *
 *  ```math
 *  \begin{align*}
 *    T_{sat} &=
 *      s_0
 *      + \frac{\sum_{i=1}^{n-1} s_i \cdot B^{i}}{b^{t_e-T_0}}
 *      + \frac{B^n \cdot  s_n}{b^{t_e-T_0}}
 *    \\
 *
 *    \frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 &=
 *      \left(\sum_{i=2}^{n-1} s_i \cdot B^{i-1} \right)
 *      + B^{n-1} \cdot s_n
 *    \\
 *
 *   \frac{\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 }{ B } -s_2 &=
 *      \left(\sum_{i=2}^{n-1} s_i \cdot B^{i-2} \right)
 *      + B^{n-2} \cdot s_n
 *  \end{align*}
 *  ```
 *
 *  When calculating the case for Y, the result is almost identical, except our definition for
 *  $T_{sat}$ requires us to multiply by $$b^{t_e}$$ rather than divide.
 *
 *  The above shows the logic applied in this function. We can allocate saturation across each
 *  tranche until the total remaining saturation is depleted. We allow less than the ideal
 *  saturation to be consumed if there is less available. Extra saturation is then carried forward
 *  to tranches closer to the price, requiring part of the position to be liquidated sooner as
 *  needed based on the available liquidity.
 *
 *  Two critical nuances of this algorithm is that we reduce by a factor of $$B$$ after each
 *  iteration and we multiply one time by $$b^{t_e - T_0}$$ after we allocate $$s_0$$ one time. The
 *  reduction of $$B$$ each iteration reflects the increase in the size of each tranche relative to
 *  a unit of X or Y as you move from one tranche to the next towards the price. The one time
 *  multiplication of $$b^{t_e - T_0}$$ is an adjustment for the offset of the start of liquidation
 *  relative to the start of the second tranche to minimize the impact of the reduction by $$B$$
 *  since the first portion of saturation does not use an entire tranche.
 *
 *  If saturation reaches the minOrMaxTick, we revert as the position is already reaching the limit
 *  of our probable price range and may require immediate liquidation if opened.
 */
library Saturation {
    // constants

    /**
     * @notice time budget added to sat before adding it to the tree; compensates for the fact that
     * the liq price moves closer to the current price over time.
     */
    uint256 internal constant SATURATION_TIME_BUFFER_IN_MAG2 = 101;

    /**
     * @notice percentage of max sat per tranche where penalization begins
     */
    uint256 internal constant START_SATURATION_PENALTY_RATIO_IN_MAG2 = 85;

    /**
     * @notice maximum initial saturation percentage when adding a new position
     */
    uint256 internal constant MAX_INITIAL_SATURATION_MAG2 = 90;

    /**
     * @notice $$\mathrm{EXPECTED\_SATURATION\_LTV\_MAG2} \cdot \mathrm{SATURATION\_TIME\_BUFFER\_IN\_MAG2}^{2}$$,
     * a constant used in calculations.
     */
    uint256 internal constant EXPECTED_SATURATION_LTV_MAG2_TIMES_SAT_BUFFER_SQUARED = 867_085;

    /**
     * @notice $$\mathrm{EXPECTED\_SATURATION\_LTV\_MAG2} + 100$$, a constant used in calculations.
     */
    uint256 internal constant EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2 = 185;

    /**
     * @notice Slope for calculating premium when resetting saturation for straddle positions
     *         where $$L^2 < X \cdot Y$$ transitions to $$L^2 > X \cdot Y$$. Applied to
     *         $$(L^{2} - X \cdot Y) / (X \cdot Y)$$ to produce `premiumBips`. Matches the
     *         Desmos coefficient $$\frac{BIPS}{10} \cdot 100 = 100000$$. At
     *         $$L^{2} = 1.02 \cdot X \cdot Y$$ the raw premium evaluates to
     *         `MAX_SAT_RESET_FOR_STRADDLE_PREMIUM_BIPS`; past that point the cap engages.
     */
    uint256 internal constant SAT_RESET_FOR_STRADDLE_SLOPE_BIPS = 100_000;

    /**
     * @notice Maximum premium when resetting saturation for zero-to-positive straddle positions.
     */
    uint256 internal constant MAX_SAT_RESET_FOR_STRADDLE_PREMIUM_BIPS = 2000;

    /**
     * @notice a constant used to change the log base from the tick math base to the saturation to
     * leaf base.
     */
    uint256 private constant SAT_CHANGE_OF_BASE_Q128 = 0xa39713406ef781154a9e682c2331a7c03;

    /**
     * @notice a constant used to shift when changing the base from tick math base to the
     * saturation leaf base.
     */
    uint256 private constant SAT_CHANGE_OF_BASE_TIMES_SHIFT = 0xb3f2fb93ad437464387b0c308d1d05537;

    /**
     * @notice tick offset added to ensure leaf calculation starts from 0 at the lowest leaf
     */
    int16 private constant TICK_OFFSET = 1112;

    /**
     * @notice the lowest possible saturation is always in penalty
     * $$MAX\_ASSETS \cdot \mathrm{START\_SATURATION\_PENALTY\_RATIO\_IN\_MAG2} / \mathrm{TICKS\_PER\_TRANCHE}$$
     */
    uint256 internal constant LOWEST_POSSIBLE_IN_PENALTY = 0xd9999999999999999999999999999999;

    /**
     * @notice the minimum liquidity to reach the possibility of being in penalty.
     * $$MINIMUM\_LIQUIDITY \cdot \mathrm{START\_SATURATION\_PENALTY\_RATIO\_IN\_MAG2} / \mathrm{TICKS\_PER\_TRANCHE}$$
     */
    uint256 private constant MIN_LIQ_TO_REACH_PENALTY = 850;

    /**
     * @notice Constant number one as an int type. Used for rounding or iterating direction.
     */
    int256 private constant INT_ONE = 1;

    /**
     * @notice Constant number negative one. Used for rounding or iterating direction.
     */
    int256 private constant INT_NEGATIVE_ONE = -1;

    /**
     * @notice Constant number zero as an int type. Used for rounding or iterating direction.
     */
    int256 private constant INT_ZERO = 0;

    /**
     * @notice Tree leafs are on level LEVELS_WITHOUT_LEAFS; root is level 0
     */
    uint256 internal constant LEVELS_WITHOUT_LEAFS = 3;

    /**
     * @notice for convenience, since used a lot, ==LEVELS_WITHOUT_LEAFS - 1
     */
    uint256 internal constant LOWEST_LEVEL_INDEX = 2;

    /**
     * @notice $$2^{\mathrm{LEAFS\_IN\_BITS}}$$
     */
    uint256 internal constant LEAFS = 4096;

    /**
     * @notice $$2^4$$
     */
    uint256 internal constant CHILDREN_PER_NODE = 16;

    /**
     * @notice $$2^{2 \cdot 4}$$
     */
    uint256 private constant CHILDREN_AT_THIRD_LEVEL = 256;

    /**
     * @notice $$b = \frac{2^9}{2^9-1}$$ is the base for ticks, then the tranche base is
     * $$B = b^{\mathrm{TICKS\_PER\_TRANCHE}}$$, int only to not need casting below, equals TICKS_PER_TRANCHE
     */
    int256 internal constant TICKS_PER_TRANCHE = 25;

    /**
     * @notice for convenience, used to determine max sat per tranche to not cross in liq swap:
     * $$\frac{B}{B-1}$$
     */
    uint256 constant TRANCHE_BASE_OVER_BASE_MINUS_ONE_Q72 = 0x5a19b9039a07efd7b39;

    /**
     * @notice `TickMath.MIN_TICK / TICKS_PER_TRANCHE - 1;` // -1 to floor
     */
    int256 internal constant MIN_TRANCHE = -795;

    /**
     * @notice `TickMath.MAX_TICK / TICKS_PER_TRANCHE;`
     */
    int256 internal constant MAX_TRANCHE = 794;

    //
    /**
     * @notice constants for bit reading and writing in nodes.
     * `type(uint256).max >> (TOTAL_BITS - FIELD_BITS);`
     */
    uint256 private constant FIELD_NODE_MASK = 0xffff;

    /**
     * @notice Buffer space (in tranches) allowed above the highest used tranche before hitting
     * maxLeaf limit
     */
    uint8 internal constant SATURATION_MAX_BUFFER_TRANCHES = 3;

    /**
     * @notice Twenty-five percent magnitude of two.
     */
    uint256 private constant QUARTER_OF_MAG2 = 25;

    /**
     * @notice Twenty-five percent minus one magnitude of two.
     */
    uint256 private constant QUARTER_MINUS_ONE = 24;

    /**
     * @notice quarters per tranche.
     */
    uint256 private constant NUMBER_OF_QUARTERS = 4;

    /**
     * @notice $$2 \cdot 2^{72}$$, used in saturation formula.
     */
    uint256 private constant TWO_Q72 = 0x2000000000000000000;

    /**
     * @notice $$4 \cdot 2^{128}$$, needed in quadratic formula is saturation.
     */
    uint256 private constant FOUR_Q144 = 0x4000000000000000000000000000000000000;

    /**
     * @notice $$MAG4 \cdot Q72$$ constant needed in formula.
     */
    uint256 private constant MAG4_TIMES_Q72 = 0x2710000000000000000000;

    /**
     * @notice $$b^2 \cdot Q72 - 1$$ used to round up results of `TickMath.getTickAtPrice()`.
     */
    uint256 private constant B_SQUARED_Q72_MINUS_ONE = 0x10100c08050301c1008;

    /**
     * @notice A large number that will not overflow when multiplied by `B_SQUARED_Q72_MINUS_ONE`
     * $$\left\lfloor \frac{ 2^{ 256 } }{ B\_SQUARED\_Q72\_MINUS\_ONE } \right\rfloor$$
     */
    uint256 private constant Q183 = 0x8000000000000000000000000000000000000000000000;

    /**
     * @notice $$\mathrm{TICKS\_PER\_TRANCHE} \cdot MAG2$$ used for calculating available liquidity.
     */
    uint256 private constant TICKS_PER_TRANCHE_MAG2 = 2500;

    // errors

    /**
     * @notice if the largest sat in the trees is too large
     */
    error MaxTrancheOverSaturated();

    /**
     * @notice raised if the start of liquidation would occur on the wrong side of the min or max
     *  tick price from the GeometricTWAP.
     */
    error LiquidationPassesMinOrMaxTick();

    /**
     * @notice raised if the the available saturation is not sufficient to keep the start of
     *  liquidation from reaching the wrong side of the min or max tick price from the
     *  GeometricTWAP.
     */
    error SaturationReachesMinOrMaxTick();

    // storage structs

    /**
     * @notice final structure containing all the storage data
     */
    struct SaturationStruct {
        // the tree containing sat and penalties for netX sat
        Tree netXTree;
        // the tree containing sat and penalties for netY sat
        Tree netYTree;
        uint16 maxLeaf;
    }

    /**
     * @notice the main storage type of tree struct within the `SaturationStruct`.
     */
    struct Tree {
        // is this tree netX xor not
        bool netX;
        // highest leaf that contains a tranche/account in the tree, useful to quickly decide whether the entire tree is over saturated
        uint16 highestSetLeaf;
        // nodes per level, each node contains a bit field of size of the number of its children
        // and a uint112 saturation
        uint128 totalSatInLAssets;
        uint256[][LEVELS_WITHOUT_LEAFS] nodes;
        // last level of nodes is kept as leafs
        Leaf[LEAFS] leafs;
        // which leaf does a tranche belong to
        mapping(int16 => uint16) trancheToLeaf;
        // sat per tranche
        mapping(int16 => SaturationPair) trancheToSaturation;
        // data per account
        mapping(address => Account) accountData;
        // cumulative penalty adjustment per tranche, bridging leaf penalty gaps when tranche moves
        mapping(int16 => int256) tranchePenaltyAdjustment;
    }

    /**
     * @notice a leaf contains multiple tranches and contains the total sat and penalty for the leaf
     */
    struct Leaf {
        // set of tranches in a leaf
        Uint16Set.Set tranches;
        // sum of sat of each tranche in this leaf
        SaturationPair leafSatPair;
        // penalty for the leaf
        uint256 penaltyInBorrowLSharesPerSatInQ72;
    }

    /**
     * @notice basic data per account associated with an address stored in the `Tree` struct in a
     * map as the value associated with the owners address as the key.
     */
    struct Account {
        //does account exist, needed as accountToTranche has default value 0 and tranche 0 is ok
        bool exists;
        // tranche that account belongs to
        int16 lastTranche;
        // penalty of account
        uint112 penaltyInBorrowLShares;
        // sat per tranche starting at `tranche` and running in the direction dictated by
        // netX/netY; netX trees have us distributing sat over increasing tranches, netY over
        // decreasing tranches, in both cases, towards the current price
        SaturationPair[] satPairPerTranche;
        // penalty per sat per tranche starting at `tranche` and running in the direction dictated
        // by netX/netY; netX trees have us distributing sat over increasing tranches, netY over
        // decreasing tranches, in both cases, towards the current price
        uint256[] treePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche;
    }

    // memory structs

    /**
     * @notice used in memory to avoid stack overflow in `calcLiqSqrtPriceQ72()`.
     */
    struct CalcLiqSqrtPriceHandleAllABCNonZeroStruct {
        int256 netLInMAG2;
        int256 netXInMAG2;
        int256 netYInMAG2;
        uint256 netYAbsInMAG2;
        uint256 borrowedXAssets;
        uint256 borrowedYAssets;
    }

    /**
     * @notice used in memory to avoid stack overflow in `addSatToTranche()`.
     */
    struct AddSatToTrancheStateUpdatesStruct {
        int256 tranche;
        uint256 newLeaf;
        SaturationPair oldTrancheSaturation;
        SaturationPair newTrancheSaturation;
        SaturationPair satAvailableToAdd;
        uint256 targetCapacityRelativeToLAssets;
        address account;
    }

    /**
     * @notice a pair of saturation values used and stored throughout this library.
     */
    struct SaturationPair {
        // the value of a debt in units of L assets at a given liquidation price.
        uint128 satInLAssets;
        // the amount of active liquidity assets, L, that the swap required to liquidate the debt
        // would consume.
        uint128 satRelativeToL;
    }

    // init functions

    /**
     * @notice  initializes the satStruct, allocating storage for all nodes
     * @dev     initCheck can be removed once the tree structure is fixed
     * @param   satStruct contains the entire sat data
     */
    function initializeSaturationStruct(
        SaturationStruct storage satStruct
    ) internal {
        // init nodes in storage
        initTree(satStruct.netXTree);
        // init nodes in storage
        initTree(satStruct.netYTree);
        // set 1 of the tree to netX, the other stays netY by default
        satStruct.netXTree.netX = true;
    }

    /**
     * @notice  init the nodes of the tree
     * @param   tree that is being read from or written to
     */
    function initTree(
        Tree storage tree
    ) internal {
        tree.nodes[0] = new uint256[](1);
        tree.nodes[1] = new uint256[](CHILDREN_PER_NODE);
        tree.nodes[2] = new uint256[](CHILDREN_AT_THIRD_LEVEL);
    }

    // update functions

    /**
     * @notice  update the borrow position of an account and potentially check (and revert) if the
     * resulting sat is too high
     * @dev     run accruePenalties before running this function
     * @param   satStruct  main data struct
     * @param   inputParams  contains the position and pair params, like account borrows/deposits,
     * current price and active liquidity
     * @param   account  for which is position is being updated
     */
    function update(
        SaturationStruct storage satStruct,
        Validation.InputParams memory inputParams,
        address account,
        uint256 userSaturationRatioMAG2,
        bool skipMinOrMaxTickCheck
    ) internal {
        if (account != ZERO_ADDRESS) {
            SaturationPair memory zeroSat = SaturationPair({satRelativeToL: 0, satInLAssets: 0});

            // if the account has no borrow position, it could be getting repaid
            if (!inputParams.hasBorrow) {
                updateTreeGivenAccountTrancheAndSat(
                    satStruct.netXTree,
                    zeroSat,
                    account,
                    0,
                    inputParams.activeLiquidityAssets,
                    0,
                    userSaturationRatioMAG2
                );

                updateTreeGivenAccountTrancheAndSat(
                    satStruct.netYTree,
                    zeroSat,
                    account,
                    0,
                    inputParams.activeLiquidityAssets,
                    0,
                    userSaturationRatioMAG2
                );
            } else {
                // calc the netX and netY prices where the position would reach LTVMAX
                (uint256 netXLiqSqrtPriceInXInQ72, uint256 netYLiqSqrtPriceInXInQ72) =
                    calcLiqSqrtPriceQ72(inputParams.userAssets);

                // if a netX exists, update the netX tree
                if (0 < netXLiqSqrtPriceInXInQ72) {
                    (SaturationPair memory saturation, int256 endOfLiquidationInTicks, int256 minTick) =
                    calcLastTickAndSaturation(
                        inputParams,
                        netXLiqSqrtPriceInXInQ72,
                        netYLiqSqrtPriceInXInQ72,
                        userSaturationRatioMAG2,
                        true,
                        skipMinOrMaxTickCheck
                    );

                    updateTreeGivenAccountTrancheAndSat(
                        satStruct.netXTree,
                        saturation,
                        account,
                        endOfLiquidationInTicks,
                        inputParams.activeLiquidityAssets,
                        minTick,
                        userSaturationRatioMAG2
                    );
                } else if (satStruct.netXTree.accountData[account].exists) {
                    updateTreeGivenAccountTrancheAndSat(
                        satStruct.netXTree,
                        zeroSat,
                        account,
                        0,
                        inputParams.activeLiquidityAssets,
                        0,
                        userSaturationRatioMAG2
                    );
                }

                // if a netY exists, update the netY tree
                if (0 < netYLiqSqrtPriceInXInQ72) {
                    (SaturationPair memory saturation, int256 endOfLiquidationInTicks, int256 maxTick) =
                    calcLastTickAndSaturation(
                        inputParams,
                        netXLiqSqrtPriceInXInQ72,
                        netYLiqSqrtPriceInXInQ72,
                        userSaturationRatioMAG2,
                        false,
                        skipMinOrMaxTickCheck
                    );

                    updateTreeGivenAccountTrancheAndSat(
                        satStruct.netYTree,
                        saturation,
                        account,
                        endOfLiquidationInTicks,
                        inputParams.activeLiquidityAssets,
                        maxTick,
                        userSaturationRatioMAG2
                    );
                } else if (satStruct.netYTree.accountData[account].exists) {
                    updateTreeGivenAccountTrancheAndSat(
                        satStruct.netYTree,
                        zeroSat,
                        account,
                        0,
                        inputParams.activeLiquidityAssets,
                        0,
                        userSaturationRatioMAG2
                    );
                }
            }
        }

        uint256 maxLeaf = satToLeaf(inputParams.activeLiquidityAssets);
        // check whether the max sat is too high
        if (
            maxLeaf
                < Math.max(satStruct.netXTree.highestSetLeaf, satStruct.netYTree.highestSetLeaf)
                    + SATURATION_MAX_BUFFER_TRANCHES
        ) {
            revert MaxTrancheOverSaturated();
        }

        satStruct.maxLeaf = uint16(maxLeaf);
    }

    /**
     * @notice  internal update that removes the account from the tree (if it exists) from its prev
     * position and adds it to its new position
     * @param   tree that is being read from or written to
     * @param   newSaturation  the new sat of the account, in units of LAssets (absolute) and
     * relative to active liquidity
     * @param   account  whos position is being considered
     * @param   newEndOfLiquidationInTicks the new tranche of the account in mag2.
     * @param   activeLiquidityInLAssets  of the pair
     */
    function updateTreeGivenAccountTrancheAndSat(
        Tree storage tree,
        SaturationPair memory newSaturation,
        address account,
        int256 newEndOfLiquidationInTicks,
        uint256 activeLiquidityInLAssets,
        int256 minOrMaxTick,
        uint256 userSaturationRatioMAG2
    ) internal {
        // flag whether the highest sat needs updating
        bool highestSetLeafRemoved;
        bool highestSetLeafAdded;

        // if account exists at all, remove from the tree
        if (tree.accountData[account].exists) {
            highestSetLeafRemoved = removeSatFromTranche(tree, account);
        }

        // if the account has any sat, add to the tree
        if (0 < newSaturation.satRelativeToL) {
            highestSetLeafAdded = addSatToTranche(
                tree,
                account,
                newEndOfLiquidationInTicks,
                newSaturation,
                activeLiquidityInLAssets,
                userSaturationRatioMAG2,
                minOrMaxTick
            );
        }

        // update highestSetLeaf
        if (highestSetLeafRemoved && !highestSetLeafAdded) {
            unchecked {
                tree.highestSetLeaf =
                    uint16(findHighestSetLeafUpwards(tree, LOWEST_LEVEL_INDEX, tree.highestSetLeaf / CHILDREN_PER_NODE));
            }
        }
    }

    /**
     * @notice  remove sat from tree, for each tranche in a loop that could hold sat for the account
     * @param   tree that is being read from or written to
     * @param   account whose position is being considered
     * @return  highestSetLeafRemoved  flag indicating whether we removed sat from the highest leaf
     * xor not
     */
    function removeSatFromTranche(Tree storage tree, address account) internal returns (bool highestSetLeafRemoved) {
        // beginning tranche
        int256 tranche = tree.accountData[account].lastTranche;
        uint256 satArrayLength = tree.accountData[account].satPairPerTranche.length;
        // loop through each tranche that could contain sat, we cannot short circuit as we might have added sat to the last tranche
        for (uint256 trancheIndex = 0; trancheIndex < satArrayLength; trancheIndex++) {
            // if we have reached the edges of price, we are definitely done
            if (MAX_TRANCHE < tranche || tranche < MIN_TRANCHE) break;

            SaturationPair memory oldAccountSaturationInTranche =
                tree.accountData[account].satPairPerTranche[trancheIndex];
            // if the account had no sat in this tranche, move to next tranche
            if (0 < oldAccountSaturationInTranche.satRelativeToL) {
                // remember old leaf before state update
                uint256 oldLeaf = tree.trancheToLeaf[int16(tranche)];

                // update sat, fields and penalties for leafs, parents
                removeSatFromTrancheStateUpdates(tree, oldAccountSaturationInTranche, tranche, oldLeaf);

                uint256 highestSetLeaf = tree.highestSetLeaf;
                bool isLeafEmpty = Uint16Set.count(tree.leafs[highestSetLeaf].tranches) == 0;
                if (oldLeaf == highestSetLeaf && isLeafEmpty) {
                    highestSetLeafRemoved = true;
                }
            }

            // move to next tranche
            unchecked {
                tranche += trancheDirection(tree.netX);
            }
        }
        // we have removed the account from the tree and update the state of the account
        delete tree.accountData[account];
    }

    /**
     * @notice  depending on old and new leaf of the tranche, update the sats, fields and penalties
     * of the tree
     * @param   tree that is being read from or written to
     * @param   oldAccountSaturationInTranche account sat
     * @param   tranche  under consideration
     * @param   oldLeaf where tranche was located before this sat removal
     */
    function removeSatFromTrancheStateUpdates(
        Tree storage tree,
        SaturationPair memory oldAccountSaturationInTranche,
        int256 tranche,
        uint256 oldLeaf
    ) internal {
        // old sat of tranche (both absolute and relative)
        SaturationPair memory oldTrancheSaturation = tree.trancheToSaturation[int16(tranche)];

        // tranche sat decreases by removed account sat, account can not be greater than tranche of
        // accounts
        SaturationPair memory newTrancheSaturation;
        unchecked {
            newTrancheSaturation.satRelativeToL =
                oldTrancheSaturation.satRelativeToL - oldAccountSaturationInTranche.satRelativeToL;
            newTrancheSaturation.satInLAssets =
                oldTrancheSaturation.satInLAssets - oldAccountSaturationInTranche.satInLAssets;
        }

        // Use relative saturation for satToLeaf calculation
        uint256 newLeaf = satToLeaf(newTrancheSaturation.satRelativeToL);

        // update both absolute and relative saturation
        tree.trancheToSaturation[int16(tranche)] = newTrancheSaturation;

        if (newTrancheSaturation.satRelativeToL == 0) {
            // case remove tranche from tree. Reset the per-tranche penalty adjustment so a
            // future account joining this tranche key starts a fresh lifecycle. Required to
            // maintain the invariant `leafPen + adjustment >= 0` — see `getEffectivePenalty`.
            removeTrancheToLeaf(tree, oldTrancheSaturation, tranche, oldLeaf);
            delete tree.tranchePenaltyAdjustment[int16(tranche)];
        } else if (newLeaf < oldLeaf) {
            // case change to lower leaf, since we are removing sat
            addSatToTrancheStateUpdatesHigherLeaf(
                tree, tranche, oldTrancheSaturation, newTrancheSaturation, oldLeaf, newLeaf
            );
        } else {
            // case change to same leaf, oldLeaf == newLeaf, less updating needed

            // decrease leaf sat (both absolute and relative)
            tree.leafs[newLeaf].leafSatPair.satInLAssets -= oldAccountSaturationInTranche.satInLAssets;
            tree.leafs[newLeaf].leafSatPair.satRelativeToL -= oldAccountSaturationInTranche.satRelativeToL;
            unchecked {
                // update sat up the tree (use absolute saturation)
                addSatUpTheTree(tree, oldAccountSaturationInTranche.satInLAssets, false);
                // penalty offset stays the same
            }
        }
        // case oldLeaf < newLeaf does not exist
    }

    /**
     * @notice  add sat to tree, for each tranche in a loop as needed. we add to each tranche as
     *          much as it can bear.
     *          Saturation Distribution Logic
     *
     *          This function distributes debt across multiple tranches, maintaining two types of
     *          saturation:
     *          1. satInLAssets: The absolute debt amount in L assets (should remain constant total)
     *          2. satRelativeToL: The relative saturation that depends on the tranche's price level
     *
     *          As we move between tranches (different price levels), the same absolute debt
     *          translates to different relative saturations due to the price-dependent formula.
     *
     *          conceptually satInLAssets should not be scaled as it represents actual debt that
     *          doesn't change with price.
     *
     *          The formula applied here, derived in the introduction, is,
     *          ```math
     *          \begin{align*}
     *            T_{sat} &=
     *              s_0
     *              + \frac{\sum_{i=1}^{n-1} s_i \cdot B^{i}}{b^{t_e-T_0}}
     *              + \frac{B^n \cdot  s_n}{b^{t_e-T_0}}
     *            \\
     *
     *            \frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 &=
     *              \left(\sum_{i=2}^{n-1} s_i \cdot B^{i-1} \right)
     *              + B^{n-1} \cdot s_n
     *            \\
     *
     *           \frac{\frac{(T_{sat} - s_0)b^{t_e-T_0}}{B} - s_1 }{ B } -s_2 &=
     *              \left(\sum_{i=2}^{n-1} s_i \cdot B^{i-2} \right)
     *              + B^{n-2} \cdot s_n
     *          \end{align*}
     *          ```
     * @param   tree that is being read from or written to
     * @param   account whose position is being considered
     * @param   newEndOfLiquidationInTicks the new tranche of the account location in MAG2
     * @param   newSaturation the new sat of the account, in units of LAssets (absolute) and
     *   relative to active liquidity
     * @param   activeLiquidityInLAssets of the pair
     * @return  highestSetLeafAdded flag indicating whether we removed sat from the highest leaf
     *   xor not
     */
    function addSatToTranche(
        Tree storage tree,
        address account,
        int256 newEndOfLiquidationInTicks,
        SaturationPair memory newSaturation,
        uint256 activeLiquidityInLAssets,
        uint256 userSaturationRatioMAG2,
        int256 minOrMaxTick
    ) internal returns (bool highestSetLeafAdded) {
        bool netDebtX = tree.netX;
        // `nextTranche` starts as the last tranche and moves forward to the first.
        (uint256 usableTicks, int256 nextTranche) = getUsableTicksAndLastTranche(newEndOfLiquidationInTicks, netDebtX);

        usableTicks = restrictUsableTicksForMinOrMaxTick(usableTicks, nextTranche, minOrMaxTick, netDebtX);

        tree.accountData[account].lastTranche = int16(nextTranche);

        uint256 endOfLiquidationAdjustmentQ72 =
            calculateEndOfLiquidationAdjustment(newEndOfLiquidationInTicks, netDebtX);

        // keep adding sat to tranches as long as more needs adding
        while (0 < newSaturation.satRelativeToL) {
            if (
                (netDebtX && nextTranche * TICKS_PER_TRANCHE >= minOrMaxTick)
                    || (!netDebtX && (nextTranche + 1) * TICKS_PER_TRANCHE <= minOrMaxTick)
            ) {
                revert SaturationReachesMinOrMaxTick();
            }

            // if we have reached the edges of price, we are definitely done
            if (MAX_TRANCHE < nextTranche || nextTranche < MIN_TRANCHE) break;

            // convenience struct to avoid 'stack too deep'
            AddSatToTrancheStateUpdatesStruct memory addSatToTrancheStateUpdatesParams =
            getAddSatToTrancheStateUpdatesParams(
                tree,
                account,
                nextTranche,
                newSaturation,
                activeLiquidityInLAssets,
                userSaturationRatioMAG2,
                usableTicks
            );

            // if we have nothing to add to this tranche (it is full), move to the next
            if (0 < addSatToTrancheStateUpdatesParams.satAvailableToAdd.satRelativeToL) {
                // update the sat per tranche
                tree.accountData[account].satPairPerTranche.push(
                    SaturationPair({
                        satInLAssets: addSatToTrancheStateUpdatesParams.satAvailableToAdd.satInLAssets,
                        satRelativeToL: addSatToTrancheStateUpdatesParams.satAvailableToAdd.satRelativeToL
                    })
                );
                // update sat, fields and penalties for leafs, parents
                tree.accountData[account].treePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche.push(
                    addSatToTrancheStateUpdates(tree, addSatToTrancheStateUpdatesParams)
                );
                // if we have a new highest leaf, we set this to true so the caller knows the
                // highestSetLeaf needs updating.
                if (tree.highestSetLeaf < addSatToTrancheStateUpdatesParams.newLeaf) {
                    tree.highestSetLeaf = uint16(addSatToTrancheStateUpdatesParams.newLeaf);
                    highestSetLeafAdded = true;
                }
            } else {
                // Keep one array slot per traversed tranche so index-to-tranche mapping
                // (lastTranche + i * direction) remains aligned for removal/penalty loops.
                tree.accountData[account].satPairPerTranche.push(SaturationPair({satInLAssets: 0, satRelativeToL: 0}));
                tree.accountData[account].treePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche.push(0);
            }

            unchecked {
                // we have less to add for the next tranches
                newSaturation.satRelativeToL -= addSatToTrancheStateUpdatesParams.satAvailableToAdd.satRelativeToL;
                newSaturation.satInLAssets -= addSatToTrancheStateUpdatesParams.satAvailableToAdd.satInLAssets;

                if (newSaturation.satRelativeToL > 0) {
                    // decrease only relative saturation by a factor of B (absolute debt doesn't
                    // change with price) safe to cast since it makes the value smaller.
                    newSaturation.satRelativeToL = uint128(
                        Convert.mulDiv(
                            newSaturation.satRelativeToL, endOfLiquidationAdjustmentQ72, TRANCHE_B_IN_Q72, false
                        )
                    );

                    // We only need to adjust by this factor once.
                    endOfLiquidationAdjustmentQ72 = Q72;

                    // move to next tranche
                    nextTranche += trancheDirection(netDebtX);
                    // Suggested change
                    // use all available ticks in tranche for the next iteration.
                    usableTicks = restrictUsableTicksForMinOrMaxTick(
                        uint256(TICKS_PER_TRANCHE), nextTranche, minOrMaxTick, netDebtX
                    );
                }
            }
        }

        // account exists in the tree now
        tree.accountData[account].exists = true;
    }

    /**
     * @notice get the number of ticks in the tranche that can be used based on where the
     *   liquidation ends.
     * @dev we approximate the this calculation using a percentage of ticks available.
     */
    function getUsableTicksAndLastTranche(
        int256 endOfLiquidationTick,
        bool netDebtX
    ) internal pure returns (uint256 usableTicks, int256 lastTranche) {
        int256 modResult = endOfLiquidationTick % TICKS_PER_TRANCHE;
        lastTranche = endOfLiquidationTick / TICKS_PER_TRANCHE;

        if ((modResult == 0 && !netDebtX) || (modResult != 0 && endOfLiquidationTick < 0)) {
            lastTranche += INT_NEGATIVE_ONE;
        }

        modResult = netDebtX ? -modResult : modResult;
        usableTicks = uint256(modResult < 0 ? modResult + TICKS_PER_TRANCHE : modResult);
        usableTicks = usableTicks == 0 ? uint256(TICKS_PER_TRANCHE) : usableTicks;
    }

    /**
     * @notice when the min or max tick bounding our price estimate is reached while allocating
     *   saturation, we limit how much of that tranche can be used so that we don't exceed the
     *   liquidation capacity of the tranche closest to the price with the given position.
     */
    function restrictUsableTicksForMinOrMaxTick(
        uint256 initialUsableTicks,
        int256 nextTranche,
        int256 minOrMaxTick,
        bool netDebtX
    ) internal pure returns (uint256 usableTicks) {
        int256 trancheToTicks = nextTranche * TICKS_PER_TRANCHE;
        uint256 subtract;

        if (netDebtX && minOrMaxTick < trancheToTicks + TICKS_PER_TRANCHE) {
            if (trancheToTicks < minOrMaxTick) {
                // reduce usable ticks by the min or max tick that is within the current tranche
                int256 minOrMaxTickMod25 = minOrMaxTick % TICKS_PER_TRANCHE;
                subtract = Math.min(
                    initialUsableTicks,
                    uint256(minOrMaxTick < 0 ? -minOrMaxTickMod25 : TICKS_PER_TRANCHE - minOrMaxTickMod25)
                );
            } else {
                // min tick is below the current tranche
                subtract = initialUsableTicks;
            }
        } else if (!netDebtX && minOrMaxTick > trancheToTicks) {
            if (trancheToTicks + TICKS_PER_TRANCHE > minOrMaxTick) {
                // reduce usable ticks by the min or max tick that is within the current tranche
                int256 minOrMaxTickMod25 = minOrMaxTick % TICKS_PER_TRANCHE;
                subtract = Math.min(
                    initialUsableTicks,
                    uint256(minOrMaxTick < 0 ? TICKS_PER_TRANCHE + minOrMaxTickMod25 : minOrMaxTickMod25)
                );
            } else {
                // max tick is above the current tranche
                subtract = initialUsableTicks;
            }
        }

        // subtract is always the minimum of initialUsableTicks and some calculated quantity.
        unchecked {
            usableTicks = initialUsableTicks - subtract;
        }
    }

    /**
     * @notice  helper function for adding saturation to appropriate tranches for the given
     *   parameters.
     * @param   tree that is being read from or written to
     * @param   account whose position is being considered
     * @param   tranche under consideration
     * @param   newSaturation the saturation values to add
     * @param   activeLiquidityInLAssets of the pair
     * @param   userSaturationRatioMAG2 user saturation ratio
     * @param   usableTicks number of ticks available to use
     * @return  addSatToTrancheStateUpdatesParams the struct with required params to
     */
    function getAddSatToTrancheStateUpdatesParams(
        Tree storage tree,
        address account,
        int256 tranche,
        SaturationPair memory newSaturation,
        uint256 activeLiquidityInLAssets,
        uint256 userSaturationRatioMAG2,
        uint256 usableTicks
    ) internal view returns (AddSatToTrancheStateUpdatesStruct memory addSatToTrancheStateUpdatesParams) {
        SaturationPair memory oldTrancheSaturation = tree.trancheToSaturation[int16(tranche)];

        // calculate how much relative sat can be added
        (uint128 satAvailableToAddRelativeToL, uint256 targetCapacityRelativeToLAssets) = calcSatAvailableToAddToTranche(
            activeLiquidityInLAssets,
            newSaturation.satRelativeToL,
            oldTrancheSaturation.satRelativeToL,
            userSaturationRatioMAG2,
            usableTicks
        );

        // Calculate absolute sat to add based on available space and remaining debt
        uint128 satAvailableToAddInLAssets;
        if (satAvailableToAddRelativeToL == newSaturation.satRelativeToL) {
            // We can add all remaining debt to this tranche
            satAvailableToAddInLAssets = newSaturation.satInLAssets;
        } else {
            // We can only add a portion of the debt to this tranche based on relative saturation
            // limits keeping the percentage of both absolute and relative saturation the same.
            // Safe to cast since we make satInLAssets smaller since we make
            // $$satAvailableToAddRelativeToL < newSaturation.satRelativeToL$$
            // in `calcSatAvailableToAddToTranche()`
            satAvailableToAddInLAssets = uint128(
                Convert.mulDiv(
                    satAvailableToAddRelativeToL, newSaturation.satInLAssets, newSaturation.satRelativeToL, false
                )
            );
        }

        SaturationPair memory newTrancheSaturation;
        newTrancheSaturation.satInLAssets = oldTrancheSaturation.satInLAssets + satAvailableToAddInLAssets;
        newTrancheSaturation.satRelativeToL = oldTrancheSaturation.satRelativeToL + satAvailableToAddRelativeToL;

        uint256 newLeaf = satToLeaf(newTrancheSaturation.satRelativeToL);

        addSatToTrancheStateUpdatesParams = AddSatToTrancheStateUpdatesStruct({
            tranche: tranche,
            newLeaf: newLeaf,
            oldTrancheSaturation: oldTrancheSaturation,
            newTrancheSaturation: newTrancheSaturation,
            satAvailableToAdd: SaturationPair({
                satInLAssets: satAvailableToAddInLAssets,
                satRelativeToL: satAvailableToAddRelativeToL
            }),
            targetCapacityRelativeToLAssets: targetCapacityRelativeToLAssets,
            account: account
        });
    }

    /**
     * @notice  depending on old and new leaf of the tranche, update the sats, fields and penalties
     * of the tree
     * @param   tree that is being read from or written to
     * @param   params  convenience struct holding params needed for these updates
     */
    function addSatToTrancheStateUpdates(
        Tree storage tree,
        AddSatToTrancheStateUpdatesStruct memory params
    ) internal returns (uint256) {
        // stack for gas savings
        int256 tranche = params.tranche;
        SaturationPair memory newTrancheSaturation = params.newTrancheSaturation;
        uint256 newLeaf = params.newLeaf;

        // Handle leaf transitions
        uint256 oldLeaf = tree.trancheToLeaf[int16(tranche)];

        // update sat of tranche
        tree.trancheToSaturation[int16(tranche)] = newTrancheSaturation;

        unchecked {
            if (
                oldLeaf == 0
                    && !Uint16Set.exists(tree.leafs[oldLeaf].tranches, uint16(uint256(tranche + MAX_TRANCHE + 1)))
            ) {
                // case tranche does not exist in tree, only add
                addTrancheToLeaf(tree, newTrancheSaturation, tranche, newLeaf);
            } else if (oldLeaf < newLeaf) {
                // case change to higher leaf, since we are adding sat
                addSatToTrancheStateUpdatesHigherLeaf(
                    tree, tranche, params.oldTrancheSaturation, newTrancheSaturation, oldLeaf, newLeaf
                );
            } else {
                // increase leaf sat (both absolute and relative)
                tree.leafs[newLeaf].leafSatPair.satInLAssets += params.satAvailableToAdd.satInLAssets;
                tree.leafs[newLeaf].leafSatPair.satRelativeToL += params.satAvailableToAdd.satRelativeToL;

                // update sat up the tree (use absolute saturation)
                addSatUpTheTree(tree, params.satAvailableToAdd.satInLAssets, true);
            }
        }

        return getEffectivePenalty(tree, newLeaf, tranche);
    }

    /**
     * @notice  Add sat to tranche state updates higher leaf
     * @param   tree that is being read from or written to
     * @param   tranche  the tranche that is being moved
     * @param   oldTrancheSaturation  the old sat of the tranche
     * @param   newTrancheSaturation  the new sat of the tranche
     * @param   oldLeaf  the leaf that the tranche was located in before it was removed
     * @param   newLeaf  the leaf that the tranche was located in after it was removed
     */
    function addSatToTrancheStateUpdatesHigherLeaf(
        Tree storage tree,
        int256 tranche,
        SaturationPair memory oldTrancheSaturation,
        SaturationPair memory newTrancheSaturation,
        uint256 oldLeaf,
        uint256 newLeaf
    ) internal {
        // Accumulate penalty adjustment before modifying leaf state.
        // Bridges the gap between old and new leaf penalty accumulators. `SafeCast.toInt256`
        // guards the uint→int conversion against the (astronomically unlikely) case where a
        // leaf penalty exceeds `type(int256).max`.
        tree.tranchePenaltyAdjustment[int16(tranche)] += SafeCast.toInt256(
            getPenaltySharesPerSatFromLeaf(tree, oldLeaf)
        ) - SafeCast.toInt256(getPenaltySharesPerSatFromLeaf(tree, newLeaf));

        // remove from old leaf by updating sats and fields
        removeTrancheToLeaf(tree, oldTrancheSaturation, tranche, oldLeaf);
        // add to new leaf by updating sats and fields
        addTrancheToLeaf(tree, newTrancheSaturation, tranche, newLeaf);
    }

    /**
     * @notice  removing a tranche from a leaf, update the fields and sats up the tree
     * @param   tree that is being read from or written to
     * @param   trancheSaturation  the saturation of the tranche being moved
     * @param   tranche  that is being moved
     * @param   leaf  the leaf
     */
    function removeTrancheToLeaf(
        Tree storage tree,
        SaturationPair memory trancheSaturation,
        int256 tranche,
        uint256 leaf
    ) internal {
        // set the new leaf of the tranche
        tree.trancheToLeaf[int16(tranche)] = 0;

        unchecked {
            // update the sat of leaf (both absolute and relative)
            tree.leafs[uint16(leaf)].leafSatPair.satInLAssets -= trancheSaturation.satInLAssets;
            tree.leafs[uint16(leaf)].leafSatPair.satRelativeToL -= trancheSaturation.satRelativeToL;

            // update the tranches set of the leaf
            uint256 nodeIndex = leaf / CHILDREN_PER_NODE;
            // unset the fields up the tree
            if (!Uint16Set.remove(tree.leafs[uint16(leaf)].tranches, uint16(uint256(tranche + MAX_TRANCHE + 1)))) {
                setXorUnsetFieldBitUpTheTree(tree, LOWEST_LEVEL_INDEX, nodeIndex, leaf % CHILDREN_PER_NODE, 0);
            }

            // update sat up the tree (use absolute saturation for tree to be used for penalty calculation)
            addSatUpTheTree(tree, trancheSaturation.satInLAssets, false);
        }
    }

    /**
     * @notice  adding a tranche from a leaf, update the fields and sats up the tree
     * @param   tree that is being read from or written to
     * @param   tranche  that is being moved
     * @param   trancheSaturation  the saturation of the tranche being moved
     * @param   leaf  the leaf
     */
    function addTrancheToLeaf(
        Tree storage tree,
        SaturationPair memory trancheSaturation,
        int256 tranche,
        uint256 leaf
    ) internal {
        unchecked {
            // set the new leaf of the tranche
            tree.trancheToLeaf[int16(tranche)] = uint16(leaf);

            // update the sat of leaf (both absolute and relative)
            tree.leafs[uint16(leaf)].leafSatPair.satInLAssets += trancheSaturation.satInLAssets;
            tree.leafs[uint16(leaf)].leafSatPair.satRelativeToL += trancheSaturation.satRelativeToL;

            // update the tranches set of the leaf
            uint256 nodeIndex = leaf / CHILDREN_PER_NODE;
            // set the fields up the tree
            if (!Uint16Set.insert(tree.leafs[uint16(leaf)].tranches, uint16(uint256(tranche + MAX_TRANCHE + 1)))) {
                setXorUnsetFieldBitUpTheTree(tree, LOWEST_LEVEL_INDEX, nodeIndex, leaf % CHILDREN_PER_NODE, 1);
            }

            // update sat up the tree (use absolute saturation for tree to be used for penalty calculation)
            addSatUpTheTree(tree, trancheSaturation.satInLAssets, true);
        }
    }

    /**
     * @notice  recursively add sat up the tree
     * @param   tree that is being read from or written to
     * @param   satInLAssets  sat to add to the current node, usually uint112, int to allow subtracting sat up the tree
     */
    function addSatUpTheTree(Tree storage tree, uint128 satInLAssets, bool add) internal {
        uint128 currentSat = tree.totalSatInLAssets;
        // We should never have negative sat, this is a precaution.
        tree.totalSatInLAssets =
            add ? currentSat + satInLAssets : currentSat - uint128(Math.min(currentSat, satInLAssets));
    }

    // penalty functions

    /**
     * @notice  update penalties in the tree given
     * @param   tree that is being read from or written to
     * @param   thresholdLeaf  from which leaf on the penalty needs to be added inclusive
     * @param   addPenaltyInBorrowLSharesPerSatInQ72  the penalty to be added
     */
    function updatePenalties(
        Tree storage tree,
        uint256 thresholdLeaf,
        uint256 addPenaltyInBorrowLSharesPerSatInQ72
    ) internal {
        uint256 highestLeafPlusOne = tree.highestSetLeaf + 1;
        if (thresholdLeaf < highestLeafPlusOne) {
            for (uint256 leafIndex = thresholdLeaf; leafIndex < highestLeafPlusOne; leafIndex++) {
                tree.leafs[leafIndex].penaltyInBorrowLSharesPerSatInQ72 += addPenaltyInBorrowLSharesPerSatInQ72;
            }
        }
    }

    /**
     * @notice  recursive function to sum penalties from leaf to root
     * @param   tree that is being read from or written to
     * @param   leaf  index (0 based) of the leaf
     * @return  penaltyInBorrowLSharesPerSatInQ72  total penalty at the leaf, non-negative but
     * returned as an int for recursion
     */
    function getPenaltySharesPerSatFromLeaf(
        Tree storage tree,
        uint256 leaf
    ) private view returns (uint256 penaltyInBorrowLSharesPerSatInQ72) {
        return tree.leafs[uint16(leaf)].penaltyInBorrowLSharesPerSatInQ72;
    }

    /**
     * @notice  get effective penalty for a tranche, combining leaf penalty and tranche adjustment.
     * When a tranche moves between leaves, the adjustment bridges the gap between the old and new
     * leaf accumulators so that existing accounts' onset values remain valid.
     * @dev Invariant: `leafPen + adjustment >= 0` always holds. Within a single tranche
     * lifecycle, moves preserve continuity of `effective` (the move logic adds the same delta
     * to `adjustment` that it subtracts from `leafPen`), so `effective` only ever grows from
     * its initial non-negative value. The `delete` in `removeSatFromTrancheStateUpdates` resets
     * the adjustment when a tranche empties so each new lifecycle starts from `adj = 0`.
     * @param   tree that is being read from
     * @param   leaf  index (0 based) of the leaf containing the tranche
     * @param   tranche  the tranche identifier
     * @return  effectivePenalty  the effective cumulative penalty for this tranche
     */
    function getEffectivePenalty(
        Tree storage tree,
        uint256 leaf,
        int256 tranche
    ) private view returns (uint256 effectivePenalty) {
        uint256 leafPenalty = getPenaltySharesPerSatFromLeaf(tree, leaf);
        int256 adjustment = tree.tranchePenaltyAdjustment[int16(tranche)];
        effectivePenalty = adjustment >= 0 ? leafPenalty + uint256(adjustment) : leafPenalty - uint256(-adjustment);
    }

    /**
     * @notice  calc penalty owed by account for repay, total over all the tranches that might
     * contain this accounts' sat
     * @param   tree that is being read from or written to
     * @param   account  whose position is being considered
     * @return  penaltyInBorrowLShares  the penalty owed by the account
     */
    function accrueAccountPenalty(
        Tree storage tree,
        address account
    ) internal returns (uint256 penaltyInBorrowLShares) {
        unchecked {
            // beginning tranche
            int256 tranche = tree.accountData[account].lastTranche;

            uint256 satArrayLength = tree.accountData[account].satPairPerTranche.length;
            // add penalty per tranche
            for (uint256 trancheIndex = 0; trancheIndex < satArrayLength; trancheIndex++) {
                // account might have no sat in this tranche
                SaturationPair memory accountSaturationInTranche =
                    tree.accountData[account].satPairPerTranche[trancheIndex];
                if (accountSaturationInTranche.satInLAssets > 0) {
                    // leaf that the tranche belongs to
                    uint256 leaf = tree.trancheToLeaf[int16(tranche)];

                    uint256 penaltyTrancheInBorrowLShares;
                    // calculate penalty for this tranche and update its onset value in the penalties array
                    (
                        penaltyTrancheInBorrowLShares,
                        tree.accountData[account].treePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche[trancheIndex]
                    ) = calcNewAccountPenalty(
                        tree, leaf, accountSaturationInTranche.satInLAssets, account, trancheIndex, tranche
                    );
                    penaltyInBorrowLShares += penaltyTrancheInBorrowLShares;
                }
                // next tranche
                tranche += trancheDirection(tree.netX);
            }
        }

        tree.accountData[account].penaltyInBorrowLShares += SafeCast.toUint112(penaltyInBorrowLShares);
    }

    /**
     * @notice move in the appropriate direction when iterating.
     * @param netDebtX direction flag
     */
    function trancheDirection(
        bool netDebtX
    ) private pure returns (int256) {
        return netDebtX ? INT_ONE : INT_NEGATIVE_ONE;
    }

    /**
     * @notice  calc penalty owed by account for repay, total over all the tranches that might
     * contain this accounts' sat
     * @param   tree that is being read from or written to
     * @param   leaf  the leaf that the tranche belongs to
     * @param   accountSatInTrancheInLAssets  the sat of the account in the tranche
     * @param   account  whose position is being considered
     * @param   trancheIndex  the index of the tranche that is being added to
     * @return  penaltyInBorrowLShares  the penalty owed by the account
     * @return  accountTreePenaltyInBorrowLSharesPerSatInQ72  the penalty owed by the account in the tranche
     */
    function calcNewAccountPenalty(
        Tree storage tree,
        uint256 leaf,
        uint256 accountSatInTrancheInLAssets,
        address account,
        uint256 trancheIndex,
        int256 tranche
    ) private view returns (uint256 penaltyInBorrowLShares, uint256 accountTreePenaltyInBorrowLSharesPerSatInQ72) {
        // account being moved in the tree => account should take penalty
        accountTreePenaltyInBorrowLSharesPerSatInQ72 = getEffectivePenalty(tree, leaf, tranche);
        // round up to assign account more penalty
        penaltyInBorrowLShares = Convert.mulDiv(
            accountTreePenaltyInBorrowLSharesPerSatInQ72
                - tree.accountData[account].treePenaltyAtOnsetInBorrowLSharesPerSatInQ72PerTranche[trancheIndex],
            accountSatInTrancheInLAssets,
            Q72,
            true
        );
    }

    /**
     * @notice  accrue penalties since last accrual based on all over saturated positions
     *
     * @param   satStruct  main data struct
     * @param   account  whose position is being considered
     * @param   externalLiquidity  Swap liquidity outside this pool
     * @param   duration  since last accrual of penalties
     * @param   allAssetsDepositL  allAsset[DEPOSIT_L]
     * @param   allAssetsBorrowL  allAsset[BORROW_L]
     * @param   allSharesBorrowL  allShares[BORROW_L]
     * @param   fragileLiquidityAssets  fragile liquidity removed from active liquidity so the penalty
     * threshold reads the same liquidity we use to measure risk capacity in update()
     * @return  penaltyInBorrowLShares  the penalty owed by the account
     * @return  accountPenaltyInBorrowLShares  the penalty owed by the account
     */
    function accruePenalties(
        SaturationStruct storage satStruct,
        address account,
        uint256 externalLiquidity,
        uint256 duration,
        uint256 allAssetsDepositL,
        uint256 allAssetsBorrowL,
        uint256 allSharesBorrowL,
        uint256 fragileLiquidityAssets
    ) internal returns (uint112 penaltyInBorrowLShares, uint112 accountPenaltyInBorrowLShares) {
        if (duration > 0) {
            // Penalty threshold leaf, on active liquidity with fragile liquidity removed, matching liquidation
            uint256 thresholdLeaf = satToLeaf(
                (externalLiquidity + allAssetsDepositL - allAssetsBorrowL - fragileLiquidityAssets)
                    * START_SATURATION_PENALTY_RATIO_IN_MAG2 / MAG2
            );
            (
                uint256 penaltyNetXInBorrowLShares,
                uint256 penaltyNetXInBorrowLSharesPerSatInQ72,
                uint256 penaltyNetYInBorrowLShares,
                uint256 penaltyNetYInBorrowLSharesPerSatInQ72
            ) = calcNewPenalties(
                satStruct, thresholdLeaf, duration, allAssetsDepositL, allAssetsBorrowL, allSharesBorrowL
            );
            penaltyInBorrowLShares = SafeCast.toUint112(penaltyNetXInBorrowLShares + penaltyNetYInBorrowLShares);

            // update penalties for the tree

            if (penaltyNetXInBorrowLSharesPerSatInQ72 > 0) {
                updatePenalties(satStruct.netXTree, thresholdLeaf, penaltyNetXInBorrowLSharesPerSatInQ72);
            }
            if (penaltyNetYInBorrowLSharesPerSatInQ72 > 0) {
                updatePenalties(satStruct.netYTree, thresholdLeaf, penaltyNetYInBorrowLSharesPerSatInQ72);
            }
        }

        // update penalties for the account

        if (account != ZERO_ADDRESS) {
            accountPenaltyInBorrowLShares = accrueAndRemoveAccountPenalty(satStruct, account);
        }
    }

    /**
     * @notice  calc new penalties
     * @param   satStruct  main data struct
     * @param   thresholdLeaf  the leaf at and above which saturation is in penalty; derived from the
     * active liquidity with fragile liquidity removed so it matches saturation updates and liquidation.
     * @param   duration  since last accrual of penalties
     * @param   allAssetsDepositL  allAsset[DEPOSIT_L]
     * @param   allAssetsBorrowL  allAsset[BORROW_L]
     * @param   allSharesBorrowL  allShares[BORROW_L]
     * @return  penaltyNetXInBorrowLShares  the penalty net X in borrow l shares
     * @return  penaltyNetXInBorrowLSharesPerSatInQ72  the penalty net X in borrow l shares per sat
     * in q72
     * @return  penaltyNetYInBorrowLShares  the penalty net Y in borrow l shares
     * @return  penaltyNetYInBorrowLSharesPerSatInQ72  the penalty net Y in borrow l shares per sat
     * in q72
     */
    function calcNewPenalties(
        SaturationStruct storage satStruct,
        uint256 thresholdLeaf,
        uint256 duration,
        uint256 allAssetsDepositL,
        uint256 allAssetsBorrowL,
        uint256 allSharesBorrowL
    )
        private
        view
        returns (
            uint256 penaltyNetXInBorrowLShares,
            uint256 penaltyNetXInBorrowLSharesPerSatInQ72,
            uint256 penaltyNetYInBorrowLShares,
            uint256 penaltyNetYInBorrowLSharesPerSatInQ72
        )
    {
        uint256 currentBorrowUtilizationInWad = Interest.getUtilizationInWads(allAssetsBorrowL, allAssetsDepositL);

        // Calculate saturation percentage using the full satStruct
        uint256 saturationUtilizationInWad = getSatPercentageInWads(satStruct);

        (penaltyNetXInBorrowLShares, penaltyNetXInBorrowLSharesPerSatInQ72) = calcNewPenaltiesGivenTree(
            satStruct.netXTree,
            thresholdLeaf,
            duration,
            currentBorrowUtilizationInWad,
            saturationUtilizationInWad,
            allAssetsDepositL,
            allAssetsBorrowL,
            allSharesBorrowL
        );
        (penaltyNetYInBorrowLShares, penaltyNetYInBorrowLSharesPerSatInQ72) = calcNewPenaltiesGivenTree(
            satStruct.netYTree,
            thresholdLeaf,
            duration,
            currentBorrowUtilizationInWad,
            saturationUtilizationInWad,
            allAssetsDepositL,
            allAssetsBorrowL,
            allSharesBorrowL
        );
    }

    /**
     * @notice  calc new penalties given tree
     * @param   tree that is being read from or written to
     * @param   thresholdLeaf the threshold leaf
     * @param   duration since last accrual of penalties
     * @param   currentBorrowUtilizationInWad current borrow utilization in WAD
     * @param   saturationUtilizationInWad saturation utilization in WAD
     * @param   allAssetsDepositL allAsset[DEPOSIT_L]
     * @param   allAssetsBorrowL allAsset[BORROW_L]
     * @param   allSharesBorrowL allShares[BORROW_L]
     * @return  penaltyInBorrowLShares the penalty net X in borrow l shares
     * @return  penaltyInBorrowLSharesPerSatInQ72 the penalty net X in borrow l shares per sat in
     * q72
     */
    function calcNewPenaltiesGivenTree(
        Tree storage tree,
        uint256 thresholdLeaf,
        uint256 duration,
        uint256 currentBorrowUtilizationInWad,
        uint256 saturationUtilizationInWad,
        uint256 allAssetsDepositL,
        uint256 allAssetsBorrowL,
        uint256 allSharesBorrowL
    ) private view returns (uint256 penaltyInBorrowLShares, uint256 penaltyInBorrowLSharesPerSatInQ72) {
        unchecked {
            // total saturation after thresholdLeaf
            uint128 totalSatLAssetsInPenalty = calcTotalSatAfterLeafInclusive(tree, thresholdLeaf);

            // if no sat over threshold, we are done
            if (totalSatLAssetsInPenalty == 0) return (0, 0);

            // Calculate penalty rate
            uint256 penaltyRatePerSecondInWads = calcSaturationPenaltyRatePerSecondInWads(
                currentBorrowUtilizationInWad, saturationUtilizationInWad, totalSatLAssetsInPenalty, allAssetsDepositL
            );

            uint256 penaltyInBorrowLAssets = Interest.computeInterestAssetsGivenRate(
                duration, totalSatLAssetsInPenalty, allAssetsDepositL, penaltyRatePerSecondInWads
            );

            // have accounts owe more (ceil)
            uint256 penaltyInBorrowLAssetsPerSatInQ72 =
                Math.ceilDiv(penaltyInBorrowLAssets * Q72, totalSatLAssetsInPenalty);

            // convert to shares
            penaltyInBorrowLSharesPerSatInQ72 =
                Convert.toShares(penaltyInBorrowLAssetsPerSatInQ72, allAssetsBorrowL, allSharesBorrowL, ROUNDING_UP);

            penaltyInBorrowLShares =
                Convert.toShares(penaltyInBorrowLAssets, allAssetsBorrowL, allSharesBorrowL, !ROUNDING_UP);
        }
    }

    /**
     * @notice  accrue and remove account penalty
     * @param   satStruct  main data struct
     * @param   account  whose position is being considered
     * @return  penaltyInBorrowLShares  the penalty owed by the account
     */
    function accrueAndRemoveAccountPenalty(
        SaturationStruct storage satStruct,
        address account
    ) internal returns (uint112 penaltyInBorrowLShares) {
        penaltyInBorrowLShares = SafeCast.toUint112(accrueAccountPenalty(satStruct.netXTree, account))
            + SafeCast.toUint112(accrueAccountPenalty(satStruct.netYTree, account));

        satStruct.netXTree.accountData[account].penaltyInBorrowLShares = 0;
        satStruct.netYTree.accountData[account].penaltyInBorrowLShares = 0;
    }

    // tree util functions

    /**
     * @notice  recursive function to unset the field when removing a tranche from a leaf
     * @param   tree that is being read from or written to
     * @param   level  level being updated
     * @param   nodeIndex  index is the position (0 based) of the node in its level
     * @param   lowerNodePos  pos is the relative position (0 based) of the node in its parent
     * @param   set  1 for set, 0 for unset
     */
    function setXorUnsetFieldBitUpTheTree(
        Tree storage tree,
        uint256 level,
        uint256 nodeIndex,
        uint256 lowerNodePos,
        uint256 set
    ) internal {
        unchecked {
            // our bit fields store the bits in reverse order of the tree
            uint256 invertedLowerNodePos = CHILDREN_PER_NODE - 1 - lowerNodePos;

            uint256 currentNode = tree.nodes[level][nodeIndex];
            // read the current bit of the node in its field
            uint256 currentBit = readFieldBitFromNode(currentNode, invertedLowerNodePos);
            // if we are unsetting and bit is unset, we are done, since all parents will already be unset
            // if we are setting and bit is set, we are done, since all parents will already be set
            if (currentBit == set) return;

            // flip un-sets the bit since the bit must have been set
            currentNode = writeFlippedFieldBitToNode(currentNode, invertedLowerNodePos);
            // write to currentNode on stack first to save gas
            tree.nodes[level][nodeIndex] = currentNode;

            // if we are at the root, we are done
            if (level == 0) return;

            if (set == 0) {
                // some other child is set, parents can remain set, since we are unsetting
                if (readFieldFromNode(currentNode) != 0) return;
            }

            // nothing else set, unset parents recursively
            setXorUnsetFieldBitUpTheTree(
                tree, level - 1, nodeIndex / CHILDREN_PER_NODE, nodeIndex % CHILDREN_PER_NODE, set
            );
        }
    }

    /**
     * @notice  recursive function to find the highest set leaf starting from a leaf, first
     * upwards, until a set field is found, then downwards to find the best set leaf
     * @param   tree that is being read from or written to
     * @param   level  that we are checking
     * @param   nodeIndex  corresponding to our leaf at our `level`
     * @return  highestSetLeaf highest leaf that is set in the tree
     */
    function findHighestSetLeafUpwards(
        Tree storage tree,
        uint256 level,
        uint256 nodeIndex
    ) private view returns (uint256 highestSetLeaf) {
        unchecked {
            if (readFieldFromNode(tree.nodes[level][nodeIndex]) == 0) {
                if (level == 0) return 0;
                return findHighestSetLeafUpwards(tree, level - 1, nodeIndex / CHILDREN_PER_NODE);
            }
            return findHighestSetLeafDownwards(tree, level, nodeIndex);
        }
    }

    /**
     * @notice  recursive function to find the highest set leaf starting from a node, downwards
     * @dev internal for testing only
     * @param   tree that is being read from or written to
     * @param   level  that we are starting from
     * @param   nodeIndex  that we are starting from
     * @return  leaf highest leaf under the node that is set
     */
    function findHighestSetLeafDownwards(
        Tree storage tree,
        uint256 level,
        uint256 nodeIndex
    ) internal view returns (uint256 leaf) {
        unchecked {
            nodeIndex = CHILDREN_PER_NODE * (nodeIndex + 1) - BitLib.ctz64(tree.nodes[level][nodeIndex]) - 1;

            // if we are at the bottom of the tree, we have found the leaf, which is the node
            if (level == LOWEST_LEVEL_INDEX) return nodeIndex;

            // recurse to the lower level
            return findHighestSetLeafDownwards(tree, level + 1, nodeIndex);
        }
    }

    // liq sqrt price functions

    /**
     * @notice Calc sqrt price at which positions' LTV would reach LTV_MAX. Given the net $$L$$,
     *   $$X$$, and Y, we define the the sqrt price $$s_p$$ at which the position would be at the
     *   expected loan to value of liquidation $$k$$, then the following formulas are what we are
     *   calculating,
     *
     *   ```math
     *     \begin{align}
     *       k &=
     *         \begin{cases}
     *           -\frac{L + \frac{X}{s_p}}{L + Y \cdot s_p}
     *           \text{ if } L+ \frac{X}{s_p} < 0
     *           \\
     *           -\frac{L + Y \cdot s_p}{L + \frac{X}{s_p}}
     *           \text{ if } L + Y \cdot s_p < 0
     *         \end{cases}
     *       \\
     *
     *       s_p &=
     *         \begin{cases}
     *           \frac{
     *             -(k+1)L +
     *             \sqrt{\left((k+1)L\right)^2 - 4 \left( k\cdot Y \right) \left(X \right)}
     *           }{
     *             2 \cdot k \cdot Y
     *           }
     *           \text{ if } L + \frac{X}{s_p} < 0
     *         \\
     *           \frac{
     *             -(k+1)L -
     *             \sqrt{((k+1)L)^2-4(Y)(k\cdot X)}
     *           }{
     *             2\cdot k
     *           }
     *           \text{ if } L + Y \cdot s_p < 0
     *         \end{cases}
     *     \end{align}
     *   ```
     *
     *  The equation gives four solutions due to the plus minus of the radical, but we choose the
     *  direction due to the conditions. When we have a net debt of x, $$L + \frac{X}{s_p} < 0$$,
     *  the loan to value will be increasing as the price decreases, thus we choose the positive
     *  value of the radical. For the net debt of y, $$L + Y \cdot s_p < 0$$ we have the loan to
     *  value increasing as the price increases, thus we use the negative value of the radical.
     *
     * @notice Output guarantees $$0 \le liqSqrtPriceXInQ72 \le uint256(type(uint56).max) << 72$$
     * (fuzz tested and logic)
     * @notice Outside above range, outputs 0 (essentially no liq)
     * @notice Does not revert if `LTV_MAX < LTV`, rather `LTV_MAX < LTV` causing liq points are
     *  returned as 0, as if they do not exist, based on the assumption `LTV \le LTV_MAX`
     * @param   userAssets  The position
     * @return  netDebtXLiqSqrtPriceXInQ72  0 if no netX liq price exists
     * @return  netDebtYLiqSqrtPriceXInQ72  0 if no netY liq price exists
     */
    function calcLiqSqrtPriceQ72(
        uint256[6] memory userAssets
    ) internal pure returns (uint256 netDebtXLiqSqrtPriceXInQ72, uint256 netDebtYLiqSqrtPriceXInQ72) {
        int256 netLInMAG2;
        int256 netXInMAG2;
        int256 netYInMAG2;
        unchecked {
            netLInMAG2 = int256(userAssets[DEPOSIT_L]) - int256(userAssets[BORROW_L]);
            netXInMAG2 = int256(userAssets[DEPOSIT_X]) - int256(userAssets[BORROW_X]);
            netYInMAG2 = int256(userAssets[DEPOSIT_Y]) - int256(userAssets[BORROW_Y]);
        }

        if (netLInMAG2 >= 0 && netXInMAG2 >= 0 && netYInMAG2 >= 0) {
            // no net debt, no liquidation sqrt price
            return (0, 0);
        }

        uint256 netLAbsInMAG2; // uint112
        uint256 netXAbsInMAG2; // uint112
        uint256 netYAbsInMAG2; // uint112

        unchecked {
            // netY*x^2 + netL*x + netX == 0
            // with netY == Y_hat, netL == L_hat * (LTV_MAX/TICKS_PER_TRANCHE + 1), netX == X_hat * LTV_MAX/TICKS_PER_TRANCHE
            // and x is the liq sqrt price in X of Y

            netYInMAG2 *= int256(MAG2); // everything in MAG2 saves some computation later
            netYAbsInMAG2 = uint256(0 <= netYInMAG2 ? netYInMAG2 : -netYInMAG2);

            bool netLPositive = 0 <= netLInMAG2;
            netLAbsInMAG2 = uint256(netLPositive ? netLInMAG2 : -netLInMAG2);
            netLAbsInMAG2 = netLAbsInMAG2 * EXPECTED_SATURATION_LTV_PLUS_ONE_MAG2;
            netLInMAG2 = int256(netLAbsInMAG2);
            if (!netLPositive) netLInMAG2 = -netLInMAG2;

            bool netXPositive = 0 <= netXInMAG2;
            netXAbsInMAG2 = uint256(netXPositive ? netXInMAG2 : -netXInMAG2);
            netXAbsInMAG2 = netXAbsInMAG2 * EXPECTED_SATURATION_LTV_MAG2;
            netXInMAG2 = int256(netXAbsInMAG2);
            if (!netXPositive) netXInMAG2 = -netXInMAG2;
        }

        unchecked {
            if (netYAbsInMAG2 == 0) {
                // Ŷ==0

                // netL != 0 != netX
                // netL xor netX < 0 else under col => 0 <= -netX/netL
                // netL*x+netX=0 <=> x=-netX/netL
                uint256 liqSqrtPriceXInQ72 = Convert.mulDiv(netXAbsInMAG2, Q72, netLAbsInMAG2, false);

                // borrowing L against X
                if (userAssets[BORROW_X] == 0) {
                    netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
                // borrowing X against L
                else {
                    netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
            }
            // netY != 0
            else if (netXAbsInMAG2 == 0) {
                // X̂==0

                // netL xor netY < 0 else under col => 0 <= -netL/netY and netY*x^2+netL*x=0 <=> x=-netL/netY
                uint256 liqSqrtPriceXInQ72 = Convert.mulDiv(netLAbsInMAG2, Q72, netYAbsInMAG2, false);

                // borrowing L against Y
                if (userAssets[BORROW_Y] == 0) {
                    netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
                // borrowing Y against L
                else {
                    netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
            }
            // netX != 0
            else if (netLAbsInMAG2 == 0) {
                // L̂==0
                // positionXY == mixed genuinely
                // netX xor netY < 0 else under col => 0 <= -netX/netY and netY*x^2+netX=0 <=> x=sqrt(-netX/netY)

                // 0 < accountLXYInAssets[BORROW_X] && 0 < accountLXYInAssets[BORROW_Y] not possible, assuming good LTV

                if (0 < userAssets[DEPOSIT_X]) {
                    if (0 < userAssets[DEPOSIT_Y]) return (0, 0);
                } // no solution

                uint256 liqSqrtPriceXInQ72 = Math.sqrt(
                    netXAbsInMAG2 < Q112
                        ? Convert.mulDiv(netXAbsInMAG2, Q144, netYAbsInMAG2, false)
                        // divide by MAG2 first to preserve more precision in Q144 / netY
                        // calculation
                        : (netXAbsInMAG2 / MAG2) * (Q144 / (netYAbsInMAG2 / MAG2))
                );

                // borrowing Y against X
                if (0 < userAssets[DEPOSIT_X]) {
                    netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
                // borrowing X against Y
                else {
                    netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXInQ72;
                }
            } else {
                // netY != 0 && netL != 0 && netX != 0

                (netDebtXLiqSqrtPriceXInQ72, netDebtYLiqSqrtPriceXInQ72) = calcLiqSqrtPriceQ72HandleAllABCNonZero(
                    CalcLiqSqrtPriceHandleAllABCNonZeroStruct(
                        netLInMAG2, netXInMAG2, netYInMAG2, netYAbsInMAG2, userAssets[BORROW_X], userAssets[BORROW_Y]
                    )
                );
            }

            // netX uses the saturation LTV divisor before bounding so the final value is checked.
            if (0 < netDebtXLiqSqrtPriceXInQ72) {
                netDebtXLiqSqrtPriceXInQ72 =
                    Convert.mulDiv(netDebtXLiqSqrtPriceXInQ72, MAG2, EXPECTED_SATURATION_LTV_MAG2, false);
            }

            // bounding
            if (
                netDebtXLiqSqrtPriceXInQ72 < TickMath.MIN_SQRT_PRICE_IN_Q72
                    || TickMath.MAX_SQRT_PRICE_IN_Q72 < netDebtXLiqSqrtPriceXInQ72
            ) {
                netDebtXLiqSqrtPriceXInQ72 = 0;
            }
            if (
                netDebtYLiqSqrtPriceXInQ72 < TickMath.MIN_SQRT_PRICE_IN_Q72
                    || TickMath.MAX_SQRT_PRICE_IN_Q72 < netDebtYLiqSqrtPriceXInQ72
            ) {
                netDebtYLiqSqrtPriceXInQ72 = 0;
            }
        }
    }

    /**
     * @notice  calc liq price when the quadratic has all 3 terms, netY,netL,netX, i.e. X, Y, L are
     * all significant
     * @param   input the position
     * @return  netDebtXLiqSqrtPriceXInQ72 0 if no netX liq price exists
     * @return  netDebtYLiqSqrtPriceXInQ72 0 if no netY liq price exists
     */
    function calcLiqSqrtPriceQ72HandleAllABCNonZero(
        CalcLiqSqrtPriceHandleAllABCNonZeroStruct memory input
    ) internal pure returns (uint256 netDebtXLiqSqrtPriceXInQ72, uint256 netDebtYLiqSqrtPriceXInQ72) {
        int256 numeratorPlusInMAG2;
        int256 numeratorMinusInMAG2;
        unchecked {
            // stack for gas savings
            int256 netLInMAG2 = input.netLInMAG2;

            // calc radical == netL^2 - 4*netY*netX
            int256 radicalInMAG4 = netLInMAG2 * netLInMAG2 - 4 * input.netYInMAG2 * input.netXInMAG2;

            // Two cases, if negative sqrt has no solution in the reals.
            // If negative, there are no solutions to the equation, this is a straddle that does
            // not ever reach our liquidation price.
            // Otherwise,
            // netL^2=4*netY*netX <=> x=-netL/2/netY => !MixedXY
            // !AllB, else would violate LTV
            // AllD, which has no liq point, except a single point where we cannot be, else bad LTV
            if (radicalInMAG4 <= 0) return (0, 0);

            // 0 < radical

            int256 sqrtRadicalInMAG2 = int256(Math.sqrt(uint256(radicalInMAG4)));
            numeratorPlusInMAG2 = netLInMAG2 + sqrtRadicalInMAG2;
            numeratorMinusInMAG2 = netLInMAG2 - sqrtRadicalInMAG2;
        }

        // stack for gas savings
        uint256 netYAbsInMAG2 = input.netYAbsInMAG2;

        // calc solution fraction
        uint256 liqSqrtPriceXPlusInQ72;
        uint256 liqSqrtPriceXMinusInQ72;
        unchecked {
            liqSqrtPriceXPlusInQ72 = Convert.mulDiv(
                uint256(numeratorPlusInMAG2 < 0 ? -numeratorPlusInMAG2 : numeratorPlusInMAG2),
                Q72,
                2 * netYAbsInMAG2,
                false
            );
            liqSqrtPriceXMinusInQ72 = Convert.mulDiv(
                uint256(numeratorMinusInMAG2 < 0 ? -numeratorMinusInMAG2 : numeratorMinusInMAG2),
                Q72,
                2 * netYAbsInMAG2,
                false
            );
        }

        if (input.borrowedXAssets == 0) {
            if (input.borrowedYAssets == 0) {
                // AllD => good LTV outside range
                netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXPlusInQ72;
                netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXMinusInQ72;
            } else {
                // YB != 0
                // XY mixed, XD != 0
                netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXPlusInQ72;
            }
        } else {
            // XB != 0
            // if (accountLXYInAssets[BORROW_Y] == 0) {
            if (input.borrowedYAssets == 0) {
                // XY mixed, YD != 0
                netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXMinusInQ72;
            } else {
                // AllB => good LTV inside range
                netDebtYLiqSqrtPriceXInQ72 = liqSqrtPriceXPlusInQ72;
                netDebtXLiqSqrtPriceXInQ72 = liqSqrtPriceXMinusInQ72;
            }
        }
    }

    // sat functions

    /**
     * @notice Calculate the ratio by which the saturation has changed for `account`.
     * @dev the algorithm here matches that of `addSatToTranche()`, but accumulates the total
     *   saturation to compare it to what is needed. If the allocated total saturation is less than
     *   what is needed, we return the ratio to help determine the saturation adjustment premium.
     * @param satStruct The saturation struct containing both netX and netY trees.
     * @param inputParams The params containing the position of `account`.
     * @param liqSqrtPriceInXInQ72 The liquidation price for netX.
     * @param liqSqrtPriceInYInQ72 The liquidation price for netY.
     * @param account The account for which we are calculating the saturation change ratio.
     * @return ratioBips The ratio representing the change in saturation for account.
     */
    function calcSatChangeRatioBips(
        SaturationStruct storage satStruct,
        Validation.InputParams memory inputParams,
        uint256 liqSqrtPriceInXInQ72,
        uint256 liqSqrtPriceInYInQ72,
        address account,
        uint256 desiredSaturationMAG2
    ) internal view returns (uint256 ratioBips) {
        uint256 ratioNetXBips;
        uint256 ratioNetYBips;

        // Calculate ratios for netX tree only if netX liquidation price exists
        if (liqSqrtPriceInXInQ72 > 0) {
            ratioNetXBips = calcTreeRatioBips(
                satStruct.netXTree.accountData[account],
                inputParams,
                liqSqrtPriceInXInQ72,
                liqSqrtPriceInYInQ72,
                desiredSaturationMAG2,
                true
            );
        }
        // Calculate ratios for netY tree only if netY liquidation price exists
        if (liqSqrtPriceInYInQ72 > 0) {
            ratioNetYBips = calcTreeRatioBips(
                satStruct.netYTree.accountData[account],
                inputParams,
                liqSqrtPriceInXInQ72,
                liqSqrtPriceInYInQ72,
                desiredSaturationMAG2,
                false
            );
        }
        ratioBips = Math.max(ratioNetXBips, ratioNetYBips);
    }

    /**
     * @dev Per-tree ratio computation extracted from `calcSatChangeRatioBips`.
     *
     * Stored `satPairs[i].satRelativeToL` lives in tranche-i units
     * (= 1/B^i of tranche-0 units, modulo the partial first-tranche adjustment).
     * `scaleAndSumSaturation` converts each stored sat back to tranche-0 units, so
     * the old and new saturation totals are compared in the same unit system.
     *
     * @param accountData Stored account saturation data for the tree being evaluated.
     * @param inputParams User asset balances and pool state used to compute the new saturation.
     * @param liqSqrtPriceInXInQ72 Liquidation sqrt price (upper root) in Q72, for the netDebtX side.
     * @param liqSqrtPriceInYInQ72 Liquidation sqrt price (lower root) in Q72, for the netDebtY side.
     * @param desiredSaturationMAG2 Target saturation level in MAG2 units used to project the new sat.
     * @param netDebtX True when evaluating the netDebtX tree; false for the netDebtY tree.
     * @return ratioBips Growth ratio in BIPS of (old + remaining) / old saturation for this tree;
     *                  zero when the new saturation does not exceed the absorbed old saturation.
     */
    function calcTreeRatioBips(
        Account storage accountData,
        Validation.InputParams memory inputParams,
        uint256 liqSqrtPriceInXInQ72,
        uint256 liqSqrtPriceInYInQ72,
        uint256 desiredSaturationMAG2,
        bool netDebtX
    ) private view returns (uint256 ratioBips) {
        // Note that we don't check the start of liquidation since we don't want this check
        // to fail during a liquidation.
        (SaturationPair memory newSaturation, int256 endOfLiquidationInTicks,) = calcLastTickAndSaturation(
            inputParams, liqSqrtPriceInXInQ72, liqSqrtPriceInYInQ72, desiredSaturationMAG2, netDebtX, true
        );

        // reduce saturation by newSaturation by buffer
        uint256 newSatInLAssets = uint256(newSaturation.satRelativeToL) * MAG2 / SATURATION_TIME_BUFFER_IN_MAG2;

        (, int256 currentLastTranche) = getUsableTicksAndLastTranche(endOfLiquidationInTicks, netDebtX);
        uint256 oldSatInLAssets = scaleAndSumSaturation(
            accountData.satPairPerTranche,
            endOfLiquidationInTicks,
            netDebtX,
            accountData.lastTranche,
            currentLastTranche
        );

        if (newSatInLAssets > oldSatInLAssets) {
            uint256 remaining = newSatInLAssets - oldSatInLAssets;
            ratioBips = oldSatInLAssets > 0
                ? (remaining + oldSatInLAssets) * BIPS / oldSatInLAssets
                : calcStraddlePremiumRatioBips(inputParams.userAssets);
        }
    }

    /**
     * @dev Sum stored per-tranche saturation in tranche-0 units.
     *
     *   `satPairs[i].satRelativeToL` is stored in tranche-`i` units (= 1/B^i of tranche-0 units,
     *   modulo the partial first-tranche adjustment from `calculateEndOfLiquidationAdjustment`).
     *   Summing them directly would mix units across tranches and undercount the total. The loop
     *   tracks an inverse Q72 scale factor `bScaleQ72` that rescales each stored sat back into
     *   tranche-0 units before accumulation. When the current endpoint has drifted from the stored
     *   `lastTranche`, `trancheShift` keeps the stored array anchored to its original tranches.
     *
     * @param satPairs Storage array of per-tranche saturation pairs.
     * @param endOfLiquidationInTicks Tick at which liquidation ends (sets the first-tranche offset).
     * @param netDebtX True when summing the netDebtX tree; false for the netDebtY tree.
     * @param storedLastTranche Account tranche anchor when the stored saturation array was written.
     * @param currentLastTranche Current tranche anchor implied by `endOfLiquidationInTicks`.
     * @return oldSatInLAssets Total saturation in tranche-0 (L-asset) units.
     */
    function scaleAndSumSaturation(
        SaturationPair[] storage satPairs,
        int256 endOfLiquidationInTicks,
        bool netDebtX,
        int256 storedLastTranche,
        int256 currentLastTranche
    ) internal view returns (uint256 oldSatInLAssets) {
        uint256 endOfLiquidationAdjustmentQ72 = calculateEndOfLiquidationAdjustment(endOfLiquidationInTicks, netDebtX);

        int256 trancheShift = (storedLastTranche - currentLastTranche) * trancheDirection(netDebtX);
        uint256 bScaleQ72 = Q72;
        if (trancheShift > 0) {
            for (int256 j; j < trancheShift; ++j) {
                bScaleQ72 =
                    Convert.mulDiv(bScaleQ72, TRANCHE_B_IN_Q72, j == 0 ? endOfLiquidationAdjustmentQ72 : Q72, false);
            }
        } else if (trancheShift < 0) {
            for (int256 j; j > trancheShift; --j) {
                bScaleQ72 =
                    Convert.mulDiv(bScaleQ72, j == 0 ? endOfLiquidationAdjustmentQ72 : Q72, TRANCHE_B_IN_Q72, false);
            }
        }

        uint256 satArrayLength = satPairs.length;

        for (uint256 i; i < satArrayLength; i++) {
            int256 relativeIndex = int256(i) + trancheShift;

            // Scale stored sat up to tranche-0 units
            // Values were computed rounding down so we add one and round up to benefit borrower.
            oldSatInLAssets += Convert.mulDiv(satPairs[i].satRelativeToL + 1, bScaleQ72, Q72, true);

            // Update scaling only if there is a next tranche to process.
            if (i + 1 < satArrayLength) {
                bScaleQ72 = Convert.mulDiv(
                    bScaleQ72,
                    TRANCHE_B_IN_Q72,
                    relativeIndex == INT_NEGATIVE_ONE || relativeIndex == 0 ? endOfLiquidationAdjustmentQ72 : Q72,
                    false
                );
            }
        }
    }

    /**
     * @notice Calculate the ratio bips for a straddle position transitioning from zero to positive saturation.
     *
     *  Let $$S$$ be `SAT_RESET_FOR_STRADDLE_SLOPE_BIPS`, the slope that controls how quickly the
     *  straddle reset premium increases once $$L^2 > X \cdot Y$$.
     *
     *  Let $$P_{max}$$ be `MAX_SAT_RESET_FOR_STRADDLE_PREMIUM_BIPS`, the maximum premium allowed for
     *  this zero-to-positive straddle reset path.
     *
     *  ```math
     *  premiumBips = \min\left(
     *      P_{max},
     *      \left\lceil\frac{(L^2 - X \cdot Y) \cdot S}{X \cdot Y}\right\rceil
     *  \right)
     *  ```
     *
     *  The ratioBips encodes premium for downstream consumption:
     *  ```math
     *  \text{ratioBips} = \text{premiumBips} \cdot \text{MAG1} + \text{BIPS}
     *  ```
     *  and premium is recovered as: `(ratioBips - BIPS) / MAG1`.
     * @param userAssets The user's position parameters.
     * @return ratioBips The ratio in bips, or 0 if $$L^2 <= X \cdot Y$$.
     */
    function calcStraddlePremiumRatioBips(
        uint256[6] memory userAssets
    ) private pure returns (uint256 ratioBips) {
        uint256 lSquared = userAssets[BORROW_L] ** 2;
        uint256 xyProduct = userAssets[DEPOSIT_X] * userAssets[DEPOSIT_Y];

        if (lSquared > xyProduct) {
            uint256 premiumBips =
                Convert.mulDiv((lSquared - xyProduct), SAT_RESET_FOR_STRADDLE_SLOPE_BIPS, xyProduct, ROUNDING_UP);
            premiumBips = Math.min(premiumBips, MAX_SAT_RESET_FOR_STRADDLE_PREMIUM_BIPS);

            ratioBips = premiumBips * MAG1 + BIPS;
        }
    }

    /**
     * @notice  a helper function to calculate the one time adjustment for the offset of the end
     *   of the liquidation relative to the the boundary of the tranches.
     * @dev This formula is described in the introduction.
     * @param   endOfLiquidationInTicks  the tick at which liquidation should end by.
     * @param   netDebtX  whether this is a net X debt path.
     * @return  endOfLiquidationSqrtPriceAdjustment  the sqrt price adjustment required to be applied.
     */
    function calculateEndOfLiquidationAdjustment(
        int256 endOfLiquidationInTicks,
        bool netDebtX
    ) internal pure returns (uint256 endOfLiquidationSqrtPriceAdjustment) {
        unchecked {
            int256 tickForAdjustment = netDebtX ? endOfLiquidationInTicks : -endOfLiquidationInTicks;
            int16 modEndOfLiquidationInTicks = int16(tickForAdjustment % TICKS_PER_TRANCHE);
            if (modEndOfLiquidationInTicks < 0) modEndOfLiquidationInTicks += int16(TICKS_PER_TRANCHE);
            endOfLiquidationSqrtPriceAdjustment =
                modEndOfLiquidationInTicks == 0 ? Q72 : TickMath.getSqrtPriceAtTick(modEndOfLiquidationInTicks);
        }
    }

    /**
     * @notice  calc total sat of all accounts/tranches/leafs higher (and same) as the threshold
     * @dev     iterate through leaves directly since penalty range is fixed (~8 leaves from 85% to
     * 95% sat)
     * @param   tree that is being read from or written to
     * @param   thresholdLeaf leaf to start adding sat from
     * @return  satInPenaltyInLAssets total sat of all accounts with tranche in a leaf from at
     * least `thresholdLeaf` (absolute saturation)
     */
    function calcTotalSatAfterLeafInclusive(
        Tree storage tree,
        uint256 thresholdLeaf
    ) internal view returns (uint128 satInPenaltyInLAssets) {
        uint256 maxLeaf = tree.highestSetLeaf;
        if (thresholdLeaf > maxLeaf) {
            return 0; // No leaves in penalty range
        }

        for (uint256 leafIndex = thresholdLeaf; leafIndex <= maxLeaf; leafIndex++) {
            // Add absolute saturation stored in each leaf
            uint128 leafSat = tree.leafs[leafIndex].leafSatPair.satInLAssets;
            satInPenaltyInLAssets += leafSat;
        }
    }

    /**
     * @notice  Get precalculated saturation percentage for a given delta (maxLeaf - highestLeaf)
     * @param   satStruct  The saturation struct
     * @return  saturationPercentage  The precalculated saturation percentage as uint256
     */
    function getSatPercentageInWads(
        SaturationStruct storage satStruct
    ) internal view returns (uint256 saturationPercentage) {
        uint16 highestLeaf = uint16(Math.max(satStruct.netXTree.highestSetLeaf, satStruct.netYTree.highestSetLeaf));
        if (satStruct.maxLeaf == 0 && highestLeaf == 0) {
            return 0;
        }
        uint16 delta = satStruct.maxLeaf - highestLeaf;
        if (delta > 7) {
            return 0;
        }

        assembly {
            switch delta
            case 4 { saturationPercentage := SAT_PERCENTAGE_DELTA_4_WAD }
            case 5 { saturationPercentage := SAT_PERCENTAGE_DELTA_5_WAD }
            case 6 { saturationPercentage := SAT_PERCENTAGE_DELTA_6_WAD }
            case 7 { saturationPercentage := SAT_PERCENTAGE_DELTA_7_WAD }
            default { saturationPercentage := SAT_PERCENTAGE_DELTA_DEFAULT_WAD } // return 95% by default
        }
    }

    /**
     * @notice  convert sat to leaf
     * @param   satLAssets sat to convert
     * @return  leaf  resulting leaf from 0 to $2^{12}-1$
     */
    function satToLeaf(
        uint256 satLAssets
    ) internal pure returns (uint256 leaf) {
        // handle edge cases
        if (satLAssets >= MIN_LIQ_TO_REACH_PENALTY) {
            if (satLAssets >= LOWEST_POSSIBLE_IN_PENALTY) return LEAFS - 1;
            // Q112 to ensure our max value of our desired range is within the range of the function.
            uint256 satInQ112 = satLAssets * Q112;
            // the smaller Q number means some of our values are less than 0, so we correct all values to be positive by adding TICK_OFFSET (1112).
            int16 tick = TickMath.getTickAtPrice(satInQ112) + TICK_OFFSET;
            // multiply by 2 since `getTickAtPrice` does a square root on the value before taking the log. Then we change the base and shift to our desired domain.
            leaf = (2 * uint256(int256(tick)) * Q128 + SAT_CHANGE_OF_BASE_TIMES_SHIFT) / SAT_CHANGE_OF_BASE_Q128;
        }
    }

    /**
     * @notice  calc how much sat can be added to a tranche such that it is healthy.
     *   With `newSaturationRelativeToLAssets` as `newSat` and
     *   `currentTrancheSatRelativeToLAssets` as `currentSat`, the return values are:
     *
     *   ```math
     *   satAvailable = min(newSat, max(trancheSat, currentSat) - currentSat)
     *   ```
     *
     *   ```math
     *   target = min(trancheSat, newSat)
     *   ```
     *
     *   Therefore `target >= satAvailable` and `newSat >= target`.
     *
     * @param   activeLiquidityInLAssets  of the pair
     * @param   newSaturationRelativeToLAssets  the sat that we want to add
     * @param   currentTrancheSatRelativeToLAssets  the sat that the tranche already holds
     * @param   userSaturationRatioMAG2  the user's desired saturation ratio
     * @param   usableTicks  the number of usable ticks within the tranche, restricted by either
     *          the end of liquidation or the min/max tick.
     * @return  satAvailableToAddRelativeToLAssets  considering the `currentTrancheSatRelativeToLAssets` and the
     * max a tranche can have
     */
    function calcSatAvailableToAddToTranche(
        uint256 activeLiquidityInLAssets,
        uint128 newSaturationRelativeToLAssets,
        uint128 currentTrancheSatRelativeToLAssets,
        uint256 userSaturationRatioMAG2,
        uint256 usableTicks
    ) internal pure returns (uint128 satAvailableToAddRelativeToLAssets, uint256 targetCapacityRelativeToLAssets) {
        uint256 trancheSaturation =
            Math.ceilDiv(activeLiquidityInLAssets * userSaturationRatioMAG2 * usableTicks, TICKS_PER_TRANCHE_MAG2);

        satAvailableToAddRelativeToLAssets = uint128(
            Math.min(
                newSaturationRelativeToLAssets,
                Math.max(trancheSaturation, currentTrancheSatRelativeToLAssets) - currentTrancheSatRelativeToLAssets
            )
        );

        // limit the returned amount to guarantee no underflow when subtracting used from the
        // target so that we know that satRelative >= target.
        targetCapacityRelativeToLAssets = Math.min(trancheSaturation, newSaturationRelativeToLAssets);
    }

    /**
     * @notice  calc the tick at which the best case liquidation would end and the saturation of
     *  the last tranche containing that tick. Not all the saturation may fit into that tranche,
     *  but we calculate it as if it will which means that adjustments to the saturation will need
     *  to be made if it doesn't fit when placing it into the tree.
     * @param   inputParams  the input params
     * @param   netXLiqSqrtPriceInXInQ72  the midpoint of liquidation sqrt price of debt X in X/Y
     * @param   netYLiqSqrtPriceInXInQ72  the midpoint of liquidation sqrt price of debt Y in X/Y
     * @param   desiredThresholdMag2  the desired threshold
     * @param   netDebtX  whether the net debt is X or Y
     * @param   skipMinOrMaxTickCheck when borrowing liquidity, the two liquidations will
     *  start facing opposite ways and the current price can only be on one side. When this
     *  happens, only one side's liquidation is valid, the other could not occur without the price
     *  moving through the valid liquidation.
     *  We also skip this check during `calcSatChangeRatioBips()` as we don't want to block
     *  liquidations.
     * @return  saturation the saturation of the tranche
     * @return  endOfLiquidationInTicks  the point at which the liquidation would end.
     * @return  currentTickLimit The point at which the liquidation can not start before due to the
     *   current price.
     */
    function calcLastTickAndSaturation(
        Validation.InputParams memory inputParams,
        uint256 netXLiqSqrtPriceInXInQ72,
        uint256 netYLiqSqrtPriceInXInQ72,
        uint256 desiredThresholdMag2,
        bool netDebtX,
        bool skipMinOrMaxTickCheck
    )
        internal
        pure
        returns (SaturationPair memory saturation, int256 endOfLiquidationInTicks, int256 currentTickLimit)
    {
        // Check if this liquidation price is on the opposite side of the price and
        // thus not checked against saturation.
        skipMinOrMaxTickCheck = skipMinOrMaxTickCheck
            || (
                netDebtX
                    ? inputParams.sqrtPriceMaxInQ72 < netYLiqSqrtPriceInXInQ72
                        && netYLiqSqrtPriceInXInQ72 < netXLiqSqrtPriceInXInQ72
                    : netYLiqSqrtPriceInXInQ72 < netXLiqSqrtPriceInXInQ72
                        && netXLiqSqrtPriceInXInQ72 < inputParams.sqrtPriceMinInQ72
            );

        currentTickLimit = skipMinOrMaxTickCheck
            ? (netDebtX ? type(int256).max : type(int256).min)
            : (netDebtX ? inputParams.minTick : inputParams.maxTick);

        uint256 startOfLiquidationPriceQ128;
        {
            uint256 liqSqrtPriceInXInQ72 = netDebtX ? netXLiqSqrtPriceInXInQ72 : netYLiqSqrtPriceInXInQ72;

            (uint256 netDebtXorYAssets, uint256 tempSatInLAssets, uint256 sqrtPriceSpanQ72) =
                calculateNetDebtAndSpan(inputParams, liqSqrtPriceInXInQ72, desiredThresholdMag2, netDebtX);

            saturation.satInLAssets = SafeCast.toUint128(tempSatInLAssets);

            uint256 endOfLiquidationPriceQ128;
            (startOfLiquidationPriceQ128, endOfLiquidationPriceQ128) =
                calculateStartAndEndOfLiquidationPriceQ128(liqSqrtPriceInXInQ72, sqrtPriceSpanQ72, netDebtX);

            // Calculate relative saturation
            uint256 endOfLiquidationSqrtPriceQ72 = Math.sqrt(endOfLiquidationPriceQ128) << 8;
            saturation.satRelativeToL = calculateSaturation(netDebtXorYAssets, endOfLiquidationSqrtPriceQ72, netDebtX);

            endOfLiquidationPriceQ128 = netDebtX
                // round up if netDebt X by multiplying by $$b^2 \cdot Q72 - 1$$ prior to
                // passing to `getTickAtPrice()`. Checks size to prior to picking division or
                // multiplication to execute first to avoid overflows or vanishing the result.
                ? endOfLiquidationPriceQ128 > Q183
                    ? endOfLiquidationPriceQ128 / Q72 * B_SQUARED_Q72_MINUS_ONE
                    : endOfLiquidationPriceQ128 * B_SQUARED_Q72_MINUS_ONE / Q72
                : endOfLiquidationPriceQ128;

            // Cap the converted tick to `TickMath`'s valid tick range. Extreme low-LTV positions
            // can push `endOfLiquidationPriceQ128` outside `[MIN_PRICE_IN_Q128, MAX_PRICE_IN_Q128]`
            // — capping here avoids a `getTickAtPrice` revert (DoS). When the b^2 round-up rescale
            // pushes past MAX_PRICE_IN_Q128 we return MAX_TICK + 1
            if (endOfLiquidationPriceQ128 > TickMath.MAX_PRICE_IN_Q128) {
                endOfLiquidationInTicks = TickMath.MAX_TICK + 1;
            } else if (endOfLiquidationPriceQ128 < TickMath.MIN_PRICE_IN_Q128) {
                endOfLiquidationInTicks = TickMath.MIN_TICK;
            } else {
                endOfLiquidationInTicks = TickMath.getTickAtPrice(endOfLiquidationPriceQ128);
            }
        }
        // Verify that the liquidation does not start past the current min or max price.

        if (
            !skipMinOrMaxTickCheck
                && (
                    (netDebtX && startOfLiquidationPriceQ128 > inputParams.sqrtPriceMinInQ72 ** 2 / Q16)
                        || (!netDebtX && startOfLiquidationPriceQ128 < inputParams.sqrtPriceMaxInQ72 ** 2 / Q16)
                )
        ) {
            revert LiquidationPassesMinOrMaxTick();
        }
    }

    /**
     * @notice Convert from sqrtPrice by squaring, but we don't square the span because we only want
     *   to shift by half of the span to move from the middle of the liquidation to the end.
     *   Division prior to multiplication to avoid overflow since sqrtPriceQ72 is is 128 bits.
     */
    function calculateStartAndEndOfLiquidationPriceQ128(
        uint256 liqSqrtPriceQ72,
        uint256 sqrtPriceSpanQ72,
        bool netDebtX
    ) internal pure returns (uint256 startOfLiquidationPriceQ128, uint256 endOfLiquidationPriceQ128) {
        uint256 liqPriceQ144 = liqSqrtPriceQ72 ** 2;
        (startOfLiquidationPriceQ128, endOfLiquidationPriceQ128) = netDebtX
            ? (
                liqPriceDividedBySpan(liqPriceQ144, sqrtPriceSpanQ72),
                liqPriceMultipliedBySpan(liqPriceQ144, sqrtPriceSpanQ72)
            )
            : (
                liqPriceMultipliedBySpan(liqPriceQ144, sqrtPriceSpanQ72),
                liqPriceDividedBySpan(liqPriceQ144, sqrtPriceSpanQ72)
            );
    }

    function liqPriceDividedBySpan(
        uint256 liqPriceQ144,
        uint256 sqrtPriceSpanQ72
    ) private pure returns (uint256 priceQ128) {
        priceQ128 = liqPriceQ144 < Q128 ? liqPriceQ144 * sqrtPriceSpanQ72 / Q88 : liqPriceQ144 / Q88 * sqrtPriceSpanQ72;
    }

    function liqPriceMultipliedBySpan(
        uint256 liqPriceQ144,
        uint256 sqrtPriceSpanQ72
    ) private pure returns (uint256 priceQ128) {
        priceQ128 =
            (liqPriceQ144 < Q200 ? liqPriceQ144 * Q56 / sqrtPriceSpanQ72 : liqPriceQ144 / sqrtPriceSpanQ72 * Q56);
    }

    /**
     * @notice  calc net debt and span
     * @param   inputParams  the input params
     * @param   desiredThresholdMag2  the desired threshold
     * @param   netDebtX  whether the net debt is X or Y
     * @return  netDebtXorYAssets  the net debt
     * @return  netDebtLAssets  the net debt in L assets
     * @return  minSqrtPriceSpanQ72  the tranche span in sqrtPrice
     */
    function calculateNetDebtAndSpan(
        Validation.InputParams memory inputParams,
        uint256 liqSqrtPriceInXInQ72,
        uint256 desiredThresholdMag2,
        bool netDebtX
    ) internal pure returns (uint256 netDebtXorYAssets, uint256 netDebtLAssets, uint256 minSqrtPriceSpanQ72) {
        Validation.CheckLtvParams memory checkLtvParams =
            Validation.getCheckLtvParams(inputParams.userAssets, liqSqrtPriceInXInQ72, liqSqrtPriceInXInQ72);
        uint256 netCollateralLAssets;
        (netDebtLAssets, netCollateralLAssets,) = Validation.calcDebtAndCollateral(checkLtvParams);

        minSqrtPriceSpanQ72 = calculateMinSqrtPriceSpanQ72(
            netCollateralLAssets, netDebtLAssets, inputParams.activeLiquidityAssets, desiredThresholdMag2
        );

        // Convert to assets of X or Y so that `calcTickAtStartOfLiquidation` &
        // `calculateSaturation()` does not need to convert from L to X or Y.
        netDebtXorYAssets = netDebtX
            ? Validation.convertLToX(netDebtLAssets, liqSqrtPriceInXInQ72, false)
            : Validation.convertLToY(netDebtLAssets, liqSqrtPriceInXInQ72, false);
    }

    /**
     * @notice  calculate the relative saturation of the position at the end of liquidation.
     *   Since we place saturation in tranches starting at the tick where the liquidation would
     *   end and moving forward to the start of liquidation, this calculates the entire saturation
     *   as if it would fit in the last tranche, we then we will need to adjust the saturation each
     *   time we move forward a tranche to the next tranche by dividing by a factor of $$B$$ when
     *   we allocate the saturation later. The equation here is slightly different than the
     *   equation in our description since we multiply by a factor of $$B$$ for each tranche we
     *   move back from the start of liquidation tick. Thus here we use, where $$tSpan$$ is the
     *   number of tranches we need to move back,
     *
     *   ```math
     *   \begin{equation}T_{sat} =
     *   \begin{cases}
     *     \Large\frac{debt}{b^{t_e}(B-1)}
     *     &\text{ when debt is in X asset }
     *   \\
     *
     *     \Large\frac{debt \cdot b^{t_e}}{B-1}
     *     &\text{ otherwise }
     *   \end{cases}
     *   \end{equation}
     *   ```
     *
     *   As we iterate through tranches, we divide by a factor of $$B$$ such that when we reach the
     *   final tranche, our equation from the start applies.
     *
     *   Note that we also magnify the debt by the `SATURATION_TIME_BUFFER_IN_MAG2` to account for
     *   the potential growth that will occur over time due to interest. This allows for our
     *   estimate of saturation to be static in spite of the dynamic impact of interest.
     *
     * @param  netDebtXOrYAssets  the net debt in X or Y assets.
     * @param  endOfLiquidationSqrtPriceQ72 the tick at which the liquidation ends.
     * @param  netDebtX  whether the debt is net in X or Y assets
     * @return saturation  the saturation relative to active liquidity assets.
     */
    function calculateSaturation(
        uint256 netDebtXOrYAssets,
        uint256 endOfLiquidationSqrtPriceQ72,
        bool netDebtX
    ) internal pure returns (uint128 saturation) {
        saturation = SafeCast.toUint128(
            Convert.mulDiv(
                netDebtXOrYAssets * SATURATION_TIME_BUFFER_IN_MAG2,
                netDebtX ? Math.ceilDiv(Q144, endOfLiquidationSqrtPriceQ72) : endOfLiquidationSqrtPriceQ72,
                (TRANCHE_B_MINUS_ONE_IN_Q72) * MAG2,
                ROUNDING_UP
            )
        );
    }

    function calculateMinSqrtPriceSpanQ72(
        uint256 collateral,
        uint256 debt,
        uint256 activeLiquidityAssets,
        uint256 desiredThresholdMag2
    ) internal pure returns (uint256 sqrtPriceSpanQ72) {
        uint256 bQ72 =
        // debt and collateral are 256 bits together, so we have to divide
        // by MAG6 before multiplying by collateral to avoid overflow on multiplication.
        Convert.mulDiv(
            Convert.mulDiv(
                Convert.mulDiv(debt, EXPECTED_SATURATION_LTV_MAG2_TIMES_SAT_BUFFER_SQUARED, MAG6, false),
                collateral,
                // divide active liquidity in two steps to avoid the result vanishing.
                activeLiquidityAssets * desiredThresholdMag2 ** 2,
                false
            ),
            // scale to Q72 and multiply by Mag4 to cancel Mag4 from last division Mag4 units.
            MAG4_TIMES_Q72,
            // divide by by the second active liquidity asset.
            activeLiquidityAssets,
            false
        ) + TWO_Q72;

        // apply quadratic formula, a and c are both 1.
        sqrtPriceSpanQ72 = Math.ceilDiv((bQ72 + Math.sqrt(bQ72 ** 2 - FOUR_Q144)), 2);
    }

    // bit functions
    // node read write
    // uint node = [112 empty bits, 16 tranche count bits, 112 sat bits, 16 field bits]

    /**
     * @notice  read single bit value from the field of a node
     * @param   node  the full node
     * @param   bitPos  position of the bit $ \le 16 $
     * @return  bit  the resulting bit, 0 xor 1, as a uint
     */
    function readFieldBitFromNode(uint256 node, uint256 bitPos) internal pure returns (uint256 bit) {
        uint256 MASK = 1 << bitPos;
        assembly ("memory-safe") {
            bit := iszero(iszero(and(node, MASK)))
        }
    }

    /**
     * @notice  write to node
     * @param   nodeIn  node to read from
     * @param   bitPos  position of the bit $ \le 16 $
     * @return  nodeOut  node with bit flipped
     */
    function writeFlippedFieldBitToNode(uint256 nodeIn, uint256 bitPos) internal pure returns (uint256 nodeOut) {
        uint256 MASK = 1 << bitPos;
        nodeOut = nodeIn ^ MASK;
    }

    /**
     * @notice  read field from node
     * @param   node  node to read from
     * @return  field  field of the node
     */
    function readFieldFromNode(
        uint256 node
    ) internal pure returns (uint256 field) {
        field = node & FIELD_NODE_MASK;
    }

    /**
     * @notice Calculates the penalty scaling factor based on current borrow utilization and
     *   saturation
     *   This implements the penalty rate function
     *      Formula:
     *      ```math
     *        ((1 - u_0) \cdot f_{interestPerSecond}(u_1) \cdot allAssetsDepositL) / (WAD
     *        \cdot satInPenaltyInLAssets)
     *      ```
     *      Where,
     *      ```math
     *        u_1 = (0.90 - (1 - u_0) \cdot (0.95 - u_s) / 0.95)
     *      ```
     * @param currentBorrowUtilizationInWad Current borrow utilization of L (u_0)
     * @param saturationUtilizationInWad Current saturation utilization (u_s)
     * @param satInPenaltyInLAssets The saturation in L assets in the penalty
     * @param allAssetsDepositL The total assets deposited in L
     * @return penaltyRatePerSecondInWads The penalty rate per second in WADs
     */
    function calcSaturationPenaltyRatePerSecondInWads(
        uint256 currentBorrowUtilizationInWad,
        uint256 saturationUtilizationInWad,
        uint128 satInPenaltyInLAssets,
        uint256 allAssetsDepositL
    ) internal pure returns (uint256 penaltyRatePerSecondInWads) {
        uint256 oneMinusCurrentUtilizationWads = WAD - currentBorrowUtilizationInWad;

        // f_interestPerSecond(u_1) | Get the interest rate at target utilization (this is already magnified by 5x for liquidity)
        uint256 interestRateAtTargetUtilizationInWads = Interest.getAnnualInterestRatePerSecondInWads(
            // in this case we have low borrow utilization and low saturation
            MAX_UTILIZATION_PERCENT_IN_WAD
                - Math.min(
                    MAX_UTILIZATION_PERCENT_IN_WAD,
                    // Calculate target utilization:
                    // u_1 = 0.90 - (1 - u_0) * (0.95 - u_s) / 0.95
                    Convert.mulDiv(
                        oneMinusCurrentUtilizationWads,
                        MAX_SATURATION_PERCENT_IN_WAD - saturationUtilizationInWad,
                        MAX_SATURATION_PERCENT_IN_WAD,
                        false
                    )
                )
        ) * LIQUIDITY_INTEREST_RATE_MAGNIFICATION;

        // penaltyRatePerSecondInWads =
        // ((1 - u_0) * f_interestPerSecond(u_1) * allAssetsDepositL) / WAD * satInPenaltyInLAssets
        penaltyRatePerSecondInWads = Convert.mulDiv(
            Convert.mulDiv(oneMinusCurrentUtilizationWads, interestRateAtTargetUtilizationInWads, WAD, false),
            allAssetsDepositL,
            satInPenaltyInLAssets,
            false
        );
    }
}

lib/core-v1/contracts/libraries/TickMath.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.34;

import {Convert} from 'contracts/libraries/Convert.sol';
import {Q128} from 'contracts/libraries/constants.sol';

/**
 * @title Math library for computing sqrt prices from ticks and vice versa
 * @notice Computes sqrt price for ticks of size $B=(1-2^{-9})^{-1}$ as fixed point Q72 numbers.
 * Supports prices between $2^{-112}$ and $2^{112}-1$.
 */
library TickMath {
    error PriceOutOfBounds();
    error TickOutOfBounds();

    // big(2)^64 / log2(B) - 1; / 2 since the input is price but ticks map to sqrt price; -1 since without is an odd number
    int256 private constant BASE_CHANGE_CONSTANT_IN_Q128 = 0xb145b7be86780ae93f;
    int256 private constant TICK_LOW_ERROR_CORRECTION_IN_Q128 = 0x1f6d22eefc342687357a94df44b0dbf;
    int256 private constant TICK_HI_ERROR_CORRECTION_IN_Q128 = 0xb33c8bdbc23c5eaf1cd8140681512562;

    uint256 internal constant MIN_PRICE_IN_Q128 = 0x10000;
    uint256 internal constant MAX_PRICE_IN_Q128 = 0xffffffffffffffffffffffffffff00000000000000000000000000000000;

    // getSqrtPriceAtTick(MIN_TICK) == MIN_SQRT_PRICE_IN_Q72 < getSqrtPriceAtTick(MIN_TICK + 1)
    // getSqrtPriceAtTick(MAX_TICK - 1) < MAX_SQRT_PRICE_IN_Q72 == getSqrtPriceAtTick(MAX_TICK)
    int16 internal constant MIN_TICK = -0x4d8f; // -19855
    int16 internal constant MAX_TICK = 0x4d8e; // -MIN_TICK - 1; // 19854
    uint256 internal constant MIN_SQRT_PRICE_IN_Q72 = 0xffc0;
    uint256 internal constant MAX_SQRT_PRICE_IN_Q72 = 0xffc00ffc00ffc00ffc00ffc00ffc00ff;

    // sqrtPrice = B^tick
    function getSqrtPriceAtTick(
        int16 tick
    ) internal pure returns (uint256 sqrtPriceInQ72) {
        // Handle edge case where we round up tick by 1.
        if (tick == MAX_TICK + 1) return MAX_SQRT_PRICE_IN_Q72;
        if (tick < MIN_TICK || MAX_TICK + 1 < tick) revert TickOutOfBounds();

        int256 intTick = int256(tick);
        uint256 absTick = uint256(intTick < 0 ? -intTick : intTick);

        sqrtPriceInQ72 = applyMultiplications(absTick) >> 56; // 72 == 128 - 56
        if (0 < tick) sqrtPriceInQ72 = type(uint144).max / sqrtPriceInQ72; // 2 * 72 == 144
    }

    // tick = log in basis B of priceInQ128
    function getTickAtPrice(
        uint256 priceInQ128
    ) internal pure returns (int16) {
        if (priceInQ128 < MIN_PRICE_IN_Q128 || MAX_PRICE_IN_Q128 < priceInQ128) revert PriceOutOfBounds();

        uint256 p = priceInQ128;
        uint256 msb = 0;

        assembly {
            let f := shl(7, gt(p, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(6, gt(p, 0xFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(5, gt(p, 0xFFFFFFFF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(4, gt(p, 0xFFFF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(3, gt(p, 0xFF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(2, gt(p, 0xF))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := shl(1, gt(p, 0x3))
            msb := or(msb, f)
            p := shr(f, p)
        }
        assembly {
            let f := gt(p, 0x1)
            msb := or(msb, f)
        }

        int256 logBase2;
        unchecked {
            if (msb >= 128) p = priceInQ128 >> (msb - 127);
            else p = priceInQ128 << (127 - msb);
            logBase2 = (int256(msb) - 128) << 64;
        }

        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(63, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(62, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(61, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(60, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(59, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(58, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(57, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(56, f))
            p := shr(f, p)
        }
        assembly {
            p := shr(127, mul(p, p))
            let f := shr(128, p)
            logBase2 := or(logBase2, shl(55, f))
            p := shr(f, p)
        }

        unchecked {
            int256 logB = BASE_CHANGE_CONSTANT_IN_Q128 * logBase2;
            int16 tickLow = int16((logB - TICK_LOW_ERROR_CORRECTION_IN_Q128) >> 128);
            int16 tickHi = int16((logB + TICK_HI_ERROR_CORRECTION_IN_Q128) >> 128);
            if (tickLow == tickHi) return tickLow;
            if (getPriceAtTick(tickHi) <= priceInQ128) return tickHi;
            return tickLow;
        }
    }

    function getPriceAtTick(
        int16 tick
    ) internal pure returns (uint256 priceInQ128) {
        if (tick == MAX_TICK + 1) return MAX_PRICE_IN_Q128;
        if (tick < MIN_TICK || MAX_TICK + 1 < tick) revert TickOutOfBounds();

        int256 intTick = tick;
        uint256 absTick = uint256(intTick < 0 ? -intTick : intTick);

        // apply the same algorithm as in getSqrtPriceAtTick using tick * 2 and adding a round.
        absTick *= 2;
        priceInQ128 = applyMultiplications(absTick);
        if (absTick & 0x8000 != 0) priceInQ128 = (priceInQ128 * 0xbef94ed7e) >> 128;

        if (0 < tick) priceInQ128 = type(uint256).max / priceInQ128;
    }

    function applyMultiplications(
        uint256 absTick
    ) private pure returns (uint256 valueInQ128) {
        unchecked {
            valueInQ128 = absTick & 0x1 != 0 ? 0xff800000000000000000000000000000 : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0) valueInQ128 = (valueInQ128 * 0xff004000000000000000000000000000) >> 128;
            if (absTick & 0x4 != 0) valueInQ128 = (valueInQ128 * 0xfe017f80100000000000000000000000) >> 128;
            if (absTick & 0x8 != 0) valueInQ128 = (valueInQ128 * 0xfc06f9045e406ff00100000000000000) >> 128;
            if (absTick & 0x10 != 0) {
                valueInQ128 = (valueInQ128 * 0xf81dba7137fcc6d22fafcfde71ae81e0) >> 128;
            }
            if (absTick & 0x20 != 0) {
                valueInQ128 = (valueInQ128 * 0xf0799caf21e927ea1252fa7400a1d886) >> 128;
            }
            if (absTick & 0x40 != 0) {
                valueInQ128 = (valueInQ128 * 0xe1e43f8ddd0922622788b108788fc191) >> 128;
            }
            if (absTick & 0x80 != 0) {
                valueInQ128 = (valueInQ128 * 0xc7530338a302e81d8229a7f1f67fa265) >> 128;
            }
            if (absTick & 0x100 != 0) {
                valueInQ128 = (valueInQ128 * 0x9b3229ed2432991a2e021bb106f5feb6) >> 128;
            }
            if (absTick & 0x200 != 0) {
                valueInQ128 = (valueInQ128 * 0x5e15c89991553a6dc1c8a8a0931572d2) >> 128;
            }
            if (absTick & 0x400 != 0) {
                valueInQ128 = (valueInQ128 * 0x2294012b4d1cbe1865fe254cef6e40bc) >> 128;
            }
            if (absTick & 0x800 != 0) {
                valueInQ128 = (valueInQ128 * 0x4aba5e0da8e29a77fabca56a012ae25) >> 128;
            }
            if (absTick & 0x1000 != 0) {
                valueInQ128 = (valueInQ128 * 0x15d0460cb40a7356d32b6966397c03) >> 128;
            }
            if (absTick & 0x2000 != 0) valueInQ128 = (valueInQ128 * 0x1dbd4effd593afec2694414e4f6) >> 128;
            if (absTick & 0x4000 != 0) valueInQ128 = (valueInQ128 * 0x3746fe3b485b7be710a06) >> 128;
        }
    }

    /**
     * @dev Get the new tick based on the current reserves.
     * @param reserveXAssets The current reserve X assets.
     * @param reserveYAssets The current reserve Y assets.
     * @return newTick The current tick.
     */
    function getTickFromReserves(uint256 reserveXAssets, uint256 reserveYAssets) internal pure returns (int16) {
        return getTickAtPrice(Convert.mulDiv(reserveXAssets, Q128, reserveYAssets, false));
    }
}

lib/core-v1/contracts/libraries/Uint16Set.sol

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

/**
 * based on https://github.com/rob-Hitchens/SetTypes/blob/master/contracts/UintSet.sol
 * @notice Key sets with enumeration and delete. Uses mappings for random
 * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced.
 * @dev Sets are unordered. Delete operations reorder keys. All operations have a
 * fixed gas cost at any scale, O(1).
 * author: Rob Hitchens
 */
library Uint16Set {
    struct Set {
        mapping(uint16 => uint16) keyPointers;
        uint16[] keyList;
    }

    /**
     * @notice insert a key.
     * @dev duplicate keys are not permitted.
     * @param self storage pointer to a Set.
     * @param key value to insert.
     * @return keyAlreadyExists whether the key already existed in the set
     */
    function insert(Set storage self, uint16 key) internal returns (bool keyAlreadyExists) {
        if (exists(self, key)) return true;
        self.keyList.push(key);
        self.keyPointers[key] = uint16(self.keyList.length) - 1;
    }

    /**
     * @notice remove a key.
     * @dev If the key does not exist, this function is a no-op and returns true.
     * @param self storage pointer to a Set.
     * @param key value to remove.
     * @return isSetEmpty whether the key did not exist or the set still has items after removal
     */
    function remove(Set storage self, uint16 key) internal returns (bool isSetEmpty) {
        if (!exists(self, key)) {
            isSetEmpty = true;
        } else {
            uint16 last = count(self) - 1;
            uint16 rowToReplace = self.keyPointers[key];
            if (rowToReplace != last) {
                uint16 keyToMove = self.keyList[last];
                self.keyPointers[keyToMove] = rowToReplace;
                self.keyList[rowToReplace] = keyToMove;
            }
            delete self.keyPointers[key];
            self.keyList.pop();
            isSetEmpty = last > 0;
        }
    }

    /**
     * @notice count the keys.
     * @param self storage pointer to a Set.
     */
    function count(
        Set storage self
    ) internal view returns (uint16) {
        return uint16(self.keyList.length);
    }

    /**
     * @notice check if a key is in the Set.
     * @param self storage pointer to a Set.
     * @param key value to check.
     * @return bool true: Set member, false: not a Set member.
     */
    function exists(Set storage self, uint16 key) internal view returns (bool) {
        if (self.keyList.length == 0) return false;
        return self.keyList[self.keyPointers[key]] == key;
    }
}

lib/core-v1/contracts/libraries/constants.sol

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

/**
 * @dev This basis was a modification to Uniswap V3's basis, to fit ticks into int16 instead of
 *  int24. We use the form $$\frac{2^{9}}{2^{9}-1}$$ which is just under 1.002. This basis
 *  format gives smaller errors since the fraction is more compatible with binary Q128
 *  fractions since the base is inverted in the tick math library before multiplications are
 *  applied.
 *  ```math
 *    \begin{align*}
 *    &   \frac{2^{9}}{2^{9}-1}^{-1} \cdot 2^{128}
 *    & & \frac{10001}{10000}^{-1} \cdot 2^{128}
 *    \\
 *    &   \frac{2^{9}-1}{2^{9}} \cdot 2^{256}
 *    & & \frac{10000\cdot2^{256}}{10001}
 *    \\
 *    &   339617752923046005526922703901628039168
 *    & & \frac{3402823669209384634633746074317682114560000}{10001}
 *    \\
 *    &   0xff800000000000000000000000000000
 *    & & 0xfffcb933bd6fad37aa2d162d1a594001
 *    \\
 *  \end{align*}
 *  ```
 *  We use this constant outside of the tick math library, and use a Q72 as that format is
 *  easier to work with multiplication without overflows.
 *  ```python
 *  >>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1) * 2**72)))
 *  ```
 *  We store in hex to reduce code size.
 */
uint256 constant B_IN_Q72 = 0x1008040201008040201;

/**
 * @dev In Saturation we combine 25 ticks to make one tranche.
 *  ```python
 *  >>> hex(int(mpm.nint(mpm.fdiv(2**9, 2**9-1)**25 * 2**72)))
 *  ```
 *  We store in hex to reduce code size.
 */
uint256 constant TRANCHE_B_IN_Q72 = 0x10cd2b2ae53a69d3552;

/**
 * @dev B - 1 or `TRANCHE_B_IN_Q72 - Q72`.
 */
uint256 constant TRANCHE_B_MINUS_ONE_IN_Q72 = 0xcd2b2ae53a69d3552;

/**
 * @dev We decrement the active liquidity used to measure available saturation by this
 *   percentage of fragile liquidity, or liquidity that has some amount of x or y borrowed
 *   against it. Reducing by 100% would ensure that that fragile liquidity could always be
 *   liquidated since burning it would not decrease the saturation. However, this also means
 *   that fragile liquidity adds no value to the risk of the pool, even if it may not be
 *   liquidated until after risk closer to the price. This value also ensures that recursively
 *   leveraging large amounts of x and y against liquidity can not allow more debt to be
 *   borrowed then the underlying stable liquidity not at risk of being seized and burned
 *   during liquidation. Crediting 10% of the fragile liquidity is a compromise to allow some
 *   benefit of leveraged liquidity to increase borrowing capacity without allowing for it to
 *   be vulnerable to allow excessive borrowing.
 */
uint256 constant FRAGILE_LIQUIDITY_DECREMENT_PERCENTAGE = 95;

/**
 * @dev The amount of LTV we expect liquidations to occur at
 */
uint256 constant EXPECTED_SATURATION_LTV_MAG2 = 85;

/**
 * @dev percentage of max sat per tranche considered healthy; max sat per
 * tranche is $$liquidity \cdot \frac{B-1}{2}$$ with B the tranche basis, which is the max
 * sat such that the liquidation would not cause a swap larger than a tranche
 */
uint256 constant MAX_SATURATION_RATIO_IN_MAG2 = 95;

/**
 * @dev the default zero address
 */
address constant ZERO_ADDRESS = address(0);

/**
 * @dev $2^{16}$.
 */
uint256 constant Q16 = 0x10000;

/**
 * @dev $2^{32}$.
 */
uint256 constant Q32 = 0x100000000;

/**
 * @dev $2^{56}$.
 */
uint256 constant Q56 = 0x100000000000000;

/**
 * @dev $2^{64}$.
 */
uint256 constant Q64 = 0x10000000000000000;

/**
 * @dev $2^{72}$.
 */
uint256 constant Q72 = 0x1000000000000000000;

/**
 * @dev $2^{88}$.
 */
uint256 constant Q88 = 0x10000000000000000000000;

/**
 * @dev $2^{112}$.
 */
uint256 constant Q112 = 0x10000000000000000000000000000;

/**
 *
 * @dev $2^{128}$.
 */
uint256 constant Q128 = 0x100000000000000000000000000000000;

/**
 * @dev $2^{144}$.
 */
uint256 constant Q144 = 0x1000000000000000000000000000000000000;

/**
 * @dev $2^{200}$.
 */
uint256 constant Q200 = 0x100000000000000000000000000000000000000000000000000;

/**
 * @dev number of bips in 1, 1 bips = 0.01%.
 */
uint256 constant BIPS = 10_000;

/**
 * @dev Initial fee applied to all newly opened debts and flash loans. This upfront fee prevents
 * griefing attacks via "dust" positions—small debts that would be unprofitable for liquidators to close.
 * The fee accumulates in the protocol, creating an economic incentive to liquidate these positions
 * if they become eligible for liquidation.
 * 5 bips = 0.05%.
 */
uint256 constant INITIAL_LENDING_FEE_BIPS = 5;

/**
 * @dev Default mid-term interval config used at the time of GeometricTWAP initialization.
 */
uint16 constant DEFAULT_MID_TERM_INTERVAL = 8;

/**
 * @dev minimum liquidity to initialize a pool, amount is burned to eliminate the threat of
 *  donation attacks.
 */
uint256 constant MINIMUM_LIQUIDITY = 1000;

/**
 * @dev Represents the minimum time period required between recorded long-term intervals.
 * Calculated as the product of `DEFAULT_MID_TERM_INTERVAL` and `GeometricTWAP.
 * MINIMUM_LONG_TERM_INTERVAL_FACTOR`.
 */
uint24 constant MINIMUM_LONG_TERM_TIME_UPDATE_CONFIG = 112;

/**
 * @dev `MAX_TICK_DELTA` limits the `newTick` to be within the outlier range of the current mid-term price.
 */
int256 constant MAX_TICK_DELTA = 10;

/**
 * @dev `DEFAULT_TICK_DELTA_FACTOR` is used when the long-term buffer is initialized.
 */
int256 constant DEFAULT_TICK_DELTA_FACTOR = 1;

/**
 * @dev the system loan to value minimum, 75% * 100.
 */
uint256 constant LTVMAX_IN_MAG2 = 75;

/**
 * @dev the system allowed leverage exposures with similar underlying assets, ie L is half X and
 * half Y, so we allow 100X leverage of borrowed X and Y against L.
 */
uint256 constant ALLOWED_LIQUIDITY_LEVERAGE = 100;

/**
 * @dev Allowed leverage minus one.
 */
uint256 constant ALLOWED_LIQUIDITY_LEVERAGE_MINUS_ONE = 99;

/**
 * @dev constant used in Quadratic swap fees that controls the speed at which fees increase with
 * respect to the price change.
 */
uint256 constant N_TIMES_FEE = 20;

/**
 * @dev Magnitude 1
 */
uint256 constant MAG1 = 10;

/**
 * @dev Magnitude 2
 */
uint256 constant MAG2 = 100;

/**
 * @dev Magnitude 4
 */
uint256 constant MAG4 = 10_000;

/**
 * @dev Magnitude 6
 */
uint256 constant MAG6 = 1_000_000;

/**
 * @dev Saturation percentages in WADs
 */
uint256 constant SAT_PERCENTAGE_DELTA_4_WAD = 94.1795538580338563e16;
uint256 constant SAT_PERCENTAGE_DELTA_5_WAD = 92.3156868017020937e16;
uint256 constant SAT_PERCENTAGE_DELTA_6_WAD = 90.4887067368814135e16;
uint256 constant SAT_PERCENTAGE_DELTA_7_WAD = 88.6978836489829983e16;
uint256 constant SAT_PERCENTAGE_DELTA_DEFAULT_WAD = 95e16;

uint256 constant LIQUIDITY_INTEREST_RATE_MAGNIFICATION = 5;
/**
 * @dev Maximum percentage for the saturation allowed, used to limit the maximum saturation per tranche.
 */
uint256 constant MAX_SATURATION_PERCENT_IN_WAD = 0.95e18; // 95%

/**
 * @dev Maximum percentage for the utilization allowed.
 */
uint256 constant MAX_UTILIZATION_PERCENT_IN_WAD = 0.9e18; // 90%

uint256 constant SECONDS_IN_YEAR = 365 days;

/**
 * @dev The interval for swap to check borrowed interest to update reserves.
 *  Updating once a day would limit rate change in price to 0.003% if one reserve
 *  had max interest and the other had none.
 *  It also would require 40 days to go from 94% depletion to 95% depletion.
 *  ref: https://www.desmos.com/calculator/sxfc3tcz8c
 */
uint32 constant INTEREST_PERIOD_FOR_SWAP = 1 days - 1;

/**
 * @dev The interval for non-swap to check borrowed interest to update reserves.
 */
uint32 constant DEFAULT_INTEREST_PERIOD = 0;

/**
 * @dev Buffer ratio at which lending of the scarce asset stops.
 *      Derived from 95 / 5.
 */
uint256 constant BUFFER = 19;

/**
 * @dev Numerator buffer used for depleted-asset threshold calculations.
 *      Derived from 100 / 5.
 */
uint256 constant BUFFER_NUMERATOR = 20;

/**
 * @dev Observation buffer used when computing the new tick from reserves.
 *      Derived from 45 / 5.
 */
uint256 constant BUFFER_OBS = 9;

/**
 * @dev Observation buffer numerator used for depleted-asset threshold calculations.
 *      Derived from 50 / 5.
 */
uint256 constant BUFFER_OBS_NUMERATOR = 10;

/**
 * @dev index implementation for default full functionality
 */
uint256 constant INDEX_FULL_IMPL = 0;
/**
 * @dev index implementation that locks borrowing, withdrawing, burning, except liquidation
 */
uint256 constant INDEX_LOCKED_LOANS = 1;
/**
 * @dev index implementation that blocks all transfers:  withdraw, burn, borrow and liquidation
 */
uint256 constant INDEX_BLOCK_ALL_TRANSFERS = 2;
/**
 * @dev index implementation that freezes any function calling the pair: mints, swaps, ..etc
 */
uint256 constant INDEX_FROZEN = 3;

lib/core-v1/lib/mangrove-core/lib/core/BitLib.sol

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

library BitLib {
  // - if x is a nonzero uint64: 
  //   return number of zeroes in x that do not have a 1 to their right
  // - otherwise:
  //    return 64
  function ctz64(uint x) internal pure returns (uint256 c) {
    unchecked {
      assembly ("memory-safe") {
        // clean
        x:= and(x,0xffffffffffffffff)

        // 7th bit
        c:= shl(6,iszero(x))

        // isolate lsb
        x := and(x, add(not(x), 1))

        // 6th bit
        c := or(c,shl(5, lt(0xffffffff, x)))

        // debruijn lookup
        c := or(c, byte(shr(251, mul(shr(c, x), shl(224, 0x077cb531))), 
            0x00011c021d0e18031e16140f191104081f1b0d17151310071a0c12060b050a09))
      }
    }
  }

  // Function fls is MIT License. Copyright (c) 2022 Solady.
/// @dev find last set.
    /// Returns the index of the most significant bit of `x`,
    /// counting from the least significant bit position.
    /// If `x` is zero, returns 256.
    /// Equivalent to `log2(x)`, but without reverting for the zero case.
    function fls(uint256 x) internal pure returns (uint256 r) {
        assembly ("memory-safe") {
            r := shl(8, iszero(x))

            r := or(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.
            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))
        }
    }
}

lib/core-v1/lib/morpho-blue/src/libraries/MathLib.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

uint256 constant WAD = 1e18;

/// @title MathLib
/// @author Morpho Labs
/// @custom:contact [email protected]
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
    /// @dev Returns (`x` * `y`) / `WAD` rounded down.
    function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded down.
    function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y);
    }

    /// @dev Returns (`x` * `WAD`) / `y` rounded up.
    function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y);
    }

    /// @dev Returns (`x` * `y`) / `d` rounded down.
    function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y) / d;
    }

    /// @dev Returns (`x` * `y`) / `d` rounded up.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
        return (x * y + (d - 1)) / d;
    }

    /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
    /// continuous compound interest rate.
    function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
        uint256 firstTerm = x * n;
        uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
        uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);

        return firstTerm + secondTerm + thirdTerm;
    }
}

lib/core-v1/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/core-v1/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

lib/core-v1/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
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);
}

lib/core-v1/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/core-v1/lib/openzeppelin-contracts/contracts/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/core-v1/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 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²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the 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.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/core-v1/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@core-v1/=lib/core-v1/",
    "@peripheral-v1/=lib/peripheral-v1/contracts/",
    "contracts/=lib/core-v1/contracts/",
    "utils/=lib/core-v1/utils/",
    "@openzeppelin/=lib/core-v1/lib/openzeppelin-contracts/",
    "@openzeppelin-upgradeable/=lib/core-v1/lib/openzeppelin-contracts-upgradeable/",
    "@1inch/=lib/core-v1/lib/1inch/",
    "@mangrovedao/mangrove-core/=lib/core-v1/lib/mangrove-core/",
    "@morpho-org/morpho-blue/=lib/core-v1/lib/morpho-blue/",
    "forge-std/=lib/core-v1/lib/forge-std/src/",
    "lib/ExcessivelySafeCall/=lib/core-v1/lib/ExcessivelySafeCall/",
    "lib/openzeppelin-contracts/=lib/core-v1/lib/openzeppelin-contracts/",
    "lib/1inch/=lib/core-v1/lib/1inch/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.