ETH Price: $2,888.07 (-1.62%)

Contract

0x000000E22477C615223E430266AD8d5285636e30

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
184062462025-06-05 20:16:45234 days ago1749154605  Contract Creation0 ETH

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
CarpetedDoubleGeometricDistribution

Compiler Version
v0.8.30+commit.73712a01

Optimization Enabled:
Yes with 100000000 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";

import "./ShiftMode.sol";
import {Guarded} from "../base/Guarded.sol";
import {LDFType} from "../types/LDFType.sol";
import {LibCarpetedDoubleGeometricDistribution} from "./LibCarpetedDoubleGeometricDistribution.sol";
import {ILiquidityDensityFunction} from "../interfaces/ILiquidityDensityFunction.sol";

/// @title CarpetedDoubleGeometricDistribution
/// @author zefram.eth
/// @notice Double geometric distribution with a "carpet" of uniform liquidity outside of the main range.
/// Should be used in production when TWAP is enabled, since we always have some liquidity in all ticks.
contract CarpetedDoubleGeometricDistribution is ILiquidityDensityFunction, Guarded {
    uint32 internal constant INITIALIZED_STATE = 1 << 24;

    constructor(address hub_, address hook_, address quoter_) Guarded(hub_, hook_, quoter_) {}

    /// @inheritdoc ILiquidityDensityFunction
    function query(
        PoolKey calldata key,
        int24 roundedTick,
        int24 twapTick,
        int24, /* spotPriceTick */
        bytes32 ldfParams,
        bytes32 ldfState
    )
        external
        view
        override
        guarded
        returns (
            uint256 liquidityDensityX96_,
            uint256 cumulativeAmount0DensityX96,
            uint256 cumulativeAmount1DensityX96,
            bytes32 newLdfState,
            bool shouldSurge
        )
    {
        LibCarpetedDoubleGeometricDistribution.Params memory params =
            LibCarpetedDoubleGeometricDistribution.decodeParams(twapTick, key.tickSpacing, ldfParams);
        (bool initialized, int24 lastMinTick) = _decodeState(ldfState);
        if (initialized) {
            params.minTick = enforceShiftMode(params.minTick, lastMinTick, params.shiftMode);
            shouldSurge = params.minTick != lastMinTick;
        }

        (liquidityDensityX96_, cumulativeAmount0DensityX96, cumulativeAmount1DensityX96) =
            LibCarpetedDoubleGeometricDistribution.query(roundedTick, key.tickSpacing, params);
        newLdfState = _encodeState(params.minTick);
    }

    /// @inheritdoc ILiquidityDensityFunction
    function computeSwap(
        PoolKey calldata key,
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 twapTick,
        int24, /* spotPriceTick */
        bytes32 ldfParams,
        bytes32 ldfState
    )
        external
        view
        override
        guarded
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        )
    {
        LibCarpetedDoubleGeometricDistribution.Params memory params =
            LibCarpetedDoubleGeometricDistribution.decodeParams(twapTick, key.tickSpacing, ldfParams);
        (bool initialized, int24 lastMinTick) = _decodeState(ldfState);
        if (initialized) {
            params.minTick = enforceShiftMode(params.minTick, lastMinTick, params.shiftMode);
        }

        return LibCarpetedDoubleGeometricDistribution.computeSwap(
            inverseCumulativeAmountInput, totalLiquidity, zeroForOne, exactIn, key.tickSpacing, params
        );
    }

    /// @inheritdoc ILiquidityDensityFunction
    function cumulativeAmount0(
        PoolKey calldata key,
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 twapTick,
        int24, /* spotPriceTick */
        bytes32 ldfParams,
        bytes32 ldfState
    ) external view override guarded returns (uint256) {
        LibCarpetedDoubleGeometricDistribution.Params memory params =
            LibCarpetedDoubleGeometricDistribution.decodeParams(twapTick, key.tickSpacing, ldfParams);
        (bool initialized, int24 lastMinTick) = _decodeState(ldfState);
        if (initialized) {
            params.minTick = enforceShiftMode(params.minTick, lastMinTick, params.shiftMode);
        }

        return LibCarpetedDoubleGeometricDistribution.cumulativeAmount0(
            roundedTick, totalLiquidity, key.tickSpacing, params
        );
    }

    /// @inheritdoc ILiquidityDensityFunction
    function cumulativeAmount1(
        PoolKey calldata key,
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 twapTick,
        int24, /* spotPriceTick */
        bytes32 ldfParams,
        bytes32 ldfState
    ) external view override guarded returns (uint256) {
        LibCarpetedDoubleGeometricDistribution.Params memory params =
            LibCarpetedDoubleGeometricDistribution.decodeParams(twapTick, key.tickSpacing, ldfParams);
        (bool initialized, int24 lastMinTick) = _decodeState(ldfState);
        if (initialized) {
            params.minTick = enforceShiftMode(params.minTick, lastMinTick, params.shiftMode);
        }

        return LibCarpetedDoubleGeometricDistribution.cumulativeAmount1(
            roundedTick, totalLiquidity, key.tickSpacing, params
        );
    }

    /// @inheritdoc ILiquidityDensityFunction
    function isValidParams(PoolKey calldata key, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        external
        pure
        override
        returns (bool)
    {
        return LibCarpetedDoubleGeometricDistribution.isValidParams(key.tickSpacing, twapSecondsAgo, ldfParams, ldfType);
    }

    function _decodeState(bytes32 ldfState) internal pure returns (bool initialized, int24 lastMinTick) {
        // | initialized - 1 byte | lastMinTick - 3 bytes |
        initialized = uint8(bytes1(ldfState)) == 1;
        lastMinTick = int24(uint24(bytes3(ldfState << 8)));
    }

    function _encodeState(int24 lastMinTick) internal pure returns (bytes32 ldfState) {
        // | initialized - 1 byte | lastMinTick - 3 bytes |
        ldfState = bytes32(bytes4(INITIALIZED_STATE + uint32(uint24(lastMinTick))));
    }
}

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

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    struct ModifyLiquidityParams {
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // how to modify the liquidity
        int256 liquidityDelta;
        // a value to set if you want unique liquidity positions at the same range
        bytes32 salt;
    }

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    struct SwapParams {
        /// Whether to swap token0 for token1 or vice versa
        bool zeroForOne;
        /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
        int256 amountSpecified;
        /// The sqrt price at which, if reached, the swap will stop executing
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

File 3 of 35 : ShiftMode.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

enum ShiftMode {
    BOTH,
    LEFT,
    RIGHT,
    STATIC
}

function enforceShiftMode(int24 tick, int24 lastTick, ShiftMode shiftMode) pure returns (int24) {
    if ((shiftMode == ShiftMode.LEFT && tick > lastTick) || (shiftMode == ShiftMode.RIGHT && tick < lastTick)) {
        return lastTick;
    }
    return tick;
}

File 4 of 35 : Guarded.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {CustomRevert} from "@uniswap/v4-core/src/libraries/CustomRevert.sol";

abstract contract Guarded {
    using CustomRevert for bytes4;

    error GuardedCall();

    /// @dev The original address of this contract
    address private immutable original;

    address private immutable hub;
    address private immutable hook;
    address private immutable quoter;

    function _guardedCheck() private view {
        if (
            (msg.sender != hub && msg.sender != hook && msg.sender != quoter && msg.sender != address(0))
                || address(this) != original
        ) {
            GuardedCall.selector.revertWith();
        }
    }

    modifier guarded() {
        _guardedCheck();
        _;
    }

    constructor(address hub_, address hook_, address quoter_) {
        // Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.
        // In other words, this variable won't change when it's checked at runtime.
        original = address(this);

        // Record permitted addresses
        hub = hub_;
        hook = hook_;
        quoter = quoter_;
    }
}

File 5 of 35 : LDFType.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

enum LDFType {
    STATIC, // LDF does not change ever
    DYNAMIC_NOT_STATEFUL, // LDF can change, does not use ldfState
    DYNAMIC_AND_STATEFUL // LDF can change, uses ldfState

}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";

import "./ShiftMode.sol";
import "../lib/Math.sol";
import "../lib/ExpMath.sol";
import "../base/Constants.sol";
import "./LibUniformDistribution.sol";
import {LDFType} from "../types/LDFType.sol";
import "./LibDoubleGeometricDistribution.sol";

library LibCarpetedDoubleGeometricDistribution {
    using SafeCastLib for uint256;
    using FixedPointMathLib for uint256;

    uint256 internal constant SCALED_Q96 = 0x10000000000000000000000000; // Q96 << QUERY_SCALE_SHIFT
    uint8 internal constant QUERY_SCALE_SHIFT = 4;

    struct Params {
        int24 minTick;
        int24 length0;
        uint256 alpha0X96;
        uint256 weight0;
        int24 length1;
        uint256 alpha1X96;
        uint256 weight1;
        uint256 weightCarpet;
        ShiftMode shiftMode;
    }

    /// @dev Queries the liquidity density and the cumulative amounts at the given rounded tick.
    /// @param roundedTick The rounded tick to query
    /// @param tickSpacing The spacing of the ticks
    /// @return liquidityDensityX96_ The liquidity density at the given rounded tick. Range is [0, 1]. Scaled by 2^96.
    /// @return cumulativeAmount0DensityX96 The cumulative amount of token0 in the rounded ticks [roundedTick + tickSpacing, minTick + length * tickSpacing)
    /// @return cumulativeAmount1DensityX96 The cumulative amount of token1 in the rounded ticks [minTick, roundedTick - tickSpacing]
    function query(int24 roundedTick, int24 tickSpacing, Params memory params)
        internal
        pure
        returns (uint256 liquidityDensityX96_, uint256 cumulativeAmount0DensityX96, uint256 cumulativeAmount1DensityX96)
    {
        // compute liquidityDensityX96
        liquidityDensityX96_ = liquidityDensityX96(roundedTick, tickSpacing, params);

        // compute cumulativeAmount0DensityX96
        cumulativeAmount0DensityX96 =
            cumulativeAmount0(roundedTick + tickSpacing, SCALED_Q96, tickSpacing, params) >> QUERY_SCALE_SHIFT;

        // compute cumulativeAmount1DensityX96
        cumulativeAmount1DensityX96 =
            cumulativeAmount1(roundedTick - tickSpacing, SCALED_Q96, tickSpacing, params) >> QUERY_SCALE_SHIFT;
    }

    /// @dev Computes the cumulative amount of token0 in the rounded ticks [roundedTick, tickUpper).
    function cumulativeAmount0(int24 roundedTick, uint256 totalLiquidity, int24 tickSpacing, Params memory params)
        internal
        pure
        returns (uint256 amount0)
    {
        int24 length = params.length0 + params.length1;
        (
            uint256 leftCarpetLiquidity,
            uint256 mainLiquidity,
            uint256 rightCarpetLiquidity,
            int24 minUsableTick,
            int24 maxUsableTick
        ) = getCarpetedLiquidity(totalLiquidity, tickSpacing, params.minTick, length, params.weightCarpet);

        return LibUniformDistribution.cumulativeAmount0(
            roundedTick, leftCarpetLiquidity, tickSpacing, minUsableTick, params.minTick, true
        )
            + LibDoubleGeometricDistribution.cumulativeAmount0(
                roundedTick,
                mainLiquidity,
                tickSpacing,
                params.minTick,
                params.length0,
                params.length1,
                params.alpha0X96,
                params.alpha1X96,
                params.weight0,
                params.weight1
            )
            + LibUniformDistribution.cumulativeAmount0(
                roundedTick, rightCarpetLiquidity, tickSpacing, params.minTick + length * tickSpacing, maxUsableTick, true
            );
    }

    /// @dev Computes the cumulative amount of token1 in the rounded ticks [tickLower, roundedTick].
    function cumulativeAmount1(int24 roundedTick, uint256 totalLiquidity, int24 tickSpacing, Params memory params)
        internal
        pure
        returns (uint256 amount1)
    {
        int24 length = params.length0 + params.length1;
        (
            uint256 leftCarpetLiquidity,
            uint256 mainLiquidity,
            uint256 rightCarpetLiquidity,
            int24 minUsableTick,
            int24 maxUsableTick
        ) = getCarpetedLiquidity(totalLiquidity, tickSpacing, params.minTick, length, params.weightCarpet);

        return LibUniformDistribution.cumulativeAmount1(
            roundedTick, leftCarpetLiquidity, tickSpacing, minUsableTick, params.minTick, true
        )
            + LibDoubleGeometricDistribution.cumulativeAmount1(
                roundedTick,
                mainLiquidity,
                tickSpacing,
                params.minTick,
                params.length0,
                params.length1,
                params.alpha0X96,
                params.alpha1X96,
                params.weight0,
                params.weight1
            )
            + LibUniformDistribution.cumulativeAmount1(
                roundedTick, rightCarpetLiquidity, tickSpacing, params.minTick + length * tickSpacing, maxUsableTick, true
            );
    }

    /// @dev Given a cumulativeAmount0, computes the rounded tick whose cumulativeAmount0 is closest to the input. Range is [tickLower, tickUpper].
    ///      The returned tick will be the largest rounded tick whose cumulativeAmount0 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount0 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount0(
        uint256 cumulativeAmount0_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        Params memory params
    ) internal pure returns (bool success, int24 roundedTick) {
        if (cumulativeAmount0_ == 0) {
            return (true, TickMath.maxUsableTick(tickSpacing));
        }

        // try LDFs in the order of right carpet, main, left carpet
        int24 length = params.length0 + params.length1;
        (
            uint256 leftCarpetLiquidity,
            uint256 mainLiquidity,
            uint256 rightCarpetLiquidity,
            int24 minUsableTick,
            int24 maxUsableTick
        ) = getCarpetedLiquidity(totalLiquidity, tickSpacing, params.minTick, length, params.weightCarpet);
        uint256 rightCarpetCumulativeAmount0 = LibUniformDistribution.cumulativeAmount0(
            params.minTick + length * tickSpacing,
            rightCarpetLiquidity,
            tickSpacing,
            params.minTick + length * tickSpacing,
            maxUsableTick,
            true
        );

        if (cumulativeAmount0_ <= rightCarpetCumulativeAmount0 && rightCarpetLiquidity != 0) {
            // use right carpet
            return LibUniformDistribution.inverseCumulativeAmount0(
                cumulativeAmount0_,
                rightCarpetLiquidity,
                tickSpacing,
                params.minTick + length * tickSpacing,
                maxUsableTick,
                true
            );
        } else {
            uint256 remainder = cumulativeAmount0_ - rightCarpetCumulativeAmount0;
            uint256 mainCumulativeAmount0 = LibDoubleGeometricDistribution.cumulativeAmount0(
                params.minTick,
                mainLiquidity,
                tickSpacing,
                params.minTick,
                params.length0,
                params.length1,
                params.alpha0X96,
                params.alpha1X96,
                params.weight0,
                params.weight1
            );

            if (remainder <= mainCumulativeAmount0) {
                // use main
                return LibDoubleGeometricDistribution.inverseCumulativeAmount0(
                    remainder,
                    mainLiquidity,
                    tickSpacing,
                    params.minTick,
                    params.length0,
                    params.length1,
                    params.alpha0X96,
                    params.alpha1X96,
                    params.weight0,
                    params.weight1
                );
            } else if (leftCarpetLiquidity != 0) {
                // use left carpet
                remainder -= mainCumulativeAmount0;
                return LibUniformDistribution.inverseCumulativeAmount0(
                    remainder, leftCarpetLiquidity, tickSpacing, minUsableTick, params.minTick, true
                );
            }
        }
        return (false, 0);
    }

    /// @dev Given a cumulativeAmount1, computes the rounded tick whose cumulativeAmount1 is closest to the input. Range is [tickLower - tickSpacing, tickUpper - tickSpacing].
    ///      The returned tick will be the smallest rounded tick whose cumulativeAmount1 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount1 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount1(
        uint256 cumulativeAmount1_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        Params memory params
    ) internal pure returns (bool success, int24 roundedTick) {
        if (cumulativeAmount1_ == 0) {
            return (true, TickMath.minUsableTick(tickSpacing) - tickSpacing);
        }

        // try LDFs in the order of left carpet, main, right carpet
        int24 length = params.length0 + params.length1;
        (
            uint256 leftCarpetLiquidity,
            uint256 mainLiquidity,
            uint256 rightCarpetLiquidity,
            int24 minUsableTick,
            int24 maxUsableTick
        ) = getCarpetedLiquidity(totalLiquidity, tickSpacing, params.minTick, length, params.weightCarpet);
        uint256 leftCarpetCumulativeAmount1 = LibUniformDistribution.cumulativeAmount1(
            params.minTick, leftCarpetLiquidity, tickSpacing, minUsableTick, params.minTick, true
        );

        if (cumulativeAmount1_ <= leftCarpetCumulativeAmount1 && leftCarpetLiquidity != 0) {
            // use left carpet
            return LibUniformDistribution.inverseCumulativeAmount1(
                cumulativeAmount1_, leftCarpetLiquidity, tickSpacing, minUsableTick, params.minTick, true
            );
        } else {
            uint256 remainder = cumulativeAmount1_ - leftCarpetCumulativeAmount1;
            uint256 mainCumulativeAmount1 = LibDoubleGeometricDistribution.cumulativeAmount1(
                params.minTick + length * tickSpacing,
                mainLiquidity,
                tickSpacing,
                params.minTick,
                params.length0,
                params.length1,
                params.alpha0X96,
                params.alpha1X96,
                params.weight0,
                params.weight1
            );

            if (remainder <= mainCumulativeAmount1) {
                // use main
                return LibDoubleGeometricDistribution.inverseCumulativeAmount1(
                    remainder,
                    mainLiquidity,
                    tickSpacing,
                    params.minTick,
                    params.length0,
                    params.length1,
                    params.alpha0X96,
                    params.alpha1X96,
                    params.weight0,
                    params.weight1
                );
            } else if (rightCarpetLiquidity != 0) {
                // use right carpet
                remainder -= mainCumulativeAmount1;
                return LibUniformDistribution.inverseCumulativeAmount1(
                    remainder,
                    rightCarpetLiquidity,
                    tickSpacing,
                    params.minTick + length * tickSpacing,
                    maxUsableTick,
                    true
                );
            }
        }
        return (false, 0);
    }

    function liquidityDensityX96(int24 roundedTick, int24 tickSpacing, Params memory params)
        internal
        pure
        returns (uint256)
    {
        int24 length = params.length0 + params.length1;
        if (roundedTick >= params.minTick && roundedTick < params.minTick + length * tickSpacing) {
            return LibDoubleGeometricDistribution.liquidityDensityX96(
                roundedTick,
                tickSpacing,
                params.minTick,
                params.length0,
                params.length1,
                params.alpha0X96,
                params.alpha1X96,
                params.weight0,
                params.weight1
            ).mulWad(WAD - params.weightCarpet);
        } else {
            (int24 minUsableTick, int24 maxUsableTick) =
                (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
            int24 numRoundedTicksCarpeted = (maxUsableTick - minUsableTick) / tickSpacing - length;
            if (numRoundedTicksCarpeted <= 0) {
                return 0;
            }
            uint256 mainLiquidity = Q96.mulWad(WAD - params.weightCarpet);
            uint256 carpetLiquidity = Q96 - mainLiquidity;
            return carpetLiquidity.divUp(uint24(numRoundedTicksCarpeted));
        }
    }

    /// @dev Combines several operations used during a swap into one function to save gas.
    ///      Given a cumulative amount, it computes its inverse to find the closest rounded tick, then computes the cumulative amount at that tick,
    ///      and finally computes the liquidity of the tick that will handle the remainder of the swap.
    function computeSwap(
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 tickSpacing,
        Params memory params
    )
        internal
        pure
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        )
    {
        if (exactIn == zeroForOne) {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round down to the rounded tick to the left
            // e.g. go from 1.5 to 1
            //       input
            //      ├──────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            (success, roundedTick) =
                inverseCumulativeAmount0(inverseCumulativeAmountInput, totalLiquidity, tickSpacing, params);
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick + tickSpacing
            // exactOut:
            //        cum
            //    ├────────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, params)
                : cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, params);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            // exactOut:
            //  cum
            // ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            // │
            // ▼
            //rick - tickSpacing
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, params)
                : cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, params);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //    liq
            //    ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            swapLiquidity = (liquidityDensityX96(roundedTick, tickSpacing, params) * totalLiquidity) >> 96;
        } else {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round up to the rounded tick to the right
            // e.g. go from 1.5 to 2
            //  input
            // ├──────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            (success, roundedTick) =
                inverseCumulativeAmount1(inverseCumulativeAmountInput, totalLiquidity, tickSpacing, params);
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick - tickSpacing
            // exactOut:
            //     cum
            // ├────────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, params)
                : cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, params);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            // exactOut:
            //           cum
            //          ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //          │
            //          ▼
            //         rick + tickSpacing
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, params)
                : cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, params);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //       liq
            //       ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            swapLiquidity = (liquidityDensityX96(roundedTick, tickSpacing, params) * totalLiquidity) >> 96;
        }
    }

    function getCarpetedLiquidity(
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 weightCarpet
    )
        internal
        pure
        returns (
            uint256 leftCarpetLiquidity,
            uint256 mainLiquidity,
            uint256 rightCarpetLiquidity,
            int24 minUsableTick,
            int24 maxUsableTick
        )
    {
        (minUsableTick, maxUsableTick) = (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
        int24 numRoundedTicksCarpeted = (maxUsableTick - minUsableTick) / tickSpacing - length;
        if (numRoundedTicksCarpeted <= 0) {
            return (0, totalLiquidity, 0, minUsableTick, maxUsableTick);
        }
        mainLiquidity = totalLiquidity.mulWad(WAD - weightCarpet);
        uint256 carpetLiquidity = totalLiquidity - mainLiquidity;
        rightCarpetLiquidity = carpetLiquidity.mulDiv(
            uint24((maxUsableTick - minTick) / tickSpacing - length), uint24(numRoundedTicksCarpeted)
        );
        leftCarpetLiquidity = carpetLiquidity - rightCarpetLiquidity;
    }

    function isValidParams(int24 tickSpacing, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        internal
        pure
        returns (bool)
    {
        // | shiftMode - 1 byte | minTickOrOffset - 3 bytes | length0 - 2 bytes | alpha0 - 4 bytes | weight0 - 4 bytes | length1 - 2 bytes | alpha1 - 4 bytes | weight1 - 4 bytes | weightCarpet - 4 bytes |
        int24 length0 = int24(int16(uint16(bytes2(ldfParams << 32))));
        uint32 alpha0 = uint32(bytes4(ldfParams << 48));
        uint32 weight0 = uint32(bytes4(ldfParams << 80));
        int24 length1 = int24(int16(uint16(bytes2(ldfParams << 112))));
        uint32 alpha1 = uint32(bytes4(ldfParams << 128));
        uint32 weight1 = uint32(bytes4(ldfParams << 160));
        uint32 weightCarpet = uint32(bytes4(ldfParams << 192));

        return LibDoubleGeometricDistribution.isValidParams(tickSpacing, twapSecondsAgo, ldfParams, ldfType)
            && weightCarpet != 0
            && LibDoubleGeometricDistribution.checkMinLiquidityDensity(
                Q96.mulWad(WAD - weightCarpet), tickSpacing, length0, alpha0, weight0, length1, alpha1, weight1
            );
    }

    /// @return params
    /// minTick The minimum rounded tick of the distribution
    /// length0 The length of the right distribution in number of rounded ticks
    /// length1 The length of the left distribution in number of rounded ticks
    /// alpha0X96 The alpha of the right distribution
    /// alpha1X96 The alpha of the left distribution
    /// weight0 The weight of the right distribution
    /// weight1 The weight of the left distribution
    /// weightCarpet The weight of the carpet distribution, 18 decimals. 32 bits means the max weight is 4.295e-9.
    /// shiftMode The shift mode of the distribution
    function decodeParams(int24 twapTick, int24 tickSpacing, bytes32 ldfParams)
        internal
        pure
        returns (Params memory params)
    {
        // | shiftMode - 1 byte | offset - 3 bytes | length0 - 2 bytes | alpha0 - 4 bytes | weight0 - 4 bytes | length1 - 2 bytes | alpha1 - 4 bytes | weight1 - 4 bytes | weightCarpet - 4 bytes |
        params.weightCarpet = uint32(bytes4(ldfParams << 192));
        (
            params.minTick,
            params.length0,
            params.length1,
            params.alpha0X96,
            params.alpha1X96,
            params.weight0,
            params.weight1,
            params.shiftMode
        ) = LibDoubleGeometricDistribution.decodeParams(twapTick, tickSpacing, ldfParams);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;
pragma abicoder v2;

import {PoolKey} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";

import {LDFType} from "../types/LDFType.sol";

/// @title ILiquidityDensityFunction
/// @author zefram.eth
/// @notice Interface for liquidity density functions (LDFs) that dictate how liquidity is distributed over a pool's rounded ticks (each with `tickSpacing` ticks).
/// Each rounded tick is identified by its leftmost tick, which is a multiple of `tickSpacing`. The liquidity density of all rounded ticks should add up to 1, similar to probability density functions (PDFs).
/// Also contains functions for efficiently computing the cumulative amount of tokens in a consecutive range of rounded ticks, as well as their inverse functions. These are essential for computing swaps.
/// Enables arbitrary liquidity shapes, shifting liquidity across ticks, and switching from one liquidity shape to another.
interface ILiquidityDensityFunction {
    /// @notice Queries the liquidity density function for the given pool and rounded tick.
    /// Returns the density of the rounded tick, cumulative token densities at adjacent ticks, and state relevant info.
    /// @param key The key of the Uniswap v4 pool
    /// @param roundedTick The rounded tick to query
    /// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
    /// @param spotPriceTick The spot price tick.
    /// @param ldfParams The parameters for the liquidity density function
    /// @param ldfState The current state of the liquidity density function
    /// @return liquidityDensityX96 The density of the rounded tick, scaled by Q96
    /// @return cumulativeAmount0DensityX96 The cumulative token0 density in rounded ticks [roundedTick + tickSpacing, maxUsableTick], scaled by Q96
    /// @return cumulativeAmount1DensityX96 The cumulative token1 density in rounded ticks [minUsableTick, roundedTick - tickSpacing], scaled by Q96
    /// @return newLdfState The new state of the liquidity density function
    /// @return shouldSurge Whether the pool should surge. Usually corresponds to whether the LDF has shifted / changed shape.
    function query(
        PoolKey calldata key,
        int24 roundedTick,
        int24 twapTick,
        int24 spotPriceTick,
        bytes32 ldfParams,
        bytes32 ldfState
    )
        external
        view
        returns (
            uint256 liquidityDensityX96,
            uint256 cumulativeAmount0DensityX96,
            uint256 cumulativeAmount1DensityX96,
            bytes32 newLdfState,
            bool shouldSurge
        );

    /// @notice Aggregates LDF queries used during a swap.
    /// @dev A Bunni swap uses the inverseCumulativeAmount function to compute the rounded tick for which the cumulativeAmount is the closest to `inverseCumulativeAmountInput`
    /// and <= `inverseCumulativeAmountInput`. This rounded tick is the starting point for swapping the remaining tokens, which is done via Uniswap math (not done in this function though).
    /// @param key The key of the Uniswap v4 pool
    /// @param inverseCumulativeAmountInput The input to the inverseCumulativeAmount function
    /// @param totalLiquidity The total liquidity in the pool
    /// @param zeroForOne Whether the input token is token0
    /// @param exactIn Whether it's an exact input swap or an exact output swap
    /// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
    /// @param spotPriceTick The spot price tick.
    /// @param ldfParams The parameters for the liquidity density function
    /// @param ldfState The current state of the liquidity density function
    /// @return success Whether the swap computation was successful
    /// @return roundedTick The rounded tick to start the remainder swap from
    /// @return cumulativeAmount0_ The cumulative amount of token0 to the right of the starting tick of the Uniswap swap
    /// @return cumulativeAmount1_ The cumulative amount of token1 to the left of the starting tick of the Uniswap swap
    /// @return swapLiquidity The liquidity used for the remainder swap
    function computeSwap(
        PoolKey calldata key,
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 twapTick,
        int24 spotPriceTick,
        bytes32 ldfParams,
        bytes32 ldfState
    )
        external
        view
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        );

    /// @notice Computes the cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick].
    /// @param key The key of the Uniswap v4 pool
    /// @param roundedTick The rounded tick to query
    /// @param totalLiquidity The total liquidity in the pool
    /// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
    /// @param spotPriceTick The spot price tick.
    /// @param ldfParams The parameters for the liquidity density function
    /// @param ldfState The current state of the liquidity density function
    /// @return The cumulative amount of token0 in the rounded ticks [roundedTick, maxUsableTick]
    function cumulativeAmount0(
        PoolKey calldata key,
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 twapTick,
        int24 spotPriceTick,
        bytes32 ldfParams,
        bytes32 ldfState
    ) external view returns (uint256);

    /// @notice Computes the cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick].
    /// @param key The key of the Uniswap v4 pool
    /// @param roundedTick The rounded tick to query
    /// @param totalLiquidity The total liquidity in the pool
    /// @param twapTick The TWAP tick. Is 0 if `twapSecondsAgo` is 0. It's up to `isValidParams` to ensure `twapSecondsAgo != 0` if the LDF uses the TWAP.
    /// @param spotPriceTick The spot price tick.
    /// @param ldfParams The parameters for the liquidity density function
    /// @param ldfState The current state of the liquidity density function
    /// @return The cumulative amount of token1 in the rounded ticks [minUsableTick, roundedTick]
    function cumulativeAmount1(
        PoolKey calldata key,
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 twapTick,
        int24 spotPriceTick,
        bytes32 ldfParams,
        bytes32 ldfState
    ) external view returns (uint256);

    /// @notice Checks if the given LDF parameters are valid.
    /// @param key The key of the Uniswap v4 pool
    /// @param twapSecondsAgo The time window for the TWAP
    /// @param ldfParams The parameters for the liquidity density function
    /// @param ldfType The type of LDF, see LDFType.sol for details.
    /// @return Whether the parameters are valid
    function isValidParams(PoolKey calldata key, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        external
        view
        returns (bool);
}

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

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

File 9 of 35 : PoolKey.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IPoolManager} from "./IPoolManager.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        IPoolManager.ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        IPoolManager.SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

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

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

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

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

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

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

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

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

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

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

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

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

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

File 18 of 35 : SafeCastLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to cast to the target type due to overflow.
    error Overflow();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*          UNSIGNED INTEGER SAFE CASTING OPERATIONS          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a uint8. Reverts on overflow.
    function toUint8(uint256 x) internal pure returns (uint8) {
        if (x >= 1 << 8) _revertOverflow();
        return uint8(x);
    }

    /// @dev Casts `x` to a uint16. Reverts on overflow.
    function toUint16(uint256 x) internal pure returns (uint16) {
        if (x >= 1 << 16) _revertOverflow();
        return uint16(x);
    }

    /// @dev Casts `x` to a uint24. Reverts on overflow.
    function toUint24(uint256 x) internal pure returns (uint24) {
        if (x >= 1 << 24) _revertOverflow();
        return uint24(x);
    }

    /// @dev Casts `x` to a uint32. Reverts on overflow.
    function toUint32(uint256 x) internal pure returns (uint32) {
        if (x >= 1 << 32) _revertOverflow();
        return uint32(x);
    }

    /// @dev Casts `x` to a uint40. Reverts on overflow.
    function toUint40(uint256 x) internal pure returns (uint40) {
        if (x >= 1 << 40) _revertOverflow();
        return uint40(x);
    }

    /// @dev Casts `x` to a uint48. Reverts on overflow.
    function toUint48(uint256 x) internal pure returns (uint48) {
        if (x >= 1 << 48) _revertOverflow();
        return uint48(x);
    }

    /// @dev Casts `x` to a uint56. Reverts on overflow.
    function toUint56(uint256 x) internal pure returns (uint56) {
        if (x >= 1 << 56) _revertOverflow();
        return uint56(x);
    }

    /// @dev Casts `x` to a uint64. Reverts on overflow.
    function toUint64(uint256 x) internal pure returns (uint64) {
        if (x >= 1 << 64) _revertOverflow();
        return uint64(x);
    }

    /// @dev Casts `x` to a uint72. Reverts on overflow.
    function toUint72(uint256 x) internal pure returns (uint72) {
        if (x >= 1 << 72) _revertOverflow();
        return uint72(x);
    }

    /// @dev Casts `x` to a uint80. Reverts on overflow.
    function toUint80(uint256 x) internal pure returns (uint80) {
        if (x >= 1 << 80) _revertOverflow();
        return uint80(x);
    }

    /// @dev Casts `x` to a uint88. Reverts on overflow.
    function toUint88(uint256 x) internal pure returns (uint88) {
        if (x >= 1 << 88) _revertOverflow();
        return uint88(x);
    }

    /// @dev Casts `x` to a uint96. Reverts on overflow.
    function toUint96(uint256 x) internal pure returns (uint96) {
        if (x >= 1 << 96) _revertOverflow();
        return uint96(x);
    }

    /// @dev Casts `x` to a uint104. Reverts on overflow.
    function toUint104(uint256 x) internal pure returns (uint104) {
        if (x >= 1 << 104) _revertOverflow();
        return uint104(x);
    }

    /// @dev Casts `x` to a uint112. Reverts on overflow.
    function toUint112(uint256 x) internal pure returns (uint112) {
        if (x >= 1 << 112) _revertOverflow();
        return uint112(x);
    }

    /// @dev Casts `x` to a uint120. Reverts on overflow.
    function toUint120(uint256 x) internal pure returns (uint120) {
        if (x >= 1 << 120) _revertOverflow();
        return uint120(x);
    }

    /// @dev Casts `x` to a uint128. Reverts on overflow.
    function toUint128(uint256 x) internal pure returns (uint128) {
        if (x >= 1 << 128) _revertOverflow();
        return uint128(x);
    }

    /// @dev Casts `x` to a uint136. Reverts on overflow.
    function toUint136(uint256 x) internal pure returns (uint136) {
        if (x >= 1 << 136) _revertOverflow();
        return uint136(x);
    }

    /// @dev Casts `x` to a uint144. Reverts on overflow.
    function toUint144(uint256 x) internal pure returns (uint144) {
        if (x >= 1 << 144) _revertOverflow();
        return uint144(x);
    }

    /// @dev Casts `x` to a uint152. Reverts on overflow.
    function toUint152(uint256 x) internal pure returns (uint152) {
        if (x >= 1 << 152) _revertOverflow();
        return uint152(x);
    }

    /// @dev Casts `x` to a uint160. Reverts on overflow.
    function toUint160(uint256 x) internal pure returns (uint160) {
        if (x >= 1 << 160) _revertOverflow();
        return uint160(x);
    }

    /// @dev Casts `x` to a uint168. Reverts on overflow.
    function toUint168(uint256 x) internal pure returns (uint168) {
        if (x >= 1 << 168) _revertOverflow();
        return uint168(x);
    }

    /// @dev Casts `x` to a uint176. Reverts on overflow.
    function toUint176(uint256 x) internal pure returns (uint176) {
        if (x >= 1 << 176) _revertOverflow();
        return uint176(x);
    }

    /// @dev Casts `x` to a uint184. Reverts on overflow.
    function toUint184(uint256 x) internal pure returns (uint184) {
        if (x >= 1 << 184) _revertOverflow();
        return uint184(x);
    }

    /// @dev Casts `x` to a uint192. Reverts on overflow.
    function toUint192(uint256 x) internal pure returns (uint192) {
        if (x >= 1 << 192) _revertOverflow();
        return uint192(x);
    }

    /// @dev Casts `x` to a uint200. Reverts on overflow.
    function toUint200(uint256 x) internal pure returns (uint200) {
        if (x >= 1 << 200) _revertOverflow();
        return uint200(x);
    }

    /// @dev Casts `x` to a uint208. Reverts on overflow.
    function toUint208(uint256 x) internal pure returns (uint208) {
        if (x >= 1 << 208) _revertOverflow();
        return uint208(x);
    }

    /// @dev Casts `x` to a uint216. Reverts on overflow.
    function toUint216(uint256 x) internal pure returns (uint216) {
        if (x >= 1 << 216) _revertOverflow();
        return uint216(x);
    }

    /// @dev Casts `x` to a uint224. Reverts on overflow.
    function toUint224(uint256 x) internal pure returns (uint224) {
        if (x >= 1 << 224) _revertOverflow();
        return uint224(x);
    }

    /// @dev Casts `x` to a uint232. Reverts on overflow.
    function toUint232(uint256 x) internal pure returns (uint232) {
        if (x >= 1 << 232) _revertOverflow();
        return uint232(x);
    }

    /// @dev Casts `x` to a uint240. Reverts on overflow.
    function toUint240(uint256 x) internal pure returns (uint240) {
        if (x >= 1 << 240) _revertOverflow();
        return uint240(x);
    }

    /// @dev Casts `x` to a uint248. Reverts on overflow.
    function toUint248(uint256 x) internal pure returns (uint248) {
        if (x >= 1 << 248) _revertOverflow();
        return uint248(x);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*           SIGNED INTEGER SAFE CASTING OPERATIONS           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a int8. Reverts on overflow.
    function toInt8(int256 x) internal pure returns (int8) {
        unchecked {
            if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int16. Reverts on overflow.
    function toInt16(int256 x) internal pure returns (int16) {
        unchecked {
            if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int24. Reverts on overflow.
    function toInt24(int256 x) internal pure returns (int24) {
        unchecked {
            if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int32. Reverts on overflow.
    function toInt32(int256 x) internal pure returns (int32) {
        unchecked {
            if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int40. Reverts on overflow.
    function toInt40(int256 x) internal pure returns (int40) {
        unchecked {
            if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int48. Reverts on overflow.
    function toInt48(int256 x) internal pure returns (int48) {
        unchecked {
            if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int56. Reverts on overflow.
    function toInt56(int256 x) internal pure returns (int56) {
        unchecked {
            if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int64. Reverts on overflow.
    function toInt64(int256 x) internal pure returns (int64) {
        unchecked {
            if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int72. Reverts on overflow.
    function toInt72(int256 x) internal pure returns (int72) {
        unchecked {
            if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int80. Reverts on overflow.
    function toInt80(int256 x) internal pure returns (int80) {
        unchecked {
            if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int88. Reverts on overflow.
    function toInt88(int256 x) internal pure returns (int88) {
        unchecked {
            if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int96. Reverts on overflow.
    function toInt96(int256 x) internal pure returns (int96) {
        unchecked {
            if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int104. Reverts on overflow.
    function toInt104(int256 x) internal pure returns (int104) {
        unchecked {
            if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int112. Reverts on overflow.
    function toInt112(int256 x) internal pure returns (int112) {
        unchecked {
            if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int120. Reverts on overflow.
    function toInt120(int256 x) internal pure returns (int120) {
        unchecked {
            if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int128. Reverts on overflow.
    function toInt128(int256 x) internal pure returns (int128) {
        unchecked {
            if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int136. Reverts on overflow.
    function toInt136(int256 x) internal pure returns (int136) {
        unchecked {
            if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int144. Reverts on overflow.
    function toInt144(int256 x) internal pure returns (int144) {
        unchecked {
            if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int152. Reverts on overflow.
    function toInt152(int256 x) internal pure returns (int152) {
        unchecked {
            if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int160. Reverts on overflow.
    function toInt160(int256 x) internal pure returns (int160) {
        unchecked {
            if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int168. Reverts on overflow.
    function toInt168(int256 x) internal pure returns (int168) {
        unchecked {
            if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int176. Reverts on overflow.
    function toInt176(int256 x) internal pure returns (int176) {
        unchecked {
            if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int184. Reverts on overflow.
    function toInt184(int256 x) internal pure returns (int184) {
        unchecked {
            if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int192. Reverts on overflow.
    function toInt192(int256 x) internal pure returns (int192) {
        unchecked {
            if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int200. Reverts on overflow.
    function toInt200(int256 x) internal pure returns (int200) {
        unchecked {
            if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int208. Reverts on overflow.
    function toInt208(int256 x) internal pure returns (int208) {
        unchecked {
            if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int216. Reverts on overflow.
    function toInt216(int256 x) internal pure returns (int216) {
        unchecked {
            if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int224. Reverts on overflow.
    function toInt224(int256 x) internal pure returns (int224) {
        unchecked {
            if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int232. Reverts on overflow.
    function toInt232(int256 x) internal pure returns (int232) {
        unchecked {
            if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int240. Reverts on overflow.
    function toInt240(int256 x) internal pure returns (int240) {
        unchecked {
            if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int248. Reverts on overflow.
    function toInt248(int256 x) internal pure returns (int248) {
        unchecked {
            if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
            _revertOverflow();
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*               OTHER SAFE CASTING OPERATIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a int8. Reverts on overflow.
    function toInt8(uint256 x) internal pure returns (int8) {
        if (x >= 1 << 7) _revertOverflow();
        return int8(int256(x));
    }

    /// @dev Casts `x` to a int16. Reverts on overflow.
    function toInt16(uint256 x) internal pure returns (int16) {
        if (x >= 1 << 15) _revertOverflow();
        return int16(int256(x));
    }

    /// @dev Casts `x` to a int24. Reverts on overflow.
    function toInt24(uint256 x) internal pure returns (int24) {
        if (x >= 1 << 23) _revertOverflow();
        return int24(int256(x));
    }

    /// @dev Casts `x` to a int32. Reverts on overflow.
    function toInt32(uint256 x) internal pure returns (int32) {
        if (x >= 1 << 31) _revertOverflow();
        return int32(int256(x));
    }

    /// @dev Casts `x` to a int40. Reverts on overflow.
    function toInt40(uint256 x) internal pure returns (int40) {
        if (x >= 1 << 39) _revertOverflow();
        return int40(int256(x));
    }

    /// @dev Casts `x` to a int48. Reverts on overflow.
    function toInt48(uint256 x) internal pure returns (int48) {
        if (x >= 1 << 47) _revertOverflow();
        return int48(int256(x));
    }

    /// @dev Casts `x` to a int56. Reverts on overflow.
    function toInt56(uint256 x) internal pure returns (int56) {
        if (x >= 1 << 55) _revertOverflow();
        return int56(int256(x));
    }

    /// @dev Casts `x` to a int64. Reverts on overflow.
    function toInt64(uint256 x) internal pure returns (int64) {
        if (x >= 1 << 63) _revertOverflow();
        return int64(int256(x));
    }

    /// @dev Casts `x` to a int72. Reverts on overflow.
    function toInt72(uint256 x) internal pure returns (int72) {
        if (x >= 1 << 71) _revertOverflow();
        return int72(int256(x));
    }

    /// @dev Casts `x` to a int80. Reverts on overflow.
    function toInt80(uint256 x) internal pure returns (int80) {
        if (x >= 1 << 79) _revertOverflow();
        return int80(int256(x));
    }

    /// @dev Casts `x` to a int88. Reverts on overflow.
    function toInt88(uint256 x) internal pure returns (int88) {
        if (x >= 1 << 87) _revertOverflow();
        return int88(int256(x));
    }

    /// @dev Casts `x` to a int96. Reverts on overflow.
    function toInt96(uint256 x) internal pure returns (int96) {
        if (x >= 1 << 95) _revertOverflow();
        return int96(int256(x));
    }

    /// @dev Casts `x` to a int104. Reverts on overflow.
    function toInt104(uint256 x) internal pure returns (int104) {
        if (x >= 1 << 103) _revertOverflow();
        return int104(int256(x));
    }

    /// @dev Casts `x` to a int112. Reverts on overflow.
    function toInt112(uint256 x) internal pure returns (int112) {
        if (x >= 1 << 111) _revertOverflow();
        return int112(int256(x));
    }

    /// @dev Casts `x` to a int120. Reverts on overflow.
    function toInt120(uint256 x) internal pure returns (int120) {
        if (x >= 1 << 119) _revertOverflow();
        return int120(int256(x));
    }

    /// @dev Casts `x` to a int128. Reverts on overflow.
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) _revertOverflow();
        return int128(int256(x));
    }

    /// @dev Casts `x` to a int136. Reverts on overflow.
    function toInt136(uint256 x) internal pure returns (int136) {
        if (x >= 1 << 135) _revertOverflow();
        return int136(int256(x));
    }

    /// @dev Casts `x` to a int144. Reverts on overflow.
    function toInt144(uint256 x) internal pure returns (int144) {
        if (x >= 1 << 143) _revertOverflow();
        return int144(int256(x));
    }

    /// @dev Casts `x` to a int152. Reverts on overflow.
    function toInt152(uint256 x) internal pure returns (int152) {
        if (x >= 1 << 151) _revertOverflow();
        return int152(int256(x));
    }

    /// @dev Casts `x` to a int160. Reverts on overflow.
    function toInt160(uint256 x) internal pure returns (int160) {
        if (x >= 1 << 159) _revertOverflow();
        return int160(int256(x));
    }

    /// @dev Casts `x` to a int168. Reverts on overflow.
    function toInt168(uint256 x) internal pure returns (int168) {
        if (x >= 1 << 167) _revertOverflow();
        return int168(int256(x));
    }

    /// @dev Casts `x` to a int176. Reverts on overflow.
    function toInt176(uint256 x) internal pure returns (int176) {
        if (x >= 1 << 175) _revertOverflow();
        return int176(int256(x));
    }

    /// @dev Casts `x` to a int184. Reverts on overflow.
    function toInt184(uint256 x) internal pure returns (int184) {
        if (x >= 1 << 183) _revertOverflow();
        return int184(int256(x));
    }

    /// @dev Casts `x` to a int192. Reverts on overflow.
    function toInt192(uint256 x) internal pure returns (int192) {
        if (x >= 1 << 191) _revertOverflow();
        return int192(int256(x));
    }

    /// @dev Casts `x` to a int200. Reverts on overflow.
    function toInt200(uint256 x) internal pure returns (int200) {
        if (x >= 1 << 199) _revertOverflow();
        return int200(int256(x));
    }

    /// @dev Casts `x` to a int208. Reverts on overflow.
    function toInt208(uint256 x) internal pure returns (int208) {
        if (x >= 1 << 207) _revertOverflow();
        return int208(int256(x));
    }

    /// @dev Casts `x` to a int216. Reverts on overflow.
    function toInt216(uint256 x) internal pure returns (int216) {
        if (x >= 1 << 215) _revertOverflow();
        return int216(int256(x));
    }

    /// @dev Casts `x` to a int224. Reverts on overflow.
    function toInt224(uint256 x) internal pure returns (int224) {
        if (x >= 1 << 223) _revertOverflow();
        return int224(int256(x));
    }

    /// @dev Casts `x` to a int232. Reverts on overflow.
    function toInt232(uint256 x) internal pure returns (int232) {
        if (x >= 1 << 231) _revertOverflow();
        return int232(int256(x));
    }

    /// @dev Casts `x` to a int240. Reverts on overflow.
    function toInt240(uint256 x) internal pure returns (int240) {
        if (x >= 1 << 239) _revertOverflow();
        return int240(int256(x));
    }

    /// @dev Casts `x` to a int248. Reverts on overflow.
    function toInt248(uint256 x) internal pure returns (int248) {
        if (x >= 1 << 247) _revertOverflow();
        return int248(int256(x));
    }

    /// @dev Casts `x` to a int256. Reverts on overflow.
    function toInt256(uint256 x) internal pure returns (int256) {
        if (int256(x) >= 0) return int256(x);
        _revertOverflow();
    }

    /// @dev Casts `x` to a uint256. Reverts on overflow.
    function toUint256(int256 x) internal pure returns (uint256) {
        if (x >= 0) return uint256(x);
        _revertOverflow();
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _revertOverflow() private pure {
        /// @solidity memory-safe-assembly
        assembly {
            // Store the function selector of `Overflow()`.
            mstore(0x00, 0x35278d12)
            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
    }
}

File 19 of 35 : FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

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

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

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

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

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

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

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

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

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

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

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

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

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

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

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

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

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

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

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

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

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(mul(y, eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

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

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

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

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

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

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

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

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

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

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

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

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

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

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    /// Note: This function is an approximation. Monotonically increasing.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            (int256 wad, int256 p) = (int256(WAD), x);
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (uint256(w >> 63) == uint256(0)) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == uint256(0)) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != uint256(0));
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c == uint256(0)) return w;
            int256 t = w | 1;
            /// @solidity memory-safe-assembly
            assembly {
                x := sdiv(mul(x, wad), t)
            }
            x = (t * (wad + lnWad(x)));
            /// @solidity memory-safe-assembly
            assembly {
                w := sdiv(x, add(wad, t))
            }
        }
    }

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

    /// @dev Returns `a * b == x * y`, with full precision.
    function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
        }
    }

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

            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`.
            for {} 1 {} {
                // If overflows.
                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.

                    /*------------------- 512 by 256 division --------------------*/

                    // Make division exact by subtracting the remainder from `[p1 p0]`.
                    let r := mulmod(x, y, d) // Compute remainder using mulmod.
                    let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                    // Make sure `z` is less than `2**256`. Also prevents `d == 0`.
                    // Placing the check here seems to give more optimal stack operations.
                    if iszero(gt(d, p1)) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    d := div(d, t) // Divide `d` by `t`, which is a power of two.
                    // Invert `d mod 2**256`
                    // Now that `d` is an odd number, it has an inverse
                    // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                    // Compute the inverse by starting with a seed that is correct
                    // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                    let inv := xor(2, mul(3, d))
                    // Now use Newton-Raphson iteration to improve the precision.
                    // Thanks to Hensel's lifting lemma, this also works in modular
                    // arithmetic, doubling the correct bits in each step.
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                    z :=
                        mul(
                            // Divide [p1 p0] by the factors of two.
                            // Shift in bits from `p1` into `p0`. For this we need
                            // to flip `t` such that it is `2**256 / t`.
                            or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                            mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                        )
                    break
                }
                z := div(z, d)
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
    /// Performs the full 512 bit calculation regardless.
    function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            let mm := mulmod(x, y, not(0))
            let p1 := sub(mm, add(z, lt(mm, z)))
            let t := and(d, sub(0, d))
            let r := mulmod(x, y, d)
            d := div(d, t)
            let inv := xor(2, mul(3, d))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            z :=
                mul(
                    or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                    mul(sub(2, mul(d, inv)), inv)
                )
        }
    }

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

    /// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
    /// Throws if result overflows a uint256.
    /// Credit to Philogy under MIT license:
    /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
    function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
            for {} 1 {} {
                if iszero(or(iszero(x), eq(div(z, x), y))) {
                    let k := and(n, 0xff) // `n`, cleaned.
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                    //         |      p1     |      z     |
                    // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                    // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                    // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                    if iszero(shr(k, p1)) {
                        z := add(shl(sub(256, k), p1), shr(k, z))
                        break
                    }
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
                z := shr(and(n, 0xff), z)
                break
            }
        }
    }

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

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

    /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
    function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
        /// @solidity memory-safe-assembly
        assembly {
            let g := n
            let r := mod(a, n)
            for { let y := 1 } 1 {} {
                let q := div(g, r)
                let t := g
                g := r
                r := sub(t, mul(r, q))
                let u := x
                x := y
                y := sub(u, mul(y, q))
                if iszero(r) { break }
            }
            x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
        }
    }

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

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

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

    /// @dev Returns `min(2 ** 256 - 1, x + y)`.
    function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(0, lt(add(x, y), x)), add(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x * y)`.
    function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `x != 0 ? x : y`, without branching.
    function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != bytes32(0) ? x : y`, without branching.
    function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != address(0) ? x : y`, without branching.
    function coalesce(address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(shl(96, x))))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if x {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

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

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

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

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

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

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

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

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

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

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`, rounded down.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // Makeshift lookup table to nudge the approximate log2 result.
            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
            // Newton-Raphson's.
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            // Round down.
            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
            z = (1 + sqrt(x)) * 10 ** 9;
            z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
        }
        /// @solidity memory-safe-assembly
        assembly {
            z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
            z = (1 + cbrt(x)) * 10 ** 12;
            z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
        }
        /// @solidity memory-safe-assembly
        assembly {
            let p := x
            for {} 1 {} {
                if iszero(shr(229, p)) {
                    if iszero(shr(199, p)) {
                        p := mul(p, 100000000000000000) // 10 ** 17.
                        break
                    }
                    p := mul(p, 100000000) // 10 ** 8.
                    break
                }
                if iszero(shr(249, p)) { p := mul(p, 100) }
                break
            }
            let t := mulmod(mul(z, z), z, p)
            z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
        }
    }

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

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

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

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

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        unchecked {
            z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
        }
    }

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

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

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

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

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

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

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

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

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
        internal
        pure
        returns (uint256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        unchecked {
            if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
            return a - fullMulDiv(a - b, t - begin, end - begin);
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
        internal
        pure
        returns (int256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        // forgefmt: disable-next-item
        unchecked {
            if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
                uint256(t - begin), uint256(end - begin)));
            return int256(uint256(a) - fullMulDiv(uint256(a - b),
                uint256(t - begin), uint256(end - begin)));
        }
    }

    /// @dev Returns if `x` is an even number. Some people may need this.
    function isEven(uint256 x) internal pure returns (bool) {
        return x & uint256(1) == uint256(0);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

            if (msb >= 128) r = price >> (msb - 127);
            else r = price << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import "../base/Constants.sol";

using FixedPointMathLib for int256;
using FixedPointMathLib for uint256;

/// @dev modified from solady
function dist(uint256 x, uint256 y) pure returns (uint256 z) {
    /// @solidity memory-safe-assembly
    assembly {
        z := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
    }
}

/// @dev modified from solady
function absDiff(uint256 x, uint256 y) pure returns (bool positive, uint256 diff) {
    /// @solidity memory-safe-assembly
    assembly {
        positive := gt(x, y)
        diff := xor(mul(xor(sub(y, x), sub(x, y)), gt(x, y)), sub(y, x))
    }
}

function roundTick(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick, int24 nextRoundedTick) {
    int24 compressed = currentTick / tickSpacing;
    if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
    roundedTick = compressed * tickSpacing;
    nextRoundedTick = roundedTick + tickSpacing;
}

function roundTickSingle(int24 currentTick, int24 tickSpacing) pure returns (int24 roundedTick) {
    int24 compressed = currentTick / tickSpacing;
    if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity
    roundedTick = compressed * tickSpacing;
}

function boundTick(int24 tick, int24 tickSpacing) pure returns (int24 boundedTick) {
    (int24 minTick, int24 maxTick) = (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
    return int24(FixedPointMathLib.clamp(tick, minTick, maxTick));
}

function weightedSum(uint256 value0, uint256 weight0, uint256 value1, uint256 weight1) pure returns (uint256) {
    return (value0 * weight0 + value1 * weight1) / (weight0 + weight1);
}

/// @dev Converts xWad, the decimal index of a rounded tick scaled by WAD, to the corresponding rounded tick.
function xWadToRoundedTick(int256 xWad, int24 mu, int24 tickSpacing, bool roundUp) pure returns (int24) {
    int24 x = SafeCastLib.toInt24(xWad / int256(WAD));
    if (roundUp) {
        if (xWad > 0 && xWad % int256(WAD) != 0) x++; // round towards positive infinity
    } else {
        if (xWad < 0 && xWad % int256(WAD) != 0) x--; // round towards negative infinity
    }
    return x * tickSpacing + mu;
}

function percentDelta(uint256 a, uint256 b) pure returns (uint256) {
    uint256 absDelta = dist(a, b);
    return FixedPointMathLib.divWad(absDelta, b);
}

/// @dev Returns ReLU(x - y) = max(x - y, 0)
function subReLU(uint256 x, uint256 y) pure returns (uint256) {
    unchecked {
        return x > y ? x - y : 0;
    }
}

function divQ96RoundUp(uint256 value) pure returns (uint256) {
    return (value + ((1 << 96) - 1)) >> 96;
}

function roundUpFullMulDivResult(uint256 x, uint256 y, uint256 d, uint256 resultRoundedDown)
    pure
    returns (uint256 result)
{
    result = resultRoundedDown;
    /// @solidity memory-safe-assembly
    assembly {
        if mulmod(x, y, d) {
            result := add(resultRoundedDown, 1)
            if iszero(result) {
                mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

library ExpMath {
    using ExpMath for int256;
    using SafeCastLib for int256;
    using SafeCastLib for uint256;
    using FixedPointMathLib for int256;
    using FixedPointMathLib for uint256;

    uint256 internal constant WAD = 1e18;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
    int256 internal constant LN_Q96_DIV_WAD = 25095597659861927392; // ln(Q96 / WAD) * WAD
    int256 internal constant HALF_LN_TICK_BASE = 49997500166654; // 1/2 ln(1.0001) * WAD
    int256 internal constant HALF_LN_TICK_BASE_Q96 = 3961210068510634698400736; // 1/2 ln(1.0001) * Q96

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

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

    /// @dev Returns `exp(x)`, denominated in `Q96`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function expQ96(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= floor(ln(1 / 2**96) * 2**96)`.
            if (x <= -5272010636899917441709581228290) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 2**96` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 2**96) * 2**96) ≈ 110 * 2**96`.
                if iszero(slt(x, 8731767617365488262831493909354)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

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

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

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

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

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

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

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            int256 shift = 117 - k;
            r = shift >= 0
                ? int256((uint256(r) * 1002132753603162656746435578141647308) >> uint256(shift))
                : int256((uint256(r) * 1002132753603162656746435578141647308) << uint256(-shift));
        }
    }

    /// @dev Returns `ln(x)`, denominated in `Q96`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    function lnQ96(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0xe65fd7ca) // `LnQ96Undefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `k * ln(2)`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 2**96`, base is now `2**192`.
            p := mul(439668470185123797622540459591, p)
            // Add `ln(2) * k * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(4350955369971217654477563090224794165364344896676135745069, sub(159, r)), p)
            // Base conversion: div `2**96`.
            r := sar(96, p)
        }
    }

    function lnQ96RoundingUp(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0xe65fd7ca) // `LnQ96Undefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `k * ln(2)`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 2**96`, base is now `2**192`.
            p := mul(439668470185123797622540459591, p)
            // Add `ln(2) * k * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(4350955369971217654477563090224794165364344896676135745069, sub(159, r)), p)
            // Base conversion: div `2**96`.
            r := sar(96, p)
            // If p % 2**96 is not 0, we need to round up.
            if and(p, 0xffffffffffffffffffffffff) { r := add(r, 1) }
        }
    }

    function getSqrtPriceAtTickWad(int256 tickWad) internal pure returns (uint160 sqrtRatioX96) {
        sqrtRatioX96 = uint256((HALF_LN_TICK_BASE_Q96 * tickWad / int256(WAD)).expQ96()).toUint160();
    }
}

File 23 of 35 : Constants.sol
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0;
pragma abicoder v2;

uint256 constant WAD = 1e18;
uint256 constant Q96 = 0x1000000000000000000000000;
uint256 constant MAX_NONCE = 1e6;
uint256 constant MIN_INITIAL_SHARES = 1e12;
uint256 constant MAX_SWAP_FEE_RATIO = 2.88e20; // max ratio that avoids overflow in swap fee calculation, roughly sqrt(SWAP_FEE_BASE) * sqrt(sqrt((type(uint256).max - SWAP_FEE_BASE) / type(uint24).max) - 1)
uint256 constant SWAP_FEE_BASE = 1e6;
uint256 constant SWAP_FEE_BASE_SQUARED = 1e12;
uint256 constant RAW_TOKEN_RATIO_BASE = 1e6;
uint256 constant LN2_WAD = 693147180559945309;
uint256 constant MAX_VAULT_FEE_ERROR = 1e6;
uint256 constant MAX_CARDINALITY = 2 ** 24 - 1;
uint56 constant WITHDRAW_DELAY = 1 minutes;
uint56 constant WITHDRAW_GRACE_PERIOD = 3 minutes;
uint256 constant REFERRAL_REWARD_PER_TOKEN_PRECISION = 1e30;
uint256 constant MODIFIER_BASE = 1e6;
uint256 constant MIN_DEPOSIT_BALANCE_INCREASE = 1e6;
uint24 constant MAX_AMAMM_FEE = 0.1e6;
uint256 constant REBALANCE_MAX_SLIPPAGE_BASE = 1e5;
uint16 constant MAX_SURGE_HALFLIFE = 1 hours;
uint16 constant MAX_SURGE_AUTOSTART_TIME = 1 hours;
uint16 constant MAX_REBALANCE_MAX_SLIPPAGE = 0.25e5; // max value for rebalanceMaxSlippage is 25%
uint16 constant MAX_REBALANCE_TWAP_SECONDS_AGO = 3 hours;
uint16 constant MAX_REBALANCE_ORDER_TTL = 1 hours;

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";

import "./ShiftMode.sol";
import "../lib/Math.sol";
import "../base/Constants.sol";
import {LDFType} from "../types/LDFType.sol";
import {FullMathX96} from "../lib/FullMathX96.sol";
import {SqrtPriceMath} from "../lib/SqrtPriceMath.sol";

library LibUniformDistribution {
    using TickMath for int24;
    using TickMath for uint160;
    using FixedPointMathLib for *;
    using SafeCastLib for uint256;
    using FullMathX96 for uint256;

    /// @dev Queries the liquidity density and the cumulative amounts at the given rounded tick.
    /// @param roundedTick The rounded tick to query
    /// @param tickSpacing The spacing of the ticks
    /// @return liquidityDensityX96_ The liquidity density at the given rounded tick. Range is [0, 1]. Scaled by 2^96.
    /// @return cumulativeAmount0DensityX96 The cumulative amount of token0 in the rounded ticks [roundedTick + tickSpacing, tickUpper)
    /// @return cumulativeAmount1DensityX96 The cumulative amount of token1 in the rounded ticks [tickLower, roundedTick - tickSpacing]
    function query(int24 roundedTick, int24 tickSpacing, int24 tickLower, int24 tickUpper)
        internal
        pure
        returns (uint256 liquidityDensityX96_, uint256 cumulativeAmount0DensityX96, uint256 cumulativeAmount1DensityX96)
    {
        // compute liquidityDensityX96
        liquidityDensityX96_ = liquidityDensityX96(roundedTick, tickSpacing, tickLower, tickUpper);

        uint24 length = uint24((tickUpper - tickLower) / tickSpacing);
        uint256 liquidity = Q96.divUp(length);

        uint160 sqrtRatioTickLower = tickLower.getSqrtPriceAtTick();
        uint160 sqrtRatioTickUpper = tickUpper.getSqrtPriceAtTick();

        // compute cumulativeAmount0DensityX96 for the rounded tick to the right of the rounded current tick
        if (roundedTick + tickSpacing >= tickUpper) {
            // cumulativeAmount0DensityX96 is just 0
            cumulativeAmount0DensityX96 = 0;
        } else if (roundedTick + tickSpacing <= tickLower) {
            cumulativeAmount0DensityX96 =
                SqrtPriceMath.getAmount0Delta(sqrtRatioTickLower, sqrtRatioTickUpper, liquidity, true);
        } else {
            cumulativeAmount0DensityX96 = SqrtPriceMath.getAmount0Delta(
                (roundedTick + tickSpacing).getSqrtPriceAtTick(), sqrtRatioTickUpper, liquidity, true
            );
        }

        // compute cumulativeAmount1DensityX96 for the rounded tick to the left of the rounded current tick
        if (roundedTick - tickSpacing < tickLower) {
            // cumulativeAmount1DensityX96 is just 0
            cumulativeAmount1DensityX96 = 0;
        } else if (roundedTick >= tickUpper) {
            cumulativeAmount1DensityX96 =
                SqrtPriceMath.getAmount1Delta(sqrtRatioTickLower, sqrtRatioTickUpper, liquidity, true);
        } else {
            cumulativeAmount1DensityX96 =
                SqrtPriceMath.getAmount1Delta(sqrtRatioTickLower, roundedTick.getSqrtPriceAtTick(), liquidity, true);
        }
    }

    /// @dev Computes the cumulative amount of token0 in the rounded ticks [roundedTick, tickUpper).
    function cumulativeAmount0(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 tickLower,
        int24 tickUpper,
        bool isCarpet
    ) internal pure returns (uint256 amount0) {
        if (roundedTick >= tickUpper || tickLower >= tickUpper) {
            // cumulativeAmount0DensityX96 is just 0
            return 0;
        } else if (roundedTick < tickLower) {
            roundedTick = tickLower;
        }

        uint24 length = uint24((tickUpper - tickLower) / tickSpacing);
        uint160 sqrtRatioTickUpper = tickUpper.getSqrtPriceAtTick();
        amount0 = isCarpet
            ? SqrtPriceMath.getAmount0Delta(
                roundedTick.getSqrtPriceAtTick(), sqrtRatioTickUpper, totalLiquidity.divUp(length), true
            )
            : totalLiquidity.fullMulX96Up(
                SqrtPriceMath.getAmount0Delta(roundedTick.getSqrtPriceAtTick(), sqrtRatioTickUpper, Q96.divUp(length), true)
            );
    }

    /// @dev Computes the cumulative amount of token1 in the rounded ticks [tickLower, roundedTick].
    function cumulativeAmount1(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 tickLower,
        int24 tickUpper,
        bool isCarpet
    ) internal pure returns (uint256 amount1) {
        if (roundedTick < tickLower || tickLower >= tickUpper) {
            // cumulativeAmount1DensityX96 is just 0
            return 0;
        } else if (roundedTick > tickUpper - tickSpacing) {
            roundedTick = tickUpper - tickSpacing;
        }

        uint24 length = uint24((tickUpper - tickLower) / tickSpacing);
        uint160 sqrtRatioTickLower = tickLower.getSqrtPriceAtTick();
        amount1 = isCarpet
            ? SqrtPriceMath.getAmount1Delta(
                sqrtRatioTickLower, (roundedTick + tickSpacing).getSqrtPriceAtTick(), totalLiquidity.divUp(length), true
            )
            : totalLiquidity.fullMulX96Up(
                SqrtPriceMath.getAmount1Delta(
                    sqrtRatioTickLower, (roundedTick + tickSpacing).getSqrtPriceAtTick(), Q96.divUp(length), true
                )
            );
    }

    /// @dev Given a cumulativeAmount0, computes the rounded tick whose cumulativeAmount0 is closest to the input. Range is [tickLower, tickUpper].
    ///      The returned tick will be the largest rounded tick whose cumulativeAmount0 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount0 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount0(
        uint256 cumulativeAmount0_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 tickLower,
        int24 tickUpper,
        bool isCarpet
    ) internal pure returns (bool success, int24 roundedTick) {
        // short circuit if cumulativeAmount0_ is 0
        if (cumulativeAmount0_ == 0) return (true, tickUpper);

        uint24 length = uint24((tickUpper - tickLower) / tickSpacing);

        uint160 sqrtRatioTickLower = tickLower.getSqrtPriceAtTick();
        uint160 sqrtRatioTickUpper = tickUpper.getSqrtPriceAtTick();
        uint160 sqrtPrice = isCarpet
            ? SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
                sqrtRatioTickUpper, totalLiquidity.divUp(length), cumulativeAmount0_, true
            )
            : SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(
                sqrtRatioTickUpper, Q96.divUp(length), cumulativeAmount0_.fullMulDiv(Q96, totalLiquidity), true
            );
        if (sqrtPrice < sqrtRatioTickLower) {
            return (false, 0);
        }
        int24 tick = sqrtPrice.getTickAtSqrtPrice();
        success = true;
        roundedTick = roundTickSingle(tick, tickSpacing);

        // ensure roundedTick is within the valid range
        if (roundedTick < tickLower || roundedTick > tickUpper) {
            return (false, 0);
        }

        // ensure that roundedTick is not tickUpper when cumulativeAmount0_ is non-zero
        // this can happen if the corresponding cumulative density is too small
        if (roundedTick == tickUpper) {
            return (true, tickUpper - tickSpacing);
        }
    }

    /// @dev Given a cumulativeAmount1, computes the rounded tick whose cumulativeAmount1 is closest to the input. Range is [tickLower - tickSpacing, tickUpper - tickSpacing].
    ///      The returned tick will be the smallest rounded tick whose cumulativeAmount1 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount1 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount1(
        uint256 cumulativeAmount1_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 tickLower,
        int24 tickUpper,
        bool isCarpet
    ) internal pure returns (bool success, int24 roundedTick) {
        // short circuit if cumulativeAmount1_ is 0
        if (cumulativeAmount1_ == 0) return (true, tickLower - tickSpacing);

        uint24 length = uint24((tickUpper - tickLower) / tickSpacing);

        uint160 sqrtRatioTickLower = tickLower.getSqrtPriceAtTick();
        uint160 sqrtRatioTickUpper = tickUpper.getSqrtPriceAtTick();
        uint160 sqrtPrice = isCarpet
            ? SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
                sqrtRatioTickLower, totalLiquidity.divUp(length), cumulativeAmount1_, true
            )
            : SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(
                sqrtRatioTickLower, Q96.divUp(length), cumulativeAmount1_.fullMulDiv(Q96, totalLiquidity), true
            );
        if (sqrtPrice > sqrtRatioTickUpper) {
            return (false, 0);
        }
        int24 tick = sqrtPrice.getTickAtSqrtPrice();
        // handle the edge case where cumulativeAmount1_ is exactly the
        // cumulative amount in [tickLower, tickUpper]
        if (tick == tickUpper) {
            tick -= 1;
        }
        success = true;
        roundedTick = roundTickSingle(tick, tickSpacing);

        // ensure roundedTick is within the valid range
        if (roundedTick < tickLower - tickSpacing || roundedTick >= tickUpper) {
            return (false, 0);
        }

        // ensure that roundedTick is not (tickLower - tickSpacing) when cumulativeAmount1_ is non-zero and rounding up
        // this can happen if the corresponding cumulative density is too small
        if (roundedTick == tickLower - tickSpacing) {
            return (true, tickLower);
        }
    }

    function liquidityDensityX96(int24 roundedTick, int24 tickSpacing, int24 tickLower, int24 tickUpper)
        internal
        pure
        returns (uint256)
    {
        if (roundedTick < tickLower || roundedTick >= tickUpper) {
            // roundedTick is outside of the distribution
            return 0;
        }
        uint256 length = uint24((tickUpper - tickLower) / tickSpacing);
        return Q96 / length;
    }

    /// @dev Combines several operations used during a swap into one function to save gas.
    ///      Given a cumulative amount, it computes its inverse to find the closest rounded tick, then computes the cumulative amount at that tick,
    ///      and finally computes the liquidity of the tick that will handle the remainder of the swap.
    function computeSwap(
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 tickSpacing,
        int24 tickLower,
        int24 tickUpper
    )
        internal
        pure
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        )
    {
        if (exactIn == zeroForOne) {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round down to the rounded tick to the left
            // e.g. go from 1.5 to 1
            //       input
            //      ├──────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            (success, roundedTick) = inverseCumulativeAmount0(
                inverseCumulativeAmountInput, totalLiquidity, tickSpacing, tickLower, tickUpper, false
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick + tickSpacing
            // exactOut:
            //        cum
            //    ├────────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, tickLower, tickUpper, false)
                : cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, tickLower, tickUpper, false);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            // exactOut:
            //  cum
            // ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            // │
            // ▼
            //rick - tickSpacing
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, tickLower, tickUpper, false)
                : cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, tickLower, tickUpper, false);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //    liq
            //    ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            swapLiquidity = (liquidityDensityX96(roundedTick, tickSpacing, tickLower, tickUpper) * totalLiquidity) >> 96;
        } else {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round up to the rounded tick to the right
            // e.g. go from 1.5 to 2
            //  input
            // ├──────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            (success, roundedTick) = inverseCumulativeAmount1(
                inverseCumulativeAmountInput, totalLiquidity, tickSpacing, tickLower, tickUpper, false
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick - tickSpacing
            // exactOut:
            //     cum
            // ├────────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, tickLower, tickUpper, false)
                : cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, tickLower, tickUpper, false);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            // exactOut:
            //           cum
            //          ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //          │
            //          ▼
            //         rick + tickSpacing
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, tickLower, tickUpper, false)
                : cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, tickLower, tickUpper, false);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //       liq
            //       ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            swapLiquidity = (liquidityDensityX96(roundedTick, tickSpacing, tickLower, tickUpper) * totalLiquidity) >> 96;
        }
    }

    function isValidParams(int24 tickSpacing, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        internal
        pure
        returns (bool)
    {
        uint8 shiftMode = uint8(bytes1(ldfParams)); // use uint8 since we don't know if the value is in range yet
        (int24 minUsableTick, int24 maxUsableTick) =
            (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
        if (shiftMode != uint8(ShiftMode.STATIC)) {
            // Shifting
            // | shiftMode - 1 byte | offset - 3 bytes | length - 3 bytes |
            int24 offset = int24(uint24(bytes3(ldfParams << 8))); // offset (in rounded ticks) of tickLower from the twap tick
            int24 length = int24(uint24(bytes3(ldfParams << 32))); // length of the position in rounded ticks

            return twapSecondsAgo != 0 && ldfType == LDFType.DYNAMIC_AND_STATEFUL && length > 0
                && offset % tickSpacing == 0 && int256(length) * int256(tickSpacing) <= type(int24).max
                && int256(length) * int256(tickSpacing) <= (maxUsableTick - minUsableTick)
                && shiftMode <= uint8(type(ShiftMode).max);
        } else {
            // Static
            // | shiftMode - 1 byte | tickLower - 3 bytes | tickUpper - 3 bytes |
            int24 tickLower = int24(uint24(bytes3(ldfParams << 8)));
            int24 tickUpper = int24(uint24(bytes3(ldfParams << 32)));

            return ldfType == LDFType.STATIC && tickLower % tickSpacing == 0 && tickUpper % tickSpacing == 0
                && tickLower < tickUpper && tickLower >= minUsableTick && tickUpper <= maxUsableTick;
        }
    }

    /// @return tickLower The lower tick of the distribution
    /// @return tickUpper The upper tick of the distribution
    function decodeParams(int24 twapTick, int24 tickSpacing, bytes32 ldfParams)
        internal
        pure
        returns (int24 tickLower, int24 tickUpper, ShiftMode shiftMode)
    {
        shiftMode = ShiftMode(uint8(bytes1(ldfParams)));

        if (shiftMode != ShiftMode.STATIC) {
            // | shiftMode - 1 byte | offset - 3 bytes | length - 3 bytes |
            int24 offset = int24(uint24(bytes3(ldfParams << 8))); // offset of tickLower from the twap tick
            int24 length = int24(uint24(bytes3(ldfParams << 32))); // length of the position in rounded ticks
            tickLower = roundTickSingle(twapTick + offset, tickSpacing);
            tickUpper = tickLower + length * tickSpacing;

            // bound distribution to be within the range of usable ticks
            (int24 minUsableTick, int24 maxUsableTick) =
                (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
            if (tickLower < minUsableTick) {
                tickLower = minUsableTick;
                tickUpper = int24(FixedPointMathLib.min(tickLower + length * tickSpacing, maxUsableTick));
            } else if (tickUpper > maxUsableTick) {
                tickUpper = maxUsableTick;
                tickLower = int24(FixedPointMathLib.max(tickUpper - length * tickSpacing, minUsableTick));
            }
        } else {
            // | shiftMode - 1 byte | tickLower - 3 bytes | tickUpper - 3 bytes |
            tickLower = int24(uint24(bytes3(ldfParams << 8)));
            tickUpper = int24(uint24(bytes3(ldfParams << 32)));
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import "./ShiftMode.sol";
import "../lib/Math.sol";
import "../lib/ExpMath.sol";
import "../base/Constants.sol";
import "./LibGeometricDistribution.sol";
import {LDFType} from "../types/LDFType.sol";

library LibDoubleGeometricDistribution {
    using SafeCastLib for uint256;
    using FixedPointMathLib for uint256;

    uint256 internal constant ALPHA_BASE = 1e8; // alpha uses 8 decimals in ldfParams
    uint256 internal constant MIN_LIQUIDITY_DENSITY = Q96 / 1e3;

    /// @dev Queries the liquidity density and the cumulative amounts at the given rounded tick.
    /// @param roundedTick The rounded tick to query
    /// @param tickSpacing The spacing of the ticks
    /// @return liquidityDensityX96_ The liquidity density at the given rounded tick. Range is [0, 1]. Scaled by 2^96.
    /// @return cumulativeAmount0DensityX96 The cumulative amount of token0 in the rounded ticks [roundedTick + tickSpacing, minTick + length * tickSpacing)
    /// @return cumulativeAmount1DensityX96 The cumulative amount of token1 in the rounded ticks [minTick, roundedTick - tickSpacing]
    function query(
        int24 roundedTick,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    )
        internal
        pure
        returns (uint256 liquidityDensityX96_, uint256 cumulativeAmount0DensityX96, uint256 cumulativeAmount1DensityX96)
    {
        // compute liquidityDensityX96
        liquidityDensityX96_ = liquidityDensityX96(
            roundedTick, tickSpacing, minTick, length0, length1, alpha0X96, alpha1X96, weight0, weight1
        );

        // compute cumulativeAmount0DensityX96
        cumulativeAmount0DensityX96 = cumulativeAmount0(
            roundedTick + tickSpacing,
            Q96,
            tickSpacing,
            minTick,
            length0,
            length1,
            alpha0X96,
            alpha1X96,
            weight0,
            weight1
        );

        // compute cumulativeAmount1DensityX96
        cumulativeAmount1DensityX96 = cumulativeAmount1(
            roundedTick - tickSpacing,
            Q96,
            tickSpacing,
            minTick,
            length0,
            length1,
            alpha0X96,
            alpha1X96,
            weight0,
            weight1
        );
    }

    /// @dev Computes the cumulative amount of token0 in the rounded ticks [roundedTick, tickUpper).
    function cumulativeAmount0(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    ) internal pure returns (uint256 amount0) {
        uint256 totalLiquidity0 = totalLiquidity.mulDiv(weight0, weight0 + weight1);
        uint256 totalLiquidity1 = totalLiquidity.mulDiv(weight1, weight0 + weight1);
        amount0 = LibGeometricDistribution.cumulativeAmount0(
            roundedTick, totalLiquidity0, tickSpacing, minTick + length1 * tickSpacing, length0, alpha0X96
        )
            + LibGeometricDistribution.cumulativeAmount0(
                roundedTick, totalLiquidity1, tickSpacing, minTick, length1, alpha1X96
            );
    }

    /// @dev Computes the cumulative amount of token1 in the rounded ticks [tickLower, roundedTick].
    function cumulativeAmount1(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    ) internal pure returns (uint256 amount1) {
        uint256 totalLiquidity0 = totalLiquidity.mulDiv(weight0, weight0 + weight1);
        uint256 totalLiquidity1 = totalLiquidity.mulDiv(weight1, weight0 + weight1);
        amount1 = LibGeometricDistribution.cumulativeAmount1(
            roundedTick, totalLiquidity0, tickSpacing, minTick + length1 * tickSpacing, length0, alpha0X96
        )
            + LibGeometricDistribution.cumulativeAmount1(
                roundedTick, totalLiquidity1, tickSpacing, minTick, length1, alpha1X96
            );
    }

    /// @dev Given a cumulativeAmount0, computes the rounded tick whose cumulativeAmount0 is closest to the input. Range is [tickLower, tickUpper].
    ///      The returned tick will be the largest rounded tick whose cumulativeAmount0 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount0 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount0(
        uint256 cumulativeAmount0_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    ) internal pure returns (bool success, int24 roundedTick) {
        // try ldf0 first, if fails then try ldf1 with remainder
        int24 minTick0 = minTick + length1 * tickSpacing;
        uint256 totalLiquidity0 = totalLiquidity.mulDiv(weight0, weight0 + weight1);
        uint256 ldf0CumulativeAmount0 = LibGeometricDistribution.cumulativeAmount0(
            minTick0, totalLiquidity0, tickSpacing, minTick0, length0, alpha0X96
        );

        if (cumulativeAmount0_ <= ldf0CumulativeAmount0) {
            return LibGeometricDistribution.inverseCumulativeAmount0(
                cumulativeAmount0_, totalLiquidity0, tickSpacing, minTick0, length0, alpha0X96
            );
        } else {
            uint256 remainder = cumulativeAmount0_ - ldf0CumulativeAmount0;
            uint256 totalLiquidity1 = totalLiquidity.mulDiv(weight1, weight0 + weight1);
            return LibGeometricDistribution.inverseCumulativeAmount0(
                remainder, totalLiquidity1, tickSpacing, minTick, length1, alpha1X96
            );
        }
    }

    /// @dev Given a cumulativeAmount1, computes the rounded tick whose cumulativeAmount1 is closest to the input. Range is [tickLower - tickSpacing, tickUpper - tickSpacing].
    ///      The returned tick will be the smallest rounded tick whose cumulativeAmount1 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount1 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount1(
        uint256 cumulativeAmount1_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    ) internal pure returns (bool success, int24 roundedTick) {
        // try ldf1 first, if fails then try ldf0 with remainder
        uint256 totalLiquidity1 = totalLiquidity.mulDiv(weight1, weight0 + weight1);
        uint256 ldf1CumulativeAmount1 = LibGeometricDistribution.cumulativeAmount1(
            minTick + length1 * tickSpacing, totalLiquidity1, tickSpacing, minTick, length1, alpha1X96
        );

        if (cumulativeAmount1_ <= ldf1CumulativeAmount1) {
            return LibGeometricDistribution.inverseCumulativeAmount1(
                cumulativeAmount1_, totalLiquidity1, tickSpacing, minTick, length1, alpha1X96
            );
        } else {
            uint256 remainder = cumulativeAmount1_ - ldf1CumulativeAmount1;
            uint256 totalLiquidity0 = totalLiquidity.mulDiv(weight0, weight0 + weight1);
            return LibGeometricDistribution.inverseCumulativeAmount1(
                remainder, totalLiquidity0, tickSpacing, minTick + length1 * tickSpacing, length0, alpha0X96
            );
        }
    }

    function checkMinLiquidityDensity(
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 length0,
        uint256 alpha0,
        uint256 weight0,
        int24 length1,
        uint256 alpha1,
        uint256 weight1
    ) internal pure returns (bool) {
        // ensure liquidity density is nowhere equal to zero
        // can check boundaries since function is monotonic
        int24 minTick = 0; // no loss of generality since shifting doesn't change the min liquidity density
        {
            uint256 alpha0X96 = uint256(alpha0).mulDiv(Q96, ALPHA_BASE);
            uint256 minLiquidityDensityX96;
            int24 minTick0 = minTick + length1 * tickSpacing;
            if (alpha0 > ALPHA_BASE) {
                // monotonically increasing
                // check left boundary
                minLiquidityDensityX96 =
                    LibGeometricDistribution.liquidityDensityX96(minTick0, tickSpacing, minTick0, length0, alpha0X96);
            } else {
                // monotonically decreasing
                // check right boundary
                minLiquidityDensityX96 = LibGeometricDistribution.liquidityDensityX96(
                    minTick0 + (length0 - 1) * tickSpacing, tickSpacing, minTick0, length0, alpha0X96
                );
            }
            minLiquidityDensityX96 =
                minLiquidityDensityX96.mulDiv(weight0, weight0 + weight1).mulDiv(totalLiquidity, Q96);
            if (minLiquidityDensityX96 < MIN_LIQUIDITY_DENSITY) {
                return false;
            }
        }

        {
            uint256 alpha1X96 = uint256(alpha1).mulDiv(Q96, ALPHA_BASE);
            uint256 minLiquidityDensityX96;
            if (alpha1 > ALPHA_BASE) {
                // monotonically increasing
                // check left boundary
                minLiquidityDensityX96 =
                    LibGeometricDistribution.liquidityDensityX96(minTick, tickSpacing, minTick, length1, alpha1X96);
            } else {
                // monotonically decreasing
                // check right boundary
                minLiquidityDensityX96 = LibGeometricDistribution.liquidityDensityX96(
                    minTick + (length1 - 1) * tickSpacing, tickSpacing, minTick, length1, alpha1X96
                );
            }
            minLiquidityDensityX96 =
                minLiquidityDensityX96.mulDiv(weight1, weight0 + weight1).mulDiv(totalLiquidity, Q96);
            if (minLiquidityDensityX96 < MIN_LIQUIDITY_DENSITY) {
                return false;
            }
        }

        return true;
    }

    function liquidityDensityX96(
        int24 roundedTick,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    ) internal pure returns (uint256) {
        return weightedSum(
            LibGeometricDistribution.liquidityDensityX96(
                roundedTick, tickSpacing, minTick + length1 * tickSpacing, length0, alpha0X96
            ),
            weight0,
            LibGeometricDistribution.liquidityDensityX96(roundedTick, tickSpacing, minTick, length1, alpha1X96),
            weight1
        );
    }

    /// @dev Combines several operations used during a swap into one function to save gas.
    ///      Given a cumulative amount, it computes its inverse to find the closest rounded tick, then computes the cumulative amount at that tick,
    ///      and finally computes the liquidity of the tick that will handle the remainder of the swap.
    function computeSwap(
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 tickSpacing,
        int24 minTick,
        int24 length0,
        int24 length1,
        uint256 alpha0X96,
        uint256 alpha1X96,
        uint256 weight0,
        uint256 weight1
    )
        internal
        pure
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        )
    {
        if (exactIn == zeroForOne) {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round down to the rounded tick to the left
            // e.g. go from 1.5 to 1
            //       input
            //      ├──────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            (success, roundedTick) = inverseCumulativeAmount0(
                inverseCumulativeAmountInput,
                totalLiquidity,
                tickSpacing,
                minTick,
                length0,
                length1,
                alpha0X96,
                alpha1X96,
                weight0,
                weight1
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick + tickSpacing
            // exactOut:
            //        cum
            //    ├────────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(
                    roundedTick + tickSpacing,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                )
                : cumulativeAmount0(
                    roundedTick,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                );

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            // exactOut:
            //  cum
            // ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            // │
            // ▼
            //rick - tickSpacing
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(
                    roundedTick,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                )
                : cumulativeAmount1(
                    roundedTick - tickSpacing,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                );

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //    liq
            //    ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            swapLiquidity = (
                liquidityDensityX96(
                    roundedTick, tickSpacing, minTick, length0, length1, alpha0X96, alpha1X96, weight0, weight1
                ) * totalLiquidity
            ) >> 96;
        } else {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round up to the rounded tick to the right
            // e.g. go from 1.5 to 2
            //  input
            // ├──────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            (success, roundedTick) = inverseCumulativeAmount1(
                inverseCumulativeAmountInput,
                totalLiquidity,
                tickSpacing,
                minTick,
                length0,
                length1,
                alpha0X96,
                alpha1X96,
                weight0,
                weight1
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick - tickSpacing
            // exactOut:
            //     cum
            // ├────────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(
                    roundedTick - tickSpacing,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                )
                : cumulativeAmount1(
                    roundedTick,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                );

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            // exactOut:
            //           cum
            //          ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //          │
            //          ▼
            //         rick + tickSpacing
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(
                    roundedTick,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                )
                : cumulativeAmount0(
                    roundedTick + tickSpacing,
                    totalLiquidity,
                    tickSpacing,
                    minTick,
                    length0,
                    length1,
                    alpha0X96,
                    alpha1X96,
                    weight0,
                    weight1
                );

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //       liq
            //       ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            swapLiquidity = (
                liquidityDensityX96(
                    roundedTick, tickSpacing, minTick, length0, length1, alpha0X96, alpha1X96, weight0, weight1
                ) * totalLiquidity
            ) >> 96;
        }
    }

    function isValidParams(int24 tickSpacing, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        internal
        pure
        returns (bool)
    {
        // | shiftMode - 1 byte | minTickOrOffset - 3 bytes | length0 - 2 bytes | alpha0 - 4 bytes | weight0 - 4 bytes | length1 - 2 bytes | alpha1 - 2 bytes | weight1 - 4 bytes |
        uint8 shiftMode = uint8(bytes1(ldfParams));
        int24 minTickOrOffset = int24(uint24(bytes3(ldfParams << 8)));
        int24 length0 = int24(int16(uint16(bytes2(ldfParams << 32))));
        uint32 alpha0 = uint32(bytes4(ldfParams << 48));
        uint256 weight0 = uint32(bytes4(ldfParams << 80));
        int24 length1 = int24(int16(uint16(bytes2(ldfParams << 112))));
        uint32 alpha1 = uint32(bytes4(ldfParams << 128));
        uint256 weight1 = uint32(bytes4(ldfParams << 160));

        // ensure length doesn't overflow when multiplied by tickSpacing
        // ensure length can be contained between minUsableTick and maxUsableTick
        (int24 minUsableTick, int24 maxUsableTick) =
            (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
        int24 length = length0 + length1;
        if (
            int256(length) * int256(tickSpacing) > type(int24).max || length > maxUsableTick / tickSpacing
                || -length < minUsableTick / tickSpacing
        ) return false;

        return LibGeometricDistribution.isValidParams(
            tickSpacing,
            twapSecondsAgo,
            bytes32(abi.encodePacked(shiftMode, minTickOrOffset, int16(length1), alpha1)),
            ldfType
        )
            && LibGeometricDistribution.isValidParams(
                tickSpacing,
                twapSecondsAgo,
                bytes32(abi.encodePacked(shiftMode, minTickOrOffset + length1 * tickSpacing, int16(length0), alpha0)),
                ldfType
            ) && weight0 != 0 && weight1 != 0
            && checkMinLiquidityDensity(Q96, tickSpacing, length0, alpha0, weight0, length1, alpha1, weight1);
    }

    /// @return minTick The minimum rounded tick of the distribution
    /// @return length0 The length of the right distribution in number of rounded ticks
    /// @return length1 The length of the left distribution in number of rounded ticks
    /// @return alpha0X96 The alpha of the right distribution
    /// @return alpha1X96 The alpha of the left distribution
    /// @return weight0 The weight of the right distribution
    /// @return weight1 The weight of the left distribution
    /// @return shiftMode The shift mode of the distribution
    function decodeParams(int24 twapTick, int24 tickSpacing, bytes32 ldfParams)
        internal
        pure
        returns (
            int24 minTick,
            int24 length0,
            int24 length1,
            uint256 alpha0X96,
            uint256 alpha1X96,
            uint256 weight0,
            uint256 weight1,
            ShiftMode shiftMode
        )
    {
        // | shiftMode - 1 byte | minTickOrOffset - 3 bytes | length0 - 2 bytes | alpha0 - 4 bytes | weight0 - 4 bytes | length1 - 2 bytes | alpha1 - 4 bytes | weight1 - 4 bytes |
        shiftMode = ShiftMode(uint8(bytes1(ldfParams)));
        length0 = int24(int16(uint16(bytes2(ldfParams << 32))));
        uint256 alpha0 = uint32(bytes4(ldfParams << 48));
        weight0 = uint32(bytes4(ldfParams << 80));
        length1 = int24(int16(uint16(bytes2(ldfParams << 112))));
        uint256 alpha1 = uint32(bytes4(ldfParams << 128));
        weight1 = uint32(bytes4(ldfParams << 160));

        alpha0X96 = alpha0.mulDiv(Q96, ALPHA_BASE);
        alpha1X96 = alpha1.mulDiv(Q96, ALPHA_BASE);

        if (shiftMode != ShiftMode.STATIC) {
            // use rounded TWAP value + offset as minTick
            int24 offset = int24(uint24(bytes3(ldfParams << 8))); // the offset applied to the twap tick to get the minTick
            minTick = roundTickSingle(twapTick + offset, tickSpacing);

            // bound distribution to be within the range of usable ticks
            (int24 minUsableTick, int24 maxUsableTick) =
                (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
            if (minTick < minUsableTick) {
                minTick = minUsableTick;
            } else if (minTick > maxUsableTick - (length0 + length1) * tickSpacing) {
                minTick = maxUsableTick - (length0 + length1) * tickSpacing;
            }
        } else {
            // static minTick set in params
            minTick = int24(uint24(bytes3(ldfParams << 8))); // must be aligned to tickSpacing
        }
    }
}

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

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

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

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

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

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

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

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

library FullMathX96 {
    uint256 internal constant Q96 = 0x1000000000000000000000000;

    /// @dev Calculates `floor(x * y / 2 ** 96)` with full precision.
    /// Throws if result overflows a uint256.
    /// Credit to Philogy under MIT license:
    /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
    function fullMulX96(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
            for {} 1 {} {
                if iszero(or(iszero(x), eq(div(z, x), y))) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                    //         |      p1     |      z     |
                    // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                    // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                    // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                    if iszero(shr(96, p1)) {
                        z := add(shl(160, p1), shr(96, z))
                        break
                    }
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
                z := shr(96, z)
                break
            }
        }
    }

    function fullMulX96Up(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = fullMulX96(x, y);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, Q96) {
                z := add(z, 1)
                if iszero(z) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }
}

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

import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {UnsafeMath} from "@uniswap/v4-core/src/libraries/UnsafeMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

    error InvalidPriceOrLiquidity();
    error InvalidPrice();
    error NotEnoughLiquidity();
    error PriceOverflow();

    /// @notice Gets the next sqrt price given a delta of currency0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of currency0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint256 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            unchecked {
                uint256 product = amount * sqrtPX96;
                if (product / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1) {
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                    }
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product = amount * sqrtPX96;
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
                assembly ("memory-safe") {
                    if iszero(
                        and(
                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                            gt(numerator1, product)
                        )
                    ) {
                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()
                        revert(0x1c, 0x04)
                    }
                }
                uint256 denominator = numerator1 - product;
                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
            }
        }
    }

    /// @notice Gets the next sqrt price given a delta of currency1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of currency1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint256 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
            assembly ("memory-safe") {
                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
                    revert(0x1c, 0x04)
                }
            }
            // always fits 160 bits
            unchecked {
                return uint160(sqrtPX96 - quotient);
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of currency0, or currency1, is being swapped in
    /// @param zeroForOne Whether the amount in is currency0 or currency1
    /// @return uint160 The price after adding the input amount to currency0 or currency1
    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint256 liquidity, uint256 amountIn, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we don't pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of currency0, or currency1, is being swapped out
    /// @param zeroForOne Whether the amount out is currency1 or currency0
    /// @return uint160 The price after removing the output amount of currency0 or currency1
    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint256 liquidity, uint256 amountOut, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)), iszero(liquidity)) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 liquidity, bool roundUp)
        internal
        pure
        returns (uint256)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
            assembly ("memory-safe") {
                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
                    mstore(0, 0x00bfc921) // selector for InvalidPrice()
                    revert(0x1c, 0x04)
                }
            }

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;

            return roundUp
                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
        }
    }

    /// @notice Equivalent to: `a >= b ? a - b : b - a`
    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly ("memory-safe") {
            let diff :=
                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
            // mask = 0 if a >= b else -1 (all 1s)
            let mask := sar(255, diff)
            // if a >= b, res = a - b = 0 ^ (a - b)
            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
            // either way, res = mask ^ (a - b + mask)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 liquidity, bool roundUp)
        internal
        pure
        returns (uint256 amount1)
    {
        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity = uint256(liquidity);

        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
        assembly ("memory-safe") {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @notice Helper that gets signed currency0 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }

    /// @notice Helper that gets signed currency1 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";

import "./ShiftMode.sol";
import "../lib/Math.sol";
import "../lib/ExpMath.sol";
import "../base/Constants.sol";
import {LDFType} from "../types/LDFType.sol";
import {FullMathX96} from "../lib/FullMathX96.sol";

library LibGeometricDistribution {
    using FullMathX96 for *;
    using TickMath for int24;
    using ExpMath for int256;
    using SafeCastLib for *;
    using FixedPointMathLib for *;

    uint256 internal constant ALPHA_BASE = 1e8; // alpha uses 8 decimals in ldfParams
    uint256 internal constant MIN_ALPHA = 1e3;
    uint256 internal constant MAX_ALPHA = 12e8;
    uint256 internal constant MIN_LIQUIDITY_DENSITY = Q96 / 1e3;

    /// @dev Queries the liquidity density and the cumulative amounts at the given rounded tick.
    /// @param roundedTick The rounded tick to query
    /// @param tickSpacing The spacing of the ticks
    /// @return liquidityDensityX96_ The liquidity density at the given rounded tick. Range is [0, 1]. Scaled by 2^96.
    /// @return cumulativeAmount0DensityX96 The cumulative amount of token0 in the rounded ticks [roundedTick + tickSpacing, minTick + length * tickSpacing)
    /// @return cumulativeAmount1DensityX96 The cumulative amount of token1 in the rounded ticks [minTick, roundedTick - tickSpacing]
    function query(int24 roundedTick, int24 tickSpacing, int24 minTick, int24 length, uint256 alphaX96)
        internal
        pure
        returns (uint256 liquidityDensityX96_, uint256 cumulativeAmount0DensityX96, uint256 cumulativeAmount1DensityX96)
    {
        // compute liquidityDensityX96
        liquidityDensityX96_ = liquidityDensityX96(roundedTick, tickSpacing, minTick, length, alphaX96);

        // x is the index of the roundedTick in the distribution
        // should be in the range [0, length)
        int24 x;
        if (roundedTick < minTick) {
            // roundedTick is to the left of the distribution
            // set x = -1
            x = -1;
        } else if (roundedTick >= minTick + length * tickSpacing) {
            // roundedTick is to the right of the distribution
            // set x = length
            x = length;
        } else {
            // roundedTick is in the distribution
            x = (roundedTick - minTick) / tickSpacing;
        }

        uint256 sqrtRatioTickSpacing = tickSpacing.getSqrtPriceAtTick();
        uint256 sqrtRatioNegTickSpacing = (-tickSpacing).getSqrtPriceAtTick();
        uint256 sqrtRatioMinTick = minTick.getSqrtPriceAtTick();
        uint256 sqrtRatioNegMinTick = (-minTick).getSqrtPriceAtTick();

        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);

            // compute cumulativeAmount0DensityX96 for the rounded tick to the right of the rounded current tick
            if (x >= length - 1) {
                // roundedTick is the last tick in the distribution
                // cumulativeAmount0DensityX96 is just 0
                cumulativeAmount0DensityX96 = 0;
            } else {
                int24 xPlus1 = x + 1; // the rounded tick to the right of the current rounded tick

                uint24 lengthMinusX = uint24(length - xPlus1);
                bool intermediateTermIsPositive = alphaInvX96 > sqrtRatioNegTickSpacing;
                uint256 numeratorTermLeft = alphaInvX96.rpow(lengthMinusX, Q96);
                uint256 numeratorTermRight = (-tickSpacing * int24(lengthMinusX)).getSqrtPriceAtTick();
                cumulativeAmount0DensityX96 = (Q96 - alphaInvX96).mulDivUp(
                    intermediateTermIsPositive
                        ? numeratorTermLeft - numeratorTermRight
                        : numeratorTermRight - numeratorTermLeft,
                    intermediateTermIsPositive
                        ? alphaInvX96 - sqrtRatioNegTickSpacing
                        : sqrtRatioNegTickSpacing - alphaInvX96
                ).mulDivUp((-tickSpacing * xPlus1).getSqrtPriceAtTick(), Q96 - alphaInvX96.rpow(uint24(length), Q96))
                    .mulDivUp(Q96 - sqrtRatioNegTickSpacing, sqrtRatioMinTick);
            }

            // compute cumulativeAmount1DensityX96 for the rounded tick to the left of the rounded current tick
            if (x <= 0) {
                // roundedTick is the first tick in the distribution
                // cumulativeAmount1DensityX96 is just 0
                cumulativeAmount1DensityX96 = 0;
            } else {
                uint256 alphaInvPowLengthX96 = alphaInvX96.rpow(uint24(length), Q96);

                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioTickSpacing, Q96);
                uint256 numerator1 = alphaX96 - Q96;
                uint256 denominator1 = baseX96 - Q96;
                uint256 numerator2 = alphaInvX96.rpow(uint24(length - x), Q96).mulDivUp(
                    (x * tickSpacing).getSqrtPriceAtTick(), Q96
                ) - alphaInvPowLengthX96;
                uint256 denominator2 = Q96 - alphaInvPowLengthX96;
                cumulativeAmount1DensityX96 = Q96.mulDivUp(numerator2, denominator2).mulDivUp(numerator1, denominator1)
                    .mulDivUp(sqrtRatioTickSpacing - Q96, sqrtRatioNegMinTick);
            }
        } else {
            // alpha <= 1
            // will revert if alpha == 1 but that's ok

            // compute cumulativeAmount0DensityX96 for the rounded tick to the right of the rounded current tick
            if (x >= length - 1) {
                // roundedTick is the last tick in the distribution
                // cumulativeAmount0DensityX96 is just 0
                cumulativeAmount0DensityX96 = 0;
            } else {
                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioNegTickSpacing, Q96);
                int24 xPlus1 = x + 1;
                uint256 alphaPowXX96 = alphaX96.rpow(uint24(xPlus1), Q96);
                uint256 alphaPowLengthX96 = alphaX96.rpow(uint24(length), Q96);
                uint256 numerator = (Q96 - alphaX96)
                    * (
                        alphaPowXX96.mulDivUp((-tickSpacing * xPlus1).getSqrtPriceAtTick(), Q96)
                            - alphaPowLengthX96.mulDivUp((-tickSpacing * length).getSqrtPriceAtTick(), Q96)
                    );
                uint256 denominator = (Q96 - alphaPowLengthX96) * (Q96 - baseX96);
                cumulativeAmount0DensityX96 =
                    (Q96 - sqrtRatioNegTickSpacing).fullMulDivUp(numerator, denominator).mulDivUp(Q96, sqrtRatioMinTick);
            }

            // compute cumulativeAmount1DensityX96 for the rounded tick to the left of the rounded current tick
            if (x <= 0) {
                // roundedTick is the first tick in the distribution
                // cumulativeAmount1DensityX96 is just 0
                cumulativeAmount1DensityX96 = 0;
            } else {
                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioTickSpacing, Q96);
                uint256 numerator = dist(
                    Q96, alphaX96.rpow(uint24(x), Q96).mulDivUp((tickSpacing * x).getSqrtPriceAtTick(), Q96)
                ) * (Q96 - alphaX96);
                uint256 denominator = dist(Q96, baseX96) * (Q96 - alphaX96.rpow(uint24(length), Q96));
                cumulativeAmount1DensityX96 =
                    (sqrtRatioTickSpacing - Q96).fullMulDivUp(numerator, denominator).mulDivUp(sqrtRatioMinTick, Q96);
            }
        }
    }

    /// @dev Computes the cumulative amount of token0 in the rounded ticks [roundedTick, tickUpper).
    function cumulativeAmount0(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 alphaX96
    ) internal pure returns (uint256 amount0) {
        uint256 cumulativeAmount0DensityX96;

        // x is the index of the roundedTick in the distribution
        // should be in the range [0, length)
        int24 x;
        if (roundedTick < minTick) {
            // roundedTick is to the left of the distribution
            x = 0;
        } else if (roundedTick >= minTick + length * tickSpacing) {
            // roundedTick is to the right of the distribution
            return 0;
        } else {
            // roundedTick is in the distribution
            x = (roundedTick - minTick) / tickSpacing;
        }

        uint256 sqrtRatioNegTickSpacing = (-tickSpacing).getSqrtPriceAtTick();
        uint256 sqrtRatioMinTick = minTick.getSqrtPriceAtTick();

        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);

            // compute cumulativeAmount0DensityX96 for the rounded tick to the right of the rounded current tick
            if (x >= length) {
                // roundedTick is to the right of the last tick in the distribution
                // amount0 is just 0
                amount0 = 0;
            } else {
                uint24 lengthMinusX = uint24(length - x);
                bool intermediateTermIsPositive = alphaInvX96 > sqrtRatioNegTickSpacing;
                uint256 numeratorTermLeft = alphaInvX96.rpow(lengthMinusX, Q96);
                uint256 numeratorTermRight = (-tickSpacing * int24(lengthMinusX)).getSqrtPriceAtTick();
                cumulativeAmount0DensityX96 = (Q96 - alphaInvX96).mulDivUp(
                    intermediateTermIsPositive
                        ? numeratorTermLeft - numeratorTermRight
                        : numeratorTermRight - numeratorTermLeft,
                    intermediateTermIsPositive
                        ? alphaInvX96 - sqrtRatioNegTickSpacing
                        : sqrtRatioNegTickSpacing - alphaInvX96
                ).mulDivUp((-tickSpacing * x).getSqrtPriceAtTick(), Q96 - alphaInvX96.rpow(uint24(length), Q96))
                    .mulDivUp(Q96 - sqrtRatioNegTickSpacing, sqrtRatioMinTick);
            }
        } else {
            // alpha <= 1
            // will revert if alpha == 1 but that's ok

            // compute cumulativeAmount0DensityX96 for the rounded tick to the right of the rounded current tick
            if (x >= length) {
                // roundedTick is to the right of the last tick in the distribution
                // amount0 is just 0
                amount0 = 0;
            } else {
                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioNegTickSpacing, Q96);
                uint256 alphaPowXX96 = alphaX96.rpow(uint24(x), Q96);
                uint256 alphaPowLengthX96 = alphaX96.rpow(uint24(length), Q96);
                uint256 numerator = (Q96 - alphaX96)
                    * (
                        alphaPowXX96.mulDivUp((-tickSpacing * x).getSqrtPriceAtTick(), Q96)
                            - alphaPowLengthX96.mulDivUp((-tickSpacing * length).getSqrtPriceAtTick(), Q96)
                    );
                uint256 denominator = (Q96 - alphaPowLengthX96) * (Q96 - baseX96);

                cumulativeAmount0DensityX96 = (Q96 - sqrtRatioNegTickSpacing).fullMulDivUp(numerator, denominator)
                    .fullMulDivUp(Q96, sqrtRatioMinTick);
            }
        }

        amount0 = cumulativeAmount0DensityX96.fullMulX96Up(totalLiquidity);
    }

    /// @dev Computes the cumulative amount of token1 in the rounded ticks [tickLower, roundedTick].
    function cumulativeAmount1(
        int24 roundedTick,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 alphaX96
    ) internal pure returns (uint256 amount1) {
        uint256 cumulativeAmount1DensityX96;

        // x is the index of the roundedTick in the distribution
        // should be in the range [0, length)
        int24 x;
        if (roundedTick < minTick) {
            // roundedTick is to the left of the distribution
            return 0;
        } else if (roundedTick >= minTick + length * tickSpacing) {
            // roundedTick is to the right of the distribution
            // set x = length
            x = length - 1;
        } else {
            // roundedTick is in the distribution
            x = (roundedTick - minTick) / tickSpacing;
        }

        uint256 sqrtRatioTickSpacing = tickSpacing.getSqrtPriceAtTick();

        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);

            // compute cumulativeAmount1DensityX96 for the rounded tick to the left of the rounded current tick
            if (x < 0) {
                // roundedTick is to the left of the first tick in the distribution
                // cumulativeAmount1DensityX96 is just 0
                cumulativeAmount1DensityX96 = 0;
            } else {
                uint256 alphaInvPowLengthX96 = alphaInvX96.rpow(uint24(length), Q96);
                uint256 sqrtRatioNegMinTick = (-minTick).getSqrtPriceAtTick();

                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioTickSpacing, Q96);
                uint256 numerator1 = alphaX96 - Q96;
                uint256 denominator1 = baseX96 - Q96;
                uint256 numerator2 = alphaInvX96.rpow(uint24(length - x - 1), Q96).mulDivUp(
                    ((x + 1) * tickSpacing).getSqrtPriceAtTick(), Q96
                ) - alphaInvPowLengthX96;
                uint256 denominator2 = Q96 - alphaInvPowLengthX96;
                cumulativeAmount1DensityX96 = Q96.mulDivUp(numerator2, denominator2).mulDivUp(numerator1, denominator1)
                    .mulDivUp(sqrtRatioTickSpacing - Q96, sqrtRatioNegMinTick);
            }
        } else {
            // alpha <= 1
            // will revert if alpha == 1 but that's ok

            // compute cumulativeAmount1DensityX96 for the rounded tick to the left of the rounded current tick
            if (x < 0) {
                // roundedTick is to the left of the first tick in the distribution
                // cumulativeAmount1DensityX96 is just 0
                cumulativeAmount1DensityX96 = 0;
            } else {
                uint256 sqrtRatioMinTick = minTick.getSqrtPriceAtTick();
                uint256 baseX96 = alphaX96.mulDiv(sqrtRatioTickSpacing, Q96);
                uint256 numerator = dist(
                    Q96, alphaX96.rpow(uint24(x + 1), Q96).mulDivUp((tickSpacing * (x + 1)).getSqrtPriceAtTick(), Q96)
                ) * (Q96 - alphaX96);
                uint256 denominator = dist(Q96, baseX96) * (Q96 - alphaX96.rpow(uint24(length), Q96));
                cumulativeAmount1DensityX96 =
                    (sqrtRatioTickSpacing - Q96).fullMulDivUp(numerator, denominator).mulDivUp(sqrtRatioMinTick, Q96);
            }
        }

        amount1 = cumulativeAmount1DensityX96.fullMulX96Up(totalLiquidity);
    }

    /// @dev Given a cumulativeAmount0, computes the rounded tick whose cumulativeAmount0 is closest to the input. Range is [tickLower, tickUpper].
    ///      The returned tick will be the largest rounded tick whose cumulativeAmount0 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount0 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount0(
        uint256 cumulativeAmount0_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 alphaX96
    ) internal pure returns (bool success, int24 roundedTick) {
        if (cumulativeAmount0_ == 0) {
            // return right boundary of distribution
            return (true, minTick + length * tickSpacing);
        }

        uint256 cumulativeAmount0DensityX96 = cumulativeAmount0_.fullMulDivUp(Q96, totalLiquidity);
        uint256 sqrtRatioNegTickSpacing = (-tickSpacing).getSqrtPriceAtTick();
        uint256 sqrtRatioMinTick = minTick.getSqrtPriceAtTick();
        uint256 baseX96 = alphaX96.mulDiv(sqrtRatioNegTickSpacing, Q96);
        int256 lnBaseX96 = int256(baseX96).lnQ96(); // int256 conversion is safe since baseX96 < Q96

        int256 xWad;
        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);

            uint256 alphaInvPowLengthX96 = alphaInvX96.rpow(uint24(length), Q96);
            bool intermediateTermIsPositive = alphaInvX96 > sqrtRatioNegTickSpacing;
            uint256 tmp = cumulativeAmount0DensityX96.mulDivUp(sqrtRatioMinTick, Q96 - sqrtRatioNegTickSpacing).mulDivUp(
                Q96 - alphaInvPowLengthX96, Q96
            ).mulDivUp(
                intermediateTermIsPositive
                    ? alphaInvX96 - sqrtRatioNegTickSpacing
                    : sqrtRatioNegTickSpacing - alphaInvX96,
                Q96 - alphaInvX96
            );
            uint160 sqrtPriceNegTickSpacingMulLength = (-tickSpacing * length).getSqrtPriceAtTick();
            if (!intermediateTermIsPositive && sqrtPriceNegTickSpacingMulLength <= tmp) {
                // this usually happens when the maximum cumulativeAmount0 is very close to zero
                // check to see that cumulativeAmount0_ <= cumulativeAmount0(minTick + (length - 1) * tickSpacing)
                int24 result = minTick + (length - 1) * tickSpacing;
                if (
                    cumulativeAmount0_
                        <= cumulativeAmount0(result, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                ) {
                    return (true, result);
                } else {
                    return (false, 0);
                }
            }
            tmp = intermediateTermIsPositive
                ? tmp + sqrtPriceNegTickSpacingMulLength
                : sqrtPriceNegTickSpacingMulLength - tmp;
            xWad = (tmp.toInt256().lnQ96RoundingUp() + int256(length) * (int256(alphaX96).lnQ96RoundingUp())).sDivWad(
                lnBaseX96
            );
        } else {
            uint256 denominator = (Q96 - alphaX96.rpow(uint24(length), Q96)) * (Q96 - baseX96);
            uint256 numerator = cumulativeAmount0DensityX96.mulDivUp(sqrtRatioMinTick, Q96).fullMulDivUp(
                denominator, Q96 - sqrtRatioNegTickSpacing
            );
            uint256 basePowXX96 = (numerator / (Q96 - alphaX96) + baseX96.rpow(uint24(length), Q96));
            xWad = basePowXX96.toInt256().lnQ96RoundingUp().sDivWad(lnBaseX96);
        }

        // early return if xWad is obviously too small
        // the result (the largest rounded tick whose cumulativeAmount0 is greater than or equal to the input) doesn't exist
        // thus return success = false
        if (xWad < 0) {
            // compare cumulativeAmount0_ with the max value of cumulativeAmount0()
            // due to precision errors sometimes xWad can be negative when cumulativeAmount0_
            // is close to the max value
            uint256 maxCumulativeAmount0 =
                cumulativeAmount0(minTick, totalLiquidity, tickSpacing, minTick, length, alphaX96);
            if (cumulativeAmount0_ > maxCumulativeAmount0) {
                return (false, 0);
            } else {
                // xWad shouldn't actually be negative
                // set it to 0
                xWad = 0;
            }
        }

        // get rounded tick from xWad
        success = true;
        roundedTick = xWadToRoundedTick(xWad, minTick, tickSpacing, false);

        // ensure roundedTick is within the valid range
        int24 maxTick = minTick + length * tickSpacing;
        if (roundedTick < minTick || roundedTick > maxTick) {
            return (false, 0);
        }

        // ensure that roundedTick is not minTick + length * tickSpacing when cumulativeAmount0_ is non-zero
        // this can happen if the corresponding cumulative density is too small
        if (roundedTick == maxTick) {
            return (true, maxTick - tickSpacing);
        }
    }

    /// @dev Given a cumulativeAmount1, computes the rounded tick whose cumulativeAmount1 is closest to the input. Range is [tickLower - tickSpacing, tickUpper - tickSpacing].
    ///      The returned tick will be the smallest rounded tick whose cumulativeAmount1 is greater than or equal to the input.
    ///      In the case that the input exceeds the cumulativeAmount1 of all rounded ticks, the function will return (false, 0).
    function inverseCumulativeAmount1(
        uint256 cumulativeAmount1_,
        uint256 totalLiquidity,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 alphaX96
    ) internal pure returns (bool success, int24 roundedTick) {
        if (cumulativeAmount1_ == 0) {
            // return left boundary of distribution
            return (true, minTick - tickSpacing);
        }

        uint256 cumulativeAmount1DensityX96 = cumulativeAmount1_.fullMulDiv(Q96, totalLiquidity);
        uint256 sqrtRatioTickSpacing = tickSpacing.getSqrtPriceAtTick();
        uint256 baseX96 = alphaX96.mulDiv(sqrtRatioTickSpacing, Q96);
        int256 lnBaseX96 = int256(baseX96).lnQ96RoundingUp(); // int256 conversion is safe since baseX96 < Q96

        int256 xWad;
        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);
            uint256 alphaInvPowLengthX96 = alphaInvX96.rpow(uint24(length), Q96);
            uint256 sqrtRatioNegMinTick = (-minTick).getSqrtPriceAtTick();

            uint256 numerator1 = alphaX96 - Q96;
            uint256 denominator1 = baseX96 - Q96;
            uint256 denominator2 = Q96 - alphaInvPowLengthX96;
            uint256 numerator2 = cumulativeAmount1DensityX96.mulDiv(sqrtRatioNegMinTick, sqrtRatioTickSpacing - Q96)
                .mulDiv(denominator1, numerator1).mulDiv(denominator2, Q96);
            if (numerator2 + alphaInvPowLengthX96 == 0) return (false, 0);
            xWad = ((numerator2 + alphaInvPowLengthX96).toInt256().lnQ96() + int256(length) * int256(alphaX96).lnQ96())
                .sDivWad(lnBaseX96) - int256(WAD);
        } else {
            uint256 sqrtRatioMinTick = minTick.getSqrtPriceAtTick();

            uint256 denominator = dist(Q96, baseX96) * (Q96 - alphaX96.rpow(uint24(length), Q96));
            uint256 numerator = cumulativeAmount1DensityX96.fullMulDiv(Q96, sqrtRatioMinTick).fullMulDiv(
                denominator, sqrtRatioTickSpacing - Q96
            );
            if (Q96 > baseX96 && Q96 <= numerator / (Q96 - alphaX96)) {
                // this usually happens when the max cumulativeAmount1 is very close to zero
                // return minTick if cumulativeAmount1_ <= cumulativeAmount1(minTick)
                if (
                    cumulativeAmount1_
                        <= cumulativeAmount1(minTick, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                ) {
                    return (true, minTick);
                } else {
                    return (false, 0);
                }
            }
            uint256 basePowXPlusOneX96 =
                Q96 > baseX96 ? Q96 - numerator / (Q96 - alphaX96) : Q96 + numerator / (Q96 - alphaX96);
            xWad = basePowXPlusOneX96.toInt256().lnQ96().sDivWad(lnBaseX96) - int256(WAD);
        }

        // early return if xWad is obviously too large
        // the result (the smallest rounded tick whose cumulativeAmount1 is greater than or equal to the input) doesn't exist
        // thus return success = false
        int256 xWadMax = (length - 1) * int256(WAD);
        if (xWad > xWadMax) {
            // compare cumulativeAmount1_ with the max value of cumulativeAmount1()
            // due to precision errors sometimes xWad can be greater than xWadMax when cumulativeAmount1_
            // is close to the max value
            uint256 maxCumulativeAmount1 = cumulativeAmount1(
                minTick + (length - 1) * tickSpacing, totalLiquidity, tickSpacing, minTick, length, alphaX96
            );
            if (cumulativeAmount1_ > maxCumulativeAmount1) {
                return (false, 0);
            } else {
                // xWad shouldn't actually be greater than xWadMax
                // set it to xWadMax
                xWad = xWadMax;
            }
        }

        // get rounded tick from xWad
        success = true;
        roundedTick = xWadToRoundedTick(xWad, minTick, tickSpacing, true);

        // ensure roundedTick is within the valid range
        if (roundedTick < minTick - tickSpacing || roundedTick >= minTick + length * tickSpacing) {
            return (false, 0);
        }

        // ensure that roundedTick is not (minTick - tickSpacing) when cumulativeAmount1_ is non-zero and rounding up
        // this can happen if the corresponding cumulative density is too small
        if (roundedTick == minTick - tickSpacing) {
            return (true, minTick);
        }
    }

    function liquidityDensityX96(int24 roundedTick, int24 tickSpacing, int24 minTick, int24 length, uint256 alphaX96)
        internal
        pure
        returns (uint256)
    {
        if (roundedTick < minTick || roundedTick >= minTick + length * tickSpacing) {
            // roundedTick is outside of the distribution
            return 0;
        }
        // x is the index of the roundedTick in the distribution
        // should be in the range [0, length)
        uint256 x = uint24((roundedTick - minTick) / tickSpacing);
        if (alphaX96 > Q96) {
            // alpha > 1
            // need to make sure that alpha^x doesn't overflow by using alpha^-1 during exponentiation
            uint256 alphaInvX96 = Q96.mulDiv(Q96, alphaX96);
            return alphaInvX96.rpow(uint24(length) - x, Q96).fullMulDiv(
                alphaX96 - Q96, Q96 - alphaInvX96.rpow(uint24(length), Q96)
            );
        } else {
            // alpha <= 1
            // will revert if alpha == 1 but that's ok
            return (Q96 - alphaX96).mulDiv(alphaX96.rpow(x, Q96), Q96 - alphaX96.rpow(uint24(length), Q96));
        }
    }

    /// @dev Combines several operations used during a swap into one function to save gas.
    ///      Given a cumulative amount, it computes its inverse to find the closest rounded tick, then computes the cumulative amount at that tick,
    ///      and finally computes the liquidity of the tick that will handle the remainder of the swap.
    function computeSwap(
        uint256 inverseCumulativeAmountInput,
        uint256 totalLiquidity,
        bool zeroForOne,
        bool exactIn,
        int24 tickSpacing,
        int24 minTick,
        int24 length,
        uint256 alphaX96
    )
        internal
        pure
        returns (
            bool success,
            int24 roundedTick,
            uint256 cumulativeAmount0_,
            uint256 cumulativeAmount1_,
            uint256 swapLiquidity
        )
    {
        if (exactIn == zeroForOne) {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round down to the rounded tick to the left
            // e.g. go from 1.5 to 1
            //       input
            //      ├──────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            (success, roundedTick) = inverseCumulativeAmount0(
                inverseCumulativeAmountInput, totalLiquidity, tickSpacing, minTick, length, alphaX96
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick + tickSpacing
            // exactOut:
            //        cum
            //    ├────────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                : cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, minTick, length, alphaX96);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            // exactOut:
            //  cum
            // ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            // │
            // ▼
            //rick - tickSpacing
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                : cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, minTick, length, alphaX96);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //    liq
            //    ├──┤
            // ┌──┬──┬──┬──┐
            // │  │ █│██│██│
            // │  │ █│██│██│
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick
            swapLiquidity =
                (liquidityDensityX96(roundedTick, tickSpacing, minTick, length, alphaX96) * totalLiquidity) >> 96;
        } else {
            // compute roundedTick by inverting the cumulative amount
            // below is an illustration of 4 rounded ticks, the input amount, and the resulting roundedTick (rick)
            // notice that the inverse tick is between two rounded ticks, and we round up to the rounded tick to the right
            // e.g. go from 1.5 to 2
            //  input
            // ├──────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            (success, roundedTick) = inverseCumulativeAmount1(
                inverseCumulativeAmountInput, totalLiquidity, tickSpacing, minTick, length, alphaX96
            );
            if (!success) return (false, 0, 0, 0, 0);

            // compute the cumulative amount up to roundedTick
            // below is an illustration of the cumulative amount at roundedTick
            // notice that exactIn ? (input - cum) : (cum - input) is the remainder of the swap that will be handled by Uniswap math
            // exactIn:
            //   cum
            // ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //    │
            //    ▼
            //   rick - tickSpacing
            // exactOut:
            //     cum
            // ├────────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            cumulativeAmount1_ = exactIn
                ? cumulativeAmount1(roundedTick - tickSpacing, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                : cumulativeAmount1(roundedTick, totalLiquidity, tickSpacing, minTick, length, alphaX96);

            // compute the cumulative amount of the complementary token
            // below is an illustration
            // exactIn:
            //         cum
            //       ├─────┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            // exactOut:
            //           cum
            //          ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //          │
            //          ▼
            //         rick + tickSpacing
            cumulativeAmount0_ = exactIn
                ? cumulativeAmount0(roundedTick, totalLiquidity, tickSpacing, minTick, length, alphaX96)
                : cumulativeAmount0(roundedTick + tickSpacing, totalLiquidity, tickSpacing, minTick, length, alphaX96);

            // compute liquidity of the rounded tick that will handle the remainder of the swap
            // below is an illustration of the liquidity of the rounded tick that will handle the remainder of the swap
            //       liq
            //       ├──┤
            // ┌──┬──┬──┬──┐
            // │██│██│█ │  │
            // │██│██│█ │  │
            // └──┴──┴──┴──┘
            // 0  1  2  3  4
            //       │
            //       ▼
            //      rick
            swapLiquidity =
                (liquidityDensityX96(roundedTick, tickSpacing, minTick, length, alphaX96) * totalLiquidity) >> 96;
        }
    }

    function isValidParams(int24 tickSpacing, uint24 twapSecondsAgo, bytes32 ldfParams, LDFType ldfType)
        internal
        pure
        returns (bool)
    {
        (int24 minUsableTick, int24 maxUsableTick) =
            (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));

        // | shiftMode - 1 byte | minTickOrOffset - 3 bytes | length - 2 bytes | alpha - 4 bytes |
        uint8 shiftMode = uint8(bytes1(ldfParams));
        int24 minTickOrOffset = int24(uint24(bytes3(ldfParams << 8)));
        int24 length = int24(int16(uint16(bytes2(ldfParams << 32))));
        uint256 alpha = uint32(bytes4(ldfParams << 48));

        // ensure shiftMode is within the valid range
        if (shiftMode > uint8(type(ShiftMode).max)) {
            return false;
        }

        if (shiftMode != uint8(ShiftMode.STATIC)) {
            // LDF shifts
            // ensure twapSecondsAgo is non-zero and ldfType is DYNAMIC_AND_STATEFUL
            if (twapSecondsAgo == 0 || ldfType != LDFType.DYNAMIC_AND_STATEFUL) return false;
        }

        // ensure ldfType is STATIC if shiftMode is static
        if (shiftMode == uint8(ShiftMode.STATIC) && ldfType != LDFType.STATIC) {
            return false;
        }

        // ensure minTickOrOffset is aligned to tickSpacing
        if (minTickOrOffset % tickSpacing != 0) {
            return false;
        }

        // ensure length > 0 and doesn't overflow when multiplied by tickSpacing
        // ensure length can be contained between minUsableTick and maxUsableTick
        if (
            length <= 0 || int256(length) * int256(tickSpacing) > type(int24).max
                || length > maxUsableTick / tickSpacing || -length < minUsableTick / tickSpacing
        ) return false;

        // ensure alpha is in range
        if (alpha < MIN_ALPHA || alpha > MAX_ALPHA || alpha == ALPHA_BASE) return false;

        // ensure alpha != sqrtRatioTickSpacing which would cause cum0 to always be 0
        uint256 alphaX96 = alpha.mulDiv(Q96, ALPHA_BASE);
        uint160 sqrtRatioTickSpacing = tickSpacing.getSqrtPriceAtTick();
        if (alphaX96 == sqrtRatioTickSpacing) return false;

        // ensure the ticks are within the valid range
        if (shiftMode == uint8(ShiftMode.STATIC)) {
            // static minTick set in params
            int24 maxTick = minTickOrOffset + length * tickSpacing;
            if (minTickOrOffset < minUsableTick || maxTick > maxUsableTick) return false;
        }

        // ensure liquidity density is nowhere equal to zero
        // can check boundaries since function is monotonic
        uint256 minLiquidityDensityX96;
        if (alpha > ALPHA_BASE) {
            // monotonically increasing
            // check left boundary
            minLiquidityDensityX96 =
                liquidityDensityX96(minTickOrOffset, tickSpacing, minTickOrOffset, length, alphaX96);
        } else {
            // monotonically decreasing
            // check right boundary
            minLiquidityDensityX96 = liquidityDensityX96(
                minTickOrOffset + (length - 1) * tickSpacing, tickSpacing, minTickOrOffset, length, alphaX96
            );
        }
        if (minLiquidityDensityX96 < MIN_LIQUIDITY_DENSITY) {
            return false;
        }

        // if all conditions are met, return true
        return true;
    }

    /// @return minTick The minimum rounded tick of the distribution
    /// @return length The length of the distribution in number of rounded ticks (i.e. the number of ticks / tickSpacing)
    /// @return alphaX96 Parameter of the discrete laplace distribution, FixedPoint96
    function decodeParams(int24 twapTick, int24 tickSpacing, bytes32 ldfParams)
        internal
        pure
        returns (int24 minTick, int24 length, uint256 alphaX96, ShiftMode shiftMode)
    {
        // | shiftMode - 1 byte | minTickOrOffset - 3 bytes | length - 2 bytes | alpha - 4 bytes |
        shiftMode = ShiftMode(uint8(bytes1(ldfParams)));
        length = int24(int16(uint16(bytes2(ldfParams << 32))));
        uint256 alpha = uint32(bytes4(ldfParams << 48));
        alphaX96 = alpha.mulDiv(Q96, ALPHA_BASE);

        if (shiftMode != ShiftMode.STATIC) {
            // use rounded TWAP value + offset as minTick
            int24 offset = int24(uint24(bytes3(ldfParams << 8))); // the offset applied to the twap tick to get the minTick
            minTick = roundTickSingle(twapTick + offset, tickSpacing);

            // bound distribution to be within the range of usable ticks
            (int24 minUsableTick, int24 maxUsableTick) =
                (TickMath.minUsableTick(tickSpacing), TickMath.maxUsableTick(tickSpacing));
            if (minTick < minUsableTick) {
                minTick = minUsableTick;
            } else if (minTick > maxUsableTick - length * tickSpacing) {
                minTick = maxUsableTick - length * tickSpacing;
            }
        } else {
            // static minTick set in params
            minTick = int24(uint24(bytes3(ldfParams << 8))); // must be aligned to tickSpacing
        }
    }
}

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // 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**256. Since the preconditions guarantee
            // that the outcome is less than 2**256, 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 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

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

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @notice Returns ceil(x / y)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly ("memory-safe") {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }

    /// @notice Calculates floor(a×b÷denominator)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result, floor(a×b÷denominator)
    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            result := div(mul(a, b), denominator)
        }
    }
}

File 35 of 35 : FixedPoint96.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

Settings
{
  "remappings": [
    "@uniswap/v4-core/=lib/v4-core/",
    "solmate/src/=lib/solmate/src/",
    "solmate/utils/=lib/solmate/src/utils/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "biddog/=lib/biddog/src/",
    "clones-with-immutable-args/=lib/clones-with-immutable-args/src/",
    "create3-factory/=lib/create3-factory/",
    "ds-test/=lib/clones-with-immutable-args/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "flood-contracts/=lib/flood-contracts/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "leb128-nooffset/=lib/flood-contracts/lib/leb128-nooffset/src/",
    "leb128/=lib/flood-contracts/lib/leb128-nooffset/src/",
    "multicaller/=lib/multicaller/src/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "permit2/=lib/permit2/",
    "solady/=lib/solady/src/",
    "v4-core/=lib/v4-core/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 100000000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"hub_","type":"address"},{"internalType":"address","name":"hook_","type":"address"},{"internalType":"address","name":"quoter_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"GuardedCall","type":"error"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"inverseCumulativeAmountInput","type":"uint256"},{"internalType":"uint256","name":"totalLiquidity","type":"uint256"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"bool","name":"exactIn","type":"bool"},{"internalType":"int24","name":"twapTick","type":"int24"},{"internalType":"int24","name":"","type":"int24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"bytes32","name":"ldfState","type":"bytes32"}],"name":"computeSwap","outputs":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"int24","name":"roundedTick","type":"int24"},{"internalType":"uint256","name":"cumulativeAmount0_","type":"uint256"},{"internalType":"uint256","name":"cumulativeAmount1_","type":"uint256"},{"internalType":"uint256","name":"swapLiquidity","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"int24","name":"roundedTick","type":"int24"},{"internalType":"uint256","name":"totalLiquidity","type":"uint256"},{"internalType":"int24","name":"twapTick","type":"int24"},{"internalType":"int24","name":"","type":"int24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"bytes32","name":"ldfState","type":"bytes32"}],"name":"cumulativeAmount0","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"int24","name":"roundedTick","type":"int24"},{"internalType":"uint256","name":"totalLiquidity","type":"uint256"},{"internalType":"int24","name":"twapTick","type":"int24"},{"internalType":"int24","name":"","type":"int24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"bytes32","name":"ldfState","type":"bytes32"}],"name":"cumulativeAmount1","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint24","name":"twapSecondsAgo","type":"uint24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"enum LDFType","name":"ldfType","type":"uint8"}],"name":"isValidParams","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"int24","name":"roundedTick","type":"int24"},{"internalType":"int24","name":"twapTick","type":"int24"},{"internalType":"int24","name":"","type":"int24"},{"internalType":"bytes32","name":"ldfParams","type":"bytes32"},{"internalType":"bytes32","name":"ldfState","type":"bytes32"}],"name":"query","outputs":[{"internalType":"uint256","name":"liquidityDensityX96_","type":"uint256"},{"internalType":"uint256","name":"cumulativeAmount0DensityX96","type":"uint256"},{"internalType":"uint256","name":"cumulativeAmount1DensityX96","type":"uint256"},{"internalType":"bytes32","name":"newLdfState","type":"bytes32"},{"internalType":"bool","name":"shouldSurge","type":"bool"}],"stateMutability":"view","type":"function"}]

610100346100a257601f614c5538819003918201601f19168301916001600160401b038311848410176100a6578084926060946040528339810103126100a257610048816100ba565b90610061604061005a602084016100ba565b92016100ba565b913060805260a05260c05260e052604051614b8690816100cf82396080518161084e015260a051816107cc015260c051816108d7015260e051816108970152f35b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036100a25756fe60806040526004361015610011575f80fd5b5f3560e01c80633e33e12714610696578063685056ff146103e1578063b50c7a9814610335578063c42d62c21461019f5763d5fac49314610050575f80fd5b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36016101a0811261019b5760a01361019b5760e435801515810361019b576101043590811515820361019b57610124358060020b810361019b576100d8906100bc610716565b506100c56107b5565b61016435906100d2610797565b9061096d565b906101843560f881901c6001149060e01c62ffffff1660020b90610138575b60a0610113848487610107610797565b9160c43560a435610ecf565b92604092919251941515855260020b6020850152604084015260608301526080820152f35b9190815160020b9361010083015194600486101561016e5760a0956101139561016092610be3565b60020b8352935090916100f7565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b5f80fd5b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601610100811261019b5760a01361019b5760a43562ffffff8116810361019b5760c4359060e435600381101561019b57610214610201610797565b918463ffffffff8160201c16948461169d565b918261032b575b8261022e575b6020836040519015158152f35b909150670de0b6b3a764000003670de0b6b3a764000081116102fe57807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff046c01000000000000000000000000116102e5575b90826102de9263ffffffff60209560401c169263ffffffff8360601c169261ffff8160801c1660010b9263ffffffff8260901c1692670de0b6b3a764000061ffff63ffffffff8560b01c169460d01c1660010b9260601b04611b29565b8280610221565b90816102f15790610281565b63bac65e5b5f526004601cfd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b801515925061021b565b3461019b5761036761037f606061034b36610727565b97949893969150919461035c6107b5565b01936100d2856107a7565b939062ffffff60018360f81c149260e01c1660020b90565b906103a4575b602061039c858786610396876107a7565b91610e2e565b604051908152f35b93909291825160020b9461010084015194600486101561016e576103d161039c9661039693602099610be3565b60020b8552929550509192610385565b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601610140811261019b5760a01361019b5760a4358060020b810361019b5760c435908160020b820361019b5761043c610706565b506104456107b5565b6104575f9261010435906100d2610797565b916101243560f881901c6001149060e01c62ffffff1660020b90610664575b5061047f610797565b9162ffffff610603856105436104968288876112ad565b9661056681610560856105436104ac848c610ca9565b80858461055a6104cb602083015160020b608084015160020b90610ca9565b6105548461054961050f6105436104fb885160020b8760e08b015191876c10000000000000000000000000611080565b9e9390888d9497939d5160020b928661113c565b93815160020b602083015160020b608084015160020b906040850151928a60a08701519560c0606089015198015198611252565b90610ce3565b995160020b92610cf0565b90610ca9565b9261113c565b97610df4565b8091846105fd610585602083015160020b608084015160020b90610ca9565b610554846105496105c96105436105b5885160020b8760e08b015191876c10000000000000000000000000611080565b9e9390888d9497939d5160020b928661148f565b93815160020b602083015160020b608084015160020b906040850151928a60a08701519560c06060890151980151986115ad565b9261148f565b94511663010000000163ffffffff81116102fe5760a0947fffffffff000000000000000000000000000000000000000000000000000000009260405195865260041c602086015260041c604085015260e01b16606083015215156080820152f35b9050825160020b610100840151600481101561016e578261068492610be3565b60020b9081845260020b141583610476565b3461019b576103676106ac606061034b36610727565b906106c9575b602061039c8587866106c3876107a7565b91610d07565b93909291825160020b9461010084015194600486101561016e576106f661039c966106c393602099610be3565b60020b85529295505091926106b2565b60e435908160020b820361019b57565b61014435908160020b820361019b57565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc01610160811261019b5760a01361019b5760049060a4358060020b810361019b579060c4359060e4358060020b810361019b5790610104358060020b810361019b579061012435906101443590565b6064358060020b810361019b5790565b358060020b810361019b5790565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016331415806108bf575b8061087f575b80610876575b8015610836575b61080e57565b7fd9711eeb000000000000000000000000000000000000000000000000000000005f5260045ffd5b5073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016301415610808565b50331515610801565b5073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163314156107fb565b5073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163314156107f5565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761094057604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b604051919392610120830167ffffffffffffffff811184821017610940576040525f8352602083015f815260408401955f875260608501965f885260808601905f825260a08701945f865260c08801955f87526101008901975f8952899b63ffffffff8460201c1660e08c01528360f81c93600485101561016e5761ffff8160d01c1660010b9963ffffffff8260b01c169561ffff8360801c1660010b9963ffffffff8460601c16956305f5e1006fffffffff0000000000000000000000008075ffffffffffffffffffff0000000000000000000000008860501c161616996c01000000000000000000000000818c04149015170215610bd6576fffffffff00000000000000000000000085169680159088046c0100000000000000000000000014176305f5e1000215610bd65760038314610baf5781610abd610ac29262ffffff8860e01c1660020b90610ca9565b611f8a565b81610acc81611fcf565b0260020b9180610adb81611ffd565b0260020b908260020b8481125f14610b255750505050926305f5e100979695939263ffffffff928996949f5b52828260401c16905260901c169052049052049052525260020b9052565b9091929350929f928f610b458f610b408591610b4b94610ca9565b610cf0565b84610df4565b60020b12610b6f575b5050926305f5e100979695939263ffffffff92899694610b07565b6305f5e10099989795929f5092610b9e8f92610b988f96610b4063ffffffff988f9c9a97610ca9565b90610df4565b9f9295979899509281949650610b54565b5050826305f5e100979695939263ffffffff9262ffffff8a979560e01c1660020b9f610b07565b63ad251c275f526004601cfd5b91600481101561016e57600181149081610c2d575b8115610c0d575b50610c08575090565b905090565b600291501480610c1e575b5f610bff565b508060020b8260020b12610c18565b90508160020b8360020b1390610bf8565b60020b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b60020b60010190627fffff82137fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008312176102fe57565b9060020b9060020b01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b919082018092116102fe57565b9060020b9060020b02908160020b9182036102fe57565b92610d9b9383610d6961055a8461055481986105496105439961054389610d56602088015160020b93610d4360808a0195865160020b90610ca9565b898860e0839c5160020b92015193611080565b9f939089859e939e5160020b928761113c565b94825160020b90602084015160020b905160020b906040850151928a60a08701519560c0606089015198015198611252565b90565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b9060020b9060020b0390627fffff82137fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008312176102fe57565b92610d9b9383610e7d6105fd8461055481986105496105439961054389610e6a602088015160020b93610d4360808a0195865160020b90610ca9565b9f939089859e939e5160020b928761148f565b94825160020b90602084015160020b905160020b906040850151928a60a08701519560c06060890151980151986115ad565b919082039182116102fe57565b818102929181159184041417156102fe57565b9085918197939594951515861515145f14610f8057610ef092918591611da5565b959095948615610f6d5790610f37610f3c92865f14610f5c57610f1e818785610f19828d610ca9565b610d07565b9615610f4257610f308187858b610e2e565b95886112ad565b610ebc565b60601c90565b610f57818785610f52828d610df4565b610e2e565b610f30565b610f688187858b610d07565b610f1e565b505093505050505f905f905f905f905f90565b93610f8e9291819695611c35565b959095948615610f6d5790610f37610f3c92855f14610fe557610fb7818885610f52828d610df4565b9515610fd057610fc98188858b610d07565b96886112ad565b610fe0818885610f19828d610ca9565b610fc9565b610ff18188858b610e2e565b610fb7565b60020b9060020b908115611053577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008214166102fe570590565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b9391928161108d81611fcf565b0260020b918061109c81611ffd565b0260020b9280946110bf846110ba856110b5868a610df4565b610ff6565b610df4565b915f8360020b131561112d5750670de0b6b3a76400000392670de0b6b3a764000084116102fe5762ffffff61111981926110ba611123966110b561111261110a8f9b61112a9c611947565b9e8f90610eaf565b9c8b610df4565b1691169086611f13565b8094610eaf565b94565b5f998a98509096509350505050565b93929190918360020b8560020b9080821290811591611244575b5015611166575050505050505f90565b8160020b1361123c575b61119261118c61118c61119a95946110b562ffffff9589610df4565b9561200e565b931690612380565b91808273ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff821611611231575b505073ffffffffffffffffffffffffffffffffffffffff82169283156112255773ffffffffffffffffffffffffffffffffffffffff611219938184169303169060601b6135d5565b90808206151591040190565b62bfc9215f526004601cfd5b915091505f806111d1565b935083611170565b90508260020b12155f611156565b9791929395610543979661128b6112a793610d9b9c6112858161127f611278828b610ce3565b8a86611f13565b98610ce3565b91611f13565b93856112a061129a828b610cf0565b89610ca9565b918c612447565b96612447565b6020830190815160020b846112cb6080820192835160020b90610ca9565b815160020b8460020b818112159182611474575b50501561138b57509261135a60c093610543611360946113548861134e60e09b6113669b5160020b985160020b945160020b60408401519960a08501519261134860608701519e8f9701519c8d998c8461134261133c828a610cf0565b88610ca9565b91613042565b99613042565b94610ebc565b92610ebc565b92610ce3565b90611994565b910151670de0b6b3a764000003670de0b6b3a764000081116102fe57610d9b91611947565b93505050506110ba826110b5816113a46113bb96611fcf565b0260020b826113b281611ffd565b0260020b610df4565b905f8260020b131561146e5760e00151670de0b6b3a764000003670de0b6b3a764000081116102fe57807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff046c010000000000000000000000001161145b575b670de0b6b3a76400009060601b046c01000000000000000000000000036c0100000000000000000000000081116102fe5762ffffff610d9b921690612380565b801561141b5763bac65e5b5f526004601cfd5b50505f90565b6114849192506105548985610cf0565b60020b135f806112df565b90939192938460020b938260020b9480861290811561159f575b50156114b9575050505050505f90565b85846001966114d6846c0100000000000000000000000098610df4565b60020b1261154f575b9262ffffff6115276115228561151c61151673ffffffffffffffffffffffffffffffffffffffff99986110b561152f998c9b610df4565b9c61200e565b98610ca9565b61200e565b981690612380565b95169116038060ff1d908101186115468185613403565b93091515160190565b935073ffffffffffffffffffffffffffffffffffffffff9262ffffff6115276115228561151c611516826110b561152f9961158b8d9c8f610df4565b9d999c5099505050505095505050506114df565b90508460020b13155f6114a9565b979192939561054397966115d36115e993610d9b9c6112858161127f611278828b610ce3565b93856115e261129a828b610cf0565b918c612816565b96612816565b81810292915f82127f80000000000000000000000000000000000000000000000000000000000000008214166102fe5781840514901517156102fe57565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146102fe575f0390565b602081519101519060208110611670575090565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060200360031b1b1690565b9291908160f81c9262ffffff8360e01c1660020b9461ffff8460d01c1660010b63ffffffff8560b01c169163ffffffff8660901c169361ffff8760801c1660010b9563ffffffff808960601c169860401c1698836116fa81611fcf565b0260020b8461170881611ffd565b0260020b90856117188b89610ca9565b8060020b627fffff61172d8460020b836115ef565b1394851561192d575b50508315611908575b5050506118f957611804836117fd8a6117f88f6117cc8f6040519485938a60208601927fffffffff00000000000000000000000000000000000000000000000000000000927fff00000000000000000000000000000000000000000000000000000000000000600a969360f81b16855260e81b600185015260f01b600484015260e01b1660068201520190565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081018352826108ff565b61165c565b8487612c36565b9a8b611855575b505050508761184b575b87611841575b8761182b575b5050505050505090565b611835975061199e565b5f808080808080611821565b861515975061181b565b8315159750611815565b849b50906117f86118706118e8936105546118ef988d610cf0565b60405160f89390931b7fff0000000000000000000000000000000000000000000000000000000000000016602084015260e81b602183015260f087901b602483015260e088901b7fffffffff0000000000000000000000000000000000000000000000000000000016602683015281602a81016117cc565b908a612c36565b965f80808061180b565b50505050505050505050505f90565b61191d9293506119179061162d565b92610ff6565b60020b9060020b125f858161173f565b61193b919295508390610ff6565b60020b12925f80611736565b90807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048211611981575b670de0b6b3a764000091020490565b80156119725763bac65e5b5f526004601cfd5b8115611053570490565b959293918060601b916305f5e1006c01000000000000000000000000838504148315170215610bd6576305f5e100611a069304906305f5e1006119e96119e48b88610cf0565b610c3e565b931115611b045782896119fb94613042565b846112858582610ce3565b946c01000000000000000000000000868060601b041486151760601b15610bd6576a4189374bc6a7ef9db22d0e9573ffffffffffffffffffffffffffffffffffffffff168611611afa578460601b906305f5e1006c01000000000000000000000000878404148715170215610bd657611a9d95611285936305f5e1008087950492115f14611ae157611a979261300f565b93610ce3565b6c01000000000000000000000000818060601b041481151760601b15610bd65773ffffffffffffffffffffffffffffffffffffffff1610611add57600190565b5f90565b82611af56119e4611a9795610b4085610d9e565b612e9e565b5050505050505f90565b611b249289611b1f611b1982610b4086610d9e565b83610ca9565b613042565b6119fb565b9594919096928060601b916305f5e1006c01000000000000000000000000838504148315170215610bd6576305f5e100611b839304906305f5e100611b716119e48c88610cf0565b931115611c2057828a6119fb94613042565b9585870296868189041490151760601b15610bd6576a4189374bc6a7ef9db22d0e809760601c10611c15578460601b906305f5e1006c01000000000000000000000000878404148715170215610bd657611bf595611285936305f5e1008087950492115f14611ae157611a979261300f565b818102918183041490151760601b15610bd65760601c10611add57600190565b505050505050505f90565b611b24928a611b1f611b1982610b4086610d9e565b919290928215611d8e57611c6e611c5b602084015160020b608085015160020b90610ca9565b9485845160020b8460e087015193611080565b9095929791611c84845160020b8888888361148f565b8089111580611d85575b15611caa5750505050611ca695505160020b9361308f565b9091565b919450929550611cba9196610eaf565b94611d05611cd0865160020b6105548785610cf0565b8689815160020b602083015160020b608084015160020b906040850151928b60a08701519560c06060890151980151986115ad565b90818711611d48575050505092611ca693825160020b602084015160020b608085015160020b9160408601519360a08701519560c0606089015198015198613225565b90918093969750611d6057505050505050505f905f90565b61055484611d74611d7f94611ca69a610eaf565b965160020b92610cf0565b9261308f565b50851515611c8e565b915050611da09150806113b281611fcf565b600191565b9192908215611efc579261055a8280611def96846020611e1098970191825160020b611dda6080860191825160020b90610ca9565b9a8b9283875160020b8660e08a015193611080565b9d939891809b8f9498929761055484611d74875160020b6105548386610cf0565b808a111580611ef3575b15611e4157505050505050611ca69561055484611e3b935160020b92610cf0565b926132ad565b9296509399509396611e54929850610eaf565b95855160020b94815160020b94835160020b97604081019586519860a083019889519a606085019b8c519160c087019e8f5194868b8b611e9399611252565b9b8c8c11611ebe575050611ca69a505160020b925160020b935160020b945195519651975198613380565b97509850989450509450505081611edb575050505050505f905f90565b611ca695611ee891610eaf565b935160020b936132ad565b50871515611e1a565b505050611f0881611ffd565b0260020b9060019190565b8181029181159183041417820215610bd6570490565b9060020b9081156110535760020b0790565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146102fe577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b90610d9b91611f998282610ff6565b90825f8260020b129182611fb9575b505015610cf0575b610b4090611f3b565b611fc39250611f29565b60020b1515825f611fa8565b60020b8015611053577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276180590565b60020b801561105357620d89e80590565b60020b908160ff1d82810118620d89e881116123545763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102700100000000000000000000000000000000189160028116612338575b6004811661231c575b60088116612300575b601081166122e4575b602081166122c8575b604081166122ac575b60808116612290575b6101008116612274575b6102008116612258575b610400811661223c575b6108008116612220575b6110008116612204575b61200081166121e8575b61400081166121cc575b61800081166121b0575b620100008116612194575b620200008116612179575b62040000811661215e575b6208000016612145575b5f1261211e575b0160201c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04612117565b6b048a170391f7dc42444e8fa290910260801c90612110565b6d2216e584f5fa1ea926041bedfe9890920260801c91612106565b916e5d6af8dedb81196699c329225ee6040260801c916120fb565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c916120f0565b916f31be135f97d08fd981231505542fcfa60260801c916120e5565b916f70d869a156d2a1b890bb3df62baf32f70260801c916120db565b916fa9f746462d870fdf8a65dc1f90e061e50260801c916120d1565b916fd097f3bdfd2022b8845ad8f792aa58250260801c916120c7565b916fe7159475a2c29b7443b29c7fa6e889d90260801c916120bd565b916ff3392b0822b70005940c7a398e4b70f30260801c916120b3565b916ff987a7253ac413176f2b074cf7815e540260801c916120a9565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c9161209f565b916ffe5dee046a99a2a811c461f1969c30530260801c91612095565b916fff2ea16466c96a3843ec78b326b528610260801c9161208c565b916fff973b41fa98c081472e6896dfb254c00260801c91612083565b916fffcb9843d60f6159c9db58835c9266440260801c9161207a565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91612071565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91612068565b916ffff97272373d413259a46990580e213a0260801c9161205f565b827f8b86327a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b90801561239257808204910615150190565b6365244e4e5f526004601cfd5b91908083028315828583041417156123e9576c010000000000000000000000009060601c915b8294096123cf5750565b600101915081156123dc57565b63ae47f7025f526004601cfd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828509818110820190038060601c1561242a5763ae47f7025f526004601cfd5b6c010000000000000000000000009160601c9060a01b01916123c5565b92919390935f938060020b8460020b81125f146127dd5750505f5b73ffffffffffffffffffffffffffffffffffffffff61248e816124876115228661162d565b169561200e565b16966c01000000000000000000000000811115612640578015610bd657780100000000000000000000000000000000000000000000000004600284810b9083900b126124e3575050505050610d9b925061239f565b9091929394506124f38285610df4565b9162ffffff86831193169073ffffffffffffffffffffffffffffffffffffffff61253761152261252385876135fe565b9461252d8961162d565b9060020b90610cf0565b1693836c0100000000000000000000000003916c0100000000000000000000000083116102fe57610b4061259f6125a594611522948c896125ad9b62ffffff9a845f14612631579061258891610eaf565b925b15612628579061259991610eaf565b916136ec565b9761162d565b9416906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe5773ffffffffffffffffffffffffffffffffffffffff6125f19316906136ec565b906c0100000000000000000000000003926c0100000000000000000000000084116102fe57610d9b93612623926136ec565b61239f565b61259991610eaf565b61263a91610eaf565b9261258a565b95969495939290600282810b9082900b126126655750505050505090610d9b9161239f565b9091928481959697500292848685041486151760601b15610bd65761268f62ffffff8316876135fe565b9061269f62ffffff8516886135fe565b966c0100000000000000000000000003926c0100000000000000000000000084116102fe5773ffffffffffffffffffffffffffffffffffffffff61270e61152261272197610b4061270861271b98866127016115226127159a610b408d61162d565b16906136bd565b9661162d565b16886136bd565b90610eaf565b90610ebc565b926c0100000000000000000000000003906c0100000000000000000000000082116102fe5760601c6c01000000000000000000000000036c0100000000000000000000000081116102fe5761277591610ebc565b906c0100000000000000000000000003916c0100000000000000000000000083116102fe576127a39261370a565b906c010000000000000000000000006127bc828461372d565b92096127cd575b90610d9b9161239f565b6001019081156123dc57906127c3565b6127f06127ea8486610cf0565b86610ca9565b60020b1361280357505050505050505f90565b816110b58561281193610df4565b612462565b9490939291948060020b8360020b81125f1461283757505050505050505f90565b8391879161284e6128488489610cf0565b85610ca9565b60020b13612c235750505061286283610d9e565b905b73ffffffffffffffffffffffffffffffffffffffff6128828761200e565b16956c01000000000000000000000000821115612a50578115610bd657817801000000000000000000000000000000000000000000000000045f8460020b125f146128d857505050505050610d9b91505f61239f565b73ffffffffffffffffffffffffffffffffffffffff61290261152261259f62ffffff8a16856135fe565b1695888402898582041460601b15610bd65760601c947fffffffffffffffffffffffffffffffffffffffff00000000000000000000000085019485116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000086019586116102fe5773ffffffffffffffffffffffffffffffffffffffff6127016115226129be96610b406129b38c9862ffffff6129ac6129a78a6129b99c610df4565b610d9e565b16906135fe565b95610c72565b610eaf565b926c0100000000000000000000000003926c0100000000000000000000000084116102fe57838160601b9173ffffffffffffffffffffffffffffffffffffffff8116140215610bd65783612a1894820491061515016136ec565b907fffffffffffffffffffffffffffffffffffffffff00000000000000000000000084019384116102fe57610d9b93612623926136ec565b91925f8460029693960b125f14612a71575050505050610d9b91505f61239f565b612a8f73ffffffffffffffffffffffffffffffffffffffff9161200e565b169286850290878683041486151760601b15610bd65773ffffffffffffffffffffffffffffffffffffffff612701611522612ae89460601c96612ae26129b362ffffff612adb88610c72565b168c6135fe565b90610cf0565b7fffffffffffffffffffffffffffffffffffffffff000000000000000000000000810190856c01000000000000000000000000036c0100000000000000000000000081116102fe57612b919282612b61936c0100000000000000000000000011906c010000000000000000000000000382180218610ebc565b9462ffffff7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000085019316906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe5782612be2936c0100000000000000000000000011906c010000000000000000000000000382180218610ebc565b937fffffffffffffffffffffffffffffffffffffffff00000000000000000000000081019081116102fe57610d9b9461262393612c1e9261370a565b6136bd565b612c30926110b591610df4565b90612864565b929183612c4281611fcf565b0260020b84612c5081611ffd565b0260020b908260f81c9162ffffff8460e01c1660020b9361ffff8160d01c1660010b9563ffffffff8260b01c169460038111612e90576003149788918215612e53575b5081612e40575b50612dcc57612ca98886611f29565b60020b612dcc575f8613801590612e28575b8015612e13575b8015612df2575b612dcc576103e884108015612de5575b8015612dd8575b612dcc5760501c6fffffffff0000000000000000000000001683158482046c0100000000000000000000000014176305f5e1000215610bd6576305f5e10090049573ffffffffffffffffffffffffffffffffffffffff612d3f8961200e565b168714612dcc57612d91575b50506305f5e1001015612d7857612d629381613042565b6a4189374bc6a7ef9db22d0e11611add57600190565b83611b1f611b19612d8c96610b4086610d9e565b612d62565b612d9e6128488887610cf0565b918412918215612dbf575b5050612db6575f80612d4b565b50505050505f90565b60020b1390505f80612da9565b50505050505050505f90565b506305f5e1008414612ce0565b506347868c008411612cd9565b50612dfc8661162d565b612e068985610ff6565b60020b9060020b12612cc9565b50612e1e8883610ff6565b60020b8613612cc2565b50627fffff612e3a8960020b886115ef565b13612cbb565b9050600381101561016e5715155f612c9a565b62ffffff91925016158015612e7c575b612e6f5787905f612c93565b5050505050505050505f90565b50600381101561016e576002811415612e63565b505050505050505050505f90565b9291928060020b5f8112908115612fef575b50612fe75762ffffff916110b55f612ec793610df4565b16916c01000000000000000000000000821115612f7a578115610bd657612f19612f1362ffffff8478010000000000000000000000000000000000000000000000000493169485610eaf565b826135fe565b927fffffffffffffffffffffffffffffffffffffffff00000000000000000000000083019283116102fe57612f4d916135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57610d9b926137ec565b9091826c0100000000000000000000000003926c0100000000000000000000000084116102fe5762ffffff612fb2612fba93836135fe565b9316906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57610d9b92611f13565b505050505f90565b9050613004612ffe8487610cf0565b5f610ca9565b60020b13155f612eb0565b91909161301f612ffe8285610cf0565b60020b5f121561303b57612ec762ffffff916110b55f80610df4565b5050505f90565b91909392938260020b8260020b811290811561306f575b50612db6576110b5612ec79262ffffff94610df4565b905061308461307e8388610cf0565b84610ca9565b60020b13155f613059565b9094929193948115613217576131009073ffffffffffffffffffffffffffffffffffffffff6130c2876110b5878b610df4565b936130e56130cf8761200e565b9362ffffff6130dd8c61200e565b971690612380565b828211613208576130f89160601b611994565b915b16610ce3565b9073ffffffffffffffffffffffffffffffffffffffff82169182036131e05773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff8216116131bb5761315a90613891565b9360020b92838560020b146131d0575b61317681600196611f8a565b936131818284610df4565b60020b908560020b9182129182156131c5575b50506131bb576131a49082610df4565b60020b8360020b146131b35750565b600193509150565b505f935083925050565b121590505f80613194565b936131da90610d9e565b9361316a565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffd5b6132119161347d565b916130fa565b5050611da092919350610df4565b989097939194969795929561324461323d8387610ce3565b8383611f13565b9461325f8a8a8a8a8a61325a61307e8386610cf0565b612816565b808c1161327557505050505050611ca695613c80565b6132a7959a50610554939894999650916132a19161128561329a8a95611ca69f610eaf565b9a82610ce3565b94610cf0565b92613c80565b949293948015613376576132fe73ffffffffffffffffffffffffffffffffffffffff916132de856110b5898b610df4565b6132f86132ea8961200e565b9562ffffff6111928c61200e565b906141da565b911673ffffffffffffffffffffffffffffffffffffffff8216106131bb5761332590613891565b9361333282600196611f8a565b938460020b9060020b8112908115613369575b506131bb578060020b8460020b1461335b575050565b90919350611da09250610df4565b90508160020b125f613345565b5060019493505050565b9297959796919490939661339d6133978784610cf0565b82610ca9565b966133b26133ab8c83610ce3565b8288611f13565b956133c18b8b8b8b8b82612447565b9b8c87116133d957505050505050611ca69650614250565b93995093995094509550611285816133f7611ca69b6133fd96610eaf565b95610ce3565b90614250565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c01000000000000000000000000111561019b5714613474576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b908160601b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c0100000000000000000000000084099282808510940393808503948584111561019b571461352f576c0100000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561019b57146135cd579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b9291906135e3828286613536565b93821561105357096135f157565b9060010190811561019b57565b919082811560601b9361360f575050565b90925060018316816c0100000000000000000000000018026c01000000000000000000000000189260011c90815b613645575050565b8080026b80000000000000000000000081019160801c908210176136b05760601c906001811661367a575b60011c908161363d565b92818082026b80000000000000000000000081019282828510920418176136a6575b5060601c92613670565b6136b0578161369c565b6349f7642b5f526004601cfd5b9080820290808383041483151760601b15610bd6576c010000000000000000000000009160601c920915150190565b818102929181159184041417810215610bd657808204910615150190565b9291906137188282866137ec565b930961372057565b906001019081156123dc57565b908160601b91816c010000000000000000000000008285041482151702156137555750900490565b816c010000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81840985811086019003920990825f03831692818111156123dc5783900480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f0304019211900302170290565b81810292918115828504821417830215613807575050900490565b807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8492840985811086019003920990825f03831692818111156123dc5783900480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f0304019211900302170290565b73fffd8963efd1fc6a506488495d951d516396168273ffffffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffd895d83011611613bf35777ffffffffffffffffffffffffffffffffffffffff000000008160201b1680811561019b5760ff826fffffffffffffffffffffffffffffffff1060071b83811c67ffffffffffffffff1060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c821060031b177f07060605060205000602030205040001060502050303040105050304000000006f8421084210842108cc6318c6db6d54be85831c1c601f161a17169160808310155f14613be757507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8182011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c67800000000000000016907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff800160401b1717171717171717171717171717693627a301d71055774c85027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f14613ba95750905090565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff613bdd8461200e565b1611610c08575090565b905081607f031b6139c1565b73ffffffffffffffffffffffffffffffffffffffff907f61487524000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b907ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c000082019182136001166102fe57565b9190915f83820193841291129080158216911516176102fe57565b9593949580156141cb57613c94828261372d565b73ffffffffffffffffffffffffffffffffffffffff613cb28561200e565b89159291168981028a81048214841760601b15610bd65760601c613cd581614674565b938a8c6c01000000000000000000000000811115613f9e575050610bd657613d1d62ffffff8b168c7801000000000000000000000000000000000000000000000000046135fe565b9273ffffffffffffffffffffffffffffffffffffffff613d3f6115228b61162d565b16917fffffffffffffffffffffffffffffffffffffffff0000000000000000000000008d01918d83116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019182116102fe57856c0100000000000000000000000003946c0100000000000000000000000086116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000081019081116102fe57613df794613df292611f13565b611f13565b818102918183041490151760601b15610bd65760601c613e178282610ce3565b15613f8f5791613e5b613e40613e3b613e36613e6095613e6597610ce3565b6148c3565b6148d8565b613e55613e4c8d6148d8565b8c60020b6115ef565b90613c65565b614aff565b613c35565b965b613e7087610d9e565b60020b92670de0b6b3a7640000840293808505670de0b6b3a764000014901517156102fe57838913613f55575b505050506001948282613eb9670de0b6b3a76400008405614b2f565b925f81139081613f41575b50613f29575b613ed790613edc93610cf0565b610ca9565b938482613ee98186610df4565b60020b9160020b918212928315613f0c575b5050506131bb576131a49082610df4565b613f1c9293509061307e91610cf0565b60020b13155f8281613efb565b505060020b627fffff81146102fe5785018282613eca565b670de0b6b3a764000091500715155f613ec4565b87969850968585809961325a61307e613f73979899610b4087610d9e565b1015613f8357505050505f905f90565b9391925f808080613e9d565b505f9850889750505050505050565b915093929173ffffffffffffffffffffffffffffffffffffffff613fc18b61200e565b16906140067fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019362ffffff836c01000000000000000000000000119816906135fe565b6c01000000000000000000000000036c0100000000000000000000000081116102fe57614050938761404a936c010000000000000000000000000382180218610ebc565b9361372d565b917fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019182116102fe57614084926137ec565b908080614187575b61416157156140fe57886c01000000000000000000000000036c0100000000000000000000000081116102fe576140c291611994565b6c01000000000000000000000000036c0100000000000000000000000081116102fe576140f891613e5b613e3b613e60936148c3565b96613e67565b886c01000000000000000000000000036c0100000000000000000000000081116102fe5761412b91611994565b6c0100000000000000000000000001806c01000000000000000000000000116102fe576140f891613e5b613e3b613e60936148c3565b505050939490928096926141759482612816565b106141805760019190565b5f91508190565b50896c01000000000000000000000000036c0100000000000000000000000081116102fe576141b69083611994565b6c01000000000000000000000000111561408c565b5050919350611da09250610df4565b9091801561424a5773ffffffffffffffffffffffffffffffffffffffff809360601b92168082028161420c8483611994565b14614232575b50906142216142269284611994565b610ce3565b80820615159104011690565b8301838110614212579150614246926135d5565b1690565b50905090565b90959394929192811561466257614267878361372d565b876c01000000000000000000000000840961464d575b73ffffffffffffffffffffffffffffffffffffffff61429e6115228761162d565b1673ffffffffffffffffffffffffffffffffffffffff6142bd8661200e565b1690808402928415938286820414851760601b15610bd65760601c936142e2856148d8565b946c010000000000000000000000008711156145605750610bd657847801000000000000000000000000000000000000000000000000049061432962ffffff8c16836135fe565b9083831194846c0100000000000000000000000003906c0100000000000000000000000082116102fe5761435c926136ec565b906c01000000000000000000000000036c0100000000000000000000000081116102fe57614389916136bd565b91818415614551579061439b91610eaf565b905b6c0100000000000000000000000003906c0100000000000000000000000082116102fe576143ca926136ec565b6143da6115228a610b408a61162d565b91801580614531575b61450e5761441d6144379493613e5b93614422935f146144ef5773ffffffffffffffffffffffffffffffffffffffff613e36921690610ce3565b614674565b613e5561442e86614674565b8b60020b6115ef565b965b5f88126144c1575b50505061447781613ed784600198614462670de0b6b3a76400008205614b2f565b905f811290816144ad575b50611fb057610cf0565b90614486613397848497610cf0565b9160020b9060020b811290811561336957506131bb578060020b8460020b1461335b575050565b670de0b6b3a764000091500715155f61446d565b8695975095838581986144d49596612447565b10156144e3575050505f905f90565b5f9391925f8080614441565b73ffffffffffffffffffffffffffffffffffffffff613e369216610eaf565b50505050918361452a611b1961417596610b408a96999a610d9e565b9788612447565b508173ffffffffffffffffffffffffffffffffffffffff841611156143e3565b61455a91610eaf565b9061439d565b949362ffffff8c169392915061457684886135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57866c0100000000000000000000000003916c0100000000000000000000000083116102fe576145d2926145cc91610ebc565b926136bd565b916c0100000000000000000000000003906c0100000000000000000000000082116102fe576146009261370a565b90846c0100000000000000000000000003916c0100000000000000000000000083116102fe576146479461054361441d93614641613e5b96613e3695611994565b926135fe565b96614439565b6001018061427d5763ae47f7025f526004601cfd5b505091935061055490611da093610cf0565b806fffffffffffffffffffffffffffffffff1060071b81811c67ffffffffffffffff1060061b1781811c63ffffffff1060051b1781811c61ffff1060041b1781811c60ff1060031b175f8213156148b6577ff8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff6f8421084210842108cc6318c6db6d54be83831c1c601f161a1890811b609f1c7ffffffffffffffff5f6af8f7b3396644f18e15796000000000000000000000000816c465772b2bbbb5f824b15207a3001820260601d6d0388eaa27412d5aca026815d636e01820260601d6d0df99ac502031bf953eff472fdcc01820260601d6d13cdffb29d51d99322bdff5f221101820260601d6d0a0f742023def783a307a986912e01820260601d6d01920d8043ca89b5239253284e4201820260601d6c0b7a86d7375468fac667a0a52701917fffffffffffffffffffffffffffffffffffffff465fda27eb4d63ded474e5f832817ffffffffffffffffffffffffffffffffffffffdc7b88c420e53a9890533129f6f817fffffffffffffffffffffffffffffffffffffff73c0c716a594e00d54e3c4cbc9818080806c29508e458543d8aa4df2abee78010260601d6d0139601a2efabe717e604cbb4894010260601d6d02247f7a7b6594320649aa03aba1010260601d010260601d010260601d010201056c058ca53c07678b86e4c893de470290609f0377b17217f7d1cf79abc9e3b39803f2f6af40f343267298b62d0201906bffffffffffffffffffffffff8260601d92166148af57565b9060010190565b63e65fd7ca5f526004601cfd5b5f811215610d9b576335278d125f526004601cfd5b806fffffffffffffffffffffffffffffffff1060071b81811c67ffffffffffffffff1060061b1781811c63ffffffff1060051b1781811c61ffff1060041b1781811c60ff1060031b175f8213156148b6577ff8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff6f8421084210842108cc6318c6db6d54be83831c1c601f161a1890811b609f1c7ffffffffffffffff5f6af8f7b3396644f18e15796000000000000000000000000816c465772b2bbbb5f824b15207a3001820260601d6d0388eaa27412d5aca026815d636e01820260601d6d0df99ac502031bf953eff472fdcc01820260601d6d13cdffb29d51d99322bdff5f221101820260601d6d0a0f742023def783a307a986912e01820260601d6d01920d8043ca89b5239253284e4201820260601d6c0b7a86d7375468fac667a0a52701917fffffffffffffffffffffffffffffffffffffff465fda27eb4d63ded474e5f832817ffffffffffffffffffffffffffffffffffffffdc7b88c420e53a9890533129f6f817fffffffffffffffffffffffffffffffffffffff73c0c716a594e00d54e3c4cbc9818080806c29508e458543d8aa4df2abee78010260601d6d0139601a2efabe717e604cbb4894010260601d6d02247f7a7b6594320649aa03aba1010260601d010260601d010260601d010201056c058ca53c07678b86e4c893de470290609f0377b17217f7d1cf79abc9e3b39803f2f6af40f343267298b62d020160601d90565b670de0b6b3a7640000810290670de0b6b3a7640000820514820215614b22570590565b635c43740d5f526004601cfd5b80628000000160181c15614b4a576335278d125f526004601cfd5b60020b9056fea2646970667358221220009e6f592473955785fbdfbe3fb5d2b055bae191143bb248d226b3999b7164cb64736f6c634300081e003300000000000000000000000000000091cb2d7914c9cd196161da0943ab7b92e1000000000000000000000000005af73a245d8171a0550ffae2631f12cc2118880000000000000000000000000000005e46de497cf4b56e47526969d6f77781ee

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f3560e01c80633e33e12714610696578063685056ff146103e1578063b50c7a9814610335578063c42d62c21461019f5763d5fac49314610050575f80fd5b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36016101a0811261019b5760a01361019b5760e435801515810361019b576101043590811515820361019b57610124358060020b810361019b576100d8906100bc610716565b506100c56107b5565b61016435906100d2610797565b9061096d565b906101843560f881901c6001149060e01c62ffffff1660020b90610138575b60a0610113848487610107610797565b9160c43560a435610ecf565b92604092919251941515855260020b6020850152604084015260608301526080820152f35b9190815160020b9361010083015194600486101561016e5760a0956101139561016092610be3565b60020b8352935090916100f7565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b5f80fd5b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601610100811261019b5760a01361019b5760a43562ffffff8116810361019b5760c4359060e435600381101561019b57610214610201610797565b918463ffffffff8160201c16948461169d565b918261032b575b8261022e575b6020836040519015158152f35b909150670de0b6b3a764000003670de0b6b3a764000081116102fe57807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff046c01000000000000000000000000116102e5575b90826102de9263ffffffff60209560401c169263ffffffff8360601c169261ffff8160801c1660010b9263ffffffff8260901c1692670de0b6b3a764000061ffff63ffffffff8560b01c169460d01c1660010b9260601b04611b29565b8280610221565b90816102f15790610281565b63bac65e5b5f526004601cfd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b801515925061021b565b3461019b5761036761037f606061034b36610727565b97949893969150919461035c6107b5565b01936100d2856107a7565b939062ffffff60018360f81c149260e01c1660020b90565b906103a4575b602061039c858786610396876107a7565b91610e2e565b604051908152f35b93909291825160020b9461010084015194600486101561016e576103d161039c9661039693602099610be3565b60020b8552929550509192610385565b3461019b577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601610140811261019b5760a01361019b5760a4358060020b810361019b5760c435908160020b820361019b5761043c610706565b506104456107b5565b6104575f9261010435906100d2610797565b916101243560f881901c6001149060e01c62ffffff1660020b90610664575b5061047f610797565b9162ffffff610603856105436104968288876112ad565b9661056681610560856105436104ac848c610ca9565b80858461055a6104cb602083015160020b608084015160020b90610ca9565b6105548461054961050f6105436104fb885160020b8760e08b015191876c10000000000000000000000000611080565b9e9390888d9497939d5160020b928661113c565b93815160020b602083015160020b608084015160020b906040850151928a60a08701519560c0606089015198015198611252565b90610ce3565b995160020b92610cf0565b90610ca9565b9261113c565b97610df4565b8091846105fd610585602083015160020b608084015160020b90610ca9565b610554846105496105c96105436105b5885160020b8760e08b015191876c10000000000000000000000000611080565b9e9390888d9497939d5160020b928661148f565b93815160020b602083015160020b608084015160020b906040850151928a60a08701519560c06060890151980151986115ad565b9261148f565b94511663010000000163ffffffff81116102fe5760a0947fffffffff000000000000000000000000000000000000000000000000000000009260405195865260041c602086015260041c604085015260e01b16606083015215156080820152f35b9050825160020b610100840151600481101561016e578261068492610be3565b60020b9081845260020b141583610476565b3461019b576103676106ac606061034b36610727565b906106c9575b602061039c8587866106c3876107a7565b91610d07565b93909291825160020b9461010084015194600486101561016e576106f661039c966106c393602099610be3565b60020b85529295505091926106b2565b60e435908160020b820361019b57565b61014435908160020b820361019b57565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc01610160811261019b5760a01361019b5760049060a4358060020b810361019b579060c4359060e4358060020b810361019b5790610104358060020b810361019b579061012435906101443590565b6064358060020b810361019b5790565b358060020b810361019b5790565b73ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000091cb2d7914c9cd196161da0943ab7b92e116331415806108bf575b8061087f575b80610876575b8015610836575b61080e57565b7fd9711eeb000000000000000000000000000000000000000000000000000000005f5260045ffd5b5073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000e22477c615223e430266ad8d5285636e3016301415610808565b50331515610801565b5073ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000005e46de497cf4b56e47526969d6f77781ee163314156107fb565b5073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000005af73a245d8171a0550ffae2631f12cc211888163314156107f5565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761094057604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b604051919392610120830167ffffffffffffffff811184821017610940576040525f8352602083015f815260408401955f875260608501965f885260808601905f825260a08701945f865260c08801955f87526101008901975f8952899b63ffffffff8460201c1660e08c01528360f81c93600485101561016e5761ffff8160d01c1660010b9963ffffffff8260b01c169561ffff8360801c1660010b9963ffffffff8460601c16956305f5e1006fffffffff0000000000000000000000008075ffffffffffffffffffff0000000000000000000000008860501c161616996c01000000000000000000000000818c04149015170215610bd6576fffffffff00000000000000000000000085169680159088046c0100000000000000000000000014176305f5e1000215610bd65760038314610baf5781610abd610ac29262ffffff8860e01c1660020b90610ca9565b611f8a565b81610acc81611fcf565b0260020b9180610adb81611ffd565b0260020b908260020b8481125f14610b255750505050926305f5e100979695939263ffffffff928996949f5b52828260401c16905260901c169052049052049052525260020b9052565b9091929350929f928f610b458f610b408591610b4b94610ca9565b610cf0565b84610df4565b60020b12610b6f575b5050926305f5e100979695939263ffffffff92899694610b07565b6305f5e10099989795929f5092610b9e8f92610b988f96610b4063ffffffff988f9c9a97610ca9565b90610df4565b9f9295979899509281949650610b54565b5050826305f5e100979695939263ffffffff9262ffffff8a979560e01c1660020b9f610b07565b63ad251c275f526004601cfd5b91600481101561016e57600181149081610c2d575b8115610c0d575b50610c08575090565b905090565b600291501480610c1e575b5f610bff565b508060020b8260020b12610c18565b90508160020b8360020b1390610bf8565b60020b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b60020b60010190627fffff82137fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008312176102fe57565b9060020b9060020b01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b919082018092116102fe57565b9060020b9060020b02908160020b9182036102fe57565b92610d9b9383610d6961055a8461055481986105496105439961054389610d56602088015160020b93610d4360808a0195865160020b90610ca9565b898860e0839c5160020b92015193611080565b9f939089859e939e5160020b928761113c565b94825160020b90602084015160020b905160020b906040850151928a60a08701519560c0606089015198015198611252565b90565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008212627fffff8313176102fe57565b9060020b9060020b0390627fffff82137fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008312176102fe57565b92610d9b9383610e7d6105fd8461055481986105496105439961054389610e6a602088015160020b93610d4360808a0195865160020b90610ca9565b9f939089859e939e5160020b928761148f565b94825160020b90602084015160020b905160020b906040850151928a60a08701519560c06060890151980151986115ad565b919082039182116102fe57565b818102929181159184041417156102fe57565b9085918197939594951515861515145f14610f8057610ef092918591611da5565b959095948615610f6d5790610f37610f3c92865f14610f5c57610f1e818785610f19828d610ca9565b610d07565b9615610f4257610f308187858b610e2e565b95886112ad565b610ebc565b60601c90565b610f57818785610f52828d610df4565b610e2e565b610f30565b610f688187858b610d07565b610f1e565b505093505050505f905f905f905f905f90565b93610f8e9291819695611c35565b959095948615610f6d5790610f37610f3c92855f14610fe557610fb7818885610f52828d610df4565b9515610fd057610fc98188858b610d07565b96886112ad565b610fe0818885610f19828d610ca9565b610fc9565b610ff18188858b610e2e565b610fb7565b60020b9060020b908115611053577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8000008214166102fe570590565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b9391928161108d81611fcf565b0260020b918061109c81611ffd565b0260020b9280946110bf846110ba856110b5868a610df4565b610ff6565b610df4565b915f8360020b131561112d5750670de0b6b3a76400000392670de0b6b3a764000084116102fe5762ffffff61111981926110ba611123966110b561111261110a8f9b61112a9c611947565b9e8f90610eaf565b9c8b610df4565b1691169086611f13565b8094610eaf565b94565b5f998a98509096509350505050565b93929190918360020b8560020b9080821290811591611244575b5015611166575050505050505f90565b8160020b1361123c575b61119261118c61118c61119a95946110b562ffffff9589610df4565b9561200e565b931690612380565b91808273ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff821611611231575b505073ffffffffffffffffffffffffffffffffffffffff82169283156112255773ffffffffffffffffffffffffffffffffffffffff611219938184169303169060601b6135d5565b90808206151591040190565b62bfc9215f526004601cfd5b915091505f806111d1565b935083611170565b90508260020b12155f611156565b9791929395610543979661128b6112a793610d9b9c6112858161127f611278828b610ce3565b8a86611f13565b98610ce3565b91611f13565b93856112a061129a828b610cf0565b89610ca9565b918c612447565b96612447565b6020830190815160020b846112cb6080820192835160020b90610ca9565b815160020b8460020b818112159182611474575b50501561138b57509261135a60c093610543611360946113548861134e60e09b6113669b5160020b985160020b945160020b60408401519960a08501519261134860608701519e8f9701519c8d998c8461134261133c828a610cf0565b88610ca9565b91613042565b99613042565b94610ebc565b92610ebc565b92610ce3565b90611994565b910151670de0b6b3a764000003670de0b6b3a764000081116102fe57610d9b91611947565b93505050506110ba826110b5816113a46113bb96611fcf565b0260020b826113b281611ffd565b0260020b610df4565b905f8260020b131561146e5760e00151670de0b6b3a764000003670de0b6b3a764000081116102fe57807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff046c010000000000000000000000001161145b575b670de0b6b3a76400009060601b046c01000000000000000000000000036c0100000000000000000000000081116102fe5762ffffff610d9b921690612380565b801561141b5763bac65e5b5f526004601cfd5b50505f90565b6114849192506105548985610cf0565b60020b135f806112df565b90939192938460020b938260020b9480861290811561159f575b50156114b9575050505050505f90565b85846001966114d6846c0100000000000000000000000098610df4565b60020b1261154f575b9262ffffff6115276115228561151c61151673ffffffffffffffffffffffffffffffffffffffff99986110b561152f998c9b610df4565b9c61200e565b98610ca9565b61200e565b981690612380565b95169116038060ff1d908101186115468185613403565b93091515160190565b935073ffffffffffffffffffffffffffffffffffffffff9262ffffff6115276115228561151c611516826110b561152f9961158b8d9c8f610df4565b9d999c5099505050505095505050506114df565b90508460020b13155f6114a9565b979192939561054397966115d36115e993610d9b9c6112858161127f611278828b610ce3565b93856115e261129a828b610cf0565b918c612816565b96612816565b81810292915f82127f80000000000000000000000000000000000000000000000000000000000000008214166102fe5781840514901517156102fe57565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146102fe575f0390565b602081519101519060208110611670575090565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060200360031b1b1690565b9291908160f81c9262ffffff8360e01c1660020b9461ffff8460d01c1660010b63ffffffff8560b01c169163ffffffff8660901c169361ffff8760801c1660010b9563ffffffff808960601c169860401c1698836116fa81611fcf565b0260020b8461170881611ffd565b0260020b90856117188b89610ca9565b8060020b627fffff61172d8460020b836115ef565b1394851561192d575b50508315611908575b5050506118f957611804836117fd8a6117f88f6117cc8f6040519485938a60208601927fffffffff00000000000000000000000000000000000000000000000000000000927fff00000000000000000000000000000000000000000000000000000000000000600a969360f81b16855260e81b600185015260f01b600484015260e01b1660068201520190565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081018352826108ff565b61165c565b8487612c36565b9a8b611855575b505050508761184b575b87611841575b8761182b575b5050505050505090565b611835975061199e565b5f808080808080611821565b861515975061181b565b8315159750611815565b849b50906117f86118706118e8936105546118ef988d610cf0565b60405160f89390931b7fff0000000000000000000000000000000000000000000000000000000000000016602084015260e81b602183015260f087901b602483015260e088901b7fffffffff0000000000000000000000000000000000000000000000000000000016602683015281602a81016117cc565b908a612c36565b965f80808061180b565b50505050505050505050505f90565b61191d9293506119179061162d565b92610ff6565b60020b9060020b125f858161173f565b61193b919295508390610ff6565b60020b12925f80611736565b90807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048211611981575b670de0b6b3a764000091020490565b80156119725763bac65e5b5f526004601cfd5b8115611053570490565b959293918060601b916305f5e1006c01000000000000000000000000838504148315170215610bd6576305f5e100611a069304906305f5e1006119e96119e48b88610cf0565b610c3e565b931115611b045782896119fb94613042565b846112858582610ce3565b946c01000000000000000000000000868060601b041486151760601b15610bd6576a4189374bc6a7ef9db22d0e9573ffffffffffffffffffffffffffffffffffffffff168611611afa578460601b906305f5e1006c01000000000000000000000000878404148715170215610bd657611a9d95611285936305f5e1008087950492115f14611ae157611a979261300f565b93610ce3565b6c01000000000000000000000000818060601b041481151760601b15610bd65773ffffffffffffffffffffffffffffffffffffffff1610611add57600190565b5f90565b82611af56119e4611a9795610b4085610d9e565b612e9e565b5050505050505f90565b611b249289611b1f611b1982610b4086610d9e565b83610ca9565b613042565b6119fb565b9594919096928060601b916305f5e1006c01000000000000000000000000838504148315170215610bd6576305f5e100611b839304906305f5e100611b716119e48c88610cf0565b931115611c2057828a6119fb94613042565b9585870296868189041490151760601b15610bd6576a4189374bc6a7ef9db22d0e809760601c10611c15578460601b906305f5e1006c01000000000000000000000000878404148715170215610bd657611bf595611285936305f5e1008087950492115f14611ae157611a979261300f565b818102918183041490151760601b15610bd65760601c10611add57600190565b505050505050505f90565b611b24928a611b1f611b1982610b4086610d9e565b919290928215611d8e57611c6e611c5b602084015160020b608085015160020b90610ca9565b9485845160020b8460e087015193611080565b9095929791611c84845160020b8888888361148f565b8089111580611d85575b15611caa5750505050611ca695505160020b9361308f565b9091565b919450929550611cba9196610eaf565b94611d05611cd0865160020b6105548785610cf0565b8689815160020b602083015160020b608084015160020b906040850151928b60a08701519560c06060890151980151986115ad565b90818711611d48575050505092611ca693825160020b602084015160020b608085015160020b9160408601519360a08701519560c0606089015198015198613225565b90918093969750611d6057505050505050505f905f90565b61055484611d74611d7f94611ca69a610eaf565b965160020b92610cf0565b9261308f565b50851515611c8e565b915050611da09150806113b281611fcf565b600191565b9192908215611efc579261055a8280611def96846020611e1098970191825160020b611dda6080860191825160020b90610ca9565b9a8b9283875160020b8660e08a015193611080565b9d939891809b8f9498929761055484611d74875160020b6105548386610cf0565b808a111580611ef3575b15611e4157505050505050611ca69561055484611e3b935160020b92610cf0565b926132ad565b9296509399509396611e54929850610eaf565b95855160020b94815160020b94835160020b97604081019586519860a083019889519a606085019b8c519160c087019e8f5194868b8b611e9399611252565b9b8c8c11611ebe575050611ca69a505160020b925160020b935160020b945195519651975198613380565b97509850989450509450505081611edb575050505050505f905f90565b611ca695611ee891610eaf565b935160020b936132ad565b50871515611e1a565b505050611f0881611ffd565b0260020b9060019190565b8181029181159183041417820215610bd6570490565b9060020b9081156110535760020b0790565b60020b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff80000081146102fe577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0190565b90610d9b91611f998282610ff6565b90825f8260020b129182611fb9575b505015610cf0575b610b4090611f3b565b611fc39250611f29565b60020b1515825f611fa8565b60020b8015611053577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff276180590565b60020b801561105357620d89e80590565b60020b908160ff1d82810118620d89e881116123545763ffffffff9192600182167001fffcb933bd6fad37aa2d162d1a59400102700100000000000000000000000000000000189160028116612338575b6004811661231c575b60088116612300575b601081166122e4575b602081166122c8575b604081166122ac575b60808116612290575b6101008116612274575b6102008116612258575b610400811661223c575b6108008116612220575b6110008116612204575b61200081166121e8575b61400081166121cc575b61800081166121b0575b620100008116612194575b620200008116612179575b62040000811661215e575b6208000016612145575b5f1261211e575b0160201c90565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff04612117565b6b048a170391f7dc42444e8fa290910260801c90612110565b6d2216e584f5fa1ea926041bedfe9890920260801c91612106565b916e5d6af8dedb81196699c329225ee6040260801c916120fb565b916f09aa508b5b7a84e1c677de54f3e99bc90260801c916120f0565b916f31be135f97d08fd981231505542fcfa60260801c916120e5565b916f70d869a156d2a1b890bb3df62baf32f70260801c916120db565b916fa9f746462d870fdf8a65dc1f90e061e50260801c916120d1565b916fd097f3bdfd2022b8845ad8f792aa58250260801c916120c7565b916fe7159475a2c29b7443b29c7fa6e889d90260801c916120bd565b916ff3392b0822b70005940c7a398e4b70f30260801c916120b3565b916ff987a7253ac413176f2b074cf7815e540260801c916120a9565b916ffcbe86c7900a88aedcffc83b479aa3a40260801c9161209f565b916ffe5dee046a99a2a811c461f1969c30530260801c91612095565b916fff2ea16466c96a3843ec78b326b528610260801c9161208c565b916fff973b41fa98c081472e6896dfb254c00260801c91612083565b916fffcb9843d60f6159c9db58835c9266440260801c9161207a565b916fffe5caca7e10e4e61c3624eaa0941cd00260801c91612071565b916ffff2e50f5f656932ef12357cf3c7fdcc0260801c91612068565b916ffff97272373d413259a46990580e213a0260801c9161205f565b827f8b86327a000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b90801561239257808204910615150190565b6365244e4e5f526004601cfd5b91908083028315828583041417156123e9576c010000000000000000000000009060601c915b8294096123cf5750565b600101915081156123dc57565b63ae47f7025f526004601cfd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828509818110820190038060601c1561242a5763ae47f7025f526004601cfd5b6c010000000000000000000000009160601c9060a01b01916123c5565b92919390935f938060020b8460020b81125f146127dd5750505f5b73ffffffffffffffffffffffffffffffffffffffff61248e816124876115228661162d565b169561200e565b16966c01000000000000000000000000811115612640578015610bd657780100000000000000000000000000000000000000000000000004600284810b9083900b126124e3575050505050610d9b925061239f565b9091929394506124f38285610df4565b9162ffffff86831193169073ffffffffffffffffffffffffffffffffffffffff61253761152261252385876135fe565b9461252d8961162d565b9060020b90610cf0565b1693836c0100000000000000000000000003916c0100000000000000000000000083116102fe57610b4061259f6125a594611522948c896125ad9b62ffffff9a845f14612631579061258891610eaf565b925b15612628579061259991610eaf565b916136ec565b9761162d565b9416906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe5773ffffffffffffffffffffffffffffffffffffffff6125f19316906136ec565b906c0100000000000000000000000003926c0100000000000000000000000084116102fe57610d9b93612623926136ec565b61239f565b61259991610eaf565b61263a91610eaf565b9261258a565b95969495939290600282810b9082900b126126655750505050505090610d9b9161239f565b9091928481959697500292848685041486151760601b15610bd65761268f62ffffff8316876135fe565b9061269f62ffffff8516886135fe565b966c0100000000000000000000000003926c0100000000000000000000000084116102fe5773ffffffffffffffffffffffffffffffffffffffff61270e61152261272197610b4061270861271b98866127016115226127159a610b408d61162d565b16906136bd565b9661162d565b16886136bd565b90610eaf565b90610ebc565b926c0100000000000000000000000003906c0100000000000000000000000082116102fe5760601c6c01000000000000000000000000036c0100000000000000000000000081116102fe5761277591610ebc565b906c0100000000000000000000000003916c0100000000000000000000000083116102fe576127a39261370a565b906c010000000000000000000000006127bc828461372d565b92096127cd575b90610d9b9161239f565b6001019081156123dc57906127c3565b6127f06127ea8486610cf0565b86610ca9565b60020b1361280357505050505050505f90565b816110b58561281193610df4565b612462565b9490939291948060020b8360020b81125f1461283757505050505050505f90565b8391879161284e6128488489610cf0565b85610ca9565b60020b13612c235750505061286283610d9e565b905b73ffffffffffffffffffffffffffffffffffffffff6128828761200e565b16956c01000000000000000000000000821115612a50578115610bd657817801000000000000000000000000000000000000000000000000045f8460020b125f146128d857505050505050610d9b91505f61239f565b73ffffffffffffffffffffffffffffffffffffffff61290261152261259f62ffffff8a16856135fe565b1695888402898582041460601b15610bd65760601c947fffffffffffffffffffffffffffffffffffffffff00000000000000000000000085019485116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000086019586116102fe5773ffffffffffffffffffffffffffffffffffffffff6127016115226129be96610b406129b38c9862ffffff6129ac6129a78a6129b99c610df4565b610d9e565b16906135fe565b95610c72565b610eaf565b926c0100000000000000000000000003926c0100000000000000000000000084116102fe57838160601b9173ffffffffffffffffffffffffffffffffffffffff8116140215610bd65783612a1894820491061515016136ec565b907fffffffffffffffffffffffffffffffffffffffff00000000000000000000000084019384116102fe57610d9b93612623926136ec565b91925f8460029693960b125f14612a71575050505050610d9b91505f61239f565b612a8f73ffffffffffffffffffffffffffffffffffffffff9161200e565b169286850290878683041486151760601b15610bd65773ffffffffffffffffffffffffffffffffffffffff612701611522612ae89460601c96612ae26129b362ffffff612adb88610c72565b168c6135fe565b90610cf0565b7fffffffffffffffffffffffffffffffffffffffff000000000000000000000000810190856c01000000000000000000000000036c0100000000000000000000000081116102fe57612b919282612b61936c0100000000000000000000000011906c010000000000000000000000000382180218610ebc565b9462ffffff7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000085019316906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe5782612be2936c0100000000000000000000000011906c010000000000000000000000000382180218610ebc565b937fffffffffffffffffffffffffffffffffffffffff00000000000000000000000081019081116102fe57610d9b9461262393612c1e9261370a565b6136bd565b612c30926110b591610df4565b90612864565b929183612c4281611fcf565b0260020b84612c5081611ffd565b0260020b908260f81c9162ffffff8460e01c1660020b9361ffff8160d01c1660010b9563ffffffff8260b01c169460038111612e90576003149788918215612e53575b5081612e40575b50612dcc57612ca98886611f29565b60020b612dcc575f8613801590612e28575b8015612e13575b8015612df2575b612dcc576103e884108015612de5575b8015612dd8575b612dcc5760501c6fffffffff0000000000000000000000001683158482046c0100000000000000000000000014176305f5e1000215610bd6576305f5e10090049573ffffffffffffffffffffffffffffffffffffffff612d3f8961200e565b168714612dcc57612d91575b50506305f5e1001015612d7857612d629381613042565b6a4189374bc6a7ef9db22d0e11611add57600190565b83611b1f611b19612d8c96610b4086610d9e565b612d62565b612d9e6128488887610cf0565b918412918215612dbf575b5050612db6575f80612d4b565b50505050505f90565b60020b1390505f80612da9565b50505050505050505f90565b506305f5e1008414612ce0565b506347868c008411612cd9565b50612dfc8661162d565b612e068985610ff6565b60020b9060020b12612cc9565b50612e1e8883610ff6565b60020b8613612cc2565b50627fffff612e3a8960020b886115ef565b13612cbb565b9050600381101561016e5715155f612c9a565b62ffffff91925016158015612e7c575b612e6f5787905f612c93565b5050505050505050505f90565b50600381101561016e576002811415612e63565b505050505050505050505f90565b9291928060020b5f8112908115612fef575b50612fe75762ffffff916110b55f612ec793610df4565b16916c01000000000000000000000000821115612f7a578115610bd657612f19612f1362ffffff8478010000000000000000000000000000000000000000000000000493169485610eaf565b826135fe565b927fffffffffffffffffffffffffffffffffffffffff00000000000000000000000083019283116102fe57612f4d916135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57610d9b926137ec565b9091826c0100000000000000000000000003926c0100000000000000000000000084116102fe5762ffffff612fb2612fba93836135fe565b9316906135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57610d9b92611f13565b505050505f90565b9050613004612ffe8487610cf0565b5f610ca9565b60020b13155f612eb0565b91909161301f612ffe8285610cf0565b60020b5f121561303b57612ec762ffffff916110b55f80610df4565b5050505f90565b91909392938260020b8260020b811290811561306f575b50612db6576110b5612ec79262ffffff94610df4565b905061308461307e8388610cf0565b84610ca9565b60020b13155f613059565b9094929193948115613217576131009073ffffffffffffffffffffffffffffffffffffffff6130c2876110b5878b610df4565b936130e56130cf8761200e565b9362ffffff6130dd8c61200e565b971690612380565b828211613208576130f89160601b611994565b915b16610ce3565b9073ffffffffffffffffffffffffffffffffffffffff82169182036131e05773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff8216116131bb5761315a90613891565b9360020b92838560020b146131d0575b61317681600196611f8a565b936131818284610df4565b60020b908560020b9182129182156131c5575b50506131bb576131a49082610df4565b60020b8360020b146131b35750565b600193509150565b505f935083925050565b121590505f80613194565b936131da90610d9e565b9361316a565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffd5b6132119161347d565b916130fa565b5050611da092919350610df4565b989097939194969795929561324461323d8387610ce3565b8383611f13565b9461325f8a8a8a8a8a61325a61307e8386610cf0565b612816565b808c1161327557505050505050611ca695613c80565b6132a7959a50610554939894999650916132a19161128561329a8a95611ca69f610eaf565b9a82610ce3565b94610cf0565b92613c80565b949293948015613376576132fe73ffffffffffffffffffffffffffffffffffffffff916132de856110b5898b610df4565b6132f86132ea8961200e565b9562ffffff6111928c61200e565b906141da565b911673ffffffffffffffffffffffffffffffffffffffff8216106131bb5761332590613891565b9361333282600196611f8a565b938460020b9060020b8112908115613369575b506131bb578060020b8460020b1461335b575050565b90919350611da09250610df4565b90508160020b125f613345565b5060019493505050565b9297959796919490939661339d6133978784610cf0565b82610ca9565b966133b26133ab8c83610ce3565b8288611f13565b956133c18b8b8b8b8b82612447565b9b8c87116133d957505050505050611ca69650614250565b93995093995094509550611285816133f7611ca69b6133fd96610eaf565b95610ce3565b90614250565b90808202917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff828209918380841093039280840393846c01000000000000000000000000111561019b5714613474576c01000000000000000000000000910990828211900360a01b910360601c1790565b50505060601c90565b908160601b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6c0100000000000000000000000084099282808510940393808503948584111561019b571461352f576c0100000000000000000000000082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b5091500490565b91818302917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8185099383808610950394808603958685111561019b57146135cd579082910981805f03168092046002816003021880820260020302808202600203028082026002030280820260020302808202600203028091026002030293600183805f03040190848311900302920304170290565b505091500490565b9291906135e3828286613536565b93821561105357096135f157565b9060010190811561019b57565b919082811560601b9361360f575050565b90925060018316816c0100000000000000000000000018026c01000000000000000000000000189260011c90815b613645575050565b8080026b80000000000000000000000081019160801c908210176136b05760601c906001811661367a575b60011c908161363d565b92818082026b80000000000000000000000081019282828510920418176136a6575b5060601c92613670565b6136b0578161369c565b6349f7642b5f526004601cfd5b9080820290808383041483151760601b15610bd6576c010000000000000000000000009160601c920915150190565b818102929181159184041417810215610bd657808204910615150190565b9291906137188282866137ec565b930961372057565b906001019081156123dc57565b908160601b91816c010000000000000000000000008285041482151702156137555750900490565b816c010000000000000000000000007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81840985811086019003920990825f03831692818111156123dc5783900480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f0304019211900302170290565b81810292918115828504821417830215613807575050900490565b807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8492840985811086019003920990825f03831692818111156123dc5783900480600302600218808202600203028082026002030280820260020302808202600203028082026002030280910260020302936001848483030494805f0304019211900302170290565b73fffd8963efd1fc6a506488495d951d516396168273ffffffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffefffd895d83011611613bf35777ffffffffffffffffffffffffffffffffffffffff000000008160201b1680811561019b5760ff826fffffffffffffffffffffffffffffffff1060071b83811c67ffffffffffffffff1060061b1783811c63ffffffff1060051b1783811c61ffff1060041b1783811c821060031b177f07060605060205000602030205040001060502050303040105050304000000006f8421084210842108cc6318c6db6d54be85831c1c601f161a17169160808310155f14613be757507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8182011c5b800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c800280607f1c8160ff1c1c80029081607f1c8260ff1c1c80029283607f1c8460ff1c1c80029485607f1c8660ff1c1c80029687607f1c8860ff1c1c80029889607f1c8a60ff1c1c80029a8b607f1c8c60ff1c1c80029c8d80607f1c9060ff1c1c800260cd1c6604000000000000169d60cc1c6608000000000000169c60cb1c6610000000000000169b60ca1c6620000000000000169a60c91c6640000000000000169960c81c6680000000000000169860c71c670100000000000000169760c61c670200000000000000169660c51c670400000000000000169560c41c670800000000000000169460c31c671000000000000000169360c21c672000000000000000169260c11c674000000000000000169160c01c67800000000000000016907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff800160401b1717171717171717171717171717693627a301d71055774c85027ffffffffffffffffffffffffffffffffffd709b7e5480fba5a50fed5e62ffc556810160801d60020b906fdb2df09e81959a81455e260799a0632f0160801d60020b918282145f14613ba95750905090565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff613bdd8461200e565b1611610c08575090565b905081607f031b6139c1565b73ffffffffffffffffffffffffffffffffffffffff907f61487524000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b907ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c000082019182136001166102fe57565b9190915f83820193841291129080158216911516176102fe57565b9593949580156141cb57613c94828261372d565b73ffffffffffffffffffffffffffffffffffffffff613cb28561200e565b89159291168981028a81048214841760601b15610bd65760601c613cd581614674565b938a8c6c01000000000000000000000000811115613f9e575050610bd657613d1d62ffffff8b168c7801000000000000000000000000000000000000000000000000046135fe565b9273ffffffffffffffffffffffffffffffffffffffff613d3f6115228b61162d565b16917fffffffffffffffffffffffffffffffffffffffff0000000000000000000000008d01918d83116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019182116102fe57856c0100000000000000000000000003946c0100000000000000000000000086116102fe577fffffffffffffffffffffffffffffffffffffffff00000000000000000000000081019081116102fe57613df794613df292611f13565b611f13565b818102918183041490151760601b15610bd65760601c613e178282610ce3565b15613f8f5791613e5b613e40613e3b613e36613e6095613e6597610ce3565b6148c3565b6148d8565b613e55613e4c8d6148d8565b8c60020b6115ef565b90613c65565b614aff565b613c35565b965b613e7087610d9e565b60020b92670de0b6b3a7640000840293808505670de0b6b3a764000014901517156102fe57838913613f55575b505050506001948282613eb9670de0b6b3a76400008405614b2f565b925f81139081613f41575b50613f29575b613ed790613edc93610cf0565b610ca9565b938482613ee98186610df4565b60020b9160020b918212928315613f0c575b5050506131bb576131a49082610df4565b613f1c9293509061307e91610cf0565b60020b13155f8281613efb565b505060020b627fffff81146102fe5785018282613eca565b670de0b6b3a764000091500715155f613ec4565b87969850968585809961325a61307e613f73979899610b4087610d9e565b1015613f8357505050505f905f90565b9391925f808080613e9d565b505f9850889750505050505050565b915093929173ffffffffffffffffffffffffffffffffffffffff613fc18b61200e565b16906140067fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019362ffffff836c01000000000000000000000000119816906135fe565b6c01000000000000000000000000036c0100000000000000000000000081116102fe57614050938761404a936c010000000000000000000000000382180218610ebc565b9361372d565b917fffffffffffffffffffffffffffffffffffffffff00000000000000000000000082019182116102fe57614084926137ec565b908080614187575b61416157156140fe57886c01000000000000000000000000036c0100000000000000000000000081116102fe576140c291611994565b6c01000000000000000000000000036c0100000000000000000000000081116102fe576140f891613e5b613e3b613e60936148c3565b96613e67565b886c01000000000000000000000000036c0100000000000000000000000081116102fe5761412b91611994565b6c0100000000000000000000000001806c01000000000000000000000000116102fe576140f891613e5b613e3b613e60936148c3565b505050939490928096926141759482612816565b106141805760019190565b5f91508190565b50896c01000000000000000000000000036c0100000000000000000000000081116102fe576141b69083611994565b6c01000000000000000000000000111561408c565b5050919350611da09250610df4565b9091801561424a5773ffffffffffffffffffffffffffffffffffffffff809360601b92168082028161420c8483611994565b14614232575b50906142216142269284611994565b610ce3565b80820615159104011690565b8301838110614212579150614246926135d5565b1690565b50905090565b90959394929192811561466257614267878361372d565b876c01000000000000000000000000840961464d575b73ffffffffffffffffffffffffffffffffffffffff61429e6115228761162d565b1673ffffffffffffffffffffffffffffffffffffffff6142bd8661200e565b1690808402928415938286820414851760601b15610bd65760601c936142e2856148d8565b946c010000000000000000000000008711156145605750610bd657847801000000000000000000000000000000000000000000000000049061432962ffffff8c16836135fe565b9083831194846c0100000000000000000000000003906c0100000000000000000000000082116102fe5761435c926136ec565b906c01000000000000000000000000036c0100000000000000000000000081116102fe57614389916136bd565b91818415614551579061439b91610eaf565b905b6c0100000000000000000000000003906c0100000000000000000000000082116102fe576143ca926136ec565b6143da6115228a610b408a61162d565b91801580614531575b61450e5761441d6144379493613e5b93614422935f146144ef5773ffffffffffffffffffffffffffffffffffffffff613e36921690610ce3565b614674565b613e5561442e86614674565b8b60020b6115ef565b965b5f88126144c1575b50505061447781613ed784600198614462670de0b6b3a76400008205614b2f565b905f811290816144ad575b50611fb057610cf0565b90614486613397848497610cf0565b9160020b9060020b811290811561336957506131bb578060020b8460020b1461335b575050565b670de0b6b3a764000091500715155f61446d565b8695975095838581986144d49596612447565b10156144e3575050505f905f90565b5f9391925f8080614441565b73ffffffffffffffffffffffffffffffffffffffff613e369216610eaf565b50505050918361452a611b1961417596610b408a96999a610d9e565b9788612447565b508173ffffffffffffffffffffffffffffffffffffffff841611156143e3565b61455a91610eaf565b9061439d565b949362ffffff8c169392915061457684886135fe565b6c0100000000000000000000000003906c0100000000000000000000000082116102fe57866c0100000000000000000000000003916c0100000000000000000000000083116102fe576145d2926145cc91610ebc565b926136bd565b916c0100000000000000000000000003906c0100000000000000000000000082116102fe576146009261370a565b90846c0100000000000000000000000003916c0100000000000000000000000083116102fe576146479461054361441d93614641613e5b96613e3695611994565b926135fe565b96614439565b6001018061427d5763ae47f7025f526004601cfd5b505091935061055490611da093610cf0565b806fffffffffffffffffffffffffffffffff1060071b81811c67ffffffffffffffff1060061b1781811c63ffffffff1060051b1781811c61ffff1060041b1781811c60ff1060031b175f8213156148b6577ff8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff6f8421084210842108cc6318c6db6d54be83831c1c601f161a1890811b609f1c7ffffffffffffffff5f6af8f7b3396644f18e15796000000000000000000000000816c465772b2bbbb5f824b15207a3001820260601d6d0388eaa27412d5aca026815d636e01820260601d6d0df99ac502031bf953eff472fdcc01820260601d6d13cdffb29d51d99322bdff5f221101820260601d6d0a0f742023def783a307a986912e01820260601d6d01920d8043ca89b5239253284e4201820260601d6c0b7a86d7375468fac667a0a52701917fffffffffffffffffffffffffffffffffffffff465fda27eb4d63ded474e5f832817ffffffffffffffffffffffffffffffffffffffdc7b88c420e53a9890533129f6f817fffffffffffffffffffffffffffffffffffffff73c0c716a594e00d54e3c4cbc9818080806c29508e458543d8aa4df2abee78010260601d6d0139601a2efabe717e604cbb4894010260601d6d02247f7a7b6594320649aa03aba1010260601d010260601d010260601d010201056c058ca53c07678b86e4c893de470290609f0377b17217f7d1cf79abc9e3b39803f2f6af40f343267298b62d0201906bffffffffffffffffffffffff8260601d92166148af57565b9060010190565b63e65fd7ca5f526004601cfd5b5f811215610d9b576335278d125f526004601cfd5b806fffffffffffffffffffffffffffffffff1060071b81811c67ffffffffffffffff1060061b1781811c63ffffffff1060051b1781811c61ffff1060041b1781811c60ff1060031b175f8213156148b6577ff8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff6f8421084210842108cc6318c6db6d54be83831c1c601f161a1890811b609f1c7ffffffffffffffff5f6af8f7b3396644f18e15796000000000000000000000000816c465772b2bbbb5f824b15207a3001820260601d6d0388eaa27412d5aca026815d636e01820260601d6d0df99ac502031bf953eff472fdcc01820260601d6d13cdffb29d51d99322bdff5f221101820260601d6d0a0f742023def783a307a986912e01820260601d6d01920d8043ca89b5239253284e4201820260601d6c0b7a86d7375468fac667a0a52701917fffffffffffffffffffffffffffffffffffffff465fda27eb4d63ded474e5f832817ffffffffffffffffffffffffffffffffffffffdc7b88c420e53a9890533129f6f817fffffffffffffffffffffffffffffffffffffff73c0c716a594e00d54e3c4cbc9818080806c29508e458543d8aa4df2abee78010260601d6d0139601a2efabe717e604cbb4894010260601d6d02247f7a7b6594320649aa03aba1010260601d010260601d010260601d010201056c058ca53c07678b86e4c893de470290609f0377b17217f7d1cf79abc9e3b39803f2f6af40f343267298b62d020160601d90565b670de0b6b3a7640000810290670de0b6b3a7640000820514820215614b22570590565b635c43740d5f526004601cfd5b80628000000160181c15614b4a576335278d125f526004601cfd5b60020b9056fea2646970667358221220009e6f592473955785fbdfbe3fb5d2b055bae191143bb248d226b3999b7164cb64736f6c634300081e0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000000000091cb2d7914c9cd196161da0943ab7b92e1000000000000000000000000005af73a245d8171a0550ffae2631f12cc2118880000000000000000000000000000005e46de497cf4b56e47526969d6f77781ee

-----Decoded View---------------
Arg [0] : hub_ (address): 0x00000091Cb2d7914C9cd196161Da0943aB7b92E1
Arg [1] : hook_ (address): 0x005aF73a245d8171A0550ffAe2631f12cc211888
Arg [2] : quoter_ (address): 0x0000005E46dE497cF4b56e47526969d6F77781eE

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 00000000000000000000000000000091cb2d7914c9cd196161da0943ab7b92e1
Arg [1] : 000000000000000000000000005af73a245d8171a0550ffae2631f12cc211888
Arg [2] : 0000000000000000000000000000005e46de497cf4b56e47526969d6f77781ee


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.