ETH Price: $2,948.39 (+1.23%)

Contract

0x2AB8626fBd141557D69c4fE202Ca9B1cbF934AA9

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

Please try again later

Advanced mode:
Parent Transaction Hash Block From To
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
InitialDepositLens

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

Other Settings:
cancun EvmVersion
File 1 of 82 : InitialDepositLens.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {MultiPositionManager} from "../MultiPositionManager.sol";
import {MultiPositionFactory} from "../MultiPositionFactory.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import {LensRatioUtils} from "../libraries/SimpleLens/LensRatioUtils.sol";
import {LensInMin} from "../libraries/SimpleLens/LensInMin.sol";
import {RebalanceLogic} from "../libraries/RebalanceLogic.sol";
import {PositionLogic} from "../libraries/PositionLogic.sol";

/**
 * @title InitialDepositLens
 * @notice Read-only contract for previewing initial deposits to pools for MultiPositionManager
 * @dev Adapted from InitialDepositLens - supports both initialized and uninitialized pools
 *
 * Key constraints (enforced from MultiPositionManager):
 * - Only proportional (0,0) or 50/50 (0.5e18, 0.5e18) weights allowed
 * - useCarpet must be true
 * - rebalanceSwap is time-locked for lockDuration after deployment
 */
contract InitialDepositLens {
    using StateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;

    // Immutable storage
    IPoolManager public immutable poolManager;

    // Custom errors
    error NoStrategySpecified();
    error InvalidWeights();
    error CarpetRequired();
    error InvalidAmount();

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }

    // ============================================
    // Structs
    // ============================================

    struct InitialDepositParams {
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        bool isToken0;
        uint256 amount;
        uint256 maxSlippageBps;
    }

    struct CustomInitialDepositParams {
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        uint256 deposit0;
        uint256 deposit1;
        uint256 maxSlippageBps;
    }

    struct InitialDepositWithSwapParams {
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        uint256 deposit0;
        uint256 deposit1;
        uint256 maxSlippageBps;
    }

    struct RebalancePreview {
        address strategy;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        IMultiPositionManager.Range[] ranges;
        uint128[] liquidities;
        LensRatioUtils.PositionStats[] expectedPositions;
        uint256 expectedTotal0;
        uint256 expectedTotal1;
    }

    struct RangeGenParams {
        PoolKey poolKey;
        uint160 sqrtPriceX96;
        int24 resolvedCenterTick;
        int24 currentTick;
        uint256 amount0;
        uint256 amount1;
    }

    // ============================================
    // Initial Deposit Preview (Initialized Pool)
    // ============================================

    /**
     * @notice Calculate deposit amounts for initial position and preview the rebalance
     * @dev FOR INITIALIZED POOLS - fetches sqrtPriceX96 from getSlot0()
     * @param poolKey The PoolKey for the Uniswap V4 pool
     * @param params Parameters for the initial deposit calculation
     * @return otherAmount The amount of the other token needed
     * @return inMin The minimum amounts for each position (for slippage protection)
     * @return preview Detailed preview of the rebalance operation
     */
    function getAmountsForInitialDeposit(PoolKey memory poolKey, InitialDepositParams calldata params)
        external
        view
        returns (uint256 otherAmount, uint256[2][] memory inMin, RebalancePreview memory preview)
    {
        _validateParams(params.weight0, params.weight1, params.useCarpet);

        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        return _getAmountsForInitialDeposit(poolKey, sqrtPriceX96, params);
    }

    /**
     * @notice Calculate deposit amounts for initial position and preview the rebalance
     * @dev FOR UNINITIALIZED POOLS - sqrtPriceX96 is provided since pool hasn't been initialized yet
     * @param poolKey The PoolKey for the Uniswap V4 pool
     * @param sqrtPriceX96 The intended sqrtPriceX96 for pool initialization
     * @param params Parameters for the initial deposit calculation
     * @return otherAmount The amount of the other token needed
     * @return inMin The minimum amounts for each position (for slippage protection)
     * @return preview Detailed preview of the rebalance operation
     */
    function getAmountsForInitialDepositUninitialized(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositParams calldata params
    ) external view returns (uint256 otherAmount, uint256[2][] memory inMin, RebalancePreview memory preview) {
        _validateParams(params.weight0, params.weight1, params.useCarpet);
        return _getAmountsForInitialDeposit(poolKey, sqrtPriceX96, params);
    }

    // ============================================
    // Custom Initial Deposit Preview
    // ============================================

    /**
     * @notice Preview initial deposit and rebalance with custom amounts (both token0 and token1)
     * @dev FOR INITIALIZED POOLS - fetches sqrtPriceX96 from getSlot0()
     * @param poolKey The pool key
     * @param params Custom initial deposit parameters with both deposit0 and deposit1
     * @return inMin Minimum input amounts for each base position
     * @return preview Detailed preview of the rebalance operation with actual distribution
     */
    function previewCustomInitialDepositAndRebalance(PoolKey memory poolKey, CustomInitialDepositParams calldata params)
        external
        view
        returns (uint256[2][] memory inMin, RebalancePreview memory preview)
    {
        _validateParams(params.weight0, params.weight1, params.useCarpet);

        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        return _previewCustomInitialDeposit(poolKey, sqrtPriceX96, params);
    }

    /**
     * @notice Preview initial deposit and rebalance with custom amounts (both token0 and token1)
     * @dev FOR UNINITIALIZED POOLS - Similar to getAmountsForInitialDeposit but accepts
     *      explicit deposit0 and deposit1 amounts
     * @param poolKey The pool key
     * @param sqrtPriceX96 The intended sqrtPriceX96 for pool initialization
     * @param params Custom initial deposit parameters with both deposit0 and deposit1
     * @return inMin Minimum input amounts for each base position
     * @return preview Detailed preview of the rebalance operation with actual distribution
     */
    function previewCustomInitialDepositAndRebalanceUninitialized(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        CustomInitialDepositParams calldata params
    ) external view returns (uint256[2][] memory inMin, RebalancePreview memory preview) {
        _validateParams(params.weight0, params.weight1, params.useCarpet);
        return _previewCustomInitialDeposit(poolKey, sqrtPriceX96, params);
    }

    // ============================================
    // Initial Deposit with Swap Preview
    // ============================================

    /**
     * @notice Calculate swap needed for initial deposit with any token ratio, then preview positions
     * @dev FOR INITIALIZED POOLS - fetches sqrtPriceX96 from getSlot0()
     *      NOTE: Swap is only available after lockDuration has passed
     * @param poolKey The PoolKey for the Uniswap V4 pool
     * @param params Parameters including both token amounts (any ratio)
     * @return finalAmount0 Amount of token0 after optimal swap
     * @return finalAmount1 Amount of token1 after optimal swap
     * @return swapParams Swap details (direction, amount, target weights)
     * @return inMin Minimum amounts for each position (slippage protection)
     * @return preview Detailed preview of the rebalance operation
     */
    function getAmountsForInitialDepositWithSwap(PoolKey memory poolKey, InitialDepositWithSwapParams calldata params)
        external
        view
        returns (
            uint256 finalAmount0,
            uint256 finalAmount1,
            LensRatioUtils.SwapParams memory swapParams,
            uint256[2][] memory inMin,
            RebalancePreview memory preview
        )
    {
        _validateParams(params.weight0, params.weight1, params.useCarpet);

        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        return _getAmountsForInitialDepositWithSwap(poolKey, sqrtPriceX96, params);
    }

    /**
     * @notice Calculate swap needed for initial deposit with any token ratio, then preview positions
     * @dev FOR UNINITIALIZED POOLS - Supports any ratio: 100/0, 90/10, 50/50, etc.
     *      NOTE: Swap is only available after lockDuration has passed
     * @param poolKey The PoolKey for the Uniswap V4 pool
     * @param sqrtPriceX96 The intended sqrtPriceX96 for pool initialization
     * @param params Parameters including both token amounts (any ratio)
     * @return finalAmount0 Amount of token0 after optimal swap
     * @return finalAmount1 Amount of token1 after optimal swap
     * @return swapParams Swap details (direction, amount, target weights)
     * @return inMin Minimum amounts for each position (slippage protection)
     * @return preview Detailed preview of the rebalance operation
     */
    function getAmountsForInitialDepositWithSwapUninitialized(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositWithSwapParams calldata params
    )
        external
        view
        returns (
            uint256 finalAmount0,
            uint256 finalAmount1,
            LensRatioUtils.SwapParams memory swapParams,
            uint256[2][] memory inMin,
            RebalancePreview memory preview
        )
    {
        _validateParams(params.weight0, params.weight1, params.useCarpet);
        return _getAmountsForInitialDepositWithSwap(poolKey, sqrtPriceX96, params);
    }

    // ============================================
    // Position Stats
    // ============================================

    /**
     * @notice Get detailed statistics for all positions in a MultiPositionManager
     * @param manager The MultiPositionManager contract to query
     * @return stats Array of statistics for each position
     */
    function getPositionStats(IMultiPositionManager manager)
        external
        view
        returns (LensRatioUtils.PositionStats[] memory stats)
    {
        PoolKey memory poolKey = manager.poolKey();
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());

        (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData) =
            manager.getPositions();

        stats = new LensRatioUtils.PositionStats[](ranges.length);
        uint256 baseLen = manager.basePositionsLength();

        for (uint256 i = 0; i < ranges.length; i++) {
            if (ranges[i].lowerTick == 0 && ranges[i].upperTick == 0) {
                continue;
            }

            uint160 sqrtPriceLowerX96 = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            uint160 sqrtPriceUpperX96 = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

            (uint256 token0Quantity, uint256 token1Quantity) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96, sqrtPriceLowerX96, sqrtPriceUpperX96, uint128(positionData[i].liquidity)
            );

            uint256 token0ValueInToken1 =
                FullMath.mulDiv(token0Quantity, uint256(sqrtPriceX96) * uint256(sqrtPriceX96), 1 << 192);
            uint256 valueInToken1 = token0ValueInToken1 + token1Quantity;

            stats[i] = LensRatioUtils.PositionStats({
                tickLower: ranges[i].lowerTick,
                tickUpper: ranges[i].upperTick,
                sqrtPriceLower: sqrtPriceLowerX96,
                sqrtPriceUpper: sqrtPriceUpperX96,
                liquidity: uint128(positionData[i].liquidity),
                token0Quantity: token0Quantity,
                token1Quantity: token1Quantity,
                valueInToken1: valueInToken1,
                isLimit: i >= baseLen
            });
        }
    }

    // ============================================
    // Internal Functions
    // ============================================

    function _validateParams(uint256 weight0, uint256 weight1, bool useCarpet) private pure {
        bool isProportional = (weight0 == 0 && weight1 == 0);
        bool isFiftyFifty = (weight0 == 0.5e18 && weight1 == 0.5e18);

        if (!isProportional && !isFiftyFifty) {
            revert InvalidWeights();
        }

        if (!useCarpet) {
            revert CarpetRequired();
        }
    }

    function _getAmountsForInitialDeposit(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositParams calldata params
    ) private view returns (uint256 otherAmount, uint256[2][] memory inMin, RebalancePreview memory preview) {
        if (params.strategyAddress == address(0)) revert NoStrategySpecified();
        if (params.amount == 0) revert InvalidAmount();

        RangeGenParams memory genParams;
        genParams.poolKey = poolKey;
        genParams.sqrtPriceX96 = sqrtPriceX96;
        genParams.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
        genParams.resolvedCenterTick = _resolveCenterTick(params.centerTick, genParams.currentTick, poolKey.tickSpacing);

        // Calculate other amount needed
        otherAmount = _calculateOtherAmount(poolKey, sqrtPriceX96, genParams.resolvedCenterTick, params);

        // Calculate final amounts
        genParams.amount0 = params.isToken0 ? params.amount : otherAmount;
        genParams.amount1 = params.isToken0 ? otherAmount : params.amount;

        // Generate ranges and liquidities
        (IMultiPositionManager.Range[] memory allRanges, uint128[] memory allLiquidities) =
            _generateRangesAndLiquidities(genParams, params);

        // Calculate inMin
        inMin = _calculateInMin(allRanges, allLiquidities, sqrtPriceX96, params.maxSlippageBps);

        // Build preview
        preview.strategy = params.strategyAddress;
        preview.centerTick = genParams.resolvedCenterTick;
        preview.ticksLeft = params.ticksLeft;
        preview.ticksRight = params.ticksRight;
        preview.ranges = allRanges;
        preview.liquidities = allLiquidities;

        _calculateExpectedTotals(sqrtPriceX96, preview, params.limitWidth);
    }

    function _previewCustomInitialDeposit(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        CustomInitialDepositParams calldata params
    ) private view returns (uint256[2][] memory inMin, RebalancePreview memory preview) {
        if (params.strategyAddress == address(0)) revert NoStrategySpecified();

        RangeGenParams memory genParams;
        genParams.poolKey = poolKey;
        genParams.sqrtPriceX96 = sqrtPriceX96;
        genParams.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
        genParams.resolvedCenterTick = _resolveCenterTick(params.centerTick, genParams.currentTick, poolKey.tickSpacing);
        genParams.amount0 = params.deposit0;
        genParams.amount1 = params.deposit1;

        // Convert params
        InitialDepositParams memory depositParams = InitialDepositParams({
            strategyAddress: params.strategyAddress,
            centerTick: params.centerTick,
            ticksLeft: params.ticksLeft,
            ticksRight: params.ticksRight,
            limitWidth: params.limitWidth,
            weight0: params.weight0,
            weight1: params.weight1,
            useCarpet: params.useCarpet,
            isToken0: true,
            amount: params.deposit0,
            maxSlippageBps: params.maxSlippageBps
        });

        // Generate ranges and liquidities
        (IMultiPositionManager.Range[] memory allRanges, uint128[] memory allLiquidities) =
            _generateRangesAndLiquidities(genParams, depositParams);

        // Calculate inMin
        inMin = _calculateInMin(allRanges, allLiquidities, sqrtPriceX96, params.maxSlippageBps);

        // Build preview
        preview.strategy = params.strategyAddress;
        preview.centerTick = genParams.resolvedCenterTick;
        preview.ticksLeft = params.ticksLeft;
        preview.ticksRight = params.ticksRight;
        preview.ranges = allRanges;
        preview.liquidities = allLiquidities;

        _calculateExpectedTotals(sqrtPriceX96, preview, params.limitWidth);
    }

    function _getAmountsForInitialDepositWithSwap(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositWithSwapParams calldata params
    )
        private
        view
        returns (
            uint256 finalAmount0,
            uint256 finalAmount1,
            LensRatioUtils.SwapParams memory swapParams,
            uint256[2][] memory inMin,
            RebalancePreview memory preview
        )
    {
        if (params.strategyAddress == address(0)) revert NoStrategySpecified();

        // Calculate swap parameters
        (swapParams, finalAmount0, finalAmount1) = _calculateSwapParams(poolKey, sqrtPriceX96, params);

        // Generate preview and inMin
        (inMin, preview) = _buildSwapPreview(poolKey, sqrtPriceX96, params, finalAmount0, finalAmount1);
    }

    function _calculateSwapParams(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositWithSwapParams calldata params
    ) private view returns (LensRatioUtils.SwapParams memory swapParams, uint256 finalAmount0, uint256 finalAmount1) {
        int24 currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
        int24 resolvedCenterTick = _resolveCenterTick(params.centerTick, currentTick, poolKey.tickSpacing);

        // Calculate target weights from strategy
        (swapParams.weight0, swapParams.weight1) = _calculateTargetWeightsInternal(
            params.strategyAddress,
            resolvedCenterTick,
            params.ticksLeft,
            params.ticksRight,
            poolKey.tickSpacing,
            params.useCarpet,
            sqrtPriceX96,
            currentTick,
            params.weight0,
            params.weight1
        );

        // Calculate and apply swap
        (swapParams.swapToken0, swapParams.swapAmount) =
            RebalanceLogic.calculateOptimalSwap(params.deposit0, params.deposit1, sqrtPriceX96, swapParams.weight0, swapParams.weight1);

        (finalAmount0, finalAmount1) =
            _applySwap(params.deposit0, params.deposit1, swapParams.swapToken0, swapParams.swapAmount, sqrtPriceX96);
    }

    function _buildSwapPreview(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        InitialDepositWithSwapParams calldata params,
        uint256 finalAmount0,
        uint256 finalAmount1
    ) private view returns (uint256[2][] memory inMin, RebalancePreview memory preview) {
        RangeGenParams memory genParams;
        genParams.poolKey = poolKey;
        genParams.sqrtPriceX96 = sqrtPriceX96;
        genParams.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
        genParams.resolvedCenterTick = _resolveCenterTick(params.centerTick, genParams.currentTick, poolKey.tickSpacing);
        genParams.amount0 = finalAmount0;
        genParams.amount1 = finalAmount1;

        InitialDepositParams memory depositParams = InitialDepositParams({
            strategyAddress: params.strategyAddress,
            centerTick: params.centerTick,
            ticksLeft: params.ticksLeft,
            ticksRight: params.ticksRight,
            limitWidth: params.limitWidth,
            weight0: params.weight0,
            weight1: params.weight1,
            useCarpet: params.useCarpet,
            isToken0: true,
            amount: finalAmount0,
            maxSlippageBps: params.maxSlippageBps
        });

        (IMultiPositionManager.Range[] memory allRanges, uint128[] memory allLiquidities) =
            _generateRangesAndLiquidities(genParams, depositParams);

        inMin = _calculateInMin(allRanges, allLiquidities, sqrtPriceX96, params.maxSlippageBps);

        preview.strategy = params.strategyAddress;
        preview.centerTick = genParams.resolvedCenterTick;
        preview.ticksLeft = params.ticksLeft;
        preview.ticksRight = params.ticksRight;
        preview.ranges = allRanges;
        preview.liquidities = allLiquidities;

        _calculateExpectedTotals(sqrtPriceX96, preview, params.limitWidth);
    }

    function _resolveCenterTick(int24 centerTick, int24 currentTick, int24 tickSpacing) private pure returns (int24) {
        int24 baseTick = centerTick == type(int24).max ? currentTick : centerTick;
        int24 compressed = baseTick / tickSpacing;
        if (baseTick < 0 && baseTick % tickSpacing != 0) {
            compressed--;
        }
        return compressed * tickSpacing;
    }

    struct OtherAmountCalcData {
        int24[] lowerTicks;
        int24[] upperTicks;
        uint256[] weights;
        int24 currentTick;
        uint256 totalWeightedToken0;
        uint256 totalWeightedToken1;
    }

    struct RangeWeights {
        IMultiPositionManager.Range[] baseRanges;
        uint256[] weights;
    }

    function _calculateOtherAmount(
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        int24 resolvedCenterTick,
        InitialDepositParams calldata params
    ) private view returns (uint256 otherAmount) {
        OtherAmountCalcData memory data;
        data.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);

        // Generate ranges
        ILiquidityStrategy strategy = ILiquidityStrategy(params.strategyAddress);
        (data.lowerTicks, data.upperTicks) = strategy.generateRanges(
            resolvedCenterTick, params.ticksLeft, params.ticksRight, poolKey.tickSpacing, params.useCarpet
        );

        // Get weights
        data.weights = _calculateWeightsForOtherAmount(strategy, data, params, resolvedCenterTick, poolKey.tickSpacing);

        // Calculate totals
        (data.totalWeightedToken0, data.totalWeightedToken1) = _sumWeightedTotals(data, sqrtPriceX96);

        // Calculate other amount
        otherAmount = _computeOtherAmount(params, data.totalWeightedToken0, data.totalWeightedToken1);
    }

    function _calculateWeightsForOtherAmount(
        ILiquidityStrategy strategy,
        OtherAmountCalcData memory data,
        InitialDepositParams calldata params,
        int24 resolvedCenterTick,
        int24 tickSpacing
    ) private view returns (uint256[] memory) {
        bool useAssetWeights = (params.weight0 == 0 && params.weight1 == 0);
        uint256[] memory weights = strategy.calculateDensities(
            data.lowerTicks,
            data.upperTicks,
            data.currentTick,
            resolvedCenterTick,
            params.ticksLeft,
            params.ticksRight,
            params.weight0,
            params.weight1,
            params.useCarpet,
            tickSpacing,
            useAssetWeights
        );
        return RebalanceLogic.adjustWeightsForFullRangeFloor(
            weights, data.lowerTicks, data.upperTicks, tickSpacing, params.useCarpet
        );
    }

    function _sumWeightedTotals(OtherAmountCalcData memory data, uint160 sqrtPriceX96)
        private pure returns (uint256 totalWeightedToken0, uint256 totalWeightedToken1)
    {
        for (uint256 i = 0; i < data.lowerTicks.length; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(data.lowerTicks[i]);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(data.upperTicks[i]);

            (uint256 amount0For1e18, uint256 amount1For1e18) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);

            totalWeightedToken0 += (amount0For1e18 * data.weights[i]) / 1e18;
            totalWeightedToken1 += (amount1For1e18 * data.weights[i]) / 1e18;
        }
    }

    function _computeOtherAmount(InitialDepositParams calldata params, uint256 totalWeightedToken0, uint256 totalWeightedToken1)
        private pure returns (uint256 otherAmount)
    {
        if (params.isToken0) {
            if (totalWeightedToken0 == 0) {
                otherAmount = 0;
            } else {
                otherAmount = FullMath.mulDiv(params.amount, totalWeightedToken1, totalWeightedToken0);
            }
        } else {
            if (totalWeightedToken1 == 0) {
                otherAmount = 0;
            } else {
                otherAmount = FullMath.mulDiv(params.amount, totalWeightedToken0, totalWeightedToken1);
            }
        }
    }

    function _generateRangesAndLiquidities(
        RangeGenParams memory genParams,
        InitialDepositParams memory params
    ) private view returns (IMultiPositionManager.Range[] memory allRanges, uint128[] memory allLiquidities) {
        // Build strategy context
        RebalanceLogic.StrategyContext memory ctx = RebalanceLogic.StrategyContext({
            resolvedStrategy: params.strategyAddress,
            center: genParams.resolvedCenterTick,
            tLeft: params.ticksLeft,
            tRight: params.ticksRight,
            strategy: ILiquidityStrategy(params.strategyAddress),
            weight0: params.weight0,
            weight1: params.weight1,
            useCarpet: params.useCarpet,
            limitWidth: params.limitWidth,
            useAssetWeights: (params.weight0 == 0 && params.weight1 == 0)
        });

        // Generate base ranges using internal helper
        (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory baseLiquidities) =
            _generateRangesAndLiquiditiesWithSqrtPrice(genParams.poolKey, ctx, genParams.amount0, genParams.amount1, genParams.sqrtPriceX96);

        // Add limit positions if needed
        if (params.limitWidth > 0) {
            (IMultiPositionManager.Range memory lowerLimit, IMultiPositionManager.Range memory upperLimit) =
                PositionLogic.calculateLimitRanges(params.limitWidth, baseRanges, genParams.poolKey.tickSpacing, genParams.currentTick);

            allRanges = new IMultiPositionManager.Range[](baseRanges.length + 2);
            allLiquidities = new uint128[](baseRanges.length + 2);

            for (uint256 i = 0; i < baseRanges.length; i++) {
                allRanges[i] = baseRanges[i];
                allLiquidities[i] = baseLiquidities[i];
            }

            // Calculate remainders
            (uint256 remainderToken0, uint256 remainderToken1) =
                _calculateRemainders(baseRanges, baseLiquidities, genParams.sqrtPriceX96, genParams.amount0, genParams.amount1);

            // Add limit positions
            allRanges[baseRanges.length] = lowerLimit;
            allRanges[baseRanges.length + 1] = upperLimit;

            // Lower limit gets remainder token1
            if (lowerLimit.lowerTick != lowerLimit.upperTick && remainderToken1 > 0) {
                allLiquidities[baseRanges.length] = LiquidityAmounts.getLiquidityForAmounts(
                    genParams.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(lowerLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(lowerLimit.upperTick),
                    0,
                    remainderToken1
                );
            }

            // Upper limit gets remainder token0
            if (upperLimit.lowerTick != upperLimit.upperTick && remainderToken0 > 0) {
                allLiquidities[baseRanges.length + 1] = LiquidityAmounts.getLiquidityForAmounts(
                    genParams.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(upperLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(upperLimit.upperTick),
                    remainderToken0,
                    0
                );
            }
        } else {
            allRanges = baseRanges;
            allLiquidities = baseLiquidities;
        }
    }

    function _calculateRemainders(
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory baseLiquidities,
        uint160 sqrtPriceX96,
        uint256 amount0,
        uint256 amount1
    ) private pure returns (uint256 remainderToken0, uint256 remainderToken1) {
        uint256 consumedToken0;
        uint256 consumedToken1;
        for (uint256 i = 0; i < baseRanges.length; i++) {
            (uint256 amt0, uint256 amt1) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96,
                TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick),
                TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick),
                baseLiquidities[i]
            );
            consumedToken0 += amt0;
            consumedToken1 += amt1;
        }
        remainderToken0 = amount0 > consumedToken0 ? amount0 - consumedToken0 : 0;
        remainderToken1 = amount1 > consumedToken1 ? amount1 - consumedToken1 : 0;
    }

    function _calculateInMin(
        IMultiPositionManager.Range[] memory ranges,
        uint128[] memory liquidities,
        uint160 sqrtPriceX96,
        uint256 maxSlippageBps
    ) private pure returns (uint256[2][] memory inMin) {
        inMin = new uint256[2][](ranges.length);
        uint256 slippageMultiplier = 10000 - maxSlippageBps;

        for (uint256 i = 0; i < ranges.length; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

            (uint256 amt0, uint256 amt1) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, liquidities[i]);

            inMin[i] =
                [FullMath.mulDiv(amt0, slippageMultiplier, 10000), FullMath.mulDiv(amt1, slippageMultiplier, 10000)];
        }
    }

    function _calculateExpectedTotals(uint160 sqrtPriceX96, RebalancePreview memory preview, uint24 limitWidth)
        private
        pure
    {
        preview.expectedPositions = new LensRatioUtils.PositionStats[](preview.ranges.length);
        preview.expectedTotal0 = 0;
        preview.expectedTotal1 = 0;

        uint256 baseLength =
            limitWidth > 0 && preview.ranges.length >= 2 ? preview.ranges.length - 2 : preview.ranges.length;

        for (uint256 i = 0; i < preview.ranges.length; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(preview.ranges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(preview.ranges[i].upperTick);

            (uint256 amt0, uint256 amt1) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, preview.liquidities[i]
            );

            uint256 valueInToken1 = amt1 + FullMath.mulDiv(amt0, uint256(sqrtPriceX96) * uint256(sqrtPriceX96), 1 << 192);

            preview.expectedPositions[i] = LensRatioUtils.PositionStats({
                tickLower: preview.ranges[i].lowerTick,
                tickUpper: preview.ranges[i].upperTick,
                sqrtPriceLower: sqrtPriceLower,
                sqrtPriceUpper: sqrtPriceUpper,
                liquidity: preview.liquidities[i],
                token0Quantity: amt0,
                token1Quantity: amt1,
                valueInToken1: valueInToken1,
                isLimit: i >= baseLength
            });

            preview.expectedTotal0 += amt0;
            preview.expectedTotal1 += amt1;
        }
    }

    function _calculateTargetWeights(
        address strategyAddress,
        int24 resolvedCenterTick,
        uint24 ticksLeft,
        uint24 ticksRight,
        int24 tickSpacing,
        bool useCarpet,
        uint160 sqrtPriceX96,
        int24 currentTick,
        uint256 weight0,
        uint256 weight1
    ) private view returns (uint256, uint256) {
        if (weight0 != 0 || weight1 != 0) {
            return (weight0, weight1);
        }

        return RebalanceLogic.calculateWeightsFromStrategy(
            ILiquidityStrategy(strategyAddress),
            resolvedCenterTick,
            ticksLeft,
            ticksRight,
            tickSpacing,
            useCarpet,
            sqrtPriceX96,
            currentTick
        );
    }

    // Alias to avoid stack too deep
    function _calculateTargetWeightsInternal(
        address strategyAddress,
        int24 resolvedCenterTick,
        uint24 ticksLeft,
        uint24 ticksRight,
        int24 tickSpacing,
        bool useCarpet,
        uint160 sqrtPriceX96,
        int24 currentTick,
        uint256 weight0,
        uint256 weight1
    ) private view returns (uint256, uint256) {
        return _calculateTargetWeights(
            strategyAddress, resolvedCenterTick, ticksLeft, ticksRight,
            tickSpacing, useCarpet, sqrtPriceX96, currentTick, weight0, weight1
        );
    }

    function _applySwap(uint256 amount0, uint256 amount1, bool swapToken0, uint256 swapAmount, uint160 sqrtPriceX96)
        private
        pure
        returns (uint256 finalAmount0, uint256 finalAmount1)
    {
        if (swapAmount == 0) {
            return (amount0, amount1);
        }

        if (swapToken0) {
            uint256 estimatedOut = FullMath.mulDiv(
                FullMath.mulDiv(swapAmount, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
            );
            finalAmount0 = amount0 - swapAmount;
            finalAmount1 = amount1 + estimatedOut;
        } else {
            uint256 estimatedOut = FullMath.mulDiv(
                FullMath.mulDiv(swapAmount, 1 << 96, uint256(sqrtPriceX96)), 1 << 96, uint256(sqrtPriceX96)
            );
            finalAmount0 = amount0 + estimatedOut;
            finalAmount1 = amount1 - swapAmount;
        }
    }

    /**
     * @notice Generate ranges and liquidities for initial deposit with provided sqrtPriceX96
     * @dev Used for both initialized and uninitialized pools
     */
    function _generateRangesAndLiquiditiesWithSqrtPrice(
        PoolKey memory poolKey,
        RebalanceLogic.StrategyContext memory ctx,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96
    ) private view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
        RangeWeights memory data = _buildRangesAndWeights(poolKey, ctx, sqrtPriceX96);
        baseRanges = data.baseRanges;

        // Calculate liquidities from weights
        liquidities = _calculateLiquiditiesWithContext(data, poolKey, ctx, amount0, amount1, sqrtPriceX96);
    }

    function _buildRangesAndWeights(
        PoolKey memory poolKey,
        RebalanceLogic.StrategyContext memory ctx,
        uint160 sqrtPriceX96
    ) private view returns (RangeWeights memory data) {
        int24 currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);
        int24 tickSpacing = poolKey.tickSpacing;

        (int24[] memory lowerTicks, int24[] memory upperTicks) =
            ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, tickSpacing, ctx.useCarpet);

        data.baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
        for (uint256 i = 0; i < lowerTicks.length; i++) {
            data.baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
        }

        RebalanceLogic.DensityParams memory params;
        params.lowerTicks = lowerTicks;
        params.upperTicks = upperTicks;
        params.tick = currentTick;
        params.center = ctx.center;
        params.tLeft = ctx.tLeft;
        params.tRight = ctx.tRight;
        params.weight0 = ctx.weight0;
        params.weight1 = ctx.weight1;
        params.useCarpet = ctx.useCarpet;
        params.tickSpacing = tickSpacing;

        data.weights = _calculateAdjustedWeights(ctx.strategy, params, ctx.useAssetWeights);
    }

    function _calculateAdjustedWeights(
        ILiquidityStrategy strategy,
        RebalanceLogic.DensityParams memory params,
        bool useAssetWeights
    ) private view returns (uint256[] memory) {
        uint256[] memory weights = strategy.calculateDensities(
            params.lowerTicks,
            params.upperTicks,
            params.tick,
            params.center,
            params.tLeft,
            params.tRight,
            params.weight0,
            params.weight1,
            params.useCarpet,
            params.tickSpacing,
            useAssetWeights
        );
        return RebalanceLogic.adjustWeightsForFullRangeFloor(
            weights, params.lowerTicks, params.upperTicks, params.tickSpacing, params.useCarpet
        );
    }

    /**
     * @notice Calculate liquidities for each position based on weights
     */
    function _calculateLiquiditiesFromWeights(
        uint128[] memory liquidities,
        uint256[] memory weights,
        IMultiPositionManager.Range[] memory baseRanges,
        RebalanceLogic.LiquidityCalcParams memory params
    ) private pure {
        uint256 rangesLength = baseRanges.length;
        if (rangesLength == 0) return;

        // Build allocation data
        RebalanceLogic.AllocationData memory data;
        data.token0Allocations = new uint256[](rangesLength);
        data.token1Allocations = new uint256[](rangesLength);
        data.currentTick = TickMath.getTickAtSqrtPrice(params.sqrtPriceX96);

        // Step 1: Calculate initial allocations based on weights
        RebalanceLogic.calculateInitialAllocations(data, baseRanges, weights, params.sqrtPriceX96, false, 1);

        // Step 2: Scale allocations proportionally
        RebalanceLogic.scaleAllocations(data, params.amount0, params.amount1, params.useAssetWeights);

        // Step 3: Fix current range and redistribute (only for proportional weights)
        if (params.useAssetWeights && data.hasCurrentRange) {
            RebalanceLogic.fixCurrentRangeAndRedistribute(data, baseRanges, params.sqrtPriceX96);
        }

        // Step 4: Convert allocations to liquidities
        for (uint256 i = 0; i < rangesLength; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);

            liquidities[i] = LiquidityAmounts.getLiquidityForAmounts(
                params.sqrtPriceX96,
                sqrtPriceLower,
                sqrtPriceUpper,
                data.token0Allocations[i],
                data.token1Allocations[i]
            );
        }
    }

    function _calculateLiquiditiesForRanges(
        IMultiPositionManager.Range[] memory baseRanges,
        uint256[] memory weights,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        bool useAssetWeights,
        int24 tickSpacing,
        bool useCarpet
    ) private pure returns (uint128[] memory liquidities) {
        liquidities = new uint128[](baseRanges.length);
        RebalanceLogic.LiquidityCalcParams memory calcParams = RebalanceLogic.LiquidityCalcParams({
            amount0: amount0,
            amount1: amount1,
            sqrtPriceX96: sqrtPriceX96,
            useAssetWeights: useAssetWeights,
            tickSpacing: tickSpacing,
            useCarpet: useCarpet
        });

        _calculateLiquiditiesFromWeights(liquidities, weights, baseRanges, calcParams);
    }

    function _calculateLiquiditiesWithContext(
        RangeWeights memory data,
        PoolKey memory poolKey,
        RebalanceLogic.StrategyContext memory ctx,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96
    ) private pure returns (uint128[] memory) {
        return _calculateLiquiditiesForRanges(
            data.baseRanges,
            data.weights,
            amount0,
            amount1,
            sqrtPriceX96,
            ctx.useAssetWeights,
            poolKey.tickSpacing,
            ctx.useCarpet
        );
    }
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {SafeCallback} from "v4-periphery/src/base/SafeCallback.sol";

import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "./interfaces/IMultiPositionFactory.sol";
import {PoolManagerUtils} from "./libraries/PoolManagerUtils.sol";
import {Multicall} from "./base/Multicall.sol";
import {SharedStructs} from "./base/SharedStructs.sol";
import {RebalanceLogic} from "./libraries/RebalanceLogic.sol";
import {RebalanceSwapLogic} from "./libraries/RebalanceSwapLogic.sol";
import {WithdrawLogic} from "./libraries/WithdrawLogic.sol";
import {DepositLogic} from "./libraries/DepositLogic.sol";
import {PositionLogic} from "./libraries/PositionLogic.sol";
import {MultiPositionFactory} from "./MultiPositionFactory.sol";
import {VolatilityDynamicFeeLimitOrderHook} from "../LimitOrderBook/hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "../LimitOrderBook/libraries/VolatilityOracle.sol";

contract MultiPositionManager is IMultiPositionManager, ERC20, ReentrancyGuard, Ownable, SafeCallback, Multicall {
    using SafeERC20 for IERC20;
    using StateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;

    uint256 public constant PRECISION = 1e36;
    event RelayerGranted(address indexed account);
    event RelayerRevoked(address indexed account);

    SharedStructs.ManagerStorage internal s;

    uint256 public immutable deployedAt;
    address public immutable unilaunchFactory;

    error UnauthorizedCaller();
    error InvalidAction();
    error OnlyOneNativeDepositPerMulticall();
    error WithdrawalsDisabled();
    error CompoundingDisabled();
    error RebalanceSwapLocked(uint256 unlockTimestamp);
    error InvalidRebalanceParams();

    event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event Burn(address indexed sender, uint256 shares, uint256 totalSupply, uint256 amount0, uint256 amount1);

    event WithdrawCustom(
        address indexed sender, address indexed to, uint256 shares, uint256 amount0Out, uint256 amount1Out
    );
    event FeeChanged(uint16 newFee);

    /**
     * @notice Constructor for MultiPositionManager
     * @dev Sets all immutable values and initializes the contract
     * @param _poolManager The Uniswap V4 pool manager
     * @param _poolKey The pool key defining the pool
     * @param _owner The owner address
     * @param _factory The factory address
     * @param _name Token name
     * @param _symbol Token symbol
     * @param _fee The protocol fee denominator
     */
    constructor(
        IPoolManager _poolManager,
        PoolKey memory _poolKey,
        address _owner,
        address _factory,
        string memory _name,
        string memory _symbol,
        uint16 _fee
    ) ERC20(_name, _symbol) Ownable(_owner) SafeCallback(_poolManager) {
        s.poolKey = _poolKey;
        s.poolId = _poolKey.toId();
        s.currency0 = _poolKey.currency0;
        s.currency1 = _poolKey.currency1;
        s.factory = _factory;
        s.fee = _fee;
        deployedAt = block.timestamp;
        unilaunchFactory = _factory;
    }

    function poolKey() external view returns (PoolKey memory) {
        return s.poolKey;
    }

    function fee() external view returns (uint16) {
        return s.fee;
    }

    function factory() external view returns (address) {
        return s.factory;
    }

    function basePositionsLength() external view returns (uint256) {
        return s.basePositionsLength;
    }

    function limitPositions(uint256 index) external view returns (Range memory) {
        return s.limitPositions[index];
    }

    function limitPositionsLength() external view returns (uint256) {
        return s.limitPositionsLength;
    }

    function lastStrategyParams()
        external
        view
        returns (
            address strategy,
            int24 centerTick,
            uint24 ticksLeft,
            uint24 ticksRight,
            uint24 limitWidth,
            uint120 weight0,
            uint120 weight1,
            bool useCarpet,
            bool useSwap,
            bool useAssetWeights
        )
    {
        SharedStructs.StrategyParams memory params = s.lastStrategyParams;
        return (
            params.strategy,
            params.centerTick,
            params.ticksLeft,
            params.ticksRight,
            params.limitWidth,
            params.weight0,
            params.weight1,
            params.useCarpet,
            params.useSwap,
            params.useAssetWeights
        );
    }

    function isRelayer(address account) public view returns (bool) {
        return s.relayers[account];
    }

    modifier onlyOwnerOrFactory() {
        require(msg.sender == owner() || msg.sender == s.factory);
        _;
    }

    modifier onlyOwnerOrRelayerOrFactory() {
        require(msg.sender == owner() || s.relayers[msg.sender] || msg.sender == s.factory);
        _;
    }

    receive() external payable {}

    /**
     * @notice Deposit tokens to vault (idle balance). Use compound() to add to positions.
     * @param deposit0Desired Maximum amount of token0 to deposit
     * @param deposit1Desired Maximum amount of token1 to deposit
     * @param to Address to receive shares
     * @param from Address to pull tokens from
     * @return shares Number of shares minted
     * @return deposit0 Actual amount of token0 deposited
     * @return deposit1 Actual amount of token1 deposited
     * @dev Tokens are pulled from 'from' and shares are minted to 'to'
     */
    function deposit(uint256 deposit0Desired, uint256 deposit1Desired, address to, address from)
        external
        payable
        onlyOwnerOrFactory
        nonReentrant
        returns (uint256 shares, uint256 deposit0, uint256 deposit1)
    {
        (shares, deposit0, deposit1) = DepositLogic.processDeposit(
            s,
            poolManager,
            deposit0Desired,
            deposit1Desired,
            to, // shares minted to 'to'
            from, // tokens pulled from 'from'
            totalSupply(),
            msg.value
        );

        _mint(to, shares);
        _transferIn(from, s.currency0, deposit0);
        _transferIn(from, s.currency1, deposit1);
    }

    /**
     * @notice Compound idle vault balance + fees into existing positions
     * @dev Collects fees via zeroBurn, then adds all idle balance to positions
     *      Marked payable for multicall compatibility - msg.value persists across delegatecalls.
     *      Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
     * @param inMin Minimum amounts for each position (slippage protection)
     */
    function compound(uint256[2][] calldata inMin) external payable onlyOwnerOrRelayerOrFactory {
        inMin;
        revert CompoundingDisabled();
    }

    /**
     * @notice Compound with swap: collect fees, swap to target ratio, then add to positions
     * @param swapParams Swap parameters for DEX aggregator execution
     * @param inMin Minimum amounts per position for slippage protection
     */
    function compoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
        external
        payable
        onlyOwnerOrRelayerOrFactory
    {
        swapParams;
        inMin;
        revert CompoundingDisabled();
    }

    /**
     * @notice Withdraw shares from the vault
     * @param shares Number of liquidity tokens to redeem as pool assets
     * @param outMin min amount returned for shares of liq
     * @param withdrawToWallet If true, transfers tokens to owner and burns shares. If false, keeps tokens in contract and preserves shares.
     * @return amount0 Amount of token0 redeemed by the submitted liquidity tokens
     * @return amount1 Amount of token1 redeemed by the submitted liquidity tokens
     * @dev Tokens are always sent to owner
     */
    function withdraw(uint256 shares, uint256[2][] memory outMin, bool withdrawToWallet)
        external
        nonReentrant
        onlyOwnerOrRelayerOrFactory
        returns (uint256 amount0, uint256 amount1)
    {
        shares;
        outMin;
        withdrawToWallet;
        amount0;
        amount1;
        revert WithdrawalsDisabled();
    }

    /**
     * @notice Withdraw custom amounts of both tokens
     * @param amount0Desired Amount of token0 to withdraw
     * @param amount1Desired Amount of token1 to withdraw
     * @param outMin Minimum amounts per position for slippage protection
     * @return amount0Out Amount of token0 withdrawn
     * @return amount1Out Amount of token1 withdrawn
     * @return sharesBurned Number of shares burned
     * @dev Tokens are always sent to owner
     */
    function withdrawCustom(uint256 amount0Desired, uint256 amount1Desired, uint256[2][] memory outMin)
        external
        nonReentrant
        onlyOwnerOrRelayerOrFactory
        returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned)
    {
        amount0Desired;
        amount1Desired;
        outMin;
        amount0Out;
        amount1Out;
        sharesBurned;
        revert WithdrawalsDisabled();
    }

    /**
     * @notice Unified rebalance function with optional weighted token distribution
     * @param params Rebalance parameters including optional weights
     * @param outMin Minimum output amounts for withdrawals
     * @param inMin Minimum input amounts for new positions (slippage protection)
     * @dev If weights are not specified or are both 0, defaults to 50/50 distribution
     *      Marked payable for multicall compatibility - msg.value persists across delegatecalls.
     *      Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
     */
    function rebalance(
        IMultiPositionManager.RebalanceParams calldata params,
        uint256[2][] memory outMin,
        uint256[2][] memory inMin
    ) public payable onlyOwnerOrRelayerOrFactory {
        _enforceRebalanceParams(params, false);
        // First call ZERO_BURN to collect fees (like compound does)
        if (s.basePositionsLength > 0 || s.limitPositionsLength > 0) {
            poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
        }

        // Now fees are in balanceOfSelf(), so liquidities will be calculated correctly
        (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth) =
            RebalanceLogic.rebalance(s, poolManager, params, outMin);

        bytes memory encodedParams = abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin, params);
        poolManager.unlock(abi.encode(IMultiPositionManager.Action.REBALANCE, encodedParams));
    }

    /**
     * @notice Rebalances positions with an external DEX swap to achieve target weights
     * @param params Swap and rebalance parameters including aggregator address and swap data
     * @param outMin Minimum output amounts for burning current positions
     * @param inMin Minimum input amounts for new positions (slippage protection)
     * @dev Burns all positions first, then swaps to target ratio, then rebalances with new amounts
     */
    function rebalanceSwap(
        IMultiPositionManager.RebalanceSwapParams calldata params,
        uint256[2][] memory outMin,
        uint256[2][] memory inMin
    ) public payable onlyOwnerOrRelayerOrFactory {
        _enforceRebalanceParams(params.rebalanceParams, true);
        if (totalSupply() > 0 && (s.basePositionsLength > 0 || s.limitPositionsLength > 0)) {
            poolManager.unlock(abi.encode(IMultiPositionManager.Action.BURN_ALL, abi.encode(outMin)));
        }

        (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth) =
            RebalanceSwapLogic.executeSwapAndCalculateRanges(s, poolManager, params);

        bytes memory encodedParams =
            abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin, params.rebalanceParams);
        poolManager.unlock(abi.encode(IMultiPositionManager.Action.REBALANCE, encodedParams));
    }

    /**
     * @notice Claims fees
     * @dev If called by owner or relayer, performs zeroBurn and claims fees (owner fees go to owner)
     * @dev If called by factory owner or CLAIM_MANAGER, only claims existing protocol fees
     */
    function claimFee() external {
        if (msg.sender == owner() || s.relayers[msg.sender]) {
            // Owner or relayer calling - collect fees and transfer owner portion to owner
            poolManager.unlock(abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(owner())));
        } else if (
            IMultiPositionFactory(s.factory).hasRoleOrOwner(
                IMultiPositionFactory(s.factory).CLAIM_MANAGER(), msg.sender
            )
        ) {
            // CLAIM_MANAGER calling - only claim protocol fees
            poolManager.unlock(abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(address(0))));
        } else {
            revert UnauthorizedCaller();
        }
    }

    function setFee(uint16 newFee) external {
        IMultiPositionFactory factoryContract = IMultiPositionFactory(s.factory);
        require(factoryContract.hasRole(factoryContract.FEE_MANAGER(), msg.sender));
        require(newFee != 0, "Fee cannot be zero");
        s.fee = newFee;
        emit FeeChanged(newFee);
    }

    /**
     * @notice Grant relayer role to an address
     * @param account The address to grant the role to
     */
    function grantRelayerRole(address account) external onlyOwner {
        require(account != address(0));
        if (!s.relayers[account]) {
            s.relayers[account] = true;
            emit RelayerGranted(account);
        }
    }

    /**
     * @notice Revoke relayer role from an address
     * @param account The address to revoke the role from
     */
    function revokeRelayerRole(address account) external onlyOwner {
        if (s.relayers[account]) {
            s.relayers[account] = false;
            emit RelayerRevoked(account);
        }
    }

    function getBasePositions() public view returns (Range[] memory, PositionData[] memory) {
        return PositionLogic.getBasePositions(s, poolManager);
    }

    function getPositions() public view returns (Range[] memory, PositionData[] memory) {
        return PositionLogic.getPositions(s, poolManager);
    }

    function getTotalAmounts()
        external
        view
        returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1)
    {
        return WithdrawLogic.getTotalAmounts(s, poolManager);
    }

    function getTotalValuesInOneToken()
        external
        view
        returns (uint256 totalValueInToken0, uint256 totalValueInToken1)
    {
        return PositionLogic.getTotalValuesInOneToken(s, poolManager);
    }

    function currentTick() public view returns (int24 tick) {
        (, tick,,) = poolManager.getSlot0(s.poolKey.toId());
    }

    function getRatios()
        external
        view
        returns (
            uint256 pool0Ratio,
            uint256 pool1Ratio,
            uint256 total0Ratio,
            uint256 total1Ratio,
            uint256 inPositionRatio,
            uint256 outOfPositionRatio,
            uint256 baseRatio,
            uint256 limitRatio,
            uint256 base0Ratio,
            uint256 base1Ratio,
            uint256 limit0Ratio,
            uint256 limit1Ratio
        )
    {
        PositionLogic.Ratios memory ratios = PositionLogic.getRatios(s, poolManager);
        return (
            ratios.pool0Ratio,
            ratios.pool1Ratio,
            ratios.total0Ratio,
            ratios.total1Ratio,
            ratios.inPositionRatio,
            ratios.outOfPositionRatio,
            ratios.baseRatio,
            ratios.limitRatio,
            ratios.base0Ratio,
            ratios.base1Ratio,
            ratios.limit0Ratio,
            ratios.limit1Ratio
        );
    }

    function _unlockCallback(bytes calldata data) internal override returns (bytes memory) {
        (Action selector, bytes memory params) = abi.decode(data, (Action, bytes));
        bytes memory result = _executeActionWithoutUnlock(selector, params);
        _closePair();
        return result;
    }

    function _executeActionWithoutUnlock(Action selector, bytes memory params) internal returns (bytes memory result) {
        if (selector == IMultiPositionManager.Action.WITHDRAW) {
            revert WithdrawalsDisabled();
        } else if (selector == IMultiPositionManager.Action.REBALANCE) {
            return RebalanceLogic.processRebalanceInCallback(s, poolManager, params, totalSupply());
        } else if (selector == IMultiPositionManager.Action.ZERO_BURN) {
            WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);
            return "";
        } else if (selector == IMultiPositionManager.Action.CLAIM_FEE) {
            address caller = abi.decode(params, (address));
            WithdrawLogic.processClaimFee(s, poolManager, caller, owner());
            return "";
        } else if (selector == IMultiPositionManager.Action.BURN_ALL) {
            return WithdrawLogic.processBurnAllInCallback(s, poolManager, totalSupply(), params);
        } else if (selector == IMultiPositionManager.Action.COMPOUND) {
            revert CompoundingDisabled();
        } else {
            revert InvalidAction();
        }
    }

    function _enforceRebalanceParams(IMultiPositionManager.RebalanceParams calldata params, bool isSwap) private view {
        bool isProportional = (params.weight0 == 0 && params.weight1 == 0);
        bool isFiftyFifty = (params.weight0 == 0.5e18 && params.weight1 == 0.5e18);
        if (!isProportional && !isFiftyFifty) revert InvalidRebalanceParams();
        if (!params.useCarpet) revert InvalidRebalanceParams();

        MultiPositionFactory factoryContract = MultiPositionFactory(unilaunchFactory);
        uint256 unlockAt = deployedAt + factoryContract.lockDuration();
        bool locked = block.timestamp < unlockAt;

        if (isSwap && locked) revert RebalanceSwapLocked(unlockAt);

        if (locked) {
            if (params.tLeft < factoryContract.minTicksLeftInitial()) revert InvalidRebalanceParams();
            if (params.tRight < factoryContract.minTicksRightInitial()) revert InvalidRebalanceParams();
            if (isFiftyFifty && params.limitWidth < factoryContract.minLimitWidthInitial()) {
                revert InvalidRebalanceParams();
            }
        } else {
            if (params.tLeft < factoryContract.minTicksLeftAfter()) revert InvalidRebalanceParams();
            if (params.tRight < factoryContract.minTicksRightAfter()) revert InvalidRebalanceParams();
            if (isFiftyFifty && params.limitWidth < factoryContract.minLimitWidthAfter()) {
                revert InvalidRebalanceParams();
            }
        }

        address resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;
        if (resolvedStrategy == address(0) || !factoryContract.strategyAllowed(resolvedStrategy)) {
            revert InvalidRebalanceParams();
        }

        uint24 maxDelta = factoryContract.maxTwapTickDelta();
        if (maxDelta != 0) {
            uint32 twapSeconds = factoryContract.twapSeconds();
            address hookAddress = address(s.poolKey.hooks);
            if (hookAddress == address(0)) revert InvalidRebalanceParams();
            VolatilityOracle oracle = VolatilityDynamicFeeLimitOrderHook(hookAddress).volatilityOracle();
            (, uint32 latestTimestamp) = oracle.getLatestObservation(s.poolKey.toId());
            if (block.timestamp >= latestTimestamp + twapSeconds) {
                (int24 twapTick,) = oracle.consult(s.poolKey, twapSeconds);
                int256 delta = int256(params.center) - int256(twapTick);
                if (delta < 0) {
                    delta = -delta;
                }
                if (uint256(delta) > maxDelta) revert InvalidRebalanceParams();
            }
        }
    }

    function _closePair() internal {
        PoolManagerUtils.close(poolManager, s.currency1);
        PoolManagerUtils.close(poolManager, s.currency0);
    }

    function _transferIn(address from, Currency currency, uint256 amount) internal {
        if (currency.isAddressZero()) {
            // In multicall: only allow ONE native deposit to prevent msg.value double-spend
            if (_inMulticallContext()) {
                if (_isNativeDepositDone()) revert OnlyOneNativeDepositPerMulticall();
                _markNativeDepositDone();
            }
            require(msg.value >= amount);
            if (msg.value > amount) {
                payable(msg.sender).transfer(msg.value - amount);
            }
        } else if (amount != 0) {
            IERC20(Currency.unwrap(currency)).safeTransferFrom(from, address(this), amount);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IMultiPositionFactory} from "./interfaces/IMultiPositionFactory.sol";
import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {MultiPositionDeployer} from "./MultiPositionDeployer.sol";
import {MultiPositionManager} from "./MultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Multicall} from "./base/Multicall.sol";

contract MultiPositionFactory is IMultiPositionFactory, Ownable, Multicall {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    // Role constants
    bytes32 public constant override CLAIM_MANAGER = keccak256("CLAIM_MANAGER");
    bytes32 public constant FEE_MANAGER = keccak256("FEE_MANAGER");

    // Role storage
    mapping(bytes32 => mapping(address => bool)) private _roles;
    // Aggregator allowlist (enum index -> router)
    mapping(uint8 => address) public override aggregatorAddress;
    // Strategy allowlist (strategy address -> allowed)
    mapping(address => bool) public override strategyAllowed;

    // Deployed managers tracking
    mapping(address => ManagerInfo) public managers;
    // Track managers by owner
    mapping(address => address[]) public managersByOwner;
    // Track all managers for pagination
    address[] private allManagers;
    // Track managers by token pair (key = keccak256(currency0, currency1))
    mapping(bytes32 => address[]) private _managersByTokenPair;
    // Track all unique token pairs
    TokenPairInfo[] private _allTokenPairs;
    /// @dev Maps pairKey to index+1 in _allTokenPairs (0 = doesn't exist)
    mapping(bytes32 => uint256) private _tokenPairIndex;

    // Protocol fee recipient
    address public feeRecipient;

    // Protocol fee (denominator for fee calculation, e.g., 10 = 10%, 20 = 5%)
    uint16 public protocolFee = 4;

    // Pool manager for all deployments
    IPoolManager public immutable poolManager;

    // Deployer contract for MultiPositionManager
    MultiPositionDeployer public immutable deployer;

    address public orderBookFactory;
    bool public orderBookFactorySet;

    uint256 public lockDuration = 180 days;
    uint24 public minTicksLeftInitial = 100000;
    uint24 public minTicksRightInitial = 100000;
    uint24 public minLimitWidthInitial = 50000;
    uint24 public minTicksLeftAfter = 5000;
    uint24 public minTicksRightAfter = 5000;
    uint24 public minLimitWidthAfter = 1000;
    uint32 public twapSeconds = 30;
    uint24 public maxTwapTickDelta = 1000;

    // Custom errors
    error UnauthorizedAccess();
    error UnauthorizedCaller();
    error OrderBookFactoryAlreadySet();
    error ManagerAlreadyExists();
    error InvalidAddress();
    error InitializationFailed();
    error InvalidFee();
    error InsufficientMsgValue();
    error PoolNotInitialized();
    error InvalidSqrtPriceX96();
    error MPMAlreadyInitialized();
    error InvalidAmount();

    constructor(address _owner, IPoolManager _poolManager) Ownable(_owner) {
        if (_owner == address(0)) revert InvalidAddress();
        if (address(_poolManager) == address(0)) revert InvalidAddress();
        feeRecipient = _owner; // Initialize fee recipient to owner
        poolManager = _poolManager;
        deployer = new MultiPositionDeployer(address(this));
    }

    modifier onlyOrderBookFactory() {
        if (msg.sender != orderBookFactory) revert UnauthorizedCaller();
        _;
    }

    function setOrderBookFactory(address newOrderBookFactory) external onlyOwner {
        if (newOrderBookFactory == address(0)) revert InvalidAddress();
        if (orderBookFactorySet) revert OrderBookFactoryAlreadySet();
        orderBookFactory = newOrderBookFactory;
        orderBookFactorySet = true;
    }

    /**
     * @notice Checks if an account has a specific role or is the owner
     * @param role The role to check
     * @param account The account to check
     * @return True if the account has the role or is the owner
     */
    function hasRoleOrOwner(bytes32 role, address account) external view override returns (bool) {
        return account == owner() || _roles[role][account];
    }

    /**
     * @notice Checks if an account has a specific role
     * @param role The role to check
     * @param account The account to check
     * @return True if the account has the role
     */
    function hasRole(bytes32 role, address account) external view override returns (bool) {
        return _roles[role][account];
    }

    /**
     * @notice Grants a role to an account
     * @param role The role to grant
     * @param account The account to grant the role to
     */
    function grantRole(bytes32 role, address account) external override onlyOwner {
        if (account == address(0)) revert InvalidAddress();
        if (!_roles[role][account]) {
            _roles[role][account] = true;
            emit RoleGranted(role, account, msg.sender);
        }
    }

    /**
     * @notice Revokes a role from an account
     * @param role The role to revoke
     * @param account The account to revoke the role from
     */
    function revokeRole(bytes32 role, address account) external override onlyOwner {
        if (_roles[role][account]) {
            _roles[role][account] = false;
            emit RoleRevoked(role, account, msg.sender);
        }
    }

    /**
     * @notice Deploys a new MultiPositionManager
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param managerOwner The owner of the new MultiPositionManager
     * @param name The name for the LP token
     * @return The address of the deployed MultiPositionManager
     */
    function deployMultiPositionManager(PoolKey memory poolKey, address managerOwner, string memory name)
        external
        onlyOrderBookFactory
        returns (address)
    {
        return _deployMultiPositionManager(poolKey, managerOwner, name);
    }

    function _deployMultiPositionManager(PoolKey memory poolKey, address managerOwner, string memory name)
        internal
        returns (address)
    {
        if (managerOwner == address(0)) revert InvalidAddress();

        address predicted = _computeAddress(poolKey, managerOwner, name);
        if (predicted.code.length > 0) {
            _validateExistingManager(predicted, poolKey, managerOwner);
            return predicted;
        }

        // Generate deterministic salt for CREATE2
        // Include name to ensure unique deployments for same poolKey/owner with different names
        bytes32 salt = keccak256(abi.encode(poolKey, managerOwner, name));

        // Use fixed symbol for all deployments
        string memory symbol = "UNILAUNCH-LP";

        // Deploy using deployer contract
        address managerAddress = deployer.deploy(
            poolManager,
            poolKey,
            managerOwner,
            address(this), // factory address
            name,
            symbol,
            protocolFee,
            salt
        );

        // Store manager info in mapping
        managers[managerAddress] =
            ManagerInfo({managerAddress: managerAddress, managerOwner: managerOwner, poolKey: poolKey, name: name});

        // Track manager by owner
        managersByOwner[managerOwner].push(managerAddress);

        // Track in global list
        allManagers.push(managerAddress);

        // Track by token pair
        address currency0 = Currency.unwrap(poolKey.currency0);
        address currency1 = Currency.unwrap(poolKey.currency1);
        bytes32 pairKey = keccak256(abi.encodePacked(currency0, currency1));
        _managersByTokenPair[pairKey].push(managerAddress);

        // Track unique token pair if new (O(1) lookup via index+1 pattern)
        uint256 indexPlusOne = _tokenPairIndex[pairKey];
        if (indexPlusOne == 0) {
            // New pair - store index+1 before pushing
            _tokenPairIndex[pairKey] = _allTokenPairs.length + 1;
            _allTokenPairs.push(TokenPairInfo({currency0: currency0, currency1: currency1, managerCount: 1}));
        } else {
            // Existing pair - direct O(1) access
            _allTokenPairs[indexPlusOne - 1].managerCount++;
        }

        emit MultiPositionManagerDeployed(managerAddress, managerOwner, poolKey);

        return managerAddress;
    }

    function _validateExistingManager(address managerAddress, PoolKey memory poolKey, address managerOwner)
        private
        view
    {
        IMultiPositionManager existing = IMultiPositionManager(managerAddress);
        if (existing.factory() != address(this)) revert ManagerAlreadyExists();
        if (!_poolKeysEqual(existing.poolKey(), poolKey)) revert ManagerAlreadyExists();
        if (Ownable(managerAddress).owner() != managerOwner) revert ManagerAlreadyExists();
    }

    function _poolKeysEqual(PoolKey memory a, PoolKey memory b) private pure returns (bool) {
        return Currency.unwrap(a.currency0) == Currency.unwrap(b.currency0)
            && Currency.unwrap(a.currency1) == Currency.unwrap(b.currency1)
            && a.fee == b.fee
            && a.tickSpacing == b.tickSpacing
            && address(a.hooks) == address(b.hooks);
    }

    /**
     * @notice Atomically deploys MPM, deposits liquidity, and rebalances to strategy
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param managerOwner The owner of the new MultiPositionManager (also receives LP shares)
     * @param name The name for the LP token
     * @param deposit0Desired Amount of token0 to deposit
     * @param deposit1Desired Amount of token1 to deposit
     * @param inMin Minimum amounts for slippage protection
     * @param rebalanceParams Strategy and rebalance parameters
     * @return mpm The address of the deployed and initialized MultiPositionManager
     * @dev LP shares are always minted to managerOwner
     */
    function deployDepositAndRebalance(
        PoolKey memory poolKey,
        address managerOwner,
        string memory name,
        uint256 deposit0Desired,
        uint256 deposit1Desired,
        address to,
        uint256[2][] memory inMin,
        IMultiPositionManager.RebalanceParams memory rebalanceParams
    ) external payable onlyOrderBookFactory returns (address mpm) {
        // Input validation
        if (managerOwner == address(0)) revert InvalidAddress();
        if (to == address(0)) revert InvalidAddress();

        address predicted = _computeAddress(poolKey, managerOwner, name);
        if (predicted.code.length > 0) {
            _ensureFreshManager(predicted);
        }

        // Deploy MPM (idempotent if already deployed at predicted address)
        mpm = _deployMultiPositionManager(poolKey, managerOwner, name);

        // Deposit liquidity (Factory can call because it's s.factory in MPM)
        // Tokens pulled from msg.sender (user), shares minted to 'to'
        MultiPositionManager(payable(mpm)).deposit{value: msg.value}(
            deposit0Desired,
            deposit1Desired,
            to,
            msg.sender // from = msg.sender (the user calling this function)
        );

        // Rebalance to strategy (Factory can call because it's s.factory in MPM)
        MultiPositionManager(payable(mpm)).rebalance(
            rebalanceParams,
            new uint256[2][](0), // outMin - empty for initial rebalance
            inMin // inMin from deposit
        );

        return mpm;
    }

    /**
     * @notice Deploy MPM, deposit, and rebalance with swap in one atomic transaction
     * @dev Enables single-token deposits by swapping to achieve strategy's target ratio
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param managerOwner The owner of the new MultiPositionManager (also receives LP shares)
     * @param name The name of the LP token
     * @param deposit0Desired Amount of token0 to deposit (can be 0)
     * @param deposit1Desired Amount of token1 to deposit (can be 0)
     * @param swapParams Complete swap parameters (aggregator, calldata, amounts, etc.)
     * @param inMin Minimum amounts for each position (slippage protection)
     * @param rebalanceParams Rebalance parameters (strategy, center, ticks, weights, etc.)
     * @return mpm Address of the deployed MultiPositionManager
     * @dev LP shares are always minted to managerOwner
     */
    /**
     * @notice Computes the address where a MultiPositionManager will be deployed
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param managerOwner The owner of the new MultiPositionManager
     * @param name The name of the LP token
     * @return The address where the MultiPositionManager will be deployed
     */
    function computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
        external
        view
        returns (address)
    {
        return _computeAddress(poolKey, managerOwner, name);
    }

    function _computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
        private
        view
        returns (address)
    {
        // Use fixed symbol for all deployments
        string memory symbol = "UNILAUNCH-LP";
        // Use the same salt calculation as deployMultiPositionManager
        // Include name to ensure unique deployments for same poolKey/owner with different names
        bytes32 salt = keccak256(abi.encode(poolKey, managerOwner, name));

        // Delegate to deployer which has access to the bytecode
        return
            deployer.computeAddress(poolManager, poolKey, managerOwner, address(this), name, symbol, protocolFee, salt);
    }

    function _ensureFreshManager(address managerAddress) private view {
        IMultiPositionManager existing = IMultiPositionManager(managerAddress);
        if (existing.totalSupply() != 0) revert MPMAlreadyInitialized();
        if (existing.basePositionsLength() != 0 || existing.limitPositionsLength() != 0) {
            revert MPMAlreadyInitialized();
        }
        (address strategy,,,,,,,,,) = existing.lastStrategyParams();
        if (strategy != address(0)) revert MPMAlreadyInitialized();
    }

    /**
     * @notice Gets all managers owned by a specific address
     * @param managerOwner The owner address to query
     * @return Array of ManagerInfo for all managers owned by the address
     */
    function getManagersByOwner(address managerOwner) external view returns (ManagerInfo[] memory) {
        address[] memory ownerManagers = managersByOwner[managerOwner];
        ManagerInfo[] memory result = new ManagerInfo[](ownerManagers.length);

        for (uint256 i = 0; i < ownerManagers.length; i++) {
            address managerAddress = ownerManagers[i];
            result[i] = managers[managerAddress];
            result[i].managerAddress = managerAddress;
        }

        return result;
    }

    /**
     * @notice Get all deployed managers with pagination
     * @param offset Starting index in the global manager list
     * @param limit Maximum number of managers to return (0 for all remaining)
     * @return managersInfo Array of ManagerInfo structs
     * @return totalCount Total number of deployed managers
     */
    function getAllManagersPaginated(uint256 offset, uint256 limit)
        external
        view
        returns (ManagerInfo[] memory managersInfo, uint256 totalCount)
    {
        totalCount = allManagers.length;

        if (limit == 0) {
            limit = totalCount; // 0 means return all managers
        }

        if (offset >= totalCount) {
            return (new ManagerInfo[](0), totalCount);
        }

        uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;

        managersInfo = new ManagerInfo[](count);

        for (uint256 i = 0; i < count; i++) {
            address managerAddress = allManagers[offset + i];
            managersInfo[i] = managers[managerAddress];
            managersInfo[i].managerAddress = managerAddress;
        }

        return (managersInfo, totalCount);
    }

    /**
     * @notice Get the total number of deployed managers
     * @return The total count of deployed managers
     */
    function getTotalManagersCount() external view returns (uint256) {
        return allManagers.length;
    }

    /**
     * @notice Checks if a pool has been initialized in the PoolManager
     * @param poolKey The pool key to check
     * @return initialized True if the pool has been initialized (sqrtPriceX96 != 0)
     */
    function isPoolInitialized(PoolKey memory poolKey) public view returns (bool initialized) {
        PoolId poolId = poolKey.toId();
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);
        return sqrtPriceX96 != 0;
    }

    /**
     * @notice Initializes a pool if it hasn't been initialized yet
     * @param poolKey The pool key to initialize
     * @param sqrtPriceX96 The initial sqrt price (Q64.96 format)
     * @return tick The initial tick of the pool
     * @dev Reverts if sqrtPriceX96 is 0 or if pool is already initialized
     *      Marked payable for multicall compatibility - msg.value persists across delegatecalls.
     *      Does not consume msg.value; it just needs to accept it to prevent multicall reverts.
     */
    function initializePoolIfNeeded(PoolKey memory poolKey, uint160 sqrtPriceX96)
        external
        payable
        returns (int24 tick)
    {
        if (sqrtPriceX96 == 0) revert InvalidSqrtPriceX96();

        if (!isPoolInitialized(poolKey)) {
            tick = poolManager.initialize(poolKey, sqrtPriceX96);
        } else {
            // Pool already initialized, return current tick
            PoolId poolId = poolKey.toId();
            (, tick,,) = poolManager.getSlot0(poolId);
        }
    }

    /**
     * @notice Sets the protocol fee recipient
     * @param _feeRecipient The new fee recipient address
     */
    function setFeeRecipient(address _feeRecipient) external onlyOwner {
        if (_feeRecipient == address(0)) revert InvalidAddress();
        feeRecipient = _feeRecipient;
    }

    function setLockDuration(uint256 newDuration) external onlyOwner {
        lockDuration = newDuration;
    }

    function setMinTicksInitial(uint24 left, uint24 right, uint24 limitWidth) external onlyOwner {
        minTicksLeftInitial = left;
        minTicksRightInitial = right;
        minLimitWidthInitial = limitWidth;
    }

    function setMinTicksAfter(uint24 left, uint24 right, uint24 limitWidth) external onlyOwner {
        minTicksLeftAfter = left;
        minTicksRightAfter = right;
        minLimitWidthAfter = limitWidth;
    }

    function setTwapConfig(uint32 newTwapSeconds, uint24 newMaxTickDelta) external onlyOwner {
        if (newTwapSeconds == 0) revert InvalidAmount();
        if (newMaxTickDelta == 0) revert InvalidAmount();
        twapSeconds = newTwapSeconds;
        maxTwapTickDelta = newMaxTickDelta;
    }

    /**
     * @notice Sets the protocol fee for all new deployments
     * @param _fee The new protocol fee denominator (e.g., 10 = 10%)
     */
    function setProtocolFee(uint16 _fee) external onlyOwner {
        if (_fee == 0) revert InvalidFee();
        protocolFee = _fee;
    }

    /**
     * @notice Set the approved router for a swap aggregator
     * @param aggregator Aggregator enum index
     * @param router Approved router address
     */
    function setAggregatorAddress(uint8 aggregator, address router) external onlyOwner {
        if (router == address(0)) revert InvalidAddress();
        aggregatorAddress[aggregator] = router;
    }

    /**
     * @notice Set whether a strategy contract is allowed for rebalances
     * @param strategy Strategy contract address
     * @param allowed True to allow, false to disallow
     */
    function setStrategyAllowed(address strategy, bool allowed) external onlyOwner {
        if (strategy == address(0)) revert InvalidAddress();
        strategyAllowed[strategy] = allowed;
    }

    /**
     * @notice Get all unique token pairs with pagination
     * @param offset Starting index in the token pairs list
     * @param limit Maximum number of pairs to return (0 for all remaining)
     * @return pairsInfo Array of TokenPairInfo structs with currency addresses and manager counts
     * @return totalCount Total number of unique token pairs
     */
    function getAllTokenPairsPaginated(uint256 offset, uint256 limit)
        external
        view
        returns (TokenPairInfo[] memory pairsInfo, uint256 totalCount)
    {
        totalCount = _allTokenPairs.length;

        if (limit == 0) {
            limit = totalCount;
        }

        if (offset >= totalCount) {
            return (new TokenPairInfo[](0), totalCount);
        }

        uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;

        pairsInfo = new TokenPairInfo[](count);

        for (uint256 i = 0; i < count; i++) {
            pairsInfo[i] = _allTokenPairs[offset + i];
        }

        return (pairsInfo, totalCount);
    }

    /**
     * @notice Get all managers for a specific token pair with pagination
     * @param currency0 The first currency address (token0)
     * @param currency1 The second currency address (token1)
     * @param offset Starting index in the managers list for this pair
     * @param limit Maximum number of managers to return (0 for all remaining)
     * @return managersInfo Array of ManagerInfo structs
     * @return totalCount Total number of managers for this token pair
     */
    function getAllManagersByTokenPair(address currency0, address currency1, uint256 offset, uint256 limit)
        external
        view
        returns (ManagerInfo[] memory managersInfo, uint256 totalCount)
    {
        bytes32 pairKey = keccak256(abi.encodePacked(currency0, currency1));
        address[] storage pairManagers = _managersByTokenPair[pairKey];
        totalCount = pairManagers.length;

        if (limit == 0) {
            limit = totalCount;
        }

        if (offset >= totalCount) {
            return (new ManagerInfo[](0), totalCount);
        }

        uint256 count = (offset + limit > totalCount) ? (totalCount - offset) : limit;

        managersInfo = new ManagerInfo[](count);

        for (uint256 i = 0; i < count; i++) {
            address managerAddress = pairManagers[offset + i];
            managersInfo[i] = managers[managerAddress];
            managersInfo[i].managerAddress = managerAddress;
        }

        return (managersInfo, totalCount);
    }
}

/// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {IImmutableState} from "v4-periphery/src/interfaces/IImmutableState.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {RebalanceLogic} from "../libraries/RebalanceLogic.sol";

interface IMultiPositionManager is IERC20, IImmutableState {
    enum Action {
        WITHDRAW,
        REBALANCE,
        ZERO_BURN,
        CLAIM_FEE,
        BURN_ALL,
        COMPOUND
    }

    struct Range {
        int24 lowerTick;
        int24 upperTick;
    }

    // @deprecated Use Range instead - Position included redundant poolKey
    struct Position {
        PoolKey poolKey;
        int24 lowerTick;
        int24 upperTick;
    }

    struct PositionData {
        uint128 liquidity;
        uint256 amount0;
        uint256 amount1;
    }

    struct RebalanceParams {
        address strategy;
        int24 center;
        uint24 tLeft;
        uint24 tRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet; // Use full-range floor
    }

    struct RebalanceSwapParams {
        RebalanceParams rebalanceParams;
        RebalanceLogic.SwapParams swapParams;
    }

    event Rebalance(Range[] ranges, PositionData[] positionData, RebalanceParams params);

    event Deposit(address indexed from, address indexed to, uint256 amount0, uint256 amount1, uint256 shares);

    function getPositions() external view returns (Range[] memory, PositionData[] memory);
    function getBasePositions() external view returns (Range[] memory, PositionData[] memory);
    function poolKey() external view returns (PoolKey memory);
    function fee() external view returns (uint16);
    function factory() external view returns (address);
    function basePositionsLength() external view returns (uint256);
    function limitPositionsLength() external view returns (uint256);
    function limitPositions(uint256 index) external view returns (Range memory);
    function getTotalAmounts()
        external
        view
        returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1);
    function currentTick() external view returns (int24);
    function rebalance(RebalanceParams calldata params, uint256[2][] memory outMin, uint256[2][] memory inMin)
        external
        payable;
    function rebalanceSwap(RebalanceSwapParams calldata params, uint256[2][] memory outMin, uint256[2][] memory inMin)
        external
        payable;
    function claimFee() external;
    function setFee(uint16 fee) external;
    // function setTickOffset(uint24 offset) external;
    function deposit(uint256 deposit0Desired, uint256 deposit1Desired, address to, address from)
        external
        payable
        returns (uint256, uint256, uint256);

    function compound(uint256[2][] calldata inMin) external payable;

    function compoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
        external
        payable;
    function withdraw(uint256 shares, uint256[2][] memory outMin, bool withdrawToWallet)
        external
        returns (uint256 amount0, uint256 amount1);
    function withdrawCustom(uint256 amount0Desired, uint256 amount1Desired, uint256[2][] memory outMin)
        external
        returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned);

    // Role management functions
    function grantRelayerRole(address account) external;
    function revokeRelayerRole(address account) external;
    function isRelayer(address account) external view returns (bool);

    // Ratio functions
    function getRatios()
        external
        view
        returns (
            uint256 pool0Ratio,
            uint256 pool1Ratio,
            uint256 total0Ratio,
            uint256 total1Ratio,
            uint256 inPositionRatio,
            uint256 outOfPositionRatio,
            uint256 baseRatio,
            uint256 limitRatio,
            uint256 base0Ratio,
            uint256 base1Ratio,
            uint256 limit0Ratio,
            uint256 limit1Ratio
        );

    // Strategy parameters
    function lastStrategyParams()
        external
        view
        returns (
            address strategy,
            int24 centerTick,
            uint24 ticksLeft,
            uint24 ticksRight,
            uint24 limitWidth,
            uint120 weight0,
            uint120 weight1,
            bool useCarpet,
            bool useSwap,
            bool useAssetWeights
        );
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

/**
 * @title ILiquidityStrategy
 * @notice Interface for liquidity distribution strategies matching Python shapes
 * @dev Each strategy implements a different distribution pattern (uniform, triangle, gaussian, etc.)
 */
interface ILiquidityStrategy {
    /**
     * @notice Generate tick ranges with optional full-range floor position
     * @param centerTick The center tick for the strategy
     * @param ticksLeft Number of ticks to the left of center for the distribution
     * @param ticksRight Number of ticks to the right of center for the distribution
     * @param tickSpacing The tick spacing of the pool
     * @param useCarpet Whether to add a full-range floor position (min/max usable ticks)
     * @return lowerTicks Array of lower ticks for each position
     * @return upperTicks Array of upper ticks for each position
     */
    function generateRanges(int24 centerTick, uint24 ticksLeft, uint24 ticksRight, int24 tickSpacing, bool useCarpet)
        external
        pure
        returns (int24[] memory lowerTicks, int24[] memory upperTicks);

    /**
     * @notice Get the strategy type identifier
     * @return strategyType String identifier for the strategy (e.g., "uniform", "triangle", "gaussian")
     */
    function getStrategyType() external pure returns (string memory strategyType);

    /**
     * @notice Get a description of the strategy
     * @return description Human-readable description of the distribution pattern
     */
    function getDescription() external pure returns (string memory description);

    /**
     * @notice Check if this strategy supports weighted distribution
     * @return supported True if the strategy implements calculateDensitiesWithWeights
     */
    function supportsWeights() external pure returns (bool supported);

    /**
     * @notice Calculate density weights with token weights and optional full-range floor
     * @dev Comprehensive function that supports both token weights and full-range floor ranges
     * @param lowerTicks Array of lower ticks for each position
     * @param upperTicks Array of upper ticks for each position
     * @param currentTick Current tick of the pool
     * @param centerTick Center tick for the distribution
     * @param ticksLeft Number of ticks to the left of center for the shape
     * @param ticksRight Number of ticks to the right of center for the shape
     * @param weight0 Weight preference for token0 (scaled to 1e18, e.g., 0.8e18 for 80%)
     * @param weight1 Weight preference for token1 (scaled to 1e18, e.g., 0.2e18 for 20%)
     * @param useCarpet Whether a full-range floor position is present
     * @param tickSpacing The tick spacing of the pool
     * @param useAssetWeights True if weights were auto-calculated from available tokens (should not filter ranges)
     * @return weights Array of weights for each position (scaled to 1e18, sum = 1e18)
     */
    function calculateDensities(
        int24[] memory lowerTicks,
        int24[] memory upperTicks,
        int24 currentTick,
        int24 centerTick,
        uint24 ticksLeft,
        uint24 ticksRight,
        uint256 weight0,
        uint256 weight1,
        bool useCarpet,
        int24 tickSpacing,
        bool useAssetWeights
    ) external pure returns (uint256[] memory weights);
}

// 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";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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);

    /// @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);

    /// @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 7 of 82 : 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 "./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;

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     * @dev Note that feeGrowthGlobal can be artificially inflated
     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

// 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.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: UNLICENSED
pragma solidity ^0.8.20;

import "../../src/libraries/FullMath.sol";
import "../../src/libraries/FixedPoint96.sol";

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x, "liquidity overflow");
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
        internal
        pure
        returns (uint128 liquidity)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
        return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96));
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
        internal
        pure
        returns (uint128 liquidity)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96));
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtPriceX96 A sqrt price representing the current pool prices
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceAX96,
        uint160 sqrtPriceBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount0)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        return FullMath.mulDiv(
            uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtPriceBX96 - sqrtPriceAX96, sqrtPriceBX96
        ) / sqrtPriceAX96;
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount1)
    {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        return FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtPriceX96 A sqrt price representing the current pool prices
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function getAmountsForLiquidity(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceAX96,
        uint160 sqrtPriceBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            amount0 = getAmount0ForLiquidity(sqrtPriceX96, sqrtPriceBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, liquidity);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {MultiPositionManager} from "../../MultiPositionManager.sol";
import {IMultiPositionManager} from "../../interfaces/IMultiPositionManager.sol";
import {ILiquidityStrategy} from "../../strategies/ILiquidityStrategy.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import {DepositRatioLib} from "../DepositRatioLib.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {RebalanceLogic} from "../RebalanceLogic.sol";

/**
 * @title LensRatioUtils
 * @notice Library for ratio management and position calculations for SimpleLens
 * @dev Adapted from SimpleLensRatioUtils - removes withdrawal/compound related functions
 */
library LensRatioUtils {
    using StateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;

    // Custom errors
    error NoStrategySpecified();

    uint256 constant PRECISION = 1e18;

    struct SwapParams {
        bool swapToken0;
        uint256 swapAmount;
        uint256 weight0;
        uint256 weight1;
    }

    struct PositionStats {
        int24 tickLower;
        int24 tickUpper;
        uint160 sqrtPriceLower;
        uint160 sqrtPriceUpper;
        uint128 liquidity;
        uint256 token0Quantity;
        uint256 token1Quantity;
        uint256 valueInToken1;
        bool isLimit;
    }

    struct PreviewData {
        uint256 total0;
        uint256 total1;
        uint256 totalFee0;
        uint256 totalFee1;
        uint256 unusedAmount0;
        uint256 unusedAmount1;
        uint256 availableAfterFees0;
        uint256 availableAfterFees1;
        bool needToBurnPositions;
    }

    struct PriceData {
        uint160 sqrtPriceX96;
        uint256 price;
        int24 tick;
    }

    struct DepositCalculationContext {
        IPoolManager pm;
        PoolKey poolKey;
        uint160 sqrtPriceX96;
        uint256 totalToken0InPositions;
        uint256 totalToken1InPositions;
        uint256 amount0ForPositions;
        uint256 amount1ForPositions;
    }

    // Helper struct for initial deposit parameters
    struct InitialDepositParams {
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        bool isToken0;
        uint256 amount;
        uint256 maxSlippageBps;
    }

    // Struct for preview data
    struct RebalancePreview {
        address strategy;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        IMultiPositionManager.Range[] baseRanges;
        uint128[] liquidities;
        uint256 expectedToken0;
        uint256 expectedToken1;
    }

    struct LiquidityCalcContext {
        uint160 sqrtPriceLower;
        uint160 sqrtPriceUpper;
        uint256 totalWeightedToken0;
        uint256 totalWeightedToken1;
        uint128 totalLiquidity;
    }

    struct StrategyCallParams {
        address strategyAddress;
        int24[] lowerTicks;
        int24[] upperTicks;
        int24 currentTick;
        int24 resolvedCenterTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        int24 tickSpacing;
    }

    struct DensityParams {
        int24 currentTick;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        int24 tickSpacing;
    }

    /**
     * @notice Calculate corresponding token amount to maintain current ratio
     * @param manager The MultiPositionManager contract
     * @param isToken0 True if user provides token0, false for token1
     * @param amount Amount of token being provided
     * @return The amount of the other token needed to maintain ratio
     */
    function getAmountsForDeposit(MultiPositionManager manager, bool isToken0, uint256 amount)
        external
        view
        returns (uint256)
    {
        (uint256 total0, uint256 total1,,) = manager.getTotalAmounts();

        if (total0 == 0 || total1 == 0) {
            return 0;
        }

        if (isToken0) {
            return FullMath.mulDiv(amount, total1, total0);
        } else {
            return FullMath.mulDiv(amount, total0, total1);
        }
    }

    /**
     * @notice Calculate deposit amounts for initial position - uses externally generated ranges
     * @param ranges The ranges to use
     * @param poolKey The PoolKey for the Uniswap V4 pool
     * @param poolManager The PoolManager instance
     * @param params Parameters for the initial deposit calculation
     * @return otherAmount The amount of the other token needed
     * @return weights The density weights for each range
     * @return sqrtPriceX96 The current sqrtPrice
     * @return resolvedCenterTick The resolved center tick
     */
    function calculateInitialDepositAmounts(
        IMultiPositionManager.Range[] memory ranges,
        PoolKey memory poolKey,
        IPoolManager poolManager,
        InitialDepositParams calldata params
    )
        external
        view
        returns (uint256 otherAmount, uint256[] memory weights, uint160 sqrtPriceX96, int24 resolvedCenterTick)
    {
        int24 currentTick;
        uint256 totalWeightedToken0;
        uint256 totalWeightedToken1;

        (totalWeightedToken0, totalWeightedToken1, resolvedCenterTick, sqrtPriceX96, currentTick, weights) =
            _calculateWeightedTokenRequirements(poolKey, poolManager, ranges, params);

        if (totalWeightedToken0 == 0 && totalWeightedToken1 == 0) {
            revert("No liquidity would be added");
        }

        if (params.isToken0) {
            if (totalWeightedToken0 == 0) {
                otherAmount = 0;
            } else {
                otherAmount = FullMath.mulDiv(params.amount, totalWeightedToken1, totalWeightedToken0);
            }
        } else {
            if (totalWeightedToken1 == 0) {
                otherAmount = 0;
            } else {
                otherAmount = FullMath.mulDiv(params.amount, totalWeightedToken0, totalWeightedToken1);
            }
        }
    }

    function _calculateWeightedTokenRequirements(
        PoolKey memory poolKey,
        IPoolManager poolManager,
        IMultiPositionManager.Range[] memory ranges,
        InitialDepositParams calldata params
    )
        private
        view
        returns (
            uint256 totalWeightedToken0,
            uint256 totalWeightedToken1,
            int24 resolvedCenterTick,
            uint160 sqrtPriceX96,
            int24 currentTick,
            uint256[] memory weights
        )
    {
        (sqrtPriceX96, currentTick,,) = poolManager.getSlot0(poolKey.toId());

        // Resolve sentinel value and snap to tickSpacing grid
        {
            if (params.centerTick == type(int24).max) {
                int24 compressed = currentTick / poolKey.tickSpacing;
                if (currentTick < 0 && currentTick % poolKey.tickSpacing != 0) {
                    compressed--;
                }
                resolvedCenterTick = compressed * poolKey.tickSpacing;
            } else {
                // Snap to tickSpacing grid using floor division (matches on-chain behavior)
                resolvedCenterTick = (params.centerTick / poolKey.tickSpacing) * poolKey.tickSpacing;
                if (params.centerTick < 0 && params.centerTick % poolKey.tickSpacing != 0) {
                    resolvedCenterTick -= poolKey.tickSpacing;
                }
            }
        }

        // Get density weights from strategy
        weights = _callStrategyForWeights(ranges, params, resolvedCenterTick, currentTick, poolKey.tickSpacing);

        // Calculate weighted token requirements
        for (uint256 i = 0; i < ranges.length; i++) {
            if (ranges[i].lowerTick != 0 || ranges[i].upperTick != 0) {
                uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
                uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

                (uint256 amount0For1e18, uint256 amount1For1e18) =
                    LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);

                totalWeightedToken0 += (amount0For1e18 * weights[i]) / 1e18;
                totalWeightedToken1 += (amount1For1e18 * weights[i]) / 1e18;
            }
        }
    }

    function _callStrategyForWeights(
        IMultiPositionManager.Range[] memory ranges,
        InitialDepositParams calldata params,
        int24 resolvedCenterTick,
        int24 currentTick,
        int24 tickSpacing
    ) private view returns (uint256[] memory) {
        (int24[] memory lowerTicks, int24[] memory upperTicks) = _extractTickArrays(ranges);

        StrategyCallParams memory callParams = StrategyCallParams({
            strategyAddress: params.strategyAddress,
            lowerTicks: lowerTicks,
            upperTicks: upperTicks,
            currentTick: currentTick,
            resolvedCenterTick: resolvedCenterTick,
            ticksLeft: params.ticksLeft,
            ticksRight: params.ticksRight,
            weight0: params.weight0,
            weight1: params.weight1,
            useCarpet: params.useCarpet,
            tickSpacing: tickSpacing
        });

        return _executeStrategyCall(callParams);
    }

    function _extractTickArrays(IMultiPositionManager.Range[] memory ranges)
        private
        pure
        returns (int24[] memory lowerTicks, int24[] memory upperTicks)
    {
        lowerTicks = new int24[](ranges.length);
        upperTicks = new int24[](ranges.length);

        for (uint256 i = 0; i < ranges.length; i++) {
            lowerTicks[i] = ranges[i].lowerTick;
            upperTicks[i] = ranges[i].upperTick;
        }
    }

    function _executeStrategyCall(StrategyCallParams memory callParams) private view returns (uint256[] memory) {
        bool useAssetWeights = (callParams.weight0 == 0 && callParams.weight1 == 0);
        return _executeStrategyCallWithAssetFlag(callParams, useAssetWeights);
    }

    function _executeStrategyCallWithAssetFlag(StrategyCallParams memory callParams, bool useAssetWeights)
        private
        view
        returns (uint256[] memory)
    {
        bytes memory callData = abi.encodeCall(
            ILiquidityStrategy.calculateDensities,
            (
                callParams.lowerTicks,
                callParams.upperTicks,
                callParams.currentTick,
                callParams.resolvedCenterTick,
                callParams.ticksLeft,
                callParams.ticksRight,
                callParams.weight0,
                callParams.weight1,
                callParams.useCarpet,
                callParams.tickSpacing,
                useAssetWeights
            )
        );

        (bool success, bytes memory returnData) = callParams.strategyAddress.staticcall(callData);

        if (!success) revert("CalculateDensitiesFailed");
        uint256[] memory weights = abi.decode(returnData, (uint256[]));
        return RebalanceLogic.adjustWeightsForFullRangeFloor(
            weights, callParams.lowerTicks, callParams.upperTicks, callParams.tickSpacing, callParams.useCarpet
        );
    }

    /**
     * @notice Calculate weights from existing positions
     * @dev Uses current position composition to determine target weights
     * @param manager The MultiPositionManager
     * @param sqrtPriceX96 Current pool price
     * @return weight0 Weight for token0
     * @return weight1 Weight for token1
     */
    function calculateWeightsFromPositions(MultiPositionManager manager, uint160 sqrtPriceX96)
        public
        view
        returns (uint256 weight0, uint256 weight1)
    {
        // Get total amounts in positions (excluding fees)
        (uint256 total0, uint256 total1,,) = manager.getTotalAmounts();

        // Calculate value in token1 terms for weight calculation
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        uint256 value0InToken1 = FullMath.mulDiv(total0, price, PRECISION);
        uint256 totalValue = value0InToken1 + total1;

        if (totalValue == 0) {
            // No positions, use 50/50
            weight0 = PRECISION / 2;
            weight1 = PRECISION / 2;
        } else {
            // Calculate weights based on current composition
            weight0 = FullMath.mulDiv(value0InToken1, PRECISION, totalValue);
            weight1 = FullMath.mulDiv(total1, PRECISION, totalValue);
        }
    }

    /**
     * @notice Apply swap simulation to calculate final amounts
     * @param amount0 Initial amount of token0
     * @param amount1 Initial amount of token1
     * @param swapToken0 True if swapping token0 for token1
     * @param swapAmount Amount to swap
     * @param sqrtPriceX96 Current sqrt price
     * @return finalAmount0 Amount of token0 after swap
     * @return finalAmount1 Amount of token1 after swap
     */
    function applySwap(uint256 amount0, uint256 amount1, bool swapToken0, uint256 swapAmount, uint160 sqrtPriceX96)
        public
        pure
        returns (uint256 finalAmount0, uint256 finalAmount1)
    {
        if (swapAmount == 0) {
            return (amount0, amount1);
        }

        if (swapToken0) {
            uint256 estimatedOut = FullMath.mulDiv(
                FullMath.mulDiv(swapAmount, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
            );
            finalAmount0 = amount0 - swapAmount;
            finalAmount1 = amount1 + estimatedOut;
        } else {
            uint256 estimatedOut = FullMath.mulDiv(
                FullMath.mulDiv(swapAmount, 1 << 96, uint256(sqrtPriceX96)), 1 << 96, uint256(sqrtPriceX96)
            );
            finalAmount0 = amount0 + estimatedOut;
            finalAmount1 = amount1 - swapAmount;
        }
    }

    /**
     * @notice Get position statistics for all positions in a manager
     * @param manager The MultiPositionManager to query
     * @return stats Array of PositionStats for each position
     */
    function getPositionStats(MultiPositionManager manager) external view returns (PositionStats[] memory stats) {
        (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData) =
            manager.getPositions();

        IPoolManager poolManager = manager.poolManager();
        PoolKey memory poolKey = manager.poolKey();
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());

        stats = new PositionStats[](ranges.length);
        uint256 baseLength = manager.basePositionsLength();

        for (uint256 i = 0; i < ranges.length; i++) {
            stats[i].tickLower = ranges[i].lowerTick;
            stats[i].tickUpper = ranges[i].upperTick;
            stats[i].sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            stats[i].sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);
            stats[i].liquidity = positionData[i].liquidity;
            stats[i].token0Quantity = positionData[i].amount0;
            stats[i].token1Quantity = positionData[i].amount1;

            // Calculate value in token1
            uint256 price = FullMath.mulDiv(
                FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
            );
            stats[i].valueInToken1 = positionData[i].amount1 + FullMath.mulDiv(positionData[i].amount0, price, PRECISION);
            stats[i].isLimit = i >= baseLength;
        }
    }

    /**
     * @notice Calculate optimal swap parameters for rebalancing
     * @param manager The MultiPositionManager
     * @param strategy Address of liquidity strategy
     * @param centerTick Center tick for new positions
     * @param ticksLeft Number of ticks left of center
     * @param ticksRight Number of ticks right of center
     * @param weight0 Weight for token0 (0 for calculate from strategy)
     * @param weight1 Weight for token1 (0 for calculate from strategy)
     * @param useCarpet Whether to use the full-range floor
     * @param poolManager The pool manager instance
     * @param amount0 Pre-computed amount of token0
     * @param amount1 Pre-computed amount of token1
     * @return swapParams Calculated swap parameters
     */
    function calculateOptimalSwapForRebalance(
        MultiPositionManager manager,
        address strategy,
        int24 centerTick,
        uint24 ticksLeft,
        uint24 ticksRight,
        uint256 weight0,
        uint256 weight1,
        bool useCarpet,
        IPoolManager poolManager,
        uint256 amount0,
        uint256 amount1
    ) external view returns (SwapParams memory swapParams) {
        // Get current pool state
        PoolKey memory poolKey = manager.poolKey();
        (uint160 sqrtPriceX96, int24 currentTick,,) = poolManager.getSlot0(poolKey.toId());

        // Resolve center tick (always floor-divide for alignment)
        int24 resolvedCenter;
        if (centerTick == type(int24).max) {
            int24 compressed = currentTick / poolKey.tickSpacing;
            if (currentTick < 0 && currentTick % poolKey.tickSpacing != 0) {
                compressed--;
            }
            resolvedCenter = compressed * poolKey.tickSpacing;
        } else {
            // Floor-divide user-provided centerTick
            int24 compressed = centerTick / poolKey.tickSpacing;
            if (centerTick < 0 && centerTick % poolKey.tickSpacing != 0) {
                compressed--;
            }
            resolvedCenter = compressed * poolKey.tickSpacing;
        }

        // Use provided weights OR calculate from strategy
        if (weight0 == 0 && weight1 == 0) {
            (swapParams.weight0, swapParams.weight1) = RebalanceLogic.calculateWeightsFromStrategy(
                ILiquidityStrategy(strategy),
                resolvedCenter,
                ticksLeft,
                ticksRight,
                poolKey.tickSpacing,
                useCarpet,
                sqrtPriceX96,
                currentTick
            );
        } else {
            swapParams.weight0 = weight0;
            swapParams.weight1 = weight1;
        }

        // Calculate optimal swap
        (swapParams.swapToken0, swapParams.swapAmount) =
            RebalanceLogic.calculateOptimalSwap(amount0, amount1, sqrtPriceX96, swapParams.weight0, swapParams.weight1);
    }

    /**
     * @notice Generate ranges from strategy
     */
    function generateRangesFromStrategy(
        MultiPositionManager manager,
        address strategyAddress,
        int24 centerTick,
        uint24 ticksLeft,
        uint24 ticksRight,
        bool useCarpet
    ) external view returns (IMultiPositionManager.Range[] memory baseRanges) {
        // Get pool key for tick spacing
        PoolKey memory poolKey = manager.poolKey();
        int24 tickSpacing = poolKey.tickSpacing;

        // Resolve CENTER_AT_CURRENT_TICK sentinel value
        if (centerTick == type(int24).max) {
            IPoolManager pm = manager.poolManager();
            (, int24 currentTick,,) = pm.getSlot0(poolKey.toId());
            int24 compressed = currentTick / tickSpacing;
            if (currentTick < 0 && currentTick % tickSpacing != 0) {
                compressed--; // Round down for negative ticks with remainder
            }
            centerTick = compressed * tickSpacing;
        } else {
            // Snap to tickSpacing grid using floor division (matches on-chain behavior)
            int24 compressed = centerTick / tickSpacing;
            if (centerTick < 0 && centerTick % tickSpacing != 0) {
                compressed--;
            }
            centerTick = compressed * tickSpacing;
        }

        // Generate ranges from strategy
        if (strategyAddress == address(0)) revert NoStrategySpecified();
        ILiquidityStrategy strategy = ILiquidityStrategy(strategyAddress);

        (int24[] memory lowerTicks, int24[] memory upperTicks) =
            strategy.generateRanges(centerTick, ticksLeft, ticksRight, tickSpacing, useCarpet);

        // Convert to Range array
        baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
        for (uint256 i = 0; i < lowerTicks.length; i++) {
            baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
        }
    }

    /**
     * @notice Simulate swap for rebalancing
     */
    function simulateSwapForRebalance(
        MultiPositionManager manager,
        uint256 amount0,
        uint256 amount1,
        uint256 weight0,
        uint256 weight1
    ) external view returns (uint256 newAmount0, uint256 newAmount1) {
        IPoolManager pm = manager.poolManager();
        PoolKey memory poolKey = manager.poolKey();

        (uint160 sqrtPriceX96ForSwap,,,) = pm.getSlot0(poolKey.toId());

        (bool swapToken0, uint256 swapAmount) =
            RebalanceLogic.calculateOptimalSwap(amount0, amount1, sqrtPriceX96ForSwap, weight0, weight1);

        newAmount0 = amount0;
        newAmount1 = amount1;

        if (swapAmount > 0) {
            if (swapToken0) {
                uint256 amountOut = FullMath.mulDiv(
                    FullMath.mulDiv(swapAmount, uint256(sqrtPriceX96ForSwap), 1 << 96),
                    uint256(sqrtPriceX96ForSwap),
                    1 << 96
                );
                newAmount0 -= swapAmount;
                newAmount1 += amountOut;
            } else {
                uint256 amountOut = FullMath.mulDiv(
                    FullMath.mulDiv(swapAmount, 1 << 96, uint256(sqrtPriceX96ForSwap)),
                    1 << 96,
                    uint256(sqrtPriceX96ForSwap)
                );
                newAmount1 -= swapAmount;
                newAmount0 += amountOut;
            }
        }
    }

    function roundToTickSpacing(int24 tick, int24 tickSpacing, bool roundDown) public pure returns (int24) {
        int24 remainder = tick % tickSpacing;
        if (remainder == 0) return tick;

        if (roundDown) {
            return
                tick < 0 ? ((tick - tickSpacing + 1) / tickSpacing) * tickSpacing : (tick / tickSpacing) * tickSpacing;
        } else {
            return
                tick < 0 ? (tick / tickSpacing) * tickSpacing : ((tick + tickSpacing - 1) / tickSpacing) * tickSpacing;
        }
    }
}

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

import {MultiPositionManager} from "../../MultiPositionManager.sol";
import {IMultiPositionManager} from "../../interfaces/IMultiPositionManager.sol";
import {ILiquidityStrategy} from "../../strategies/ILiquidityStrategy.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import {PoolManagerUtils} from "../PoolManagerUtils.sol";
import {RebalanceLogic} from "../RebalanceLogic.sol";
import {PositionLogic} from "../PositionLogic.sol";
import {LensRatioUtils} from "./LensRatioUtils.sol";

/**
 * @title LensInMin
 * @notice Library for calculating minimum amounts (slippage protection) for SimpleLens
 * @dev Adapted from SimpleLensInMin - removes withdrawal-related functions
 */
library LensInMin {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    /// @notice Parameters for getOutMinAndInMinForRebalance
    struct RebalanceMinParams {
        MultiPositionManager manager;
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        bool swap;
        uint256 maxSlippageOutMin;
        uint256 maxSlippageInMin;
        bool deductFees;
    }

    struct InMinRebalanceParams {
        MultiPositionManager manager;
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint24 limitWidth;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        bool swap;
        uint256 maxSlippage;
        bool deductFees;
    }

    struct RebalancePreview {
        // Input parameters
        IMultiPositionManager.Range[] ranges;
        address strategy;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        // Calculated liquidities per position
        uint128[] liquidities;
        // Expected position data after rebalance
        LensRatioUtils.PositionStats[] expectedPositions;
        // Total amounts after rebalance
        uint256 expectedTotal0;
        uint256 expectedTotal1;
        // Swap details (if swap is performed)
        bool swapToken0;
        uint256 swapAmount;
        uint256 expectedAmountOut;
        // Post-swap amounts (if swap)
        uint256 postSwapAmount0;
        uint256 postSwapAmount1;
    }

    struct DensityCalcParams {
        address strategyAddress;
        int24 centerTick;
        uint24 ticksLeft;
        uint24 ticksRight;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        bool useAssetWeights;
        int24 currentTick;
        int24 tickSpacing;
    }

    struct InMinCalcData {
        uint256 amount0;
        uint256 amount1;
        uint160 sqrtPriceX96;
        int24 currentTick;
        int24 tickSpacing;
        uint256 maxSlippage;
    }

    struct InMinCalcState {
        uint256 totalWeightedToken0;
        uint256 totalWeightedToken1;
        uint128 maxLiquidityFromToken0;
        uint128 maxLiquidityFromToken1;
        uint128 totalLiquidity;
        uint256 slippageMultiplier;
    }

    struct PreviewContext {
        uint160 sqrtPriceX96;
        int24 currentTick;
        int24 resolvedCenter;
        uint256 finalAmount0;
        uint256 finalAmount1;
    }

    struct LimitPositionsParams {
        uint24 limitWidth;
        int24 currentTick;
        int24 tickSpacing;
        uint256 maxSlippageBps;
        uint160 sqrtPriceX96;
        uint256 totalAmount0;
        uint256 totalAmount1;
    }

    /**
     * @notice Calculate inMin for rebalance
     * @param params Parameters for the calculation
     * @return inMin Array of minimum amounts for each position
     */
    function calculateInMinForRebalance(InMinRebalanceParams memory params)
        external
        view
        returns (uint256[2][] memory)
    {
        return _calculateInMinInternal(params);
    }

    /**
     * @notice Calculate minimum input amounts from existing ranges and weights
     */
    function calculateInMinFromExistingData(
        IMultiPositionManager.Range[] memory ranges,
        uint256[] memory weights,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        uint256 maxSlippage
    ) external pure returns (uint256[2][] memory inMin) {
        return _calculateInMinFromExistingData(ranges, weights, amount0, amount1, sqrtPriceX96, maxSlippage);
    }

    function _calculateInMinFromExistingData(
        IMultiPositionManager.Range[] memory ranges,
        uint256[] memory weights,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        uint256 maxSlippage
    ) private pure returns (uint256[2][] memory inMin) {
        uint256 rangesLength = ranges.length;
        inMin = new uint256[2][](rangesLength);

        if (rangesLength == 0) return inMin;

        InMinCalcState memory state;

        // First pass: calculate weighted token requirements
        for (uint256 i = 0; i < rangesLength; i++) {
            if (ranges[i].lowerTick == 0 && ranges[i].upperTick == 0) continue;

            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

            (uint256 amount0For1e18, uint256 amount1For1e18) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);

            state.totalWeightedToken0 += (amount0For1e18 * weights[i]) / 1e18;
            state.totalWeightedToken1 += (amount1For1e18 * weights[i]) / 1e18;
        }

        // Calculate total liquidity based on limiting token
        {
            state.maxLiquidityFromToken0 = state.totalWeightedToken0 > 0
                ? uint128((amount0 * 1e18) / state.totalWeightedToken0)
                : type(uint128).max;
            state.maxLiquidityFromToken1 = state.totalWeightedToken1 > 0
                ? uint128((amount1 * 1e18) / state.totalWeightedToken1)
                : type(uint128).max;

            state.totalLiquidity = state.maxLiquidityFromToken0 < state.maxLiquidityFromToken1
                ? state.maxLiquidityFromToken0
                : state.maxLiquidityFromToken1;
        }

        // Apply slippage protection
        state.slippageMultiplier = 10000 - maxSlippage;

        // Second pass: calculate inMin for each position
        for (uint256 i = 0; i < rangesLength; i++) {
            if (ranges[i].lowerTick == 0 && ranges[i].upperTick == 0) {
                inMin[i] = [uint256(0), uint256(0)];
                continue;
            }

            // Check if this is a carpet position (extreme ticks)
            bool isCarpet = _isCarpetPosition(ranges[i].lowerTick, ranges[i].upperTick);

            if (isCarpet) {
                // For carpet positions, use minimal inMin
                inMin[i] = [uint256(0), uint256(0)];
                continue;
            }

            uint128 positionLiquidity = uint128((uint256(state.totalLiquidity) * weights[i]) / 1e18);

            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

            (uint256 amount0For, uint256 amount1For) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, positionLiquidity);

            inMin[i] = [
                FullMath.mulDiv(amount0For, state.slippageMultiplier, 10000),
                FullMath.mulDiv(amount1For, state.slippageMultiplier, 10000)
            ];
        }
    }

    /**
     * @notice Check if a position is a carpet position (extreme ticks)
     */
    function _isCarpetPosition(int24 lowerTick, int24 upperTick) private pure returns (bool) {
        return (lowerTick < -800000 || upperTick > 800000);
    }

    function _calculateInMinInternal(InMinRebalanceParams memory params) private view returns (uint256[2][] memory) {
        DensityCalcParams memory densityParams;
        InMinCalcData memory calcData;

        // Block 1: Get amounts and estimate post-swap if needed
        {
            (uint256 amount0, uint256 amount1) = _getTotalAmountsForRebalance(params.manager, params.deductFees);

            // If swap is involved, estimate post-swap amounts
            if (params.swap) {
                (amount0, amount1) = _estimatePostSwapAmounts(params, amount0, amount1);
            }

            calcData.amount0 = amount0;
            calcData.amount1 = amount1;
        }

        // Block 2: Get pool state
        {
            PoolKey memory poolKey = params.manager.poolKey();
            IPoolManager poolManager = params.manager.poolManager();
            (calcData.sqrtPriceX96, calcData.currentTick,,) = poolManager.getSlot0(poolKey.toId());
            calcData.tickSpacing = poolKey.tickSpacing;
            calcData.maxSlippage = params.maxSlippage;
        }

        // Block 3: Prepare density params
        {
            int24 resolvedCenterTick = params.centerTick;
            if (params.centerTick == type(int24).max) {
                int24 compressed = calcData.currentTick / calcData.tickSpacing;
                if (calcData.currentTick < 0 && calcData.currentTick % calcData.tickSpacing != 0) {
                    compressed--;
                }
                resolvedCenterTick = compressed * calcData.tickSpacing;
            }

            // For proportional weights, calculate from post-swap amounts
            uint256 weight0 = params.weight0;
            uint256 weight1 = params.weight1;
            if (params.weight0 == 0 && params.weight1 == 0) {
                (weight0, weight1) = RebalanceLogic.calculateWeightsFromAmounts(
                    calcData.amount0, calcData.amount1, calcData.sqrtPriceX96
                );
            }

            densityParams = DensityCalcParams({
                strategyAddress: params.strategyAddress,
                centerTick: resolvedCenterTick,
                ticksLeft: params.ticksLeft,
                ticksRight: params.ticksRight,
                weight0: weight0,
                weight1: weight1,
                useCarpet: params.useCarpet,
                useAssetWeights: (params.weight0 == 0 && params.weight1 == 0),
                currentTick: calcData.currentTick,
                tickSpacing: calcData.tickSpacing
            });
        }

        return _calculateInMinWithStructs(densityParams, calcData);
    }

    function _calculateInMinWithStructs(DensityCalcParams memory densityParams, InMinCalcData memory calcData)
        private
        view
        returns (uint256[2][] memory)
    {
        int24[] memory lowerTicks;
        int24[] memory upperTicks;
        uint256[] memory weights;

        // Step 1: Generate ranges
        {
            (lowerTicks, upperTicks) =
                _callGenerateRanges(densityParams.strategyAddress, densityParams, calcData.tickSpacing);
        }

        // Step 2: Calculate weights
        {
            weights = _callCalculateDensities(densityParams, lowerTicks, upperTicks);
        }

        // Step 3: Calculate final inMin
        {
            return _calculateInMinArrayFromAmounts(
                lowerTicks,
                upperTicks,
                weights,
                calcData.amount0,
                calcData.amount1,
                calcData.sqrtPriceX96,
                calcData.maxSlippage,
                densityParams.useAssetWeights
            );
        }
    }

    function _calculateInMinArrayFromAmounts(
        int24[] memory lowerTicks,
        int24[] memory upperTicks,
        uint256[] memory weights,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        uint256 maxSlippage,
        bool useAssetWeights
    ) private pure returns (uint256[2][] memory inMin) {
        inMin = new uint256[2][](lowerTicks.length);
        if (lowerTicks.length == 0) return inMin;

        // Use RebalanceLogic's allocation algorithm to match actual rebalance behavior
        RebalanceLogic.AllocationData memory data;
        data.token0Allocations = new uint256[](lowerTicks.length);
        data.token1Allocations = new uint256[](lowerTicks.length);
        data.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);

        // Convert ticks to ranges for RebalanceLogic functions
        IMultiPositionManager.Range[] memory baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
        for (uint256 i = 0; i < lowerTicks.length; i++) {
            baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
        }

        // Step 1: Calculate initial allocations based on weights
        RebalanceLogic.calculateInitialAllocations(data, baseRanges, weights, sqrtPriceX96, false, 1);

        // Step 2: Scale allocations proportionally
        RebalanceLogic.scaleAllocations(data, amount0, amount1, useAssetWeights);

        // Step 3: Fix current range and redistribute (only for proportional weights)
        if (useAssetWeights && data.hasCurrentRange) {
            RebalanceLogic.fixCurrentRangeAndRedistribute(data, baseRanges, sqrtPriceX96);
        }

        // Step 4: Convert allocations to inMin with slippage using round-trip calculation
        uint256 slippageMultiplier = 10000 - maxSlippage;
        _convertAllocationsToInMin(inMin, data, lowerTicks, upperTicks, sqrtPriceX96, slippageMultiplier);

        return inMin;
    }

    /**
     * @notice Convert token allocations to inMin values using round-trip calculation
     */
    function _convertAllocationsToInMin(
        uint256[2][] memory inMin,
        RebalanceLogic.AllocationData memory data,
        int24[] memory lowerTicks,
        int24[] memory upperTicks,
        uint160 sqrtPriceX96,
        uint256 slippageMultiplier
    ) private pure {
        uint256 length = lowerTicks.length;

        for (uint256 i = 0; i < length; i++) {
            // Check if this is a carpet position (extreme ticks)
            bool isCarpet = _isCarpetPosition(lowerTicks[i], upperTicks[i]);
            if (isCarpet) {
                // For carpet positions, use minimal inMin (0)
                inMin[i] = [uint256(0), uint256(0)];
                continue;
            }

            // Round-trip calculation to get actual consumption amounts
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(lowerTicks[i]);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(upperTicks[i]);

            // Get liquidity that will be minted (constraining factor)
            uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
                sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, data.token0Allocations[i], data.token1Allocations[i]
            );

            // Get actual amounts that will be consumed
            (uint256 actualAmount0, uint256 actualAmount1) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, liquidity);

            // Apply slippage to actual consumption (not allocated amounts)
            inMin[i] = [
                FullMath.mulDiv(actualAmount0, slippageMultiplier, 10000),
                FullMath.mulDiv(actualAmount1, slippageMultiplier, 10000)
            ];
        }
    }

    function _getTotalAmountsForRebalance(MultiPositionManager manager, bool deductFees)
        private
        view
        returns (uint256 total0, uint256 total1)
    {
        uint256 fee0;
        uint256 fee1;
        (total0, total1, fee0, fee1) = manager.getTotalAmounts();

        // When compoundFees=false, fees are claimed before rebalance, so subtract them
        if (deductFees) {
            total0 = total0 > fee0 ? total0 - fee0 : 0;
            total1 = total1 > fee1 ? total1 - fee1 : 0;
        }
    }

    function _estimatePostSwapAmounts(InMinRebalanceParams memory params, uint256 amount0, uint256 amount1)
        private
        view
        returns (uint256, uint256)
    {
        // Get pool state
        PoolKey memory poolKey = params.manager.poolKey();
        IPoolManager poolManager = params.manager.poolManager();
        (uint160 sqrtPriceX96, int24 currentTick,,) = poolManager.getSlot0(poolKey.toId());

        // Calculate target weights using helper function to avoid stack too deep
        (uint256 weight0, uint256 weight1) = _calculateTargetWeights(params, poolKey, sqrtPriceX96, currentTick);

        // Estimate post-swap amounts (simplified calculation)
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), 1e18, 1 << 96);

        uint256 total0InToken1 = amount0 + FullMath.mulDiv(amount1, 1e18, price);
        uint256 targetAmount0 = FullMath.mulDiv(total0InToken1, weight0, weight0 + weight1);
        uint256 targetAmount1 = FullMath.mulDiv(total0InToken1, weight1, weight0 + weight1);

        // Convert back to token amounts
        targetAmount1 = FullMath.mulDiv(targetAmount1, price, 1e18);

        return (targetAmount0, targetAmount1);
    }

    function _calculateTargetWeights(
        InMinRebalanceParams memory params,
        PoolKey memory poolKey,
        uint160 sqrtPriceX96,
        int24 currentTick
    ) private view returns (uint256 weight0, uint256 weight1) {
        // Get resolved center tick
        int24 centerTick = params.centerTick;
        if (params.centerTick == type(int24).max) {
            int24 tickSpacing = poolKey.tickSpacing;
            int24 compressed = currentTick / tickSpacing;
            if (currentTick < 0 && currentTick % tickSpacing != 0) {
                compressed--;
            }
            centerTick = compressed * tickSpacing;
        }

        // Calculate target weights from strategy (not from current amounts)
        weight0 = params.weight0;
        weight1 = params.weight1;
        if (params.weight0 == 0 && params.weight1 == 0) {
            (weight0, weight1) = RebalanceLogic.calculateWeightsFromStrategy(
                ILiquidityStrategy(params.strategyAddress),
                centerTick,
                params.ticksLeft,
                params.ticksRight,
                poolKey.tickSpacing,
                params.useCarpet,
                sqrtPriceX96,
                currentTick
            );
        }
    }

    function _callGenerateRanges(address strategyAddress, DensityCalcParams memory params, int24 tickSpacing)
        private
        view
        returns (int24[] memory lowerTicks, int24[] memory upperTicks)
    {
        ILiquidityStrategy strategy = ILiquidityStrategy(strategyAddress);

        (lowerTicks, upperTicks) = strategy.generateRanges(
            params.centerTick, params.ticksLeft, params.ticksRight, tickSpacing, params.useCarpet
        );
    }

    function _callCalculateDensities(
        DensityCalcParams memory params,
        int24[] memory lowerTicks,
        int24[] memory upperTicks
    ) private view returns (uint256[] memory) {
        return ILiquidityStrategy(params.strategyAddress).calculateDensities(
            lowerTicks,
            upperTicks,
            params.currentTick,
            params.centerTick,
            params.ticksLeft,
            params.ticksRight,
            params.weight0,
            params.weight1,
            params.useCarpet,
            params.tickSpacing,
            params.useAssetWeights
        );
    }

    /**
     * @notice Public function to get all outMin and inMin for rebalance (struct version)
     * @param params RebalanceMinParams struct containing all parameters
     */
    function getOutMinAndInMinForRebalance(RebalanceMinParams memory params)
        external
        view
        returns (uint256[2][] memory outMin, uint256[2][] memory inMin)
    {
        // In proportional mode (weights 0,0), force limitWidth to 0
        uint24 limitWidth = params.limitWidth;
        if (params.weight0 == 0 && params.weight1 == 0) {
            limitWidth = 0;
        }

        outMin = _calculateOutMinForRebalance(params.manager, params.maxSlippageOutMin);

        InMinRebalanceParams memory inMinParams;
        inMinParams.manager = params.manager;
        inMinParams.strategyAddress = params.strategyAddress;
        inMinParams.centerTick = params.centerTick;
        inMinParams.ticksLeft = params.ticksLeft;
        inMinParams.ticksRight = params.ticksRight;
        inMinParams.limitWidth = limitWidth;
        inMinParams.weight0 = params.weight0;
        inMinParams.weight1 = params.weight1;
        inMinParams.useCarpet = params.useCarpet;
        inMinParams.swap = params.swap;
        inMinParams.maxSlippage = params.maxSlippageInMin;
        inMinParams.deductFees = params.deductFees;

        inMin = _calculateInMinInternal(inMinParams);

        return (outMin, inMin);
    }

    function _calculateOutMinForRebalance(MultiPositionManager manager, uint256 maxSlippage)
        private
        view
        returns (uint256[2][] memory outMin)
    {
        (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData) =
            manager.getPositions();

        return PoolManagerUtils.calculateOutMinForRebalance(
            manager.poolManager(), manager.poolKey(), ranges, positionData, maxSlippage
        );
    }

    /**
     * @notice Simulate rebalance positions
     * @param manager The MultiPositionManager
     * @param totalAmount0 Total token0 to rebalance
     * @param totalAmount1 Total token1 to rebalance
     * @param params Rebalance parameters
     * @return preview Rebalance preview
     */
    function simulateRebalance(
        MultiPositionManager manager,
        uint256 totalAmount0,
        uint256 totalAmount1,
        IMultiPositionManager.RebalanceParams memory params
    ) internal view returns (RebalancePreview memory preview) {
        IPoolManager poolManager = manager.poolManager();
        PoolKey memory poolKey = manager.poolKey();

        // Get pool state and resolve center
        PreviewContext memory ctx;
        (ctx.sqrtPriceX96, ctx.currentTick,,) = poolManager.getSlot0(poolKey.toId());
        ctx.resolvedCenter = _resolveCenterTick(params.center, ctx.currentTick, poolKey.tickSpacing);

        // Calculate swap (assuming no swap for simplicity, weight0/weight1 passed through)
        ctx.finalAmount0 = totalAmount0;
        ctx.finalAmount1 = totalAmount1;

        // Use RebalanceLogic to generate ranges and liquidities
        RebalanceLogic.StrategyContext memory rbCtx = RebalanceLogic.StrategyContext({
            resolvedStrategy: params.strategy,
            center: ctx.resolvedCenter,
            tLeft: params.tLeft,
            tRight: params.tRight,
            strategy: ILiquidityStrategy(params.strategy),
            weight0: params.weight0,
            weight1: params.weight1,
            useCarpet: params.useCarpet,
            limitWidth: params.limitWidth,
            useAssetWeights: (params.weight0 == 0 && params.weight1 == 0)
        });

        (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory baseLiquidities) = RebalanceLogic
            .generateRangesAndLiquiditiesWithPoolKey(poolKey, poolManager, rbCtx, ctx.finalAmount0, ctx.finalAmount1);

        // Add limit positions
        IMultiPositionManager.Range[] memory allRanges;
        uint128[] memory allLiquidities;

        if (params.limitWidth > 0) {
            // Calculate limit ranges using PositionLogic
            (IMultiPositionManager.Range memory lowerLimit, IMultiPositionManager.Range memory upperLimit) =
                PositionLogic.calculateLimitRanges(params.limitWidth, baseRanges, poolKey.tickSpacing, ctx.currentTick);

            // Create arrays for base + 2 limit positions
            allRanges = new IMultiPositionManager.Range[](baseRanges.length + 2);
            allLiquidities = new uint128[](baseRanges.length + 2);

            // Copy base ranges and liquidities
            for (uint256 i = 0; i < baseRanges.length; i++) {
                allRanges[i] = baseRanges[i];
                allLiquidities[i] = baseLiquidities[i];
            }

            // Calculate remainders from base positions
            (uint256 remainderToken0, uint256 remainderToken1) =
                _calculateRemainders(baseRanges, baseLiquidities, ctx.sqrtPriceX96, ctx.finalAmount0, ctx.finalAmount1);

            // Add limit positions
            allRanges[baseRanges.length] = lowerLimit;
            allRanges[baseRanges.length + 1] = upperLimit;

            // Lower limit (below current tick) gets remainder token1
            if (lowerLimit.lowerTick != lowerLimit.upperTick && remainderToken1 > 0) {
                allLiquidities[baseRanges.length] = LiquidityAmounts.getLiquidityForAmounts(
                    ctx.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(lowerLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(lowerLimit.upperTick),
                    0,
                    remainderToken1
                );
            }

            // Upper limit (above current tick) gets remainder token0
            if (upperLimit.lowerTick != upperLimit.upperTick && remainderToken0 > 0) {
                allLiquidities[baseRanges.length + 1] = LiquidityAmounts.getLiquidityForAmounts(
                    ctx.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(upperLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(upperLimit.upperTick),
                    remainderToken0,
                    0
                );
            }
        } else {
            allRanges = baseRanges;
            allLiquidities = baseLiquidities;
        }

        // Build preview
        preview.ranges = allRanges;
        preview.strategy = params.strategy;
        preview.centerTick = ctx.resolvedCenter;
        preview.ticksLeft = params.tLeft;
        preview.ticksRight = params.tRight;
        preview.liquidities = allLiquidities;
        preview.postSwapAmount0 = ctx.finalAmount0;
        preview.postSwapAmount1 = ctx.finalAmount1;

        // Calculate expected positions
        preview.expectedPositions = new LensRatioUtils.PositionStats[](allRanges.length);
        _populateExpectedPositions(allRanges, allLiquidities, ctx.sqrtPriceX96, preview, baseRanges.length);
    }

    function _resolveCenterTick(int24 centerTick, int24 currentTick, int24 tickSpacing)
        private
        pure
        returns (int24 resolvedCenter)
    {
        if (centerTick == type(int24).max) {
            int24 compressed = currentTick / tickSpacing;
            if (currentTick < 0 && currentTick % tickSpacing != 0) {
                compressed--;
            }
            resolvedCenter = compressed * tickSpacing;
        } else {
            resolvedCenter = centerTick;
        }
    }

    function _calculateRemainders(
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory baseLiquidities,
        uint160 sqrtPriceX96,
        uint256 totalAmount0,
        uint256 totalAmount1
    ) private pure returns (uint256 remainderToken0, uint256 remainderToken1) {
        uint256 consumedToken0;
        uint256 consumedToken1;
        for (uint256 i = 0; i < baseRanges.length; i++) {
            (uint256 amt0, uint256 amt1) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96,
                TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick),
                TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick),
                baseLiquidities[i]
            );
            consumedToken0 += amt0;
            consumedToken1 += amt1;
        }
        remainderToken0 = totalAmount0 > consumedToken0 ? totalAmount0 - consumedToken0 : 0;
        remainderToken1 = totalAmount1 > consumedToken1 ? totalAmount1 - consumedToken1 : 0;
    }

    function _populateExpectedPositions(
        IMultiPositionManager.Range[] memory ranges,
        uint128[] memory liquidities,
        uint160 sqrtPriceX96,
        RebalancePreview memory preview,
        uint256 baseLength
    ) private pure {
        // Get current price for value calculations
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), 1e18, 1 << 96);

        preview.expectedTotal0 = 0;
        preview.expectedTotal1 = 0;

        for (uint256 i = 0; i < ranges.length; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(ranges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(ranges[i].upperTick);

            (uint256 amount0, uint256 amount1) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, liquidities[i]);

            uint256 valueInToken1 = amount1 + FullMath.mulDiv(amount0, price, 1e18);

            preview.expectedPositions[i] = LensRatioUtils.PositionStats({
                tickLower: ranges[i].lowerTick,
                tickUpper: ranges[i].upperTick,
                sqrtPriceLower: sqrtPriceLower,
                sqrtPriceUpper: sqrtPriceUpper,
                liquidity: liquidities[i],
                token0Quantity: amount0,
                token1Quantity: amount1,
                valueInToken1: valueInToken1,
                isLimit: i >= baseLength
            });

            preview.expectedTotal0 += amount0;
            preview.expectedTotal1 += amount1;
        }
    }

    /**
     * @notice Add limit positions and calculate inMin
     */
    function addLimitPositionsAndCalculateInMin(
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory baseLiquidities,
        LimitPositionsParams memory params
    )
        external
        pure
        returns (
            IMultiPositionManager.Range[] memory allRanges,
            uint128[] memory allLiquidities,
            uint256[2][] memory inMin
        )
    {
        // Add limit positions if needed
        if (params.limitWidth > 0) {
            IMultiPositionManager.Range memory lowerLimit;
            IMultiPositionManager.Range memory upperLimit;

            {
                (lowerLimit, upperLimit) = PositionLogic.calculateLimitRanges(
                    params.limitWidth, baseRanges, params.tickSpacing, params.currentTick
                );
            }

            allRanges = new IMultiPositionManager.Range[](baseRanges.length + 2);
            allLiquidities = new uint128[](baseRanges.length + 2);

            // Copy base ranges and liquidities
            for (uint256 i = 0; i < baseRanges.length; i++) {
                allRanges[i] = baseRanges[i];
                allLiquidities[i] = baseLiquidities[i];
            }

            // Calculate consumed tokens and remainders
            (uint256 remainderToken0, uint256 remainderToken1) = _calculateRemainders(
                baseRanges, baseLiquidities, params.sqrtPriceX96, params.totalAmount0, params.totalAmount1
            );

            // Add limit positions with liquidity from remainders
            allRanges[baseRanges.length] = lowerLimit;
            allRanges[baseRanges.length + 1] = upperLimit;

            // Lower limit (below current tick) gets remainder token1
            if (lowerLimit.lowerTick != lowerLimit.upperTick && remainderToken1 > 0) {
                allLiquidities[baseRanges.length] = LiquidityAmounts.getLiquidityForAmounts(
                    params.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(lowerLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(lowerLimit.upperTick),
                    0,
                    remainderToken1
                );
            }

            // Upper limit (above current tick) gets remainder token0
            if (upperLimit.lowerTick != upperLimit.upperTick && remainderToken0 > 0) {
                allLiquidities[baseRanges.length + 1] = LiquidityAmounts.getLiquidityForAmounts(
                    params.sqrtPriceX96,
                    TickMath.getSqrtPriceAtTick(upperLimit.lowerTick),
                    TickMath.getSqrtPriceAtTick(upperLimit.upperTick),
                    remainderToken0,
                    0
                );
            }
        } else {
            allRanges = baseRanges;
            allLiquidities = baseLiquidities;
        }

        // Calculate inMin
        inMin = _calculateInMin(baseRanges, baseLiquidities, params.maxSlippageBps, params.sqrtPriceX96);
    }

    function _calculateInMin(
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory baseLiquidities,
        uint256 maxSlippageBps,
        uint160 sqrtPriceX96
    ) internal pure returns (uint256[2][] memory inMin) {
        inMin = new uint256[2][](baseRanges.length);
        uint256 slippageMultiplier = 10000 - maxSlippageBps;

        for (uint256 i = 0; i < baseRanges.length; i++) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);

            (uint256 amt0, uint256 amt1) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, baseLiquidities[i]
            );

            inMin[i] =
                [FullMath.mulDiv(amt0, slippageMultiplier, 10000), FullMath.mulDiv(amt1, slippageMultiplier, 10000)];
        }
    }
}

File 15 of 82 : RebalanceLogic.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/libraries/FixedPoint96.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {PositionLogic} from "./PositionLogic.sol";

/**
 * @title RebalanceLogic
 * @notice Library containing all rebalance-related logic for MultiPositionManager
 */
library RebalanceLogic {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    uint256 constant PRECISION = 1e18;
    uint256 constant FLOOR_MIN_TOKEN0 = 1;
    uint256 constant FLOOR_MIN_TOKEN1 = 1;

    // Custom errors
    error OutMinLengthMismatch();
    error InvalidWeightSum();
    error NoStrategySpecified();
    error InvalidTickRange();
    error DuplicatedRange(IMultiPositionManager.Range range);
    error InvalidAggregator();
    error StrategyDoesNotSupportWeights();
    error InMinLengthMismatch(uint256 provided, uint256 required);
    error InsufficientTokensForSwap();
    error InsufficientOutput();

    // Events
    event SwapExecuted(address indexed aggregator, uint256 amountIn, uint256 amountOut, bool swapToken0);

    struct StrategyContext {
        address resolvedStrategy;
        int24 center;
        uint24 tLeft;
        uint24 tRight;
        ILiquidityStrategy strategy;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        uint24 limitWidth;
        bool useAssetWeights;
    }

    struct DensityParams {
        int24[] lowerTicks;
        int24[] upperTicks;
        int24 tick;
        int24 center;
        uint24 tLeft;
        uint24 tRight;
        uint256 weight0;
        uint256 weight1;
        bool useCarpet;
        int24 tickSpacing;
    }

    struct WeightCalculationParams {
        ILiquidityStrategy strategy;
        int24 center;
        uint24 tLeft;
        uint24 tRight;
        int24 tickSpacing;
        bool useCarpet;
        uint160 sqrtPriceX96;
        int24 currentTick;
    }

    /// @notice Supported swap aggregators
    enum Aggregator {
        ZERO_X, // 0
        KYBERSWAP, // 1
        ODOS, // 2
        PARASWAP // 3

    }

    /// @notice Parameters for executing a swap through an aggregator
    struct SwapParams {
        Aggregator aggregator; // Which aggregator to use
        address aggregatorAddress; // Aggregator router address (must match factory allowlist)
        bytes swapData; // Complete encoded function call from JavaScript
        bool swapToken0; // Direction: true = swap token0 for token1
        uint256 swapAmount; // Amount being swapped (for validation)
        uint256 minAmountOut; // Minimum output amount (slippage protection)
    }

    /**
     * @notice Main rebalance function
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param params Rebalance parameters
     * @param outMin Minimum output amounts for withdrawals (validated for length)
     * @return baseRanges The base ranges to rebalance to
     * @return liquidities The liquidity amounts for each range
     * @return limitWidth The limit width for limit positions
     */
    function rebalance(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        IMultiPositionManager.RebalanceParams calldata params,
        uint256[2][] memory outMin
    )
        external
        returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
    {
        if (outMin.length != s.basePositionsLength + s.limitPositionsLength) {
            revert OutMinLengthMismatch();
        }

        // Process in helper to avoid stack issues
        return _processRebalance(s, poolManager, params);
    }

    function _processRebalance(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        IMultiPositionManager.RebalanceParams memory params
    )
        internal
        returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
    {
        // Bundle strategy parameters in a struct to reduce stack depth
        StrategyContext memory ctx;

        ctx.weight0 = params.weight0;
        ctx.weight1 = params.weight1;
        ctx.useAssetWeights = (ctx.weight0 == 0 && ctx.weight1 == 0);
        if (ctx.useAssetWeights) {
            (uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);
            (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
            (ctx.weight0, ctx.weight1) = calculateWeightsFromAmounts(available0, available1, sqrtPriceX96);
        }

        if (ctx.weight0 + ctx.weight1 != 1e18) revert InvalidWeightSum();

        // Resolve strategy parameters
        ctx.resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;

        if (params.center == type(int24).max) {
            (, int24 currentTick,,) = poolManager.getSlot0(s.poolKey.toId());
            // Always round down to ensure the range contains the current tick
            int24 compressed = currentTick / s.poolKey.tickSpacing;
            if (currentTick < 0 && currentTick % s.poolKey.tickSpacing != 0) {
                compressed--; // Round down for negative ticks with remainder
            }
            ctx.center = compressed * s.poolKey.tickSpacing;
        } else {
            // Snap to tickSpacing grid using floor division (handles negatives correctly)
            int24 tickSpacing = s.poolKey.tickSpacing;
            ctx.center = (params.center / tickSpacing) * tickSpacing;
            if (params.center < 0 && params.center % tickSpacing != 0) {
                ctx.center -= tickSpacing;
            }
        }

        ctx.tLeft = params.tLeft;
        ctx.tRight = params.tRight;
        ctx.useCarpet = params.useCarpet;

        // In proportional mode (weights 0,0), force limitWidth to 0
        // Limit positions don't make sense when weights are derived from amounts
        if (params.weight0 == 0 && params.weight1 == 0) {
            ctx.limitWidth = 0;
        } else {
            ctx.limitWidth = params.limitWidth;
        }

        // Get strategy interface
        if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
        ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);

        // Generate ranges
        (int24[] memory lowerTicks, int24[] memory upperTicks) =
            ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, s.poolKey.tickSpacing, ctx.useCarpet);

        // Convert to Range array
        uint256 length = lowerTicks.length;
        baseRanges = new IMultiPositionManager.Range[](length);
        for (uint256 i = 0; i < length;) {
            baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
            unchecked {
                ++i;
            }
        }

        // Calculate weights in separate function to avoid stack issues
        uint256[] memory weights = calculateWeights(s, poolManager, ctx, lowerTicks, upperTicks);

        // Continue processing in another helper to further reduce stack
        return _executeRebalance(s, poolManager, ctx, baseRanges, weights);
    }

    /**
     * @notice Calculate weights for positions from strategy
     * @dev Made public so SimpleLens can use the exact same logic for preview
     */
    function calculateWeights(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        int24[] memory lowerTicks,
        int24[] memory upperTicks
    ) public view returns (uint256[] memory) {
        return calculateWeightsWithPoolKey(s.poolKey, poolManager, ctx, lowerTicks, upperTicks);
    }

    /**
     * @notice Calculate weights (pure version for SimpleLens)
     * @dev Accepts poolKey as parameter instead of reading from storage
     */
    function calculateWeightsWithPoolKey(
        PoolKey memory poolKey,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        int24[] memory lowerTicks,
        int24[] memory upperTicks
    ) public view returns (uint256[] memory) {
        // Store flag early to avoid stack too deep
        bool useAssetWeights = ctx.useAssetWeights;

        DensityParams memory params;
        params.lowerTicks = lowerTicks;
        params.upperTicks = upperTicks;

        // Get current tick
        (, params.tick,,) = poolManager.getSlot0(poolKey.toId());

        params.center = ctx.center;
        params.tLeft = ctx.tLeft;
        params.tRight = ctx.tRight;
        params.weight0 = ctx.weight0;
        params.weight1 = ctx.weight1;
        params.useCarpet = ctx.useCarpet;
        params.tickSpacing = poolKey.tickSpacing;

        // Check weights support
        {
            bool supportsWeightedDist = false;
            try ctx.strategy.supportsWeights() returns (bool supported) {
                supportsWeightedDist = supported;
            } catch {}

            // If strategy doesn't support explicit weights, revert when non-default weights are provided.
            if (!params.useCarpet && !supportsWeightedDist && (params.weight0 != 0.5e18 || params.weight1 != 0.5e18)) {
                revert StrategyDoesNotSupportWeights();
            }
        }

        uint256[] memory weights = ctx.strategy.calculateDensities(
            params.lowerTicks,
            params.upperTicks,
            params.tick,
            params.center,
            params.tLeft,
            params.tRight,
            params.weight0,
            params.weight1,
            params.useCarpet,
            params.tickSpacing,
            useAssetWeights
        );

        return adjustWeightsForFullRangeFloor(weights, lowerTicks, upperTicks, poolKey.tickSpacing, ctx.useCarpet);
    }

    function adjustWeightsForFullRangeFloor(
        uint256[] memory weights,
        int24[] memory lowerTicks,
        int24[] memory upperTicks,
        int24 tickSpacing,
        bool useCarpet
    ) public pure returns (uint256[] memory) {
        if (!useCarpet || weights.length == 0 || lowerTicks.length != upperTicks.length) {
            return weights;
        }

        int24 minUsable = TickMath.minUsableTick(tickSpacing);
        int24 maxUsable = TickMath.maxUsableTick(tickSpacing);
        uint256 floorIdx = _findFullRangeIndex(lowerTicks, upperTicks, minUsable, maxUsable);
        if (floorIdx == type(uint256).max) {
            return weights;
        }
        if (weights.length == 1) {
            return weights;
        }

        _adjustWeightsForFloorIndex(weights, floorIdx);
        return weights;
    }

    function _executeRebalance(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256[] memory weights
    ) internal returns (IMultiPositionManager.Range[] memory, uint128[] memory, uint24) {
        // Calculate liquidities from weights
        uint128[] memory liquidities = new uint128[](baseRanges.length);

        _calculateLiquiditiesForRebalance(s, poolManager, ctx, weights, baseRanges, liquidities, ctx.useCarpet);

        // Store the parameters for future use (useSwap = false for regular rebalance)
        _updateStrategyParams(s, ctx, false);

        // Return the data needed for the unlock
        // Note: Rebalance event will be emitted in MultiPositionManager after unlock completes
        return (baseRanges, liquidities, ctx.limitWidth);
    }

    function _updateStrategyParams(SharedStructs.ManagerStorage storage s, StrategyContext memory ctx, bool useSwap)
        internal
    {
        s.lastStrategyParams = SharedStructs.StrategyParams({
            strategy: ctx.resolvedStrategy,
            centerTick: ctx.center,
            ticksLeft: ctx.tLeft,
            ticksRight: ctx.tRight,
            limitWidth: ctx.limitWidth,
            weight0: uint120(ctx.weight0),
            weight1: uint120(ctx.weight1),
            useCarpet: ctx.useCarpet,
            useSwap: useSwap,
            useAssetWeights: ctx.useAssetWeights
        });
    }

    function _calculateLiquiditiesForRebalance(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        uint256[] memory weights,
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory liquidities,
        bool useCarpet
    ) private view {
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());
        (uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);

        LiquidityCalcParams memory calcParams = LiquidityCalcParams({
            amount0: available0,
            amount1: available1,
            sqrtPriceX96: sqrtPriceX96,
            useAssetWeights: ctx.useAssetWeights,
            tickSpacing: s.poolKey.tickSpacing,
            useCarpet: useCarpet
        });
        _calculateLiquiditiesFromWeightsWithParams(liquidities, weights, baseRanges, calcParams);
    }

    struct AllocationData {
        uint256[] token0Allocations;
        uint256[] token1Allocations;
        uint256 totalToken0Needed;
        uint256 totalToken1Needed;
        uint256 currentRangeIndex;
        int24 currentTick;
        bool hasCurrentRange;
    }

    struct LiquidityCalcParams {
        uint256 amount0;
        uint256 amount1;
        uint160 sqrtPriceX96;
        bool useAssetWeights;
        int24 tickSpacing;
        bool useCarpet;
    }

    struct FloorReserveInfo {
        bool active;
        uint256 index;
        uint256 reserve0;
        uint256 reserve1;
        uint128 liquidity;
    }

    struct FloorRangeContext {
        uint256 total0;
        uint256 total1;
        uint160 sqrtPriceX96;
        int24 tickSpacing;
        int24 minUsable;
        int24 maxUsable;
        int24 currentTick;
    }

    /**
     * @notice Helper to calculate liquidities from weights using pre-mint allocation fixing
     * @dev Allocate, fix current range, redistribute excess, then mint
     */
    function _calculateLiquiditiesFromWeights(
        uint128[] memory liquidities,
        uint256[] memory weights,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 total0,
        uint256 total1,
        uint160 sqrtPriceX96,
        bool useAssetWeights,
        int24 tickSpacing,
        bool useCarpet
    ) internal pure {
        FloorReserveInfo memory floorInfo;
        uint256 remaining0 = total0;
        uint256 remaining1 = total1;

        if (useCarpet) {
            (floorInfo, remaining0, remaining1) =
                _reserveFloorLiquidity(baseRanges, total0, total1, sqrtPriceX96, tickSpacing, useCarpet);
            if (floorInfo.active) {
                _adjustWeightsForFloorIndex(weights, floorInfo.index);
            }
        }

        if (!useAssetWeights) {
            // For explicit weights, use direct liquidity calculation (old approach)
            calculateLiquiditiesDirectly(liquidities, weights, baseRanges, remaining0, remaining1, sqrtPriceX96);
            if (floorInfo.active && floorInfo.index < liquidities.length) {
                uint256 combined = uint256(liquidities[floorInfo.index]) + floorInfo.liquidity;
                liquidities[floorInfo.index] =
                    combined > type(uint128).max ? type(uint128).max : uint128(combined);
            }
            return;
        }

        // For proportional weights, use allocation-based approach with redistribution
        AllocationData memory data;
        uint256 rangesLength = baseRanges.length;

        // Initialize arrays
        data.token0Allocations = new uint256[](rangesLength);
        data.token1Allocations = new uint256[](rangesLength);

        // Get current tick from sqrtPrice
        data.currentTick = TickMath.getTickAtSqrtPrice(sqrtPriceX96);

        // Step 1: Calculate initial token allocations based on weights
        calculateInitialAllocations(data, baseRanges, weights, sqrtPriceX96, useCarpet, tickSpacing);

        // Step 2: Scale allocations proportionally to available tokens
        scaleAllocations(data, remaining0, remaining1, true);

        // Step 3: Fix current range allocation and redistribute excess
        if (data.hasCurrentRange) {
            fixCurrentRangeAndRedistribute(data, baseRanges, sqrtPriceX96);
        }

        // Step 4: Mint all positions with corrected allocations
        mintFromAllocations(liquidities, data, baseRanges, sqrtPriceX96);
        if (floorInfo.active && floorInfo.index < liquidities.length) {
            uint256 combined = uint256(liquidities[floorInfo.index]) + floorInfo.liquidity;
            liquidities[floorInfo.index] = combined > type(uint128).max ? type(uint128).max : uint128(combined);
        }
    }

    function _calculateLiquiditiesFromWeightsWithParams(
        uint128[] memory liquidities,
        uint256[] memory weights,
        IMultiPositionManager.Range[] memory baseRanges,
        LiquidityCalcParams memory params
    ) internal pure {
        _calculateLiquiditiesFromWeights(
            liquidities,
            weights,
            baseRanges,
            params.amount0,
            params.amount1,
            params.sqrtPriceX96,
            params.useAssetWeights,
            params.tickSpacing,
            params.useCarpet
        );
    }

    /**
     * @notice Calculate liquidities directly using limiting token approach (for explicit weights)
     * @dev Old approach: calculate global limiting factor, then set each position's liquidity
     */
    function calculateLiquiditiesDirectly(
        uint128[] memory liquidities,
        uint256[] memory weights,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 total0,
        uint256 total1,
        uint160 sqrtPriceX96
    ) internal pure {
        uint256 rangesLength = baseRanges.length;

        // Calculate total weighted amounts needed for liquidity = 1e18
        uint256 totalWeightedToken0;
        uint256 totalWeightedToken1;

        for (uint256 i = 0; i < rangesLength;) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);

            // Get amounts needed for 1e18 liquidity
            (uint256 amount0For1e18, uint256 amount1For1e18) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);

            // Add weighted amounts
            totalWeightedToken0 += FullMath.mulDiv(amount0For1e18, weights[i], 1e18);
            totalWeightedToken1 += FullMath.mulDiv(amount1For1e18, weights[i], 1e18);
            unchecked {
                ++i;
            }
        }

        // Calculate maximum liquidity we can provide given our token amounts
        uint256 maxLiquidityFromToken0 =
            totalWeightedToken0 != 0 ? FullMath.mulDiv(total0, 1e18, totalWeightedToken0) : type(uint256).max;
        uint256 maxLiquidityFromToken1 =
            totalWeightedToken1 != 0 ? FullMath.mulDiv(total1, 1e18, totalWeightedToken1) : type(uint256).max;

        // Use the limiting factor (smaller of the two)
        uint256 totalLiquidity =
            maxLiquidityFromToken0 < maxLiquidityFromToken1 ? maxLiquidityFromToken0 : maxLiquidityFromToken1;

        // Set each position's liquidity based on its weight and the total liquidity
        for (uint256 i = 0; i < rangesLength;) {
            liquidities[i] = uint128(FullMath.mulDiv(weights[i], totalLiquidity, 1e18));
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Calculate initial token allocations based on weights
     */
    function calculateInitialAllocations(
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256[] memory weights,
        uint160 sqrtPriceX96,
        bool useCarpet,
        int24 tickSpacing
    ) internal pure {
        uint256 rangesLength = baseRanges.length;
        int24 minUsable = 0;
        int24 maxUsable = 0;
        if (useCarpet) {
            minUsable = TickMath.minUsableTick(tickSpacing);
            maxUsable = TickMath.maxUsableTick(tickSpacing);
        }

        for (uint256 i = 0; i < rangesLength;) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);

            // Calculate token amounts for 1e18 liquidity
            (uint256 token0For1e18, uint256 token1For1e18) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, 1e18);

            // Apply weights to get initial allocations
            data.token0Allocations[i] = FullMath.mulDiv(token0For1e18, weights[i], 1e18);
            data.token1Allocations[i] = FullMath.mulDiv(token1For1e18, weights[i], 1e18);

            // Track totals
            data.totalToken0Needed += data.token0Allocations[i];
            data.totalToken1Needed += data.token1Allocations[i];

            // Check if this is the current range
            if (baseRanges[i].lowerTick <= data.currentTick && data.currentTick < baseRanges[i].upperTick) {
                if (
                    useCarpet && rangesLength > 1 && baseRanges[i].lowerTick == minUsable
                        && baseRanges[i].upperTick == maxUsable
                ) {
                    // Skip full-range floor for currentRangeIndex bookkeeping.
                } else {
                    data.currentRangeIndex = i;
                    data.hasCurrentRange = true;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Scale allocations proportionally to available tokens
     * @dev Two modes:
     *      - Proportional weights (0,0): Scale independently, will redistribute later
     *      - Explicit weights: Use limiting token approach, leave excess
     */
    function scaleAllocations(
        AllocationData memory data,
        uint256 available0,
        uint256 available1,
        bool useAssetWeights
    ) internal pure {
        uint256 rangesLength = data.token0Allocations.length;

        if (useAssetWeights) {
            // Proportional mode: Scale each token independently to use 100%
            // Excess will be redistributed in _fixCurrentRangeAndRedistribute
            if (data.totalToken0Needed != 0) {
                for (uint256 i = 0; i < rangesLength;) {
                    data.token0Allocations[i] =
                        FullMath.mulDiv(data.token0Allocations[i], available0, data.totalToken0Needed);
                    unchecked {
                        ++i;
                    }
                }
            }

            if (data.totalToken1Needed != 0) {
                for (uint256 i = 0; i < rangesLength;) {
                    data.token1Allocations[i] =
                        FullMath.mulDiv(data.token1Allocations[i], available1, data.totalToken1Needed);
                    unchecked {
                        ++i;
                    }
                }
            }
        } else {
            // Explicit weights mode: Use limiting token approach
            // Calculate max liquidity from each token
            uint256 maxLiquidityFromToken0 = data.totalToken0Needed != 0
                ? FullMath.mulDiv(available0, 1e18, data.totalToken0Needed)
                : type(uint256).max;
            uint256 maxLiquidityFromToken1 = data.totalToken1Needed != 0
                ? FullMath.mulDiv(available1, 1e18, data.totalToken1Needed)
                : type(uint256).max;

            // Use the limiting factor (smaller of the two)
            uint256 scaleFactor =
                maxLiquidityFromToken0 < maxLiquidityFromToken1 ? maxLiquidityFromToken0 : maxLiquidityFromToken1;

            // Scale both allocations by the same factor
            for (uint256 i = 0; i < rangesLength;) {
                data.token0Allocations[i] = FullMath.mulDiv(data.token0Allocations[i], scaleFactor, 1e18);
                data.token1Allocations[i] = FullMath.mulDiv(data.token1Allocations[i], scaleFactor, 1e18);
                unchecked {
                    ++i;
                }
            }
        }
    }

    struct ExcessData {
        uint256 excessToken0;
        uint256 excessToken1;
        uint256 actualToken0;
        uint256 actualToken1;
    }

    /**
     * @notice Fix current range allocation and redistribute excess
     */
    function fixCurrentRangeAndRedistribute(
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint160 sqrtPriceX96
    ) internal pure {
        ExcessData memory excess = calculateCurrentRangeExcess(data, baseRanges[data.currentRangeIndex], sqrtPriceX96);

        // Update current range to actual usage
        data.token0Allocations[data.currentRangeIndex] = excess.actualToken0;
        data.token1Allocations[data.currentRangeIndex] = excess.actualToken1;

        // Redistribute excesses
        if (excess.excessToken0 > 0) {
            redistributeToken0(data, baseRanges, excess.excessToken0);
        }
        if (excess.excessToken1 > 0) {
            redistributeToken1(data, baseRanges, excess.excessToken1);
        }
    }

    /**
     * @notice Calculate excess from current range allocation
     */
    function calculateCurrentRangeExcess(
        AllocationData memory data,
        IMultiPositionManager.Range memory range,
        uint160 sqrtPriceX96
    ) internal pure returns (ExcessData memory excess) {
        uint256 idx = data.currentRangeIndex;

        uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
        uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);

        // EXACT Python logic from mint_position function:
        // if lower_price<pool_price<upper_price:

        // Python: assume token y (token1) is in excess
        // position_y=y
        // position_liquidity=position_y/(np.sqrt(pool_price)-np.sqrt(lower_price))
        uint256 liquidityFrom1 = 0;
        if (sqrtPriceX96 > sqrtPriceLower) {
            // Direct division as Python does: liquidity = amount1 / (sqrtPrice - sqrtPriceLower)
            liquidityFrom1 =
                FullMath.mulDiv(data.token1Allocations[idx], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower);
        }

        uint256 actualLiquidity;
        if (sqrtPriceX96 <= sqrtPriceLower) {
            // At the lower boundary, the range is token0-only.
            if (data.token0Allocations[idx] > 0 && sqrtPriceUpper > sqrtPriceLower) {
                uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
                actualLiquidity =
                    FullMath.mulDiv(data.token0Allocations[idx], intermediate, sqrtPriceUpper - sqrtPriceLower);
            } else {
                actualLiquidity = 0;
            }
        } else {
            // Python: position_x=position_liquidity*(1/np.sqrt(pool_price)-1/np.sqrt(upper_price))
            uint256 token0Needed = 0;
            if (sqrtPriceX96 < sqrtPriceUpper && liquidityFrom1 > 0) {
                // Calculate how much token0 would be needed with this liquidity
                uint256 denom = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
                if (denom == 0) {
                    uint256 scaled = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, sqrtPriceUpper);
                    token0Needed = FullMath.mulDiv(scaled, FixedPoint96.Q96, sqrtPriceX96);
                } else {
                    token0Needed = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, denom);
                }
            }

            // Python: if x<position_x:  #if token y is actually in excess
            if (data.token0Allocations[idx] < token0Needed) {
                // Token0 is actually limiting, recalculate
                // token0Needed > 0 implies sqrtPriceX96 < sqrtPriceUpper
                uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
                actualLiquidity =
                    FullMath.mulDiv(data.token0Allocations[idx], intermediate, sqrtPriceUpper - sqrtPriceX96);
            } else {
                // Token1 is limiting, use liquidityFrom1
                actualLiquidity = liquidityFrom1;
            }
        }

        // Calculate actual usage with the determined liquidity
        (excess.actualToken0, excess.actualToken1) =
            LiquidityAmounts.getAmountsForLiquidity(
                sqrtPriceX96,
                sqrtPriceLower,
                sqrtPriceUpper,
                _capLiquidity(actualLiquidity)
            );

        // Calculate excess
        excess.excessToken0 =
            data.token0Allocations[idx] > excess.actualToken0 ? data.token0Allocations[idx] - excess.actualToken0 : 0;
        excess.excessToken1 =
            data.token1Allocations[idx] > excess.actualToken1 ? data.token1Allocations[idx] - excess.actualToken1 : 0;
    }

    /**
     * @notice Redistribute excess token0 to positions above current tick
     */
    function redistributeToken0(
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 excessToken0
    ) internal pure {
        uint256 totalToken0Only;
        uint256 rangesLength = data.token0Allocations.length;

        // Find total weight of positions above current tick
        for (uint256 i = 0; i < rangesLength;) {
            if (baseRanges[i].lowerTick > data.currentTick) {
                totalToken0Only += data.token0Allocations[i];
            }
            unchecked {
                ++i;
            }
        }

        // Redistribute proportionally
        if (totalToken0Only != 0) {
            for (uint256 i = 0; i < rangesLength;) {
                if (baseRanges[i].lowerTick > data.currentTick) {
                    data.token0Allocations[i] +=
                        FullMath.mulDiv(excessToken0, data.token0Allocations[i], totalToken0Only);
                }
                unchecked {
                    ++i;
                }
            }
        }
    }

    /**
     * @notice Redistribute excess token1 to positions below current tick
     */
    function redistributeToken1(
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 excessToken1
    ) internal pure {
        uint256 totalToken1Only;
        uint256 rangesLength = data.token0Allocations.length;

        // Find total weight of positions below current tick
        for (uint256 i = 0; i < rangesLength;) {
            if (baseRanges[i].upperTick <= data.currentTick) {
                totalToken1Only += data.token1Allocations[i];
            }
            unchecked {
                ++i;
            }
        }

        // Redistribute proportionally
        if (totalToken1Only != 0) {
            for (uint256 i = 0; i < rangesLength;) {
                if (baseRanges[i].upperTick <= data.currentTick) {
                    data.token1Allocations[i] +=
                        FullMath.mulDiv(excessToken1, data.token1Allocations[i], totalToken1Only);
                }
                unchecked {
                    ++i;
                }
            }
        }
    }

    /**
     * @notice Mint positions from corrected allocations
     */
    function mintFromAllocations(
        uint128[] memory liquidities,
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint160 sqrtPriceX96
    ) internal pure {
        uint256 rangesLength = baseRanges.length;

        for (uint256 i = 0; i < rangesLength;) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(baseRanges[i].lowerTick);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(baseRanges[i].upperTick);

            // EXACT Python mint_position logic for each position type
            if (baseRanges[i].upperTick <= data.currentTick) {
                // Position entirely below current tick - only needs token1
                // Python: position_liquidity=position_y/(np.sqrt(upper_price)-np.sqrt(lower_price))
                if (sqrtPriceUpper > sqrtPriceLower && data.token1Allocations[i] > 0) {
                    uint256 liquidity = FullMath.mulDiv(
                        data.token1Allocations[i],
                        FixedPoint96.Q96,
                        sqrtPriceUpper - sqrtPriceLower
                    );
                    liquidities[i] = _capLiquidity(liquidity);
                } else {
                    liquidities[i] = 0;
                }
            } else if (baseRanges[i].lowerTick > data.currentTick) {
                // Position entirely above current tick - only needs token0
                // Python: position_liquidity=position_x/(1/np.sqrt(lower_price)-1/np.sqrt(upper_price))
                if (sqrtPriceUpper > sqrtPriceLower && data.token0Allocations[i] > 0) {
                    uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
                    uint256 liquidity =
                        FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceLower);
                    liquidities[i] = _capLiquidity(liquidity);
                } else {
                    liquidities[i] = 0;
                }
            } else {
                // Current range - use Python's exact logic
                if (sqrtPriceX96 <= sqrtPriceLower) {
                    // At the lower boundary, the range is token0-only.
                    if (data.token0Allocations[i] > 0 && sqrtPriceUpper > sqrtPriceLower) {
                        uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceLower, FixedPoint96.Q96);
                        uint256 liquidity =
                            FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceLower);
                        liquidities[i] = _capLiquidity(liquidity);
                    } else {
                        liquidities[i] = 0;
                    }
                } else {
                    // First assume token1 is limiting
                    uint256 liquidityFrom1 = 0;
                    if (sqrtPriceX96 > sqrtPriceLower && data.token1Allocations[i] > 0) {
                        liquidityFrom1 =
                            FullMath.mulDiv(data.token1Allocations[i], FixedPoint96.Q96, sqrtPriceX96 - sqrtPriceLower);
                    }

                    // Calculate token0 needed with this liquidity
                    uint256 token0Needed = 0;
                    if (sqrtPriceX96 < sqrtPriceUpper && liquidityFrom1 > 0) {
                        uint256 denom = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
                        if (denom == 0) {
                            uint256 scaled =
                                FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, sqrtPriceUpper);
                            token0Needed = FullMath.mulDiv(scaled, FixedPoint96.Q96, sqrtPriceX96);
                        } else {
                            token0Needed = FullMath.mulDiv(liquidityFrom1, sqrtPriceUpper - sqrtPriceX96, denom);
                        }
                    }

                    // Check if token0 is actually limiting
                    if (data.token0Allocations[i] < token0Needed) {
                        // Token0 is limiting
                        // token0Needed > 0 implies sqrtPriceX96 < sqrtPriceUpper
                        uint256 intermediate = FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96);
                        uint256 liquidity =
                            FullMath.mulDiv(data.token0Allocations[i], intermediate, sqrtPriceUpper - sqrtPriceX96);
                        liquidities[i] = _capLiquidity(liquidity);
                    } else {
                        // Token1 is limiting
                        liquidities[i] = _capLiquidity(liquidityFrom1);
                    }
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    function _adjustWeightsForFloorIndex(uint256[] memory weights, uint256 floorIdx) private pure {
        if (weights.length == 0) {
            return;
        }

        uint256 sum;
        for (uint256 i = 0; i < weights.length; ++i) {
            if (i == floorIdx) {
                continue;
            }
            sum += weights[i];
        }

        if (sum == 0) {
            weights[floorIdx] = 0;
            return;
        }

        for (uint256 i = 0; i < weights.length; ++i) {
            if (i == floorIdx) {
                continue;
            }
            weights[i] = FullMath.mulDiv(weights[i], PRECISION, sum);
        }
        weights[floorIdx] = 0;
    }

    function _findFullRangeIndex(
        int24[] memory lowerTicks,
        int24[] memory upperTicks,
        int24 minUsable,
        int24 maxUsable
    ) private pure returns (uint256) {
        uint256 length = lowerTicks.length;
        for (uint256 i = 0; i < length; ++i) {
            if (lowerTicks[i] == minUsable && upperTicks[i] == maxUsable) {
                return i;
            }
        }
        return type(uint256).max;
    }

    function _findFullRangeIndex(
        IMultiPositionManager.Range[] memory ranges,
        int24 minUsable,
        int24 maxUsable
    ) private pure returns (uint256) {
        uint256 length = ranges.length;
        for (uint256 i = 0; i < length; ++i) {
            if (ranges[i].lowerTick == minUsable && ranges[i].upperTick == maxUsable) {
                return i;
            }
        }
        return type(uint256).max;
    }

    function _reserveFloorLiquidity(
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 total0,
        uint256 total1,
        uint160 sqrtPriceX96,
        int24 tickSpacing,
        bool useCarpet
    ) private pure returns (FloorReserveInfo memory info, uint256 remaining0, uint256 remaining1) {
        remaining0 = total0;
        remaining1 = total1;

        if (!useCarpet || baseRanges.length == 0) {
            return (info, remaining0, remaining1);
        }

        FloorRangeContext memory ctx;
        ctx.total0 = total0;
        ctx.total1 = total1;
        ctx.sqrtPriceX96 = sqrtPriceX96;
        ctx.tickSpacing = tickSpacing;
        ctx.minUsable = TickMath.minUsableTick(tickSpacing);
        ctx.maxUsable = TickMath.maxUsableTick(tickSpacing);

        uint256 floorIdx = _findFullRangeIndex(baseRanges, ctx.minUsable, ctx.maxUsable);
        if (floorIdx == type(uint256).max) {
            return (info, remaining0, remaining1);
        }
        if (baseRanges.length == 1) {
            return (info, remaining0, remaining1);
        }

        info = _computeFloorReservation(ctx, baseRanges, floorIdx);

        if (info.active) {
            remaining0 = ctx.total0 - info.reserve0;
            remaining1 = ctx.total1 - info.reserve1;
        }

        return (info, remaining0, remaining1);
    }

    function _computeFloorReservation(
        FloorRangeContext memory ctx,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 floorIdx
    ) private pure returns (FloorReserveInfo memory info) {
        info.index = floorIdx;
        ctx.currentTick = TickMath.getTickAtSqrtPrice(ctx.sqrtPriceX96);

        (uint128 minLiquidity, uint256 reserve0, uint256 reserve1) =
            _minFloorLiquidityAndReserves(baseRanges[floorIdx], ctx.currentTick, ctx.sqrtPriceX96);

        if (reserve0 <= ctx.total0 && reserve1 <= ctx.total1) {
            info.active = true;
            info.reserve0 = reserve0;
            info.reserve1 = reserve1;
            info.liquidity = minLiquidity;
            return info;
        }

        FloorReserveInfo memory candidate = _tryOneSidedFloor(ctx, baseRanges, floorIdx);
        if (candidate.active) {
            info.active = true;
            info.reserve0 = candidate.reserve0;
            info.reserve1 = candidate.reserve1;
            info.liquidity = candidate.liquidity;
        }
        return info;
    }

    function _selectOneSidedFloorRange(FloorRangeContext memory ctx)
        private
        pure
        returns (
            bool hasRange,
            IMultiPositionManager.Range memory range,
            uint256 reserve0,
            uint256 reserve1,
            uint128 liquidity
        )
    {
        int24 alignedDown = _roundDownTick(ctx.currentTick, ctx.tickSpacing);
        int24 alignedUp = _roundUpTick(ctx.currentTick, ctx.tickSpacing);

        if (alignedDown < ctx.minUsable) alignedDown = ctx.minUsable;
        if (alignedUp > ctx.maxUsable) alignedUp = ctx.maxUsable;

        {
            (bool canToken0, IMultiPositionManager.Range memory token0Range, uint256 token0Reserve, uint128 token0Liquidity)
            = _evaluateToken0OneSided(ctx, alignedUp);
            if (canToken0) {
                return (true, token0Range, token0Reserve, 0, token0Liquidity);
            }
        }

        {
            (bool canToken1, IMultiPositionManager.Range memory token1Range, uint256 token1Reserve, uint128 token1Liquidity)
            = _evaluateToken1OneSided(ctx, alignedDown);
            if (canToken1) {
                return (true, token1Range, 0, token1Reserve, token1Liquidity);
            }
        }

        return (false, range, 0, 0, 0);
    }

    function _evaluateToken0OneSided(FloorRangeContext memory ctx, int24 alignedUp)
        private
        pure
        returns (bool canToken0, IMultiPositionManager.Range memory range, uint256 reserve0, uint128 liquidity)
    {
        if (alignedUp < ctx.maxUsable) {
            range = IMultiPositionManager.Range({lowerTick: alignedUp, upperTick: ctx.maxUsable});
            (liquidity, reserve0,) = _minFloorLiquidityAndReserves(range, ctx.currentTick, ctx.sqrtPriceX96);
            canToken0 = reserve0 <= ctx.total0;
        }
    }

    function _evaluateToken1OneSided(FloorRangeContext memory ctx, int24 alignedDown)
        private
        pure
        returns (bool canToken1, IMultiPositionManager.Range memory range, uint256 reserve1, uint128 liquidity)
    {
        if (alignedDown > ctx.minUsable) {
            range = IMultiPositionManager.Range({lowerTick: ctx.minUsable, upperTick: alignedDown});
            (liquidity,, reserve1) = _minFloorLiquidityAndReserves(range, ctx.currentTick, ctx.sqrtPriceX96);
            canToken1 = reserve1 <= ctx.total1;
        }
    }

    function _tryOneSidedFloor(
        FloorRangeContext memory ctx,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256 floorIdx
    ) private pure returns (FloorReserveInfo memory info) {
        (
            bool hasRange,
            IMultiPositionManager.Range memory oneSided,
            uint256 oneReserve0,
            uint256 oneReserve1,
            uint128 oneLiquidity
        ) = _selectOneSidedFloorRange(ctx);
        if (hasRange && !_rangeExists(baseRanges, oneSided, floorIdx)) {
            baseRanges[floorIdx] = oneSided;
            info.active = true;
            info.reserve0 = oneReserve0;
            info.reserve1 = oneReserve1;
            info.liquidity = oneLiquidity;
        }
    }

    function _roundDownTick(int24 tick, int24 tickSpacing) private pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) {
            compressed -= 1;
        }
        return compressed * tickSpacing;
    }

    function _roundUpTick(int24 tick, int24 tickSpacing) private pure returns (int24) {
        int24 roundedDown = _roundDownTick(tick, tickSpacing);
        if (roundedDown < tick) {
            return roundedDown + tickSpacing;
        }
        return roundedDown;
    }

    function _rangeExists(
        IMultiPositionManager.Range[] memory ranges,
        IMultiPositionManager.Range memory candidate,
        uint256 skipIndex
    ) private pure returns (bool) {
        uint256 length = ranges.length;
        for (uint256 i = 0; i < length; ++i) {
            if (i == skipIndex) {
                continue;
            }
            if (ranges[i].lowerTick == candidate.lowerTick && ranges[i].upperTick == candidate.upperTick) {
                return true;
            }
        }
        return false;
    }

    function _minFloorLiquidityAndReserves(
        IMultiPositionManager.Range memory range,
        int24 currentTick,
        uint160 sqrtPriceX96
    ) private pure returns (uint128 liquidity, uint256 reserve0, uint256 reserve1) {
        if (range.upperTick <= range.lowerTick) {
            return (0, 0, 0);
        }

        uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
        uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);

        bool needsToken0 = currentTick <= range.lowerTick || (range.lowerTick < currentTick && currentTick < range.upperTick);
        bool needsToken1 = currentTick >= range.upperTick || (range.lowerTick < currentTick && currentTick < range.upperTick);

        uint256 minLiquidity0;
        uint256 minLiquidity1;
        if (currentTick <= range.lowerTick) {
            minLiquidity0 = _liquidityForAmount0RoundingUp(sqrtPriceLower, sqrtPriceUpper, FLOOR_MIN_TOKEN0);
        } else if (currentTick >= range.upperTick) {
            minLiquidity1 = _liquidityForAmount1RoundingUp(sqrtPriceLower, sqrtPriceUpper, FLOOR_MIN_TOKEN1);
        } else {
            minLiquidity0 = _liquidityForAmount0RoundingUp(sqrtPriceX96, sqrtPriceUpper, FLOOR_MIN_TOKEN0);
            minLiquidity1 = _liquidityForAmount1RoundingUp(sqrtPriceLower, sqrtPriceX96, FLOOR_MIN_TOKEN1);
        }

        uint256 minLiquidity = minLiquidity0 > minLiquidity1 ? minLiquidity0 : minLiquidity1;
        liquidity = _capLiquidity(minLiquidity);
        (reserve0, reserve1) =
            _getAmountsForLiquidityRoundingUp(sqrtPriceX96, sqrtPriceLower, sqrtPriceUpper, liquidity);
        if (!_meetsMinAmounts(needsToken0, needsToken1, reserve0, reserve1)) {
            return (0, 0, 0);
        }
        return (liquidity, reserve0, reserve1);
    }

    function _meetsMinAmounts(bool needsToken0, bool needsToken1, uint256 amount0, uint256 amount1)
        private
        pure
        returns (bool)
    {
        if (needsToken0 && amount0 < FLOOR_MIN_TOKEN0) return false;
        if (needsToken1 && amount1 < FLOOR_MIN_TOKEN1) return false;
        return true;
    }

    function _liquidityForAmount0RoundingUp(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
        private
        pure
        returns (uint256)
    {
        if (amount0 == 0) {
            return 0;
        }
        if (sqrtPriceAX96 > sqrtPriceBX96) {
            (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        }
        if (sqrtPriceBX96 <= sqrtPriceAX96) {
            return 0;
        }

        uint256 intermediate = FullMath.mulDivRoundingUp(uint256(sqrtPriceAX96), uint256(sqrtPriceBX96), FixedPoint96.Q96);
        return FullMath.mulDivRoundingUp(amount0, intermediate, uint256(sqrtPriceBX96) - uint256(sqrtPriceAX96));
    }

    function _liquidityForAmount1RoundingUp(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
        private
        pure
        returns (uint256)
    {
        if (amount1 == 0) {
            return 0;
        }
        if (sqrtPriceAX96 > sqrtPriceBX96) {
            (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        }
        if (sqrtPriceBX96 <= sqrtPriceAX96) {
            return 0;
        }

        return FullMath.mulDivRoundingUp(amount1, FixedPoint96.Q96, uint256(sqrtPriceBX96) - uint256(sqrtPriceAX96));
    }

    function _getAmountsForLiquidityRoundingUp(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceLower,
        uint160 sqrtPriceUpper,
        uint128 liquidity
    ) private pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtPriceX96 <= sqrtPriceLower) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
        } else if (sqrtPriceX96 < sqrtPriceUpper) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceUpper, liquidity, true);
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceX96, liquidity, true);
        } else {
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
        }
    }

    function _capLiquidity(uint256 liquidity) private pure returns (uint128) {
        return liquidity > type(uint128).max ? type(uint128).max : uint128(liquidity);
    }

    /**
     * @notice Get total available token amounts
     * @dev Gets total amounts from all positions including fees and unused balances
     */
    function _getTotalAvailable(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        internal
        view
        returns (uint256 total0, uint256 total1)
    {
        uint256 totalFee0;
        uint256 totalFee1;

        // Cache poolKey to avoid repeated SLOADs
        PoolKey memory poolKey = s.poolKey;

        // Get amounts from base positions including fees
        for (uint256 i = 0; i < s.basePositionsLength;) {
            (, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
                PoolManagerUtils.getAmountsOf(poolManager, poolKey, s.basePositions[i]);
            total0 += amount0;
            total1 += amount1;
            totalFee0 += feesOwed0;
            totalFee1 += feesOwed1;
            unchecked {
                ++i;
            }
        }

        // Get amounts from limit positions including fees
        for (uint256 i = 0; i < 2;) {
            IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
            if (limitRange.lowerTick != limitRange.upperTick) {
                (, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
                    PoolManagerUtils.getAmountsOf(poolManager, poolKey, limitRange);
                total0 += amount0;
                total1 += amount1;
                totalFee0 += feesOwed0;
                totalFee1 += feesOwed1;
            }
            unchecked {
                ++i;
            }
        }

        // Exclude protocol fee from the total fees
        totalFee0 = totalFee0 - (totalFee0 / s.fee);
        totalFee1 = totalFee1 - (totalFee1 / s.fee);

        // Add fees net of protocol fees to the total amount
        total0 += totalFee0;
        total1 += totalFee1;

        // Add unused balances
        total0 += s.currency0.balanceOfSelf();
        total1 += s.currency1.balanceOfSelf();

        return (total0, total1);
    }

    /**
     * @notice Process REBALANCE action in callback
     * @dev Handles the complete rebalance flow including zeroBurn, burn old positions, and mint new ones
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param params Encoded rebalance parameters
     * @param totalSupply Current total supply
     * @return Empty bytes (no return value needed)
     */
    function processRebalanceInCallback(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        bytes memory params,
        uint256 totalSupply
    ) external returns (bytes memory) {
        // Decode parameters
        (
            IMultiPositionManager.Range[] memory baseRanges,
            uint128[] memory liquidities,
            uint24 limitWidth,
            uint256[2][] memory inMin,
            uint256[2][] memory outMin,
            IMultiPositionManager.RebalanceParams memory rebalanceParams
        ) = abi.decode(
            params,
            (
                IMultiPositionManager.Range[],
                uint128[],
                uint24,
                uint256[2][],
                uint256[2][],
                IMultiPositionManager.RebalanceParams
            )
        );

        // Burn old positions and set up new ones
        _burnAndSetupPositions(s, poolManager, baseRanges, limitWidth, outMin, totalSupply);

        // Ensure inMin has correct length for slippage protection
        // If empty array passed, create zero-filled array (no slippage protection)
        if (inMin.length == 0) {
            inMin = new uint256[2][](baseRanges.length);
        } else if (inMin.length != baseRanges.length) {
            if (rebalanceParams.useCarpet) {
                inMin = new uint256[2][](baseRanges.length);
            } else {
                revert InMinLengthMismatch(inMin.length, baseRanges.length);
            }
        }

        // Mint new positions and capture position data
        IMultiPositionManager.PositionData[] memory positionData =
            PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin, rebalanceParams.useCarpet);

        // Build complete ranges array including base and limit positions
        uint256 baseLength = s.basePositionsLength;
        IMultiPositionManager.Range[] memory ranges = new IMultiPositionManager.Range[](baseLength + 2);
        uint256 rangeCount = 0;

        for (uint8 i = 0; i < baseLength;) {
            ranges[rangeCount++] = s.basePositions[i];
            unchecked {
                ++i;
            }
        }

        if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
            ranges[rangeCount++] = s.limitPositions[0];
        }

        if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
            ranges[rangeCount++] = s.limitPositions[1];
        }

        // Resize ranges array to actual count
        assembly {
            mstore(ranges, rangeCount)
        }

        // Emit rebalance event
        emit IMultiPositionManager.Rebalance(ranges, positionData, rebalanceParams);

        return "";
    }

    /**
     * @notice Perform zeroBurn if there are active positions
     */
    function _performZeroBurnIfNeeded(SharedStructs.ManagerStorage storage s, IPoolManager poolManager) private {
        uint256 baseLength = s.basePositionsLength;
        // Check cheaper condition first for short-circuit optimization
        if (baseLength != 0 || s.limitPositionsLength != 0) {
            // Get ranges for zeroBurn
            IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](baseLength);
            for (uint8 i = 0; i < baseLength;) {
                baseRangesArray[i] = s.basePositions[i];
                unchecked {
                    ++i;
                }
            }
            IMultiPositionManager.Range[2] memory limitRangesArray = [s.limitPositions[0], s.limitPositions[1]];

            PoolManagerUtils.zeroBurnAll(
                poolManager, s.poolKey, baseRangesArray, limitRangesArray, s.currency0, s.currency1, s.fee
            );
        }
    }

    /**
     * @notice Burn old positions and set up new ones
     */
    function _burnAndSetupPositions(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        IMultiPositionManager.Range[] memory baseRanges,
        uint24 limitWidth,
        uint256[2][] memory outMin,
        uint256 totalSupply
    ) private {
        // Only burn if there are actual positions to burn
        if (totalSupply > 0 && (s.basePositionsLength > 0 || s.limitPositionsLength > 0)) {
            PositionLogic.burnLiquidities(poolManager, s, totalSupply, totalSupply, outMin);
        }

        // Set up new base positions
        uint256 newBaseLength = baseRanges.length;
        IMultiPositionManager.Range[] memory allRanges = new IMultiPositionManager.Range[](newBaseLength + 2);
        s.basePositionsLength = newBaseLength;
        for (uint8 i = 0; i < newBaseLength;) {
            s.basePositions[i] = baseRanges[i];
            allRanges[i] = baseRanges[i];
            unchecked {
                ++i;
            }
        }

        // Set limit ranges
        (, int24 curTick,,) = poolManager.getSlot0(s.poolId);
        PositionLogic.setLimitRanges(s, limitWidth, baseRanges, s.poolKey.tickSpacing, curTick);
        allRanges[baseRanges.length] = s.limitPositions[0];
        allRanges[baseRanges.length + 1] = s.limitPositions[1];

        // Check ranges for duplicates
        PositionLogic.checkRanges(allRanges);
    }

    /**
     * @notice Calculate weights based on current token amounts and price
     * @param amount0 Current amount of token0
     * @param amount1 Current amount of token1
     * @param sqrtPriceX96 Current pool sqrt price
     * @return weight0 Weight for token0 (in 1e18)
     * @return weight1 Weight for token1 (in 1e18)
     */
    function calculateWeightsFromAmounts(uint256 amount0, uint256 amount1, uint160 sqrtPriceX96)
        internal
        pure
        returns (uint256 weight0, uint256 weight1)
    {
        // Calculate value0 in token1 terms using sqrtPriceX96 directly
        uint256 value0InToken1 =
            FullMath.mulDiv(FullMath.mulDiv(amount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96);
        uint256 totalValue = value0InToken1 + amount1;

        if (totalValue == 0) {
            return (0.5e18, 0.5e18);
        }

        weight0 = FullMath.mulDiv(value0InToken1, 1e18, totalValue);
        weight1 = 1e18 - weight0;
    }

    /**
     * @notice Get density weights from strategy
     */
    function _getDensities(WeightCalculationParams memory params, int24[] memory lowerTicks, int24[] memory upperTicks)
        private
        pure
        returns (uint256[] memory)
    {
        return params.strategy.calculateDensities(
            lowerTicks,
            upperTicks,
            params.currentTick,
            params.center,
            params.tLeft,
            params.tRight,
            0,
            0,
            params.useCarpet,
            params.tickSpacing,
            true
        );
    }

    /**
     * @notice Calculate weighted token amounts based on strategy densities
     * @dev Helper function to avoid stack too deep in calculateWeightsFromStrategy
     */
    function _calculateWeightedAmounts(
        WeightCalculationParams memory params,
        int24[] memory lowerTicks,
        int24[] memory upperTicks
    ) private pure returns (uint256 totalAmount0, uint256 totalAmount1) {
        uint256[] memory densities = _getDensities(params, lowerTicks, upperTicks);
        densities = adjustWeightsForFullRangeFloor(densities, lowerTicks, upperTicks, params.tickSpacing, params.useCarpet);

        uint160 sqrtPrice = params.sqrtPriceX96;
        uint256 length = lowerTicks.length;
        for (uint256 i = 0; i < length;) {
            uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(lowerTicks[i]);
            uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(upperTicks[i]);

            (uint256 amount0For1e18, uint256 amount1For1e18) =
                LiquidityAmounts.getAmountsForLiquidity(sqrtPrice, sqrtPriceLower, sqrtPriceUpper, 1e18);

            totalAmount0 += (amount0For1e18 * densities[i]) / 1e18;
            totalAmount1 += (amount1For1e18 * densities[i]) / 1e18;
            unchecked {
                ++i;
            }
        }
    }

    function calculateWeightsFromStrategy(
        ILiquidityStrategy strategy,
        int24 center,
        uint24 tLeft,
        uint24 tRight,
        int24 tickSpacing,
        bool useCarpet,
        uint160 sqrtPriceX96,
        int24 currentTick
    ) internal pure returns (uint256 weight0, uint256 weight1) {
        WeightCalculationParams memory params = WeightCalculationParams({
            strategy: strategy,
            center: center,
            tLeft: tLeft,
            tRight: tRight,
            tickSpacing: tickSpacing,
            useCarpet: useCarpet,
            sqrtPriceX96: sqrtPriceX96,
            currentTick: currentTick
        });

        (int24[] memory lowerTicks, int24[] memory upperTicks) =
            strategy.generateRanges(center, tLeft, tRight, tickSpacing, useCarpet);

        if (lowerTicks.length == 0) return (0.5e18, 0.5e18);

        (uint256 totalAmount0, uint256 totalAmount1) = _calculateWeightedAmounts(params, lowerTicks, upperTicks);

        if (totalAmount0 == 0 && totalAmount1 == 0) return (0.5e18, 0.5e18);

        uint256 value0InToken1 = FullMath.mulDiv(
            FullMath.mulDiv(totalAmount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
        );
        uint256 totalValue = value0InToken1 + totalAmount1;

        if (totalValue == 0) return (0.5e18, 0.5e18);

        weight0 = FullMath.mulDiv(value0InToken1, 1e18, totalValue);
        weight1 = 1e18 - weight0;
    }

    /**
     * @notice Calculate optimal swap amount to achieve target weight distribution
     * @param amount0 Current amount of token0
     * @param amount1 Current amount of token1
     * @param sqrtPriceX96 Current pool sqrt price
     * @param weight0 Target weight for token0 (in 1e18)
     * @return swapToken0 True if swapping token0 to token1, false otherwise
     * @return swapAmount Amount to swap
     */
    function calculateOptimalSwap(
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        uint256 weight0,
        uint256 /* weight1 */
    ) public pure returns (bool swapToken0, uint256 swapAmount) {
        // Calculate value0 in token1 terms using sqrtPriceX96 directly to avoid precision loss
        uint256 value0InToken1 =
            FullMath.mulDiv(FullMath.mulDiv(amount0, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96);

        // Total value in token1 terms
        uint256 totalValue = value0InToken1 + amount1;

        // Target token0 value in token1 terms
        uint256 target0ValueInToken1 = FullMath.mulDiv(totalValue, weight0, 1e18);

        // Convert target back to token0 amount
        // target0Amount = target0ValueInToken1 / (sqrtPriceX96^2 / 2^192)
        // = target0ValueInToken1 * 2^192 / sqrtPriceX96^2
        // = (target0ValueInToken1 * 2^96 / sqrtPriceX96) * 2^96 / sqrtPriceX96
        uint256 target0Amount = FullMath.mulDiv(
            FullMath.mulDiv(target0ValueInToken1, 1 << 96, uint256(sqrtPriceX96)), 1 << 96, uint256(sqrtPriceX96)
        );

        if (amount0 > target0Amount) {
            swapToken0 = true;
            swapAmount = amount0 - target0Amount;
        } else {
            swapToken0 = false;
            uint256 token0Deficit = target0Amount - amount0;
            // Convert token0Deficit to token1 amount
            swapAmount = FullMath.mulDiv(
                FullMath.mulDiv(token0Deficit, uint256(sqrtPriceX96), 1 << 96), uint256(sqrtPriceX96), 1 << 96
            );
        }
    }
    /**
     * @notice Generate ranges and calculate liquidities for given amounts
     * @dev Made public so SimpleLens can use the exact same logic for preview
     */
    function generateRangesAndLiquidities(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        uint256 amount0,
        uint256 amount1
    ) public view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
        return generateRangesAndLiquiditiesWithPoolKey(s.poolKey, poolManager, ctx, amount0, amount1);
    }

    function _generateRangesAndWeights(
        PoolKey memory poolKey,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        bool useCarpet
    ) private view returns (IMultiPositionManager.Range[] memory baseRanges, uint256[] memory weights) {
        (int24[] memory lowerTicks, int24[] memory upperTicks) =
            ctx.strategy.generateRanges(ctx.center, ctx.tLeft, ctx.tRight, poolKey.tickSpacing, useCarpet);

        baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
        for (uint256 i = 0; i < lowerTicks.length;) {
            baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[i]);
            unchecked {
                ++i;
            }
        }

        StrategyContext memory weightCtx = ctx;
        weightCtx.useCarpet = useCarpet;
        weights = calculateWeightsWithPoolKey(poolKey, poolManager, weightCtx, lowerTicks, upperTicks);
    }

    function generateRangesAndLiquiditiesWithPoolKey(
        PoolKey memory poolKey,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        uint256 amount0,
        uint256 amount1
    ) public view returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities) {
        // Get current sqrt price
        (uint160 sqrtPriceX96Current,,,) = poolManager.getSlot0(poolKey.toId());
        uint256[] memory weights;
        (baseRanges, weights) = _generateRangesAndWeights(poolKey, poolManager, ctx, ctx.useCarpet);
        liquidities = new uint128[](baseRanges.length);
        LiquidityCalcParams memory calcParams = LiquidityCalcParams({
            amount0: amount0,
            amount1: amount1,
            sqrtPriceX96: sqrtPriceX96Current,
            useAssetWeights: ctx.useAssetWeights,
            tickSpacing: poolKey.tickSpacing,
            useCarpet: ctx.useCarpet
        });
        _calculateLiquiditiesFromWeightsWithParams(liquidities, weights, baseRanges, calcParams);
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {WithdrawLogic} from "./WithdrawLogic.sol";

/**
 * @title PositionLogic
 * @notice Library containing position management logic for MultiPositionManager
 */
library PositionLogic {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    // Constants
    uint256 constant PRECISION = 1e36;
    uint256 constant RATIO_PRECISION = 1e18;

    // Structs
    struct Ratios {
        uint256 pool0Ratio;
        uint256 pool1Ratio;
        uint256 total0Ratio;
        uint256 total1Ratio;
        uint256 inPositionRatio;
        uint256 outOfPositionRatio;
        uint256 baseRatio;
        uint256 limitRatio;
        uint256 base0Ratio;
        uint256 base1Ratio;
        uint256 limit0Ratio;
        uint256 limit1Ratio;
    }

    // Custom errors
    error DuplicatedRange(IMultiPositionManager.Range range);

    /**
     * @notice Set limit ranges based on limit width and base ranges
     * @param s Storage struct
     * @param limitWidth Width of limit positions
     * @param baseRanges Base position ranges
     * @param tickSpacing Tick spacing of the pool
     * @param currentTick Current tick of the pool
     */
    function setLimitRanges(
        SharedStructs.ManagerStorage storage s,
        uint24 limitWidth,
        IMultiPositionManager.Range[] memory baseRanges,
        int24 tickSpacing,
        int24 currentTick
    ) external {
        if (limitWidth == 0) {
            delete s.limitPositions;
            s.limitPositionsLength = 0;
            return;
        }

        if (int24(limitWidth) % tickSpacing != 0) {
            // increase `limitWidth` to round up multiple of tickSpacing
            limitWidth = uint24((int24(limitWidth) / tickSpacing + 1) * tickSpacing);
        }

        // Check against NEW base ranges (not historical ones)
        // Use do-while to handle consecutive width collisions
        uint256 baseRangesLength = baseRanges.length;
        bool collision;
        do {
            collision = false;
            for (uint256 i = 0; i < baseRangesLength;) {
                int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
                if (rangeWidth == int24(limitWidth)) {
                    limitWidth = uint24(int24(limitWidth) + tickSpacing);
                    collision = true;
                    break;
                }
                unchecked {
                    ++i;
                }
            }
        } while (collision);

        int24 baseTick;
        if (currentTick % tickSpacing == 0) {
            baseTick = currentTick;
        } else if (currentTick % tickSpacing > 0) {
            baseTick = (currentTick / tickSpacing) * tickSpacing;
        } else {
            baseTick = (currentTick / tickSpacing - 1) * tickSpacing;
        }

        (s.limitPositions[0].lowerTick, s.limitPositions[0].upperTick) =
            roundUp(baseTick - int24(limitWidth), baseTick, tickSpacing);
        (s.limitPositions[1].lowerTick, s.limitPositions[1].upperTick) =
            roundUp(baseTick + tickSpacing, baseTick + tickSpacing + int24(limitWidth), tickSpacing);

        // Update limitPositionsLength based on non-empty positions
        s.limitPositionsLength = 0;
        if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
            unchecked {
                ++s.limitPositionsLength;
            }
        }
        if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
            unchecked {
                ++s.limitPositionsLength;
            }
        }
    }

    /**
     * @notice Calculate limit ranges without modifying storage (for SimpleLens preview)
     * @param limitWidth Width of limit positions
     * @param baseRanges Base position ranges
     * @param tickSpacing Tick spacing of the pool
     * @param currentTick Current tick of the pool
     * @return lowerLimit Lower limit range
     * @return upperLimit Upper limit range
     */
    function calculateLimitRanges(
        uint24 limitWidth,
        IMultiPositionManager.Range[] memory baseRanges,
        int24 tickSpacing,
        int24 currentTick
    )
        public
        pure
        returns (IMultiPositionManager.Range memory lowerLimit, IMultiPositionManager.Range memory upperLimit)
    {
        if (limitWidth == 0) {
            return (
                IMultiPositionManager.Range({lowerTick: 0, upperTick: 0}),
                IMultiPositionManager.Range({lowerTick: 0, upperTick: 0})
            );
        }

        if (int24(limitWidth) % tickSpacing != 0) {
            // increase `limitWidth` to round up multiple of tickSpacing
            limitWidth = uint24((int24(limitWidth) / tickSpacing + 1) * tickSpacing);
        }

        // Check against NEW base ranges (not historical ones)
        // Use do-while to handle consecutive width collisions
        uint256 baseRangesLength = baseRanges.length;
        bool collision;
        do {
            collision = false;
            for (uint256 i = 0; i < baseRangesLength;) {
                int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
                if (rangeWidth == int24(limitWidth)) {
                    limitWidth = uint24(int24(limitWidth) + tickSpacing);
                    collision = true;
                    break;
                }
                unchecked {
                    ++i;
                }
            }
        } while (collision);

        int24 baseTick;
        if (currentTick % tickSpacing == 0) {
            baseTick = currentTick;
        } else if (currentTick % tickSpacing > 0) {
            baseTick = (currentTick / tickSpacing) * tickSpacing;
        } else {
            baseTick = (currentTick / tickSpacing - 1) * tickSpacing;
        }

        (lowerLimit.lowerTick, lowerLimit.upperTick) = roundUp(baseTick - int24(limitWidth), baseTick, tickSpacing);
        (upperLimit.lowerTick, upperLimit.upperTick) =
            roundUp(baseTick + tickSpacing, baseTick + tickSpacing + int24(limitWidth), tickSpacing);
    }

    /**
     * @notice Round up tick values to valid range
     * @param tickLower Lower tick
     * @param tickUpper Upper tick
     * @param tickSpacing Tick spacing of the pool
     * @return Rounded lower and upper ticks
     */
    function roundUp(int24 tickLower, int24 tickUpper, int24 tickSpacing) public pure returns (int24, int24) {
        // Get min/max usable ticks that are aligned with tick spacing
        int24 minUsableTick = TickMath.minUsableTick(tickSpacing);
        int24 maxUsableTick = TickMath.maxUsableTick(tickSpacing);

        // Ensure lower tick is at least the min usable tick
        if (tickLower < minUsableTick) {
            tickLower = minUsableTick;
        }
        // Ensure upper tick is at most the max usable tick
        if (tickUpper > maxUsableTick) {
            tickUpper = maxUsableTick;
        }
        // Handle invalid ranges
        if (tickLower >= tickUpper) {
            return (0, 0);
        }

        return (tickLower, tickUpper);
    }

    /**
     * @notice Check for duplicate ranges
     * @param allRanges All ranges to check
     */
    function checkRanges(IMultiPositionManager.Range[] memory allRanges) external pure {
        uint256 rangesLength = allRanges.length;
        for (uint256 i = 0; i < rangesLength;) {
            for (uint256 j = i + 1; j < rangesLength;) {
                // Skip empty ranges
                if (allRanges[j].lowerTick == allRanges[j].upperTick) {
                    unchecked {
                        ++j;
                    }
                    continue;
                }

                if (
                    allRanges[i].lowerTick == allRanges[j].lowerTick && allRanges[i].upperTick == allRanges[j].upperTick
                ) {
                    revert DuplicatedRange(allRanges[j]);
                }
                unchecked {
                    ++j;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Get base positions as array
     * @param s Storage struct
     * @return ranges Array of base positions
     */
    function getBasePositionsArray(SharedStructs.ManagerStorage storage s)
        public
        view
        returns (IMultiPositionManager.Range[] memory ranges)
    {
        uint256 baseLength = s.basePositionsLength;
        ranges = new IMultiPositionManager.Range[](baseLength);
        for (uint8 i = 0; i < baseLength;) {
            ranges[i] = s.basePositions[i];
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Get limit positions as array
     * @param s Storage struct
     * @return ranges Array of limit positions (always size 2)
     */
    function getLimitPositionsArray(SharedStructs.ManagerStorage storage s)
        public
        view
        returns (IMultiPositionManager.Range[2] memory ranges)
    {
        ranges[0] = s.limitPositions[0];
        ranges[1] = s.limitPositions[1];
    }

    /**
     * @notice Mint liquidity to positions
     * @param poolManager Pool manager contract
     * @param s Storage struct
     * @param liquidities Liquidity amounts for each position
     * @param inMin Minimum input amounts per position
     */
    function mintLiquidities(
        IPoolManager poolManager,
        SharedStructs.ManagerStorage storage s,
        uint128[] memory liquidities,
        uint256[2][] memory inMin,
        bool useCarpet
    ) external returns (IMultiPositionManager.PositionData[] memory) {
        IMultiPositionManager.Range[] memory baseRangesArray = getBasePositionsArray(s);
        IMultiPositionManager.Range[2] memory limitRangesArray = getLimitPositionsArray(s);

        return PoolManagerUtils.mintLiquidities(
            poolManager, s.poolKey, baseRangesArray, limitRangesArray, liquidities, inMin, useCarpet
        );
    }

    /**
     * @notice Burn liquidity from positions
     * @param poolManager Pool manager contract
     * @param s Storage struct
     * @param shares Number of shares to burn
     * @param totalSupply Total supply of shares
     * @param outMin Minimum output amounts per position
     * @return amount0 Amount of token0 returned
     * @return amount1 Amount of token1 returned
     */
    function burnLiquidities(
        IPoolManager poolManager,
        SharedStructs.ManagerStorage storage s,
        uint256 shares,
        uint256 totalSupply,
        uint256[2][] memory outMin
    ) external returns (uint256 amount0, uint256 amount1) {
        if (shares == 0) return (amount0, amount1);

        IMultiPositionManager.Range[] memory baseRangesArray = getBasePositionsArray(s);
        IMultiPositionManager.Range[2] memory limitRangesArray = getLimitPositionsArray(s);

        (amount0, amount1) = PoolManagerUtils.burnLiquidities(
            poolManager, s.poolKey, baseRangesArray, limitRangesArray, shares, totalSupply, outMin
        );
    }

    /**
     * @notice Get base positions with their data
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @return ranges Array of base position ranges
     * @return positionData Array of position data for each base position
     */
    function getBasePositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        external
        view
        returns (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData)
    {
        ranges = new IMultiPositionManager.Range[](s.basePositionsLength);
        positionData = new IMultiPositionManager.PositionData[](s.basePositionsLength);

        for (uint8 i = 0; i < s.basePositionsLength;) {
            ranges[i] = s.basePositions[i];

            (uint128 liquidity, uint256 amount0, uint256 amount1,,) =
                PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[i]);

            positionData[i] =
                IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Get all positions (base + non-empty limit) with their data
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @return ranges Array of all position ranges
     * @return positionData Array of position data for each position
     */
    function getPositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        external
        view
        returns (IMultiPositionManager.Range[] memory ranges, IMultiPositionManager.PositionData[] memory positionData)
    {
        // Count non-empty limit positions
        uint8 nonEmptyLimitPositions = 0;
        if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
            unchecked {
                ++nonEmptyLimitPositions;
            }
        }
        if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
            unchecked {
                ++nonEmptyLimitPositions;
            }
        }

        ranges = new IMultiPositionManager.Range[](s.basePositionsLength + nonEmptyLimitPositions);
        positionData = new IMultiPositionManager.PositionData[](s.basePositionsLength + nonEmptyLimitPositions);

        // Include base positions
        for (uint8 i = 0; i < s.basePositionsLength;) {
            ranges[i] = s.basePositions[i];

            (uint128 liquidity, uint256 amount0, uint256 amount1,,) =
                PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[i]);

            positionData[i] =
                IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});

            unchecked {
                ++i;
            }
        }

        // Include limit positions only if they are non-empty
        uint8 limitIndex = 0;
        for (uint8 i = 0; i < 2;) {
            if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
                ranges[s.basePositionsLength + limitIndex] = s.limitPositions[i];

                (uint128 liquidity, uint256 amount0, uint256 amount1,,) =
                    PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, ranges[s.basePositionsLength + limitIndex]);

                positionData[s.basePositionsLength + limitIndex] =
                    IMultiPositionManager.PositionData({liquidity: liquidity, amount0: amount0, amount1: amount1});

                unchecked {
                    ++limitIndex;
                }
            }

            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Calculate token ratios given amounts and price
     * @dev Converts token0 to token1 terms and calculates distribution ratios
     * @param token0Amount Amount of token0
     * @param token1Amount Amount of token1
     * @param sqrtPriceX96 Square root price in Q96 format
     * @return token0Ratio Ratio of token0 value (1e18 = 100%)
     * @return token1Ratio Ratio of token1 value (1e18 = 100%)
     */
    function _getTokenRatios(uint256 token0Amount, uint256 token1Amount, uint160 sqrtPriceX96)
        internal
        pure
        returns (uint256 token0Ratio, uint256 token1Ratio)
    {
        // Handle edge case: no tokens
        if (token0Amount == 0 && token1Amount == 0) {
            return (0, 0);
        }

        // Calculate price of token0 in terms of token1 with PRECISION
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        // Convert token0 to token1 terms
        uint256 token0InToken1 = FullMath.mulDiv(token0Amount, price, PRECISION);
        uint256 totalValueInToken1 = token0InToken1 + token1Amount;

        // Calculate ratios (1e18 precision)
        token1Ratio = FullMath.mulDiv(token1Amount, RATIO_PRECISION, totalValueInToken1);
        token0Ratio = RATIO_PRECISION - token1Ratio;
    }

    /**
     * @notice Sum base position amounts
     */
    function _sumBasePositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        internal
        view
        returns (uint256 base0, uint256 base1)
    {
        uint256 baseLength = s.basePositionsLength;
        for (uint8 i = 0; i < baseLength;) {
            if (s.basePositions[i].lowerTick != s.basePositions[i].upperTick) {
                (, uint256 amt0, uint256 amt1,,) =
                    PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.basePositions[i]);
                unchecked {
                    base0 += amt0;
                    base1 += amt1;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Sum limit position amounts
     */
    function _sumLimitPositions(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        internal
        view
        returns (uint256 limit0, uint256 limit1)
    {
        for (uint8 i = 0; i < 2;) {
            if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
                (, uint256 amt0, uint256 amt1,,) =
                    PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.limitPositions[i]);
                unchecked {
                    limit0 += amt0;
                    limit1 += amt1;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Calculate in-position and base/limit ratios
     */
    function _calculateDeploymentRatios(
        uint256 total0,
        uint256 total1,
        uint256 position0,
        uint256 position1,
        uint256 base0,
        uint256 base1,
        uint160 sqrtPriceX96
    )
        internal
        pure
        returns (uint256 inPositionRatio, uint256 outOfPositionRatio, uint256 baseRatio, uint256 limitRatio)
    {
        // In-position ratios
        if (total0 == 0 && total1 == 0) {
            inPositionRatio = 0;
            outOfPositionRatio = 0;
        } else {
            uint256 price = FullMath.mulDiv(
                FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
            );
            uint256 totalVal = FullMath.mulDiv(total0, price, PRECISION) + total1;
            uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
            inPositionRatio = FullMath.mulDiv(posVal, RATIO_PRECISION, totalVal);
            outOfPositionRatio = RATIO_PRECISION - inPositionRatio;
        }

        // Base/limit ratios
        if (position0 == 0 && position1 == 0) {
            baseRatio = 0;
            limitRatio = 0;
        } else {
            uint256 price = FullMath.mulDiv(
                FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
            );
            uint256 baseVal = FullMath.mulDiv(base0, price, PRECISION) + base1;
            uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
            baseRatio = FullMath.mulDiv(baseVal, RATIO_PRECISION, posVal);
            limitRatio = RATIO_PRECISION - baseRatio;
        }
    }

    /**
     * @notice Get total portfolio value denominated in each token
     * @dev Converts entire portfolio value to both token0 and token1 terms
     * @param s Storage struct
     * @param poolManager The pool manager instance
     * @return totalValueInToken0 Total value in token0 terms
     * @return totalValueInToken1 Total value in token1 terms
     */
    function getTotalValuesInOneToken(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        external
        view
        returns (uint256 totalValueInToken0, uint256 totalValueInToken1)
    {
        // Get current price
        uint160 sqrtPriceX96;
        (sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());

        // Get total amounts (positions + fees + idle)
        uint256 total0;
        uint256 total1;
        (total0, total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);

        // Handle edge case: no tokens
        if (total0 == 0 && total1 == 0) {
            return (0, 0);
        }

        // Calculate price of token0 in terms of token1 with PRECISION
        // price = (sqrtPriceX96)² / 2^192
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        // Convert token0 to token1 terms
        uint256 token0InToken1 = FullMath.mulDiv(total0, price, PRECISION);
        totalValueInToken1 = token0InToken1 + total1;

        // Convert token1 to token0 terms
        // token1InToken0 = token1 / price = token1 * PRECISION / price
        uint256 token1InToken0 = FullMath.mulDiv(total1, PRECISION, price);
        totalValueInToken0 = total0 + token1InToken0;
    }

    /**
     * @notice Get comprehensive ratios for token distribution and position deployment
     * @dev Returns 8 ratios that provide complete picture of vault state
     * @param s Storage struct
     * @param poolManager The pool manager instance
     * @return ratios Struct containing all ratio values (1e18 = 100%)
     */
    function getRatios(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        external
        view
        returns (Ratios memory ratios)
    {
        uint160 sqrtPriceX96;
        (sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());

        // Get all amounts once (avoid duplicate calls)
        uint256 total0;
        uint256 total1;
        (total0, total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);

        uint256 base0;
        uint256 base1;
        (base0, base1) = _sumBasePositions(s, poolManager);

        uint256 limit0;
        uint256 limit1;
        (limit0, limit1) = _sumLimitPositions(s, poolManager);

        uint256 position0;
        uint256 position1;
        unchecked {
            position0 = base0 + limit0;
            position1 = base1 + limit1;
        }

        // Calculate all token ratios
        (ratios.pool0Ratio, ratios.pool1Ratio) = _getTokenRatios(position0, position1, sqrtPriceX96);
        (ratios.total0Ratio, ratios.total1Ratio) = _getTokenRatios(total0, total1, sqrtPriceX96);
        (ratios.base0Ratio, ratios.base1Ratio) = _getTokenRatios(base0, base1, sqrtPriceX96);
        (ratios.limit0Ratio, ratios.limit1Ratio) = _getTokenRatios(limit0, limit1, sqrtPriceX96);

        // Calculate deployment ratios in scoped block
        {
            // In-position ratios
            if (total0 == 0 && total1 == 0) {
                ratios.inPositionRatio = 0;
                ratios.outOfPositionRatio = 0;
            } else {
                uint256 price = FullMath.mulDiv(
                    FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
                );
                uint256 totalVal = FullMath.mulDiv(total0, price, PRECISION) + total1;
                uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
                ratios.inPositionRatio = FullMath.mulDiv(posVal, RATIO_PRECISION, totalVal);
                ratios.outOfPositionRatio = RATIO_PRECISION - ratios.inPositionRatio;
            }

            // Base/limit ratios
            if (position0 == 0 && position1 == 0) {
                ratios.baseRatio = 0;
                ratios.limitRatio = 0;
            } else {
                uint256 price = FullMath.mulDiv(
                    FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96
                );
                uint256 baseVal = FullMath.mulDiv(base0, price, PRECISION) + base1;
                uint256 posVal = FullMath.mulDiv(position0, price, PRECISION) + position1;
                ratios.baseRatio = FullMath.mulDiv(baseVal, RATIO_PRECISION, posVal);
                ratios.limitRatio = RATIO_PRECISION - ratios.baseRatio;
            }
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

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

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

// 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)));
    }
}

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

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

/// @title Safe Callback
/// @notice A contract that only allows the Uniswap v4 PoolManager to call the unlockCallback
abstract contract SafeCallback is ImmutableState, IUnlockCallback {
    constructor(IPoolManager _poolManager) ImmutableState(_poolManager) {}

    /// @inheritdoc IUnlockCallback
    /// @dev We force the onlyPoolManager modifier by exposing a virtual function after the onlyPoolManager check.
    function unlockCallback(bytes calldata data) external onlyPoolManager returns (bytes memory) {
        return _unlockCallback(data);
    }

    /// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the PoolManager
    function _unlockCallback(bytes calldata data) internal virtual returns (bytes memory);
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";

interface IMultiPositionFactory {
    // Manager info struct
    struct ManagerInfo {
        address managerAddress; // Note: only used when returning from getters
        address managerOwner;
        PoolKey poolKey;
        string name;
    }

    // Token pair info struct
    struct TokenPairInfo {
        address currency0;
        address currency1;
        uint256 managerCount;
    }

    // Roles
    function CLAIM_MANAGER() external view returns (bytes32);
    function FEE_MANAGER() external pure returns (bytes32);

    // Access control
    function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
    function grantRole(bytes32 role, address account) external;
    function revokeRole(bytes32 role, address account) external;
    function hasRole(bytes32 role, address account) external view returns (bool);

    // Factory
    function feeRecipient() external view returns (address);
    function setFeeRecipient(address _feeRecipient) external;
    function protocolFee() external view returns (uint16);
    function setProtocolFee(uint16 _fee) external;
    function deployMultiPositionManager(PoolKey memory poolKey, address owner, string memory name)
        external
        returns (address);
    function computeAddress(PoolKey memory poolKey, address managerOwner, string memory name)
        external
        view
        returns (address);
    function getManagersByOwner(address managerOwner) external view returns (ManagerInfo[] memory);
    function getAllManagersPaginated(uint256 offset, uint256 limit)
        external
        view
        returns (ManagerInfo[] memory managersInfo, uint256 totalCount);
    function getTotalManagersCount() external view returns (uint256);
    function getAllTokenPairsPaginated(uint256 offset, uint256 limit)
        external
        view
        returns (TokenPairInfo[] memory pairsInfo, uint256 totalCount);
    function getAllManagersByTokenPair(address currency0, address currency1, uint256 offset, uint256 limit)
        external
        view
        returns (ManagerInfo[] memory managersInfo, uint256 totalCount);

    // Aggregator allowlist
    function aggregatorAddress(uint8 aggregator) external view returns (address);
    // Strategy allowlist
    function strategyAllowed(address strategy) external view returns (bool);

    // Events
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
    event MultiPositionManagerDeployed(address indexed multiPositionManager, address indexed owner, PoolKey poolKey);
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "v4-core/types/PoolOperation.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {CurrencySettler} from "./CurrencySettler.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint128} from "v4-core/libraries/FixedPoint128.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {SignedMath} from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";

library PoolManagerUtils {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using TransientStateLibrary for IPoolManager;
    using CurrencySettler for Currency;
    using SignedMath for int256;
    using SafeCast for *;

    bytes32 constant POSITION_ID = bytes32(uint256(1));
    bytes constant HOOK_DATA = "";

    event ZeroBurn(int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1);

    error SlippageExceeded();
    error InvalidPositionData(IMultiPositionManager.Position position);
    error PoolNotInitialized(PoolKey poolKey);

    function mintLiquidities(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[] memory baseRanges,
        IMultiPositionManager.Range[2] memory limitRanges,
        uint128[] memory liquidities,
        uint256[2][] memory inMin,
        bool useCarpet
    ) external returns (IMultiPositionManager.PositionData[] memory) {
        // Allocate array for all positions (base + max 2 limit positions)
        IMultiPositionManager.PositionData[] memory positionData =
            new IMultiPositionManager.PositionData[](baseRanges.length + 2);
        uint256 positionCount = 0;
        bool useFloorRounding = useCarpet && baseRanges.length > 1;
        int24 minUsable = 0;
        int24 maxUsable = 0;
        if (useFloorRounding) {
            minUsable = TickMath.minUsableTick(poolKey.tickSpacing);
            maxUsable = TickMath.maxUsableTick(poolKey.tickSpacing);
        }

        for (uint8 i = 0; i < baseRanges.length;) {
            positionData[positionCount] = _mintBasePosition(
                poolManager,
                poolKey,
                baseRanges[i],
                liquidities[i],
                inMin[i],
                useFloorRounding,
                minUsable,
                maxUsable
            );
            unchecked {
                ++positionCount;
                ++i;
            }
        }

        // mint limit positions if they are defined (checked inside the function)
        positionCount = _mintLimitPositions(poolManager, poolKey, limitRanges, positionData, positionCount);

        // Resize array to actual count (remove empty slots)
        assembly {
            mstore(positionData, positionCount)
        }

        return positionData;
    }

    function _mintBasePosition(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint128 liquidity,
        uint256[2] memory inMin,
        bool useFloorRounding,
        int24 minUsable,
        int24 maxUsable
    ) private returns (IMultiPositionManager.PositionData memory) {
        (uint256 currencyDelta0, uint256 currencyDelta1) =
            _getCurrencyDeltas(poolManager, poolKey.currency0, poolKey.currency1);
        (uint256 amount0, uint256 amount1) =
            _getAmountsForLiquidityForMint(poolManager, poolKey, range, liquidity, useFloorRounding, minUsable, maxUsable);
        if (amount0 > currencyDelta0) {
            amount0 = currencyDelta0;
        }
        if (amount1 > currencyDelta1) {
            amount1 = currencyDelta1;
        }

        return _mintLiquidityForAmounts(poolManager, poolKey, range, amount0, amount1, inMin);
    }

    // if there's still remaining tokens, create a limit position(single-sided position)
    function _mintLimitPositions(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[2] memory limitRanges,
        IMultiPositionManager.PositionData[] memory positionData,
        uint256 positionCount
    ) internal returns (uint256) {
        if (limitRanges[0].lowerTick != limitRanges[0].upperTick) {
            uint256 currencyDelta1 = _getCurrencyDelta(poolManager, poolKey.currency1);

            if (currencyDelta1 != 0) {
                IMultiPositionManager.PositionData memory data = _mintLiquidityForAmounts(
                    poolManager, poolKey, limitRanges[0], 0, currencyDelta1, [uint256(0), uint256(0)]
                );
                positionData[positionCount] = data;
                unchecked {
                    ++positionCount;
                }
            }
        }

        if (limitRanges[1].lowerTick != limitRanges[1].upperTick) {
            uint256 currencyDelta0 = _getCurrencyDelta(poolManager, poolKey.currency0);

            if (currencyDelta0 != 0) {
                IMultiPositionManager.PositionData memory data = _mintLiquidityForAmounts(
                    poolManager, poolKey, limitRanges[1], currencyDelta0, 0, [uint256(0), uint256(0)]
                );
                positionData[positionCount] = data;
                unchecked {
                    ++positionCount;
                }
            }
        }

        return positionCount;
    }

    function _mintLiquidityForAmounts(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint256 amount0,
        uint256 amount1,
        uint256[2] memory inMin
    ) internal returns (IMultiPositionManager.PositionData memory) {
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        if (sqrtPriceX96 == 0) {
            revert PoolNotInitialized(poolKey);
        }

        if (
            range.lowerTick >= range.upperTick || range.lowerTick % poolKey.tickSpacing != 0
                || range.upperTick % poolKey.tickSpacing != 0
        ) {
            IMultiPositionManager.Position memory pos = IMultiPositionManager.Position({
                poolKey: poolKey,
                lowerTick: range.lowerTick,
                upperTick: range.upperTick
            });
            revert InvalidPositionData(pos);
        }

        uint128 liquidity = LiquidityAmounts.getLiquidityForAmounts(
            sqrtPriceX96,
            TickMath.getSqrtPriceAtTick(range.lowerTick),
            TickMath.getSqrtPriceAtTick(range.upperTick),
            amount0,
            amount1
        );

        uint256 actualAmount0;
        uint256 actualAmount1;

        if (liquidity != 0) {
            (BalanceDelta callerDelta,) = poolManager.modifyLiquidity(
                poolKey,
                ModifyLiquidityParams({
                    tickLower: range.lowerTick,
                    tickUpper: range.upperTick,
                    liquidityDelta: liquidity.toInt128(),
                    salt: POSITION_ID
                }),
                HOOK_DATA
            );

            /// callerDelta.amount0() and callerDelta.amount0() are all negative
            actualAmount0 = int256(callerDelta.amount0()).abs();
            actualAmount1 = int256(callerDelta.amount1()).abs();

            if (actualAmount0 < inMin[0] || actualAmount1 < inMin[1]) {
                revert SlippageExceeded();
            }
        }

        return
            IMultiPositionManager.PositionData({liquidity: liquidity, amount0: actualAmount0, amount1: actualAmount1});
    }

    function burnLiquidities(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[] memory baseRanges,
        IMultiPositionManager.Range[2] memory limitRanges,
        uint256 shares,
        uint256 totalSupply,
        uint256[2][] memory outMin
    ) external returns (uint256 amount0, uint256 amount1) {
        if (shares == 0) return (amount0, amount1);

        uint256 baseRangesLength = baseRanges.length;
        uint256 amountOut0;
        uint256 amountOut1;

        // Burn base positions
        for (uint8 i = 0; i < baseRangesLength;) {
            (amountOut0, amountOut1) =
                burnLiquidityForShare(poolManager, poolKey, baseRanges[i], shares, totalSupply, outMin[i]);

            unchecked {
                amount0 = amount0 + amountOut0;
                amount1 = amount1 + amountOut1;
                ++i;
            }
        }

        // Burn limit positions with their specific outMin
        (amountOut0, amountOut1) =
            _burnLimitPositions(poolManager, poolKey, limitRanges, shares, totalSupply, outMin, baseRangesLength);
        unchecked {
            amount0 = amount0 + amountOut0;
            amount1 = amount1 + amountOut1;
        }
    }

    function _burnLimitPositions(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[2] memory limitRanges,
        uint256 shares,
        uint256 totalSupply,
        uint256[2][] memory outMin,
        uint256 baseRangesLength
    ) internal returns (uint256 amount0, uint256 amount1) {
        if (shares == 0) return (0, 0);

        uint256 limitIndex = 0;
        for (uint8 i = 0; i < 2;) {
            // Skip empty limit positions
            if (limitRanges[i].lowerTick != limitRanges[i].upperTick) {
                uint256 outMinIndex = baseRangesLength + limitIndex;
                // Use provided outMin if available, otherwise use [0, 0] for backward compatibility
                uint256[2] memory positionOutMin =
                    outMinIndex < outMin.length ? outMin[outMinIndex] : [uint256(0), uint256(0)];

                (uint256 amountOut0, uint256 amountOut1) =
                    burnLiquidityForShare(poolManager, poolKey, limitRanges[i], shares, totalSupply, positionOutMin);

                unchecked {
                    amount0 = amount0 + amountOut0;
                    amount1 = amount1 + amountOut1;
                    ++limitIndex;
                }
            }

            unchecked {
                ++i;
            }
        }
    }

    function burnLiquidityForShare(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint256 shares,
        uint256 totalSupply,
        uint256[2] memory outMin
    ) public returns (uint256 amountOut0, uint256 amountOut1) {
        if (range.lowerTick == range.upperTick) {
            return (0, 0);
        }
        (uint128 liquidity,,) =
            poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);

        uint256 liquidityForShares = FullMath.mulDiv(liquidity, shares, totalSupply);

        if (liquidityForShares != 0) {
            (BalanceDelta callerDelta, BalanceDelta feesAccrued) = poolManager.modifyLiquidity(
                poolKey,
                ModifyLiquidityParams({
                    tickLower: range.lowerTick,
                    tickUpper: range.upperTick,
                    liquidityDelta: -(liquidityForShares).toInt128(),
                    salt: POSITION_ID
                }),
                HOOK_DATA
            );

            // when withdrawing liquidity or collecting fee (collecting fee is same as withdrawing liquidity 0 ),
            // callerDelta is always positive
            // when adding liquidity, most of time callerDelta is negative but could be positive
            //  when fee is larger than liquidity itself (but fee already settled in `zeroBurn`)
            // Slippage checks should only apply to principal (exclude accrued fees).
            BalanceDelta principalDelta = callerDelta - feesAccrued;
            uint256 principalOut0 = principalDelta.amount0().toUint128();
            uint256 principalOut1 = principalDelta.amount1().toUint128();

            amountOut0 = callerDelta.amount0().toUint128();
            amountOut1 = callerDelta.amount1().toUint128();

            if (principalOut0 < outMin[0] || principalOut1 < outMin[1]) {
                revert SlippageExceeded();
            }
        }
    }

    function zeroBurnAll(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[] memory baseRanges,
        IMultiPositionManager.Range[2] memory limitRanges,
        Currency currency0,
        Currency currency1,
        uint16 fee
    ) external returns (uint256 totalFee0, uint256 totalFee1) {
        uint256 baseRangesLength = baseRanges.length;
        uint256 fee0;
        uint256 fee1;
        for (uint8 i = 0; i < baseRangesLength;) {
            (fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, baseRanges[i]);
            unchecked {
                totalFee0 = totalFee0 + fee0;
                totalFee1 = totalFee1 + fee1;
                ++i;
            }
        }

        (fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, limitRanges[0]);
        unchecked {
            totalFee0 = totalFee0 + fee0;
            totalFee1 = totalFee1 + fee1;
        }
        (fee0, fee1) = _zeroBurnWithoutUnlock(poolManager, poolKey, limitRanges[1]);
        unchecked {
            totalFee0 = totalFee0 + fee0;
            totalFee1 = totalFee1 + fee1;
        }

        // Calculate fees by dividing by fee denominator
        uint256 treasuryFee0 = totalFee0 / fee;
        uint256 treasuryFee1 = totalFee1 / fee;

        if (treasuryFee0 != 0) {
            poolManager.mint(address(this), uint256(uint160(Currency.unwrap(currency0))), treasuryFee0);
        }
        if (treasuryFee1 != 0) {
            poolManager.mint(address(this), uint256(uint160(Currency.unwrap(currency1))), treasuryFee1);
        }
    }

    function getTotalFeesOwed(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[] memory baseRanges,
        IMultiPositionManager.Range[2] memory limitRanges
    ) internal view returns (uint256 totalFee0, uint256 totalFee1) {
        uint256 baseRangesLength = baseRanges.length;
        for (uint8 i = 0; i < baseRangesLength;) {
            if (baseRanges[i].lowerTick != baseRanges[i].upperTick) {
                (uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, baseRanges[i]);
                unchecked {
                    totalFee0 = totalFee0 + fee0;
                    totalFee1 = totalFee1 + fee1;
                }
            }
            unchecked {
                ++i;
            }
        }

        if (limitRanges[0].lowerTick != limitRanges[0].upperTick) {
            (uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, limitRanges[0]);
            unchecked {
                totalFee0 = totalFee0 + fee0;
                totalFee1 = totalFee1 + fee1;
            }
        }
        if (limitRanges[1].lowerTick != limitRanges[1].upperTick) {
            (uint256 fee0, uint256 fee1) = _getFeesOwed(poolManager, poolKey, limitRanges[1]);
            unchecked {
                totalFee0 = totalFee0 + fee0;
                totalFee1 = totalFee1 + fee1;
            }
        }
    }

    function _zeroBurnWithoutUnlock(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range
    ) internal returns (uint256 fee0, uint256 fee1) {
        if (range.lowerTick == range.upperTick) {
            return (0, 0);
        }
        (uint128 liquidity,,) =
            poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);

        if (liquidity != 0) {
            // Check fees first
            (uint256 feesOwed0, uint256 feesOwed1) = _getFeesOwed(poolManager, poolKey, range);
            // Only proceed with modifyLiquidity if either fee is non-zero
            if (feesOwed0 != 0 || feesOwed1 != 0) {
                (, BalanceDelta feesAccrued) = poolManager.modifyLiquidity(
                    poolKey,
                    ModifyLiquidityParams({
                        tickLower: range.lowerTick,
                        tickUpper: range.upperTick,
                        liquidityDelta: 0,
                        salt: POSITION_ID
                    }),
                    HOOK_DATA
                );

                fee0 = uint128(feesAccrued.amount0());
                fee1 = uint128(feesAccrued.amount1());
                emit ZeroBurn(range.lowerTick, range.upperTick, fee0, fee1);
            }
        }
    }

    function close(IPoolManager poolManager, Currency currency) internal {
        int256 currencyDelta = poolManager.currencyDelta(address(this), currency);
        if (currencyDelta == 0) {
            return;
        } else if (currencyDelta < 0) {
            currency.settle(poolManager, address(this), uint256(-currencyDelta), false);
        } else {
            currency.take(poolManager, address(this), uint256(currencyDelta), false);
        }
    }

    function _getCurrencyDelta(IPoolManager poolManager, Currency currency) internal view returns (uint256 delta) {
        int256 currencyDelta = poolManager.currencyDelta(address(this), currency);

        if (currencyDelta > 0) {
            delta = currency.balanceOfSelf() + uint256(currencyDelta);
        } else {
            delta = currency.balanceOfSelf() - uint256(-currencyDelta);
        }

        return delta;
    }

    function _getCurrencyDeltas(IPoolManager poolManager, Currency currency0, Currency currency1)
        internal
        view
        returns (uint256 delta0, uint256 delta1)
    {
        int256 currencyDelta0 = poolManager.currencyDelta(address(this), currency0);
        int256 currencyDelta1 = poolManager.currencyDelta(address(this), currency1);

        if (currencyDelta0 > 0) {
            delta0 = currency0.balanceOfSelf() + uint256(currencyDelta0);
        } else {
            delta0 = currency0.balanceOfSelf() - uint256(-currencyDelta0);
        }
        if (currencyDelta1 > 0) {
            delta1 = currency1.balanceOfSelf() + uint256(currencyDelta1);
        } else {
            delta1 = currency1.balanceOfSelf() - uint256(-currencyDelta1);
        }

        return (delta0, delta1);
    }

    function getAmountsForLiquidity(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint128 liquidity
    ) internal view returns (uint256 amount0, uint256 amount1) {
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
            sqrtPriceX96,
            TickMath.getSqrtPriceAtTick(range.lowerTick),
            TickMath.getSqrtPriceAtTick(range.upperTick),
            liquidity
        );
    }

    function _getAmountsForLiquidityForMint(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint128 liquidity,
        bool useFloorRounding,
        int24 minUsable,
        int24 maxUsable
    ) private view returns (uint256 amount0, uint256 amount1) {
        if (useFloorRounding && (range.lowerTick == minUsable || range.upperTick == maxUsable)) {
            return _getAmountsForLiquidityRoundedUp(poolManager, poolKey, range, liquidity);
        }
        return getAmountsForLiquidity(poolManager, poolKey, range, liquidity);
    }

    function _getAmountsForLiquidityRoundedUp(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range memory range,
        uint128 liquidity
    ) private view returns (uint256 amount0, uint256 amount1) {
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());
        uint160 sqrtPriceLower = TickMath.getSqrtPriceAtTick(range.lowerTick);
        uint160 sqrtPriceUpper = TickMath.getSqrtPriceAtTick(range.upperTick);

        if (sqrtPriceX96 <= sqrtPriceLower) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
        } else if (sqrtPriceX96 < sqrtPriceUpper) {
            amount0 = SqrtPriceMath.getAmount0Delta(sqrtPriceX96, sqrtPriceUpper, liquidity, true);
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceX96, liquidity, true);
        } else {
            amount1 = SqrtPriceMath.getAmount1Delta(sqrtPriceLower, sqrtPriceUpper, liquidity, true);
        }
    }

    function getAmountsOf(IPoolManager poolManager, PoolKey memory poolKey, IMultiPositionManager.Range memory range)
        external
        view
        returns (uint128 liquidity, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1)
    {
        if (range.lowerTick == range.upperTick) {
            return (0, 0, 0, 0, 0);
        }
        PoolId poolId = poolKey.toId();
        (liquidity,,) =
            poolManager.getPositionInfo(poolId, address(this), range.lowerTick, range.upperTick, POSITION_ID);

        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolId);

        (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
            sqrtPriceX96,
            TickMath.getSqrtPriceAtTick(range.lowerTick),
            TickMath.getSqrtPriceAtTick(range.upperTick),
            liquidity
        );

        (feesOwed0, feesOwed1) = _getFeesOwed(poolManager, poolKey, range);
    }

    function _getFeesOwed(IPoolManager poolManager, PoolKey memory poolKey, IMultiPositionManager.Range memory range)
        internal
        view
        returns (uint256 feesOwed0, uint256 feesOwed1)
    {
        (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
            poolManager.getFeeGrowthInside(poolKey.toId(), range.lowerTick, range.upperTick);

        (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) =
            poolManager.getPositionInfo(poolKey.toId(), address(this), range.lowerTick, range.upperTick, POSITION_ID);

        unchecked {
            feesOwed0 = FullMath.mulDiv(feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 = FullMath.mulDiv(feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }
    }

    /**
     * @notice Calculate outMin for rebalance with slippage protection
     * @param poolManager The pool manager
     * @param poolKey The pool key
     * @param ranges Array of position ranges
     * @param positionData Array of position data (liquidity values)
     * @param maxSlippage Maximum slippage in basis points (10000 = 100%)
     * @return outMin Array of minimum amounts [token0, token1] for each position
     */
    function calculateOutMinForRebalance(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        IMultiPositionManager.Range[] memory ranges,
        IMultiPositionManager.PositionData[] memory positionData,
        uint256 maxSlippage
    ) internal view returns (uint256[2][] memory outMin) {
        uint256 totalPositionsLength = ranges.length;

        if (totalPositionsLength == 0) {
            return outMin;
        }

        outMin = new uint256[2][](totalPositionsLength);
        uint256 slippageMultiplier = 10000 - maxSlippage;

        for (uint256 i = 0; i < totalPositionsLength;) {
            (uint256 amount0, uint256 amount1) =
                getAmountsForLiquidity(poolManager, poolKey, ranges[i], uint128(positionData[i].liquidity));

            unchecked {
                outMin[i] = [amount0 * slippageMultiplier / 10000, amount1 * slippageMultiplier / 10000];
                ++i;
            }
        }

        return outMin;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import "../interfaces/IMulticall.sol";

/**
 * @title Multicall
 * @notice Enables calling multiple methods in a single transaction
 * @dev Provides a function to batch together multiple calls in a single external call
 *      Uses transient storage to track multicall context and prevent native ETH double-spend
 */
abstract contract Multicall is IMulticall {
    error MulticallFailed(uint256 index, bytes reason);

    /// @dev Transient storage slot for multicall context flag: keccak256("multicall.context")
    bytes32 private constant _MULTICALL_CONTEXT_SLOT =
        0x2e40f768ac3179109b141c8c4ebd71d79ff175997abe8aa5bd1bbfe613dc9f1f;

    /// @dev Transient storage slot for tracking if native deposit already done: keccak256("multicall.nativeDepositDone")
    bytes32 private constant _NATIVE_DEPOSIT_DONE_SLOT =
        0x11ac6ef1c72502e61aa6ad82b1888cc53ee565c9bcc98d36d57afcf87daa78d4;

    /**
     * @notice Execute multiple calls in a single transaction
     * @param data Array of encoded function calls
     * @return results Array of return data from each call
     */
    function multicall(bytes[] calldata data) public payable virtual override returns (bytes[] memory results) {
        // Set multicall context flag
        assembly {
            tstore(_MULTICALL_CONTEXT_SLOT, 1)
        }

        results = new bytes[](data.length);

        for (uint256 i = 0; i < data.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(data[i]);

            if (!success) {
                // Clear flags before reverting
                assembly {
                    tstore(_MULTICALL_CONTEXT_SLOT, 0)
                    tstore(_NATIVE_DEPOSIT_DONE_SLOT, 0)
                }
                // Decode revert reason if possible
                if (result.length > 0) {
                    // Bubble up the revert reason
                    assembly {
                        revert(add(32, result), mload(result))
                    }
                } else {
                    revert MulticallFailed(i, result);
                }
            }

            results[i] = result;
        }

        // Clear flags at end of multicall
        assembly {
            tstore(_MULTICALL_CONTEXT_SLOT, 0)
            tstore(_NATIVE_DEPOSIT_DONE_SLOT, 0)
        }
    }

    /// @notice Check if currently executing within a multicall
    /// @return inContext True if in multicall context
    function _inMulticallContext() internal view returns (bool inContext) {
        assembly {
            inContext := tload(_MULTICALL_CONTEXT_SLOT)
        }
    }

    /// @notice Mark that a native ETH deposit has been done in this multicall
    function _markNativeDepositDone() internal {
        assembly {
            tstore(_NATIVE_DEPOSIT_DONE_SLOT, 1)
        }
    }

    /// @notice Check if a native ETH deposit has already been done in this multicall
    /// @return done True if native deposit already done
    function _isNativeDepositDone() internal view returns (bool done) {
        assembly {
            done := tload(_NATIVE_DEPOSIT_DONE_SLOT)
        }
    }
}

File 27 of 82 : SharedStructs.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {Currency} from "v4-core/types/Currency.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";

/// @title SharedStructs
/// @notice Contains structs shared between the main contract and libraries
library SharedStructs {
    /// @notice The complete storage of MultiPositionManager
    /// @dev Consolidated into a single struct following Bunni's pattern
    struct ManagerStorage {
        // Pool configuration
        PoolKey poolKey;
        PoolId poolId;
        Currency currency0;
        Currency currency1;
        // Positions
        mapping(uint256 => IMultiPositionManager.Range) basePositions;
        uint256 basePositionsLength;
        IMultiPositionManager.Range[2] limitPositions;
        uint256 limitPositionsLength;
        // External contracts
        address factory;
        // Fees
        uint16 fee;
        // Role management
        mapping(address => bool) relayers;
        // Strategy parameters - efficiently packed
        StrategyParams lastStrategyParams;
    }

    /// @notice Last used strategy parameters
    /// @dev Efficiently packed into 2 storage slots
    struct StrategyParams {
        address strategy; // 20 bytes
        int24 centerTick; // 3 bytes
        uint24 ticksLeft; // 3 bytes
        uint24 ticksRight; // 3 bytes
        uint24 limitWidth; // 3 bytes
        // Total: 32 bytes - fills slot 1
        uint120 weight0; // 15 bytes (enough for 1e18 precision)
        uint120 weight1; // 15 bytes
        bool useCarpet; // 1 byte (full-range floor flag)
        bool useSwap; // 1 byte
        bool useAssetWeights; // 1 byte
            // Total: 32 bytes - fills slot 2 efficiently
    }

    /// @notice Environment variables passed to libraries
    /// @dev Contains immutable values and frequently accessed contracts
    struct Env {
        address poolManager;
        uint16 protocolFee;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "../interfaces/IMultiPositionFactory.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {RebalanceLogic} from "./RebalanceLogic.sol";

/**
 * @title RebalanceSwapLogic
 * @notice Swap execution and swap-based rebalance helpers split from RebalanceLogic to reduce byte size.
 */
library RebalanceSwapLogic {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using SafeERC20 for IERC20;

    error InvalidAggregator();
    error InsufficientTokensForSwap();
    error InsufficientOutput();
    error NoStrategySpecified();

    event SwapExecuted(address indexed aggregator, uint256 amountIn, uint256 amountOut, bool swapToken0);

    /**
     * @notice Execute swap and calculate rebalance ranges in one call
     * @dev Combines swap execution and range calculation for cleaner flow
     * @param s Storage struct
     * @param poolManager The pool manager
     * @param params Rebalance parameters including swap details
     * @return baseRanges The base ranges to rebalance to
     * @return liquidities The liquidity amounts for each range
     * @return limitWidth The limit width for limit positions
     */
    function executeSwapAndCalculateRanges(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        IMultiPositionManager.RebalanceSwapParams calldata params
    )
        external
        returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
    {
        // 1. Get current balances
        uint256 amount0 = s.currency0.balanceOfSelf();
        uint256 amount1 = s.currency1.balanceOfSelf();

        // 2. Execute swap if needed
        if (params.swapParams.swapData.length > 0) {
            (amount0, amount1) = _executeProvidedSwap(s, params.swapParams, amount0, amount1);
        }

        // 3. Calculate ranges with updated amounts
        return _calculateRebalanceRanges(s, poolManager, params.rebalanceParams, amount0, amount1);
    }

    /**
     * @notice Execute swap for compound operation
     * @dev Used by compoundSwap to execute validated swap between ZERO_BURN and COMPOUND
     * @param s Storage struct
     * @param params Swap parameters including aggregator details
     * @return amount0 Updated amount of token0 after swap
     * @return amount1 Updated amount of token1 after swap
     */
    function executeCompoundSwap(SharedStructs.ManagerStorage storage s, RebalanceLogic.SwapParams calldata params)
        external
        returns (uint256 amount0, uint256 amount1)
    {
        // Get current balances
        amount0 = s.currency0.balanceOfSelf();
        amount1 = s.currency1.balanceOfSelf();

        // Execute swap if swap data provided
        if (params.swapData.length > 0) {
            (amount0, amount1) = _executeProvidedSwap(s, params, amount0, amount1);
        }

        return (amount0, amount1);
    }

    /**
     * @notice Execute swap exactly as specified in swapParams
     * @dev Trusts off-chain calculation from SimpleLens.calculateOptimalSwapForRebalance
     * @param s Storage struct
     * @param swapParams Complete swap parameters from JavaScript including aggregator and calldata
     * @param amount0 Current amount of token0
     * @param amount1 Current amount of token1
     * @return Updated amount0 and amount1 after swap
     */
    function _executeProvidedSwap(
        SharedStructs.ManagerStorage storage s,
        RebalanceLogic.SwapParams calldata swapParams,
        uint256 amount0,
        uint256 amount1
    ) private returns (uint256, uint256) {
        if (swapParams.swapData.length == 0) {
            // No swap needed
            return (amount0, amount1);
        }

        // Get token addresses for swap execution
        address currency0 = Currency.unwrap(s.poolKey.currency0);
        address currency1 = Currency.unwrap(s.poolKey.currency1);

        // Execute aggregator swap with validation
        uint256 amountOut = _executeAggregatorSwap(swapParams, amount0, amount1, currency0, currency1, s.factory);

        emit SwapExecuted(
            IMultiPositionFactory(s.factory).aggregatorAddress(uint8(swapParams.aggregator)),
            swapParams.swapAmount,
            amountOut,
            swapParams.swapToken0
        );

        // Update amounts based on swap direction
        if (swapParams.swapToken0) {
            return (amount0 - swapParams.swapAmount, amount1 + amountOut);
        }
        return (amount0 + amountOut, amount1 - swapParams.swapAmount);
    }

    /**
     * @notice Execute swap through aggregator with validation
     * @dev JavaScript builds complete function call, Solidity just executes it
     * @param params Swap parameters including aggregator type and encoded calldata
     * @param amount0 Available amount of token0
     * @param amount1 Available amount of token1
     * @param currency0 Address of token0
     * @param currency1 Address of token1
     * @return amountOut Amount of output token received
     */
    function _executeAggregatorSwap(
        RebalanceLogic.SwapParams calldata params,
        uint256 amount0,
        uint256 amount1,
        address currency0,
        address currency1,
        address factory
    ) private returns (uint256 amountOut) {
        // Validate aggregator type and address (prevents arbitrary contract calls)
        if (uint8(params.aggregator) > 3) revert InvalidAggregator();
        address approvedAggregator = IMultiPositionFactory(factory).aggregatorAddress(uint8(params.aggregator));
        if (approvedAggregator == address(0) || params.aggregatorAddress != approvedAggregator) {
            revert InvalidAggregator();
        }

        // Validate we have sufficient tokens for the swap
        if (params.swapToken0) {
            if (amount0 < params.swapAmount) revert InsufficientTokensForSwap();
        } else {
            if (amount1 < params.swapAmount) revert InsufficientTokensForSwap();
        }

        // Determine input and output tokens
        address inputToken = params.swapToken0 ? currency0 : currency1;
        address outputToken = params.swapToken0 ? currency1 : currency0;

        // Check if input token is native ETH (address(0))
        bool isETHIn = inputToken == address(0);

        // Approve aggregator to spend input tokens (skip if native ETH)
        if (!isETHIn) {
            IERC20(inputToken).forceApprove(approvedAggregator, params.swapAmount);
        }

        // Record balance before swap
        uint256 balanceBefore = _getBalance(outputToken);

        // Determine ETH value to send with call
        // If swapping native ETH, send the swap amount; otherwise send 0
        uint256 ethValue = isETHIn ? params.swapAmount : 0;

        // Execute the aggregator's function call
        // swapData already contains the complete, ready-to-execute function call from JavaScript
        (bool success,) = approvedAggregator.call{value: ethValue}(params.swapData);

        // Reset approval for security (skip if native ETH)
        if (!isETHIn) {
            IERC20(inputToken).forceApprove(approvedAggregator, 0);
        }

        // Bubble up revert reason if swap failed
        if (!success) {
            assembly {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
        }

        // Calculate and validate output amount
        amountOut = _getBalance(outputToken) - balanceBefore;
        if (amountOut < params.minAmountOut) revert InsufficientOutput();

        return amountOut;
    }

    /**
     * @notice Get balance of a token (handles both ERC20 and native ETH)
     * @param token Token address (address(0) for native ETH)
     * @return balance Current balance
     */
    function _getBalance(address token) private view returns (uint256) {
        if (token == address(0)) {
            return address(this).balance;
        } else {
            return IERC20(token).balanceOf(address(this));
        }
    }

    /**
     * @notice Process the rebalance result after swap
     * @dev Helper to avoid stack too deep
     */
    function _calculateRebalanceRanges(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        IMultiPositionManager.RebalanceParams calldata params,
        uint256 amount0,
        uint256 amount1
    )
        private
        returns (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, uint24 limitWidth)
    {
        (uint160 sqrtPriceX96, int24 currentTick,,) = poolManager.getSlot0(s.poolKey.toId());
        RebalanceLogic.StrategyContext memory ctx =
            _buildStrategyContext(s, params, amount0, amount1, sqrtPriceX96, currentTick);

        (baseRanges, liquidities) = RebalanceLogic.generateRangesAndLiquidities(s, poolManager, ctx, amount0, amount1);

        RebalanceLogic._updateStrategyParams(s, ctx, true);

        s.basePositionsLength = 0;
        s.limitPositionsLength = 0;

        return (baseRanges, liquidities, ctx.limitWidth);
    }

    /**
     * @notice Build strategy context from params
     */
    function _buildStrategyContext(
        SharedStructs.ManagerStorage storage s,
        IMultiPositionManager.RebalanceParams calldata params,
        uint256 amount0,
        uint256 amount1,
        uint160 sqrtPriceX96,
        int24 currentTick
    ) private view returns (RebalanceLogic.StrategyContext memory ctx) {
        ctx.useAssetWeights = (params.weight0 == 0 && params.weight1 == 0);
        if (ctx.useAssetWeights) {
            (ctx.weight0, ctx.weight1) = RebalanceLogic.calculateWeightsFromAmounts(amount0, amount1, sqrtPriceX96);
        } else {
            ctx.weight0 = params.weight0;
            ctx.weight1 = params.weight1;
        }
        if (!ctx.useAssetWeights && ctx.weight0 + ctx.weight1 != 1e18) {
            revert RebalanceLogic.InvalidWeightSum();
        }

        ctx.resolvedStrategy = params.strategy != address(0) ? params.strategy : s.lastStrategyParams.strategy;

        if (params.center == type(int24).max) {
            // Always round down to ensure the range contains the current tick
            int24 compressed = currentTick / s.poolKey.tickSpacing;
            if (currentTick < 0 && currentTick % s.poolKey.tickSpacing != 0) {
                compressed--; // Round down for negative ticks with remainder
            }
            ctx.center = compressed * s.poolKey.tickSpacing;
        } else {
            // Snap to tickSpacing grid using floor division (handles negatives correctly)
            int24 tickSpacing = s.poolKey.tickSpacing;
            ctx.center = (params.center / tickSpacing) * tickSpacing;
            if (params.center < 0 && params.center % tickSpacing != 0) {
                ctx.center -= tickSpacing;
            }
        }

        ctx.tLeft = params.tLeft;
        ctx.tRight = params.tRight;
        ctx.useCarpet = params.useCarpet;
        // In proportional mode (weights 0,0), force limitWidth to 0
        // Limit positions don't make sense when weights are derived from amounts
        if (ctx.useAssetWeights) {
            ctx.limitWidth = 0;
        } else {
            ctx.limitWidth = params.limitWidth;
        }

        if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
        ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {LiquidityAmounts} from "v4-periphery/lib/v4-core/test/utils/LiquidityAmounts.sol";
import {IERC20} from "@openzeppelin/contracts/interfaces/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "../interfaces/IMultiPositionFactory.sol";
import {ILiquidityStrategy} from "../strategies/ILiquidityStrategy.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {RebalanceLogic} from "./RebalanceLogic.sol";
import {PositionLogic} from "./PositionLogic.sol";

/**
 * @title WithdrawLogic
 * @notice Library containing all withdrawal-related logic for MultiPositionManager
 */
library WithdrawLogic {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using SafeERC20 for IERC20;

    uint256 constant PRECISION = 1e36;

    // Struct to reduce stack depth
    struct CustomWithdrawParams {
        uint256 amount0Desired;
        uint256 amount1Desired;
        address to;
        uint256[2][] outMin;
        uint256 totalSupply;
        uint256 senderBalance;
        address sender;
    }

    // Custom errors
    error ZeroValue();
    error ZeroAddress();
    error InvalidRecipient();
    error AmountMustBePositive();
    error InsufficientBalance();
    error NoSharesExist();
    error OutMinLengthMismatch();

    // Events (will be emitted by main contract)
    event Withdraw(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);
    event Burn(address indexed sender, uint256 shares, uint256 totalSupply, uint256 amount0, uint256 amount1);
    event WithdrawCustom(address indexed sender, address indexed to, uint256 shares, uint256 amount0, uint256 amount1);

    // Withdrawal path enum
    enum WithdrawPath {
        USE_CURRENT_BALANCE, // Step 1: sufficient idle balance
        USE_BALANCE_PLUS_FEES, // Step 2: need zeroBurn for fees
        BURN_AND_REBALANCE // Step 3: burn all + rebalance remaining

    }

    // Withdrawal path info struct
    struct WithdrawPathInfo {
        WithdrawPath path;
        uint256 currentBalance0;
        uint256 currentBalance1;
        uint256 total0;
        uint256 total1;
        uint256 totalFee0;
        uint256 totalFee1;
    }

    /**
     * @notice Determine which withdrawal path to take (shared by processWithdrawCustom and preview)
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param amount0Desired Amount of token0 to withdraw
     * @param amount1Desired Amount of token1 to withdraw
     * @return info Withdrawal path information
     */
    function determineWithdrawPath(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal view returns (WithdrawPathInfo memory info) {
        // Get totals
        (info.total0, info.total1, info.totalFee0, info.totalFee1) = getTotalAmounts(s, poolManager);

        // Get current balances
        info.currentBalance0 = s.currency0.balanceOfSelf();
        info.currentBalance1 = s.currency1.balanceOfSelf();

        // PATH 1: Current balance sufficient
        if (info.currentBalance0 >= amount0Desired && info.currentBalance1 >= amount1Desired) {
            info.path = WithdrawPath.USE_CURRENT_BALANCE;
            return info;
        }

        // PATH 2: Balance + fees sufficient
        uint256 availableWithFees0 = info.currentBalance0 + info.totalFee0;
        uint256 availableWithFees1 = info.currentBalance1 + info.totalFee1;

        if (availableWithFees0 >= amount0Desired && availableWithFees1 >= amount1Desired) {
            info.path = WithdrawPath.USE_BALANCE_PLUS_FEES;
            return info;
        }

        // PATH 3: Need to burn and rebalance
        info.path = WithdrawPath.BURN_AND_REBALANCE;
    }

    /**
     * @notice Process a standard withdrawal
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param shares Number of shares to burn
     * @param to Recipient address
     * @param outMin Minimum output amounts per position
     * @param totalSupply Current total supply
     * @param sender Address of the caller
     * @param withdrawToWallet If true, transfers tokens to 'to'. If false, keeps tokens in contract.
     * @return amount0 Amount of token0 withdrawn
     * @return amount1 Amount of token1 withdrawn
     */
    function processWithdraw(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 shares,
        address to,
        uint256[2][] memory outMin,
        uint256 totalSupply,
        address sender,
        bool withdrawToWallet
    ) external returns (uint256 amount0, uint256 amount1) {
        if (shares == 0) revert ZeroValue();
        if (withdrawToWallet && to == address(0)) revert ZeroAddress();
        if (outMin.length != s.basePositionsLength + s.limitPositionsLength) revert OutMinLengthMismatch();

        // Execute withdrawal via callback
        {
            bytes memory params = abi.encode(shares, outMin);
            bytes memory result = poolManager.unlock(abi.encode(IMultiPositionManager.Action.WITHDRAW, params));
            (amount0, amount1) = abi.decode(result, (uint256, uint256));
        }

        // Calculate and transfer unused amounts only if withdrawing to wallet
        if (withdrawToWallet) {
            // Transfer withdrawn amounts
            if (amount0 != 0) s.currency0.transfer(to, amount0);
            if (amount1 != 0) s.currency1.transfer(to, amount1);

            // Calculate and transfer unused amounts in a scoped block
            {
                uint256 unusedAmount0 = FullMath.mulDiv(s.currency0.balanceOfSelf(), shares, totalSupply);
                uint256 unusedAmount1 = FullMath.mulDiv(s.currency1.balanceOfSelf(), shares, totalSupply);

                if (unusedAmount0 != 0) {
                    unchecked {
                        amount0 += unusedAmount0;
                    }
                    s.currency0.transfer(to, unusedAmount0);
                }
                if (unusedAmount1 != 0) {
                    unchecked {
                        amount1 += unusedAmount1;
                    }
                    s.currency1.transfer(to, unusedAmount1);
                }
            }

            // Note: Main contract will handle burning shares
            emit Withdraw(sender, to, shares, amount0, amount1);
        } else {
            // For non-wallet withdrawals, just calculate unused amounts for reporting
            {
                uint256 unusedAmount0 = FullMath.mulDiv(s.currency0.balanceOfSelf(), shares, totalSupply);
                uint256 unusedAmount1 = FullMath.mulDiv(s.currency1.balanceOfSelf(), shares, totalSupply);

                unchecked {
                    amount0 += unusedAmount0;
                    amount1 += unusedAmount1;
                }
            }

            // Tokens stay in contract, emit Burn event
            emit Burn(sender, shares, totalSupply, amount0, amount1);
        }
    }

    /**
     * @notice Helper function to transfer tokens
     */
    function _transferWithdrawCustom(
        SharedStructs.ManagerStorage storage s,
        address to,
        uint256 amount0Out,
        uint256 amount1Out
    ) private {
        if (amount0Out != 0) {
            s.currency0.transfer(to, amount0Out);
        }
        if (amount1Out != 0) {
            s.currency1.transfer(to, amount1Out);
        }
    }

    /**
     * @notice Helper function to transfer tokens and emit event
     */
    function _transferAndEmitWithdrawCustom(
        SharedStructs.ManagerStorage storage s,
        address sender,
        address to,
        uint256 amount0Out,
        uint256 amount1Out,
        uint256 sharesBurned
    ) private {
        _transferWithdrawCustom(s, to, amount0Out, amount1Out);
        emit WithdrawCustom(sender, to, sharesBurned, amount0Out, amount1Out);
    }

    /**
     * @notice Process a custom withdrawal (both tokens)
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param params Withdrawal parameters bundled to reduce stack depth
     * @return amount0Out Amount of token0 withdrawn
     * @return amount1Out Amount of token1 withdrawn
     * @return sharesBurned Number of shares to burn
     */
    function processWithdrawCustom(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        CustomWithdrawParams memory params
    ) external returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned) {
        if (params.to == address(0)) revert InvalidRecipient();
        if (params.amount0Desired == 0 && params.amount1Desired == 0) revert AmountMustBePositive();

        // Determine withdrawal path using shared helper
        WithdrawPathInfo memory pathInfo =
            determineWithdrawPath(s, poolManager, params.amount0Desired, params.amount1Desired);

        // Check if requested amounts exceed total available
        if (params.amount0Desired > pathInfo.total0) revert InsufficientBalance();
        if (params.amount1Desired > pathInfo.total1) revert InsufficientBalance();

        // Calculate shares to burn based on combined withdrawal value
        {
            sharesBurned = calculateSharesToBurn(
                s,
                poolManager,
                params.amount0Desired,
                params.amount1Desired,
                params.totalSupply,
                pathInfo.total0,
                pathInfo.total1
            );
            if (sharesBurned > params.senderBalance) revert InsufficientBalance();
        }

        // Execute withdrawal based on path
        if (pathInfo.path == WithdrawPath.USE_CURRENT_BALANCE) {
            // Step 1: Direct transfer from current balance
            amount0Out = params.amount0Desired;
            amount1Out = params.amount1Desired;
            _transferAndEmitWithdrawCustom(s, params.sender, params.to, amount0Out, amount1Out, sharesBurned);
            return (amount0Out, amount1Out, sharesBurned);
        }

        if (pathInfo.path == WithdrawPath.USE_BALANCE_PLUS_FEES) {
            // Step 2: Collect fees via unlock callback, then transfer
            poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN, ""));
            amount0Out = params.amount0Desired;
            amount1Out = params.amount1Desired;
            _transferAndEmitWithdrawCustom(s, params.sender, params.to, amount0Out, amount1Out, sharesBurned);
            return (amount0Out, amount1Out, sharesBurned);
        }

        // Step 3: Partial position burn to get sufficient assets
        // Calculate how much of positions to burn
        uint256 positionSharesToBurn = calculatePositionSharesToBurn(
            s, poolManager, params.amount0Desired, params.amount1Desired, params.totalSupply
        );

        // Execute partial withdrawal using standard WITHDRAW action
        bytes memory withdrawParams = abi.encode(positionSharesToBurn, params.outMin);
        poolManager.unlock(abi.encode(IMultiPositionManager.Action.WITHDRAW, withdrawParams));

        // The WITHDRAW action has:
        // 1. Collected ALL fees from positions
        // 2. Burned liquidity pro-rata
        // 3. Taken pro-rata share of unused balance

        // Get balances after burn
        uint256 balance0 = s.currency0.balanceOfSelf();
        uint256 balance1 = s.currency1.balanceOfSelf();

        // Transfer actual balance when short due to rounding, otherwise transfer requested amount
        amount0Out = balance0 < params.amount0Desired ? balance0 : params.amount0Desired;
        amount1Out = balance1 < params.amount1Desired ? balance1 : params.amount1Desired;
        _transferWithdrawCustom(s, params.to, amount0Out, amount1Out);

        // NO REBALANCING - excess remains as unused balance

        emit WithdrawCustom(params.sender, params.to, sharesBurned, amount0Out, amount1Out);
        return (amount0Out, amount1Out, sharesBurned);
    }

    /**
     * @notice Calculate minimum shares worth of positions to burn to get desired amounts
     * @dev PUBLIC so SimpleLens can call it directly
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param amount0Desired Amount of token0 needed
     * @param amount1Desired Amount of token1 needed
     * @param totalSupply Total supply of shares
     * @return positionShares Shares worth of positions to burn
     */
    function calculatePositionSharesToBurn(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 totalSupply
    ) internal view returns (uint256 positionShares) {
        if (totalSupply == 0) revert NoSharesExist();

        // Get total amounts (positions + fees + unused balances)
        (uint256 total0, uint256 total1,,) = getTotalAmounts(s, poolManager);

        // Calculate shares needed for each token (ceiling division for safety)
        uint256 sharesForToken0;
        uint256 sharesForToken1;

        if (amount0Desired != 0 && total0 != 0) {
            // Ceiling division
            unchecked {
                sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
            }
        }

        if (amount1Desired != 0 && total1 != 0) {
            unchecked {
                sharesForToken1 = (amount1Desired * totalSupply + total1 - 1) / total1;
            }
        }

        // Take maximum to ensure both requirements met
        positionShares = sharesForToken0 > sharesForToken1 ? sharesForToken0 : sharesForToken1;

        // Cap at total supply
        if (positionShares > totalSupply) {
            positionShares = totalSupply;
        }
    }

    /**
     * @notice Calculate shares to burn for custom withdrawal (both tokens)
     */
    function calculateSharesToBurn(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 totalSupply,
        uint256 pool0,
        uint256 pool1
    ) internal view returns (uint256 shares) {
        if (totalSupply == 0) revert NoSharesExist();

        // Get current price from pool
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());

        // Calculate price of token0 in terms of token1 with PRECISION
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        // Calculate total withdrawal value in token1 terms (combining both tokens)
        uint256 withdrawalValue0InToken1 = FullMath.mulDiv(amount0Desired, price, PRECISION);
        uint256 withdrawalValueInToken1;
        uint256 poolValueInToken1;

        unchecked {
            withdrawalValueInToken1 = withdrawalValue0InToken1 + amount1Desired;
            // Calculate pool value in token1 terms
            poolValueInToken1 = pool1 + FullMath.mulDiv(pool0, price, PRECISION);
        }

        // Calculate shares to burn
        shares = FullMath.mulDiv(withdrawalValueInToken1, totalSupply, poolValueInToken1);
    }

    /**
     * @notice Public wrapper for calculateSharesToBurn that works with MultiPositionManager
     * @param manager The MultiPositionManager contract
     * @param amount0Desired Amount of token0 desired to withdraw
     * @param amount1Desired Amount of token1 desired to withdraw
     * @param totalSupply Total supply of vault shares
     * @param pool0 Total amount of token0 in pool
     * @param pool1 Total amount of token1 in pool
     * @return shares Number of shares to burn
     */
    function calculateSharesToBurnForManager(
        address manager,
        uint256 amount0Desired,
        uint256 amount1Desired,
        uint256 totalSupply,
        uint256 pool0,
        uint256 pool1
    ) external view returns (uint256 shares) {
        if (totalSupply == 0) revert NoSharesExist();

        // Get manager's pool key and pool manager using interface
        IMultiPositionManager mpm = IMultiPositionManager(manager);
        IPoolManager poolManager = mpm.poolManager();
        PoolKey memory poolKey = mpm.poolKey();

        // Get current price from pool
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(poolKey.toId());

        // Calculate price of token0 in terms of token1 with PRECISION
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        // Calculate total withdrawal value in token1 terms (combining both tokens)
        uint256 withdrawalValue0InToken1 = FullMath.mulDiv(amount0Desired, price, PRECISION);
        uint256 withdrawalValueInToken1;
        uint256 poolValueInToken1;

        unchecked {
            withdrawalValueInToken1 = withdrawalValue0InToken1 + amount1Desired;
            // Calculate pool value in token1 terms
            poolValueInToken1 = pool1 + FullMath.mulDiv(pool0, price, PRECISION);
        }

        // Calculate shares to burn
        shares = FullMath.mulDiv(withdrawalValueInToken1, totalSupply, poolValueInToken1);
    }

    /**
     * @notice Public wrapper for calculatePositionSharesToBurn for SimpleLens
     * @param manager The MultiPositionManager contract address
     * @param amount0Desired Amount of token0 needed
     * @param amount1Desired Amount of token1 needed
     * @return positionShares Shares worth of positions to burn
     */
    function calculatePositionSharesToBurnForSimpleLens(address manager, uint256 amount0Desired, uint256 amount1Desired)
        external
        view
        returns (uint256 positionShares)
    {
        IMultiPositionManager mpm = IMultiPositionManager(manager);

        uint256 totalSupply = mpm.totalSupply();
        if (totalSupply == 0) revert NoSharesExist();

        // Get total amounts using the interface
        (uint256 total0, uint256 total1,,) = mpm.getTotalAmounts();

        // Calculate shares needed for each token (ceiling division for safety)
        uint256 sharesForToken0;
        uint256 sharesForToken1;

        if (amount0Desired != 0 && total0 != 0) {
            // Ceiling division
            unchecked {
                sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
            }
        }

        if (amount1Desired != 0 && total1 != 0) {
            unchecked {
                sharesForToken1 = (amount1Desired * totalSupply + total1 - 1) / total1;
            }
        }

        // Take maximum to ensure both requirements met
        positionShares = sharesForToken0 > sharesForToken1 ? sharesForToken0 : sharesForToken1;

        // Cap at total supply
        if (positionShares > totalSupply) {
            positionShares = totalSupply;
        }
    }

    /**
     * @notice Claim accumulated fees to the fee recipient (internal helper)
     * @param poolManager Pool manager contract
     * @param factory Factory contract address to get fee recipient
     * @param currency Currency to claim fees for
     */
    function _claimFeeCurrency(IPoolManager poolManager, address factory, Currency currency) internal {
        uint256 amount = poolManager.balanceOf(address(this), currency.toId());
        if (amount == 0) return;
        poolManager.burn(address(this), currency.toId(), amount);
        // Get feeRecipient from factory
        address recipient = IMultiPositionFactory(factory).feeRecipient();
        poolManager.take(currency, recipient, amount);
    }

    /**
     * @notice Claim accumulated fees to the fee recipient (external)
     * @param poolManager Pool manager contract
     * @param factory Factory contract address to get fee recipient
     * @param currency Currency to claim fees for
     */
    function claimFee(IPoolManager poolManager, address factory, Currency currency) external {
        _claimFeeCurrency(poolManager, factory, currency);
    }

    /**
     * @notice Process claim fee action - collects fees and distributes to owner and treasury
     * @param s Storage pointer
     * @param poolManager Pool manager contract
     * @param caller Address initiating the claim
     * @param owner Owner address
     */
    function processClaimFee(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        address caller,
        address owner
    ) external {
        // If owner is calling, perform zeroBurn to collect new fees
        if (caller == owner) {
            // Perform zeroBurn and get the exact fee amounts
            (uint256 totalFee0, uint256 totalFee1) = zeroBurnAllWithoutUnlock(s, poolManager);

            // After zeroBurnAll, treasury portion is minted as ERC-6909 to contract
            // The owner's portion creates negative deltas that are settled by close
            PoolManagerUtils.close(poolManager, s.currency1);
            PoolManagerUtils.close(poolManager, s.currency0);

            // If there are fees, transfer owner's portion
            // After close, owner's fees are in contract as ETH or ERC20
            if (s.fee != 0) {
                // Calculate exact splits
                uint256 treasuryFee0;
                uint256 treasuryFee1;
                uint256 ownerFee0;
                uint256 ownerFee1;

                unchecked {
                    treasuryFee0 = totalFee0 / s.fee;
                    treasuryFee1 = totalFee1 / s.fee;
                    ownerFee0 = totalFee0 - treasuryFee0;
                    ownerFee1 = totalFee1 - treasuryFee1;
                }

                // Transfer owner's portion (now in contract after close)
                if (ownerFee0 != 0) {
                    if (s.currency0.isAddressZero()) {
                        // Native token - transfer ETH
                        payable(owner).transfer(ownerFee0);
                    } else {
                        // ERC20 token
                        IERC20(Currency.unwrap(s.currency0)).safeTransfer(owner, ownerFee0);
                    }
                }
                if (ownerFee1 != 0) {
                    // Currency1 is never native, always ERC20
                    IERC20(Currency.unwrap(s.currency1)).safeTransfer(owner, ownerFee1);
                }
            }
        }

        // Always transfer treasury portion to fee recipient
        // For protocol fee claims (caller == address(0)), this just transfers existing balance
        // For owner claims, this transfers the freshly collected treasury portion
        _claimFeeCurrency(poolManager, s.factory, s.currency0);
        _claimFeeCurrency(poolManager, s.factory, s.currency1);
    }

    /**
     * @notice Get total amounts including fees
     */
    function getTotalAmounts(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        internal
        view
        returns (uint256 total0, uint256 total1, uint256 totalFee0, uint256 totalFee1)
    {
        // Get amounts from base positions
        for (uint8 i = 0; i < s.basePositionsLength;) {
            (, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
                PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, s.basePositions[i]);
            unchecked {
                total0 += amount0;
                total1 += amount1;
                totalFee0 += feesOwed0;
                totalFee1 += feesOwed1;
                ++i;
            }
        }

        // Get amounts from limit positions
        for (uint8 i = 0; i < 2;) {
            IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
            if (limitRange.lowerTick != limitRange.upperTick) {
                (, uint256 amount0, uint256 amount1, uint256 feesOwed0, uint256 feesOwed1) =
                    PoolManagerUtils.getAmountsOf(poolManager, s.poolKey, limitRange);
                unchecked {
                    total0 += amount0;
                    total1 += amount1;
                    totalFee0 += feesOwed0;
                    totalFee1 += feesOwed1;
                }
            }
            unchecked {
                ++i;
            }
        }

        // Exclude protocol fee from the total amount
        unchecked {
            totalFee0 -= (totalFee0 / s.fee);
            totalFee1 -= (totalFee1 / s.fee);

            // Add fees net of protocol fees to the total amount
            total0 += totalFee0;
            total1 += totalFee1;

            // Add unused balances
            total0 += s.currency0.balanceOfSelf();
            total1 += s.currency1.balanceOfSelf();
        }
    }

    /**
     * @notice Process BURN_ALL action in callback
     * @dev Burns all positions and clears storage
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param totalSupply Current total supply
     * @param params Encoded parameters (outMin array)
     * @return Encoded burned amounts (amount0, amount1)
     */
    function processBurnAllInCallback(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 totalSupply,
        bytes memory params
    ) external returns (bytes memory) {
        // Decode parameters
        uint256[2][] memory outMin = abi.decode(params, (uint256[2][]));

        // Calculate fees owed before burning liquidity (burning clears fee growth state)
        uint256 totalFee0;
        uint256 totalFee1;
        {
            uint256 baseLength = s.basePositionsLength;
            IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](baseLength);
            for (uint8 i = 0; i < baseLength;) {
                baseRangesArray[i] = s.basePositions[i];
                unchecked {
                    ++i;
                }
            }

            IMultiPositionManager.Range[2] memory limitRangesArray;
            limitRangesArray[0] = s.limitPositions[0];
            limitRangesArray[1] = s.limitPositions[1];

            (totalFee0, totalFee1) =
                PoolManagerUtils.getTotalFeesOwed(poolManager, s.poolKey, baseRangesArray, limitRangesArray);
        }

        // Burn all positions
        (uint256 amount0, uint256 amount1) =
            PositionLogic.burnLiquidities(poolManager, s, totalSupply, totalSupply, outMin);

        // Mint protocol fee claims based on total fees collected
        uint256 treasuryFee0 = totalFee0 / s.fee;
        uint256 treasuryFee1 = totalFee1 / s.fee;

        if (treasuryFee0 != 0) {
            poolManager.mint(address(this), uint256(uint160(Currency.unwrap(s.currency0))), treasuryFee0);
        }
        if (treasuryFee1 != 0) {
            poolManager.mint(address(this), uint256(uint160(Currency.unwrap(s.currency1))), treasuryFee1);
        }

        // Clear position storage
        s.basePositionsLength = 0;
        delete s.limitPositions[0];
        delete s.limitPositions[1];
        s.limitPositionsLength = 0;

        // Return burned amounts
        return abi.encode(amount0, amount1);
    }

    /**
     * @notice Zero burn all positions without unlock to collect fees
     * @dev Collects fees from all positions without burning liquidity
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @return totalFee0 Total fees collected in token0
     * @return totalFee1 Total fees collected in token1
     */
    function zeroBurnAllWithoutUnlock(SharedStructs.ManagerStorage storage s, IPoolManager poolManager)
        public
        returns (uint256 totalFee0, uint256 totalFee1)
    {
        // Build base positions array inline to avoid cross-library storage parameter issues
        uint256 baseLength = s.basePositionsLength;
        IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](baseLength);
        for (uint8 i = 0; i < baseLength;) {
            baseRangesArray[i] = s.basePositions[i];
            unchecked {
                ++i;
            }
        }

        // Build limit positions array inline
        IMultiPositionManager.Range[2] memory limitRangesArray;
        limitRangesArray[0] = s.limitPositions[0];
        limitRangesArray[1] = s.limitPositions[1];

        // Collect fees from all positions
        (totalFee0, totalFee1) = PoolManagerUtils.zeroBurnAll(
            poolManager, s.poolKey, baseRangesArray, limitRangesArray, s.currency0, s.currency1, s.fee
        );
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {SharedStructs} from "../base/SharedStructs.sol";
import {WithdrawLogic} from "./WithdrawLogic.sol";
import {DepositRatioLib} from "./DepositRatioLib.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";

/**
 * @title DepositLogic
 * @notice Library containing all deposit-related logic for MultiPositionManager
 */
library DepositLogic {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;

    uint256 constant PRECISION = 1e36;

    // Custom errors
    error InvalidRecipient();
    error CannotSendETHForERC20Pair();
    error NoSharesMinted();
    error InvalidInMinLength();

    // Events
    event Deposit(address indexed from, address indexed to, uint256 amount0, uint256 amount1, uint256 shares);

    event Compound(uint256 amount0, uint256 amount1);

    /**
     * @notice Process a deposit (tokens go to vault as idle balance)
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param deposit0Desired Desired amount of token0 to deposit
     * @param deposit1Desired Desired amount of token1 to deposit
     * @param to Recipient address for shares
     * @param totalSupply Current total supply of shares
     * @param msgValue Value sent with transaction
     * @return shares Number of shares minted
     * @return deposit0 Actual amount of token0 deposited
     * @return deposit1 Actual amount of token1 deposited
     */
    function processDeposit(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 deposit0Desired,
        uint256 deposit1Desired,
        address to,
        address from,
        uint256 totalSupply,
        uint256 msgValue
    ) external returns (uint256 shares, uint256 deposit0, uint256 deposit1) {
        if (to == address(0)) revert InvalidRecipient();
        if (!s.currency0.isAddressZero() && msgValue != 0) {
            revert CannotSendETHForERC20Pair();
        }

        // Use the actual deposit amounts
        deposit0 = deposit0Desired;
        deposit1 = deposit1Desired;

        if (totalSupply == 0) {
            // First deposit - use simple max since we don't have positions yet
            shares = Math.max(deposit0, deposit1);
        } else {
            // Calculate shares for subsequent deposits
            shares = calculateShares(s, poolManager, deposit0, deposit1, totalSupply);
        }

        if (shares == 0) revert NoSharesMinted();

        // Emit event
        emit Deposit(from, to, deposit0, deposit1, shares);

        // Return values for main contract to handle minting and transfers
        return (shares, deposit0, deposit1);
    }

    /**
     * @notice Calculate shares to mint for a deposit
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param deposit0 Amount of token0 to deposit
     * @param deposit1 Amount of token1 to deposit
     * @param totalSupply Current total supply of shares
     * @return shares Number of shares to mint
     */
    function calculateShares(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 deposit0,
        uint256 deposit1,
        uint256 totalSupply
    ) public view returns (uint256 shares) {
        // Get current pool totals
        (uint256 pool0, uint256 pool1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);

        // Get price from the pool
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(s.poolKey.toId());

        // Calculate price of token0 in terms of token1 with PRECISION
        uint256 price =
            FullMath.mulDiv(FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96), PRECISION, 1 << 96);

        // Calculate deposit value in token1 terms
        uint256 depositValueInToken1 = deposit1 + FullMath.mulDiv(deposit0, price, PRECISION);

        // Calculate pool value in token1 terms
        uint256 pool0PricedInToken1 = FullMath.mulDiv(pool0, price, PRECISION);
        uint256 poolValueInToken1 = pool0PricedInToken1 + pool1;

        // Calculate shares
        if (poolValueInToken1 != 0) {
            shares = FullMath.mulDiv(depositValueInToken1, totalSupply, poolValueInToken1);
        } else {
            shares = depositValueInToken1;
        }
    }

    /**
     * @notice Get amounts for direct deposit into positions
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param deposit0 Amount of token0 being deposited
     * @param deposit1 Amount of token1 being deposited
     * @param inMin Minimum input amounts per position
     * @return amount0ForPositions Amount of token0 for positions
     * @return amount1ForPositions Amount of token1 for positions
     */
    function getDirectDepositAmounts(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 deposit0,
        uint256 deposit1,
        uint256[2][] memory inMin
    ) external view returns (uint256 amount0ForPositions, uint256 amount1ForPositions) {
        if (s.basePositionsLength == 0) {
            return (0, 0);
        }

        // Validate inMin array size (basePositions + actual limit positions count)
        if (inMin.length != s.basePositionsLength + s.limitPositionsLength) revert InvalidInMinLength();

        // Get current totals
        (uint256 total0, uint256 total1,,) = WithdrawLogic.getTotalAmounts(s, poolManager);

        // Use library to calculate amounts that fit the ratio
        return DepositRatioLib.getRatioAmounts(total0, total1, deposit0, deposit1);
    }

    /**
     * @notice Process direct deposit liquidity addition to existing positions
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param amount0 Amount of token0 to deposit
     * @param amount1 Amount of token1 to deposit
     * @param inMin Minimum amounts per position for slippage protection
     */
    function directDepositLiquidity(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 amount0,
        uint256 amount1,
        uint256[2][] memory inMin
    ) external {
        // Calculate distribution amounts and add liquidity
        (uint256[] memory amounts0, uint256[] memory amounts1) =
            calculateDirectDepositAmounts(s, poolManager, amount0, amount1);
        addLiquidityToPositions(s, poolManager, amounts0, amounts1, inMin);
    }

    struct DepositAmountsParams {
        IPoolManager poolManager;
        PoolKey poolKey;
        uint256 amount0;
        uint256 amount1;
        uint256 basePositionsLength;
        uint256 limitPositionsLength;
        uint256 totalPositions;
    }

    /**
     * @notice Calculate how to distribute deposit amounts across positions
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param amount0 Amount of token0 to distribute
     * @param amount1 Amount of token1 to distribute
     * @return amounts0 Array of token0 amounts for each position
     * @return amounts1 Array of token1 amounts for each position
     */
    function calculateDirectDepositAmounts(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 amount0,
        uint256 amount1
    ) public view returns (uint256[] memory amounts0, uint256[] memory amounts1) {
        DepositAmountsParams memory params = DepositAmountsParams({
            poolManager: poolManager,
            poolKey: s.poolKey,
            amount0: amount0,
            amount1: amount1,
            basePositionsLength: s.basePositionsLength,
            limitPositionsLength: s.limitPositionsLength,
            totalPositions: s.basePositionsLength + s.limitPositionsLength
        });

        // Get current token amounts in each position
        uint256[] memory positionToken0 = new uint256[](params.totalPositions);
        uint256[] memory positionToken1 = new uint256[](params.totalPositions);
        (uint256 totalToken0InPositions, uint256 totalToken1InPositions) =
            _populatePositionTokens(s, params, positionToken0, positionToken1);

        // If no tokens in positions, fall back to liquidity-based distribution
        if (totalToken0InPositions == 0 && totalToken1InPositions == 0) {
            // Get total liquidity for fallback
            uint256 totalLiquidity = _getTotalLiquidityForFallback(s, params);

            if (totalLiquidity == 0) {
                // No positions to add to
                amounts0 = new uint256[](params.totalPositions);
                amounts1 = new uint256[](params.totalPositions);
                return (amounts0, amounts1);
            }

            // For now, just return empty arrays since we can't distribute without knowing token requirements
            // This case should be rare (positions with liquidity but no tokens)
            amounts0 = new uint256[](params.totalPositions);
            amounts1 = new uint256[](params.totalPositions);
            return (amounts0, amounts1);
        }

        // First determine what CAN actually go into positions based on their ratio
        // Use library function to calculate amounts that maintain the ratio
        (amount0, amount1) = DepositRatioLib.getRatioAmounts(
            totalToken0InPositions, totalToken1InPositions, params.amount0, params.amount1
        );

        // Now distribute these amounts proportionally based on current holdings
        amounts0 = new uint256[](params.totalPositions);
        amounts1 = new uint256[](params.totalPositions);

        // Distribute token0 to positions that hold token0
        if (totalToken0InPositions != 0 && amount0 != 0) {
            for (uint256 i = 0; i < params.totalPositions;) {
                if (positionToken0[i] != 0) {
                    amounts0[i] = FullMath.mulDiv(amount0, positionToken0[i], totalToken0InPositions);
                }
                unchecked {
                    ++i;
                }
            }
        }

        // Distribute token1 to positions that hold token1
        if (totalToken1InPositions != 0 && amount1 != 0) {
            for (uint256 i = 0; i < params.totalPositions;) {
                if (positionToken1[i] != 0) {
                    amounts1[i] = FullMath.mulDiv(amount1, positionToken1[i], totalToken1InPositions);
                }
                unchecked {
                    ++i;
                }
            }
        }
    }

    function _populatePositionTokens(
        SharedStructs.ManagerStorage storage s,
        DepositAmountsParams memory params,
        uint256[] memory positionToken0,
        uint256[] memory positionToken1
    ) private view returns (uint256 totalToken0InPositions, uint256 totalToken1InPositions) {
        // Get token amounts for base positions
        for (uint8 i = 0; i < params.basePositionsLength;) {
            IMultiPositionManager.Range memory range = s.basePositions[i];
            (, uint256 amount0InPos, uint256 amount1InPos,,) =
                PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, range);
            positionToken0[i] = amount0InPos;
            positionToken1[i] = amount1InPos;
            unchecked {
                totalToken0InPositions += amount0InPos;
                totalToken1InPositions += amount1InPos;
                ++i;
            }
        }

        // Get token amounts for limit positions if they exist
        uint256 limitIndex;
        for (uint8 i = 0; i < 2;) {
            IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
            if (limitRange.lowerTick != limitRange.upperTick) {
                uint256 idx = params.basePositionsLength + limitIndex;
                (, uint256 amount0InPos, uint256 amount1InPos,,) =
                    PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, limitRange);
                positionToken0[idx] = amount0InPos;
                positionToken1[idx] = amount1InPos;
                unchecked {
                    totalToken0InPositions += amount0InPos;
                    totalToken1InPositions += amount1InPos;
                    ++limitIndex;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    function _getTotalLiquidityForFallback(SharedStructs.ManagerStorage storage s, DepositAmountsParams memory params)
        private
        view
        returns (uint256 totalLiquidity)
    {
        for (uint8 i = 0; i < params.basePositionsLength;) {
            IMultiPositionManager.Range memory range = s.basePositions[i];
            (uint128 liquidity,,,,) = PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, range);
            unchecked {
                totalLiquidity += liquidity;
                ++i;
            }
        }

        for (uint8 i = 0; i < 2;) {
            IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
            if (limitRange.lowerTick != limitRange.upperTick) {
                (uint128 liquidity,,,,) = PoolManagerUtils.getAmountsOf(params.poolManager, params.poolKey, limitRange);
                unchecked {
                    totalLiquidity += liquidity;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Add liquidity to positions with calculated amounts
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param amounts0 Array of token0 amounts for each position
     * @param amounts1 Array of token1 amounts for each position
     * @param inMin Minimum amounts per position for slippage protection
     */
    function addLiquidityToPositions(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256[] memory amounts0,
        uint256[] memory amounts1,
        uint256[2][] memory inMin
    ) private {
        // Add liquidity to each base position
        uint256 baseLength = s.basePositionsLength;
        uint256 totalPositions = baseLength + s.limitPositionsLength;

        // If empty inMin passed, create zero-filled array (no slippage protection)
        if (inMin.length == 0) {
            inMin = new uint256[2][](totalPositions);
        }
        for (uint8 i = 0; i < baseLength;) {
            if (amounts0[i] != 0 || amounts1[i] != 0) {
                PoolManagerUtils._mintLiquidityForAmounts(
                    poolManager, s.poolKey, s.basePositions[i], amounts0[i], amounts1[i], inMin[i]
                );
            }
            unchecked {
                ++i;
            }
        }

        // Add liquidity to limit positions if they exist
        uint256 limitIndex;
        for (uint8 i = 0; i < 2;) {
            if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick) {
                uint256 idx = baseLength + limitIndex;
                if (amounts0[idx] != 0 || amounts1[idx] != 0) {
                    PoolManagerUtils._mintLiquidityForAmounts(
                        poolManager, s.poolKey, s.limitPositions[i], amounts0[idx], amounts1[idx], inMin[idx]
                    );
                }
                unchecked {
                    ++limitIndex;
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    /**
     * @notice Process compound: collect fees via zeroBurn, add idle to positions
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param inMin Minimum amounts for slippage protection
     */
    function processCompound(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256[2][] memory inMin
    ) external {
        if (s.basePositionsLength == 0) return;

        // Step 1: Collect fees into vault via zeroBurn
        WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);

        // Step 2: Get idle balances (fees + existing idle)
        uint256 idle0 = s.currency0.balanceOfSelf();
        uint256 idle1 = s.currency1.balanceOfSelf();

        if (idle0 == 0 && idle1 == 0) return;

        // Step 3: Add liquidity to positions
        // Calculate distribution amounts and add liquidity
        (uint256[] memory amounts0, uint256[] memory amounts1) =
            calculateDirectDepositAmounts(s, poolManager, idle0, idle1);
        addLiquidityToPositions(s, poolManager, amounts0, amounts1, inMin);

        // Emit compound event
        emit Compound(idle0, idle1);
    }
}

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {BaseHook} from "v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta} from "v4-core/types/BeforeSwapDelta.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TransientSlot} from "@openzeppelin-latest/contracts/utils/TransientSlot.sol";
import {ILimitOrderManager} from "../interfaces/ILimitOrderManager.sol";
import {BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {FixedPointMathLib} from "solmate/src/utils/FixedPointMathLib.sol";
import {VolatilityOracle} from "../libraries/VolatilityOracle.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

/// @title VolatilityDynamicFeeLimitOrderHook
/// @notice Singleton volatility hook for Unilaunch pools with limit order execution
contract VolatilityDynamicFeeLimitOrderHook is BaseHook, Ownable {
    using PoolIdLibrary for PoolKey;
    using TransientSlot for *;
    using SafeCast for *;
    using FixedPointMathLib for uint256;

    uint256 private constant FEE_DENOMINATOR = 1_000_000;
    uint256 private constant BPS_DENOMINATOR = 10_000;
    uint24 private constant MAX_LP_FEE = 1_000_000;

    ILimitOrderManager public immutable limitOrderManager;
    VolatilityOracle public immutable volatilityOracle;
    address public immutable orderBookFactory;

    mapping(PoolId => bool) public managedPools;
    mapping(bytes32 => bool) public poolParametersUsed;
    mapping(PoolId => uint256) public tradingEnabledBlock;

    struct FeeParams {
        uint24 baseFee;
        bool enabled;
    }

    mapping(PoolId => FeeParams) public feeParams;

    struct SurgeState {
        uint24 surgeMultiplier;
        uint32 surgeDuration;
        uint32 capStartTime;
        bool isActive;
    }

    mapping(PoolId => SurgeState) public surgeStates;

    uint24 public defaultMinCap = 10;
    uint24 public defaultMaxCap = 1000;
    uint32 public defaultStepPpm = 20000;
    uint32 public defaultBudgetPpm = 1000000;
    uint32 public defaultDecayWindow = 15552000;
    uint32 public defaultUpdateInterval = 86400;

    error TradingNotYetEnabled(uint256 enabledBlock, uint256 currentBlock);
    error InvalidFeeConfiguration();
    error UnauthorizedInitializer();

    event DynamicLPFeeUpdated(PoolId indexed poolId, uint24 newFee, uint24 surgeFee);
    event FeeParamsUpdated(PoolId indexed poolId, uint24 baseFee);
    event CAPDetected(PoolId indexed poolId, uint32 timestamp, int24 tickDelta);
    event SurgeFeeApplied(PoolId indexed poolId, uint24 surgeFee, uint32 timeRemaining);
    event SurgeDeactivated(PoolId indexed poolId, uint32 timestamp);
    event PoolRegistered(
        PoolId indexed poolId,
        uint24 baseFee,
        uint24 surgeMultiplier,
        uint32 surgeDuration,
        uint24 initialMaxTicksPerBlock
    );
    event DefaultOraclePolicyUpdated(
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    );

    constructor(
        IPoolManager _poolManager,
        address _limitOrderManager,
        address _volatilityOracle,
        address _orderBookFactory
    ) BaseHook(_poolManager) Ownable(_orderBookFactory) {
        if (_limitOrderManager == address(0)) revert("ZeroAddress");
        if (_volatilityOracle == address(0)) revert("ZeroAddress");
        if (_orderBookFactory == address(0)) revert("ZeroAddress");
        limitOrderManager = ILimitOrderManager(_limitOrderManager);
        volatilityOracle = VolatilityOracle(_volatilityOracle);
        orderBookFactory = _orderBookFactory;
    }

    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true,
            afterInitialize: false,
            beforeAddLiquidity: false,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: false,
            afterRemoveLiquidity: false,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: false,
            afterSwapReturnDelta: false,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    function _beforeInitialize(address sender, PoolKey calldata, uint160)
        internal
        override
        returns (bytes4)
    {
        if (sender != orderBookFactory) revert UnauthorizedInitializer();
        return this.beforeInitialize.selector;
    }

    function _beforeSwap(
        address,
        PoolKey calldata key,
        SwapParams calldata,
        bytes calldata
    ) internal override returns (bytes4, BeforeSwapDelta, uint24) {
        PoolId poolId = key.toId();

        uint256 enabledBlock = tradingEnabledBlock[poolId];
        if (enabledBlock > 0) {
            if (block.number < enabledBlock) {
                revert TradingNotYetEnabled(enabledBlock, block.number);
            }
            delete tradingEnabledBlock[poolId];
        }

        uint24 lpFee;
        {
            (,int24 tickBeforeSwap,,uint24 fee) = StateLibrary.getSlot0(poolManager, poolId);
            lpFee = fee;
            bytes32 slot = _getPreviousTickSlot(poolId);
            assembly ("memory-safe") {
                tstore(slot, tickBeforeSwap)
            }
        }

        FeeParams memory params_ = feeParams[poolId];
        if (!params_.enabled) {
            return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
        }

        uint24 totalFee;
        {
            SurgeState storage surge = surgeStates[poolId];
            uint24 surgeFee = 0;

            if (surge.isActive) {
                uint32 elapsed = uint32(block.timestamp) - surge.capStartTime;

                if (elapsed >= surge.surgeDuration) {
                    surge.isActive = false;
                    emit SurgeDeactivated(poolId, uint32(block.timestamp));
                } else {
                    uint32 remaining = surge.surgeDuration - elapsed;
                    surgeFee = uint24(
                        (uint256(params_.baseFee) * surge.surgeMultiplier * remaining / surge.surgeDuration) / BPS_DENOMINATOR
                    );
                    emit SurgeFeeApplied(poolId, surgeFee, remaining);
                }
            }

            totalFee = params_.baseFee + surgeFee;
            if (totalFee != lpFee) {
                poolManager.updateDynamicLPFee(key, totalFee);
                emit DynamicLPFeeUpdated(poolId, totalFee, surgeFee);
            }
        }

        return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
    }

    function _afterSwap(
        address,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta,
        bytes calldata
    ) internal override returns (bytes4, int128) {
        PoolId poolId = key.toId();

        int24 tickBeforeSwap;
        bytes32 slot = _getPreviousTickSlot(poolId);
        assembly ("memory-safe") {
            tickBeforeSwap := tload(slot)
        }

        (, int24 tickAfterSwap,,) = StateLibrary.getSlot0(poolManager, poolId);

        limitOrderManager.executeOrder(key, tickBeforeSwap, tickAfterSwap, params.zeroForOne);

        bool wasCapped = volatilityOracle.pushObservationAndCheckCap(poolId, tickBeforeSwap);
        if (wasCapped) {
            surgeStates[poolId].isActive = true;
            surgeStates[poolId].capStartTime = uint32(block.timestamp);
            emit CAPDetected(poolId, uint32(block.timestamp), tickAfterSwap - tickBeforeSwap);
        }

        return (BaseHook.afterSwap.selector, 0);
    }

    function _getPreviousTickSlot(PoolId poolId) private pure returns (bytes32) {
        return keccak256(abi.encodePacked("unilaunch.hooks.volatility.previous-tick", poolId));
    }

    function _validateFeeParams(uint24 baseFee, uint24 surgeMultiplier) internal pure {
        uint256 maxPossibleFee = uint256(baseFee) + (uint256(baseFee) * surgeMultiplier / BPS_DENOMINATOR);
        if (maxPossibleFee > MAX_LP_FEE) revert InvalidFeeConfiguration();
    }

    function registerPool(
        PoolKey calldata key,
        uint24 baseFee,
        uint24 surgeMultiplier,
        uint32 surgeDuration,
        uint24 initialMaxTicksPerBlock
    ) external {
        if (msg.sender != orderBookFactory) revert("OnlyOrderBookFactory");
        _validateFeeParams(baseFee, surgeMultiplier);

        PoolId poolId = key.toId();

        bytes32 parametersHash = keccak256(abi.encodePacked(
            Currency.unwrap(key.currency0),
            Currency.unwrap(key.currency1),
            key.tickSpacing
        ));

        if (poolParametersUsed[parametersHash]) revert("PoolParametersAlreadyUsed");

        managedPools[poolId] = true;
        poolParametersUsed[parametersHash] = true;

        feeParams[poolId] = FeeParams({baseFee: baseFee, enabled: true});
        surgeStates[poolId] = SurgeState({
            surgeMultiplier: surgeMultiplier,
            surgeDuration: surgeDuration,
            capStartTime: 0,
            isActive: false
        });

        volatilityOracle.enableOracleForPool(
            key,
            initialMaxTicksPerBlock,
            defaultMinCap,
            defaultMaxCap,
            defaultStepPpm,
            defaultBudgetPpm,
            defaultDecayWindow,
            defaultUpdateInterval
        );

        tradingEnabledBlock[poolId] = block.number + 1;

        emit PoolRegistered(poolId, baseFee, surgeMultiplier, surgeDuration, initialMaxTicksPerBlock);
    }

    function updateBaseFee(PoolKey calldata key, uint24 newBaseFee) external onlyOwner {
        PoolId poolId = key.toId();
        if (!managedPools[poolId]) revert("NotManagedPool");
        _validateFeeParams(newBaseFee, surgeStates[poolId].surgeMultiplier);
        feeParams[poolId].baseFee = newBaseFee;
        emit FeeParamsUpdated(poolId, newBaseFee);
    }

    function updateSurgeParams(PoolKey calldata key, uint24 multiplier, uint32 duration) external onlyOwner {
        PoolId poolId = key.toId();
        if (!managedPools[poolId]) revert("NotManagedPool");
        _validateFeeParams(feeParams[poolId].baseFee, multiplier);
        surgeStates[poolId].surgeMultiplier = multiplier;
        surgeStates[poolId].surgeDuration = duration;
    }

    function updateOraclePolicy(
        PoolKey calldata key,
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external onlyOwner {
        volatilityOracle.refreshPolicyCache(
            key.toId(),
            minCap,
            maxCap,
            stepPpm,
            budgetPpm,
            decayWindow,
            updateInterval
        );
    }

    function updateDefaultOraclePolicy(
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external onlyOwner {
        defaultMinCap = minCap;
        defaultMaxCap = maxCap;
        defaultStepPpm = stepPpm;
        defaultBudgetPpm = budgetPpm;
        defaultDecayWindow = decayWindow;
        defaultUpdateInterval = updateInterval;
        emit DefaultOraclePolicyUpdated(minCap, maxCap, stepPpm, budgetPpm, decayWindow, updateInterval);
    }
}

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

// - - - external deps - - -

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {ReentrancyGuard} from "solmate/src/utils/ReentrancyGuard.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";

// - - - local deps - - -

import {Errors} from "../errors/Errors.sol";
import {TruncatedOracle} from "./TruncatedOracle.sol";

contract VolatilityOracle is ReentrancyGuard {
    /* ========== paged ring – each "leaf" holds 512 observations ========== */
    uint16 internal constant PAGE_SIZE = 512;

    using TruncatedOracle for TruncatedOracle.Observation[PAGE_SIZE];
    using PoolIdLibrary for PoolKey;
    using SafeCast for int256;

    /* -------------------------------------------------------------------------- */
    /*                               Library constants                            */
    /* -------------------------------------------------------------------------- */
    /* seconds in one day (for readability) */
    uint32 internal constant ONE_DAY_SEC = 86_400;
    /* parts-per-million constant */
    uint32 internal constant PPM = 1_000_000;
    /* pre-computed ONE_DAY × PPM to avoid a mul on every cap event            *
     * 86_400 * 1_000_000  ==  86 400 000 000  <  2¹²⁷ – safe for uint128      */
    uint64 internal constant ONE_DAY_PPM = 86_400 * 1_000_000;
    /* one add (ONE_DAY_PPM) short of uint64::max */
    uint64 internal constant CAP_FREQ_MAX = type(uint64).max - ONE_DAY_PPM + 1;
    /* minimum change required to emit MaxTicksPerBlockUpdated event */
    uint24 internal constant EVENT_DIFF = 5;

    // Custom errors
    error NotAuthorizedHook();
    error OnlyOwner();
    error OnlyOwnerOrFactory();
    error ObservationOverflow(uint16 cardinality);
    error ObservationTooOld(uint32 time, uint32 target);
    error TooManyObservationsRequested();

    event TickCapParamChanged(PoolId indexed poolId, uint24 newMaxTicksPerBlock);
    event MaxTicksPerBlockUpdated(
        PoolId indexed poolId, uint24 oldMaxTicksPerBlock, uint24 newMaxTicksPerBlock, uint32 blockTimestamp
    );
    event PolicyCacheRefreshed(PoolId indexed poolId);
    /// emitted once per pool when the oracle is first enabled
    event OracleConfigured(PoolId indexed poolId, address indexed hook, address indexed owner, uint24 initialCap);
    event HookAuthorized(address indexed hook);
    event HookRevoked(address indexed hook);
    event AuthorizedFactorySet(address indexed factory);

    /* ─────────────────── IMMUTABLE STATE ────────────────────── */
    IPoolManager public immutable poolManager;
    address public immutable owner; // Governance address that can refresh policy cache

    /* ─────────────────── MULTI-HOOK AUTHORIZATION ────────────────────── */
    /// @notice Mapping of authorized hook addresses that can push observations
    mapping(address => bool) public authorizedHooks;
    /// @notice Factory address that can register new hooks
    address public authorizedFactory;

    /* ───────────────────── MUTABLE STATE ────────────────────── */
    mapping(PoolId => uint24) public maxTicksPerBlock; // adaptive cap
    /* ppm-seconds never exceeds 8.64 e10 per event or 7.45 e15 per year  →
       well inside uint64.  Using uint64 halves slot gas / SLOAD cost.   */
    mapping(PoolId => uint64) private capFreq; // ***saturating*** counter
    mapping(PoolId => uint48) private lastFreqTs; // last decay update

    struct ObservationState {
        uint16 index;
        /**
         * @notice total number of populated observations.
         * Includes the bootstrap slot written by `enableOracleForPool`,
         * so after N user pushes the value is **N + 1**.
         */
        uint16 cardinality;
        uint16 cardinalityNext;
    }

    struct ObserveContext {
        uint32 time;
        int24 currentTick;
        uint128 liquidity;
        uint16 newestLocalIdx;
        uint16 newestCard;
    }

    /* ─────────────── cached policy parameters (baseFee logic removed) ─────────────── */
    struct CachedPolicy {
        uint24 minCap;
        uint24 maxCap;
        uint32 stepPpm;
        uint32 budgetPpm;
        uint32 decayWindow;
        uint32 updateInterval;
    }

    mapping(PoolId => CachedPolicy) internal _policy;

    /* ──────────────────  CHUNKED OBSERVATION RING  ──────────────────
       Each pool owns *pages* (index ⇒ Observation[PAGE_SIZE]).
       A page is allocated lazily the first time it is touched, so the
       storage footprint grows with `grow()` instead of pre-allocating
       65 k slots (≈ 4 MiB) per pool.                                        */
    /// pool ⇒ page# ⇒ 512-slot chunk (lazily created)
    mapping(PoolId => mapping(uint16 => TruncatedOracle.Observation[PAGE_SIZE])) internal _pages;

    function _leaf(PoolId poolId, uint16 globalIdx)
        internal
        view
        returns (TruncatedOracle.Observation[PAGE_SIZE] storage)
    {
        return _pages[poolId][globalIdx / PAGE_SIZE];
    }

    mapping(PoolId => ObservationState) public states;

    // Store last max tick update time for rate limiting governance changes
    mapping(PoolId => uint32) private _lastMaxTickUpdate;

    /* ────────────────────── CONSTRUCTOR ─────────────────────── */
    /// -----------------------------------------------------------------------
    /// @notice Deploy the oracle and wire the immutable dependencies.
    /// @param _poolManager Canonical v4 `PoolManager` contract
    /// @param _owner Governor address that can refresh the cached policy
    /// -----------------------------------------------------------------------
    constructor(IPoolManager _poolManager, address _owner) {
        if (address(_poolManager) == address(0)) revert Errors.ZeroAddress();
        if (_owner == address(0)) revert Errors.ZeroAddress();

        poolManager = _poolManager;
        owner = _owner;
    }

    /* ────────────────────── AUTHORIZATION MANAGEMENT ─────────────────────── */

    /// @notice Sets the authorized factory that can register hooks
    /// @param _factory The factory address to authorize
    function setAuthorizedFactory(address _factory) external {
        if (msg.sender != owner) revert OnlyOwner();
        authorizedFactory = _factory;
        emit AuthorizedFactorySet(_factory);
    }

    /// @notice Adds an authorized hook that can push observations
    /// @dev Can be called by owner or the authorized factory
    /// @param _hook The hook address to authorize
    function addAuthorizedHook(address _hook) external {
        if (msg.sender != owner && msg.sender != authorizedFactory) revert OnlyOwnerOrFactory();
        if (_hook == address(0)) revert Errors.ZeroAddress();
        authorizedHooks[_hook] = true;
        emit HookAuthorized(_hook);
    }

    /// @notice Removes an authorized hook
    /// @dev Can only be called by owner
    /// @param _hook The hook address to revoke
    function removeAuthorizedHook(address _hook) external {
        if (msg.sender != owner) revert OnlyOwner();
        authorizedHooks[_hook] = false;
        emit HookRevoked(_hook);
    }

    /**
     * @notice Refreshes the cached policy parameters for a pool.
     * @dev Can only be called by the owner (governance).
     * @param poolId The PoolId of the pool.
     * @param minCap Minimum maxTicksPerBlock value
     * @param maxCap Maximum maxTicksPerBlock value
     * @param stepPpm Auto-tune step size in PPM
     * @param budgetPpm Target CAP frequency in PPM
     * @param decayWindow Frequency decay window in seconds
     * @param updateInterval Minimum time between auto-tune adjustments
     */
    function refreshPolicyCache(
        PoolId poolId,
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external {
        if (msg.sender != owner) revert OnlyOwner();

        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("refreshPolicyCache", "Pool not enabled");
        }

        CachedPolicy storage pc = _policy[poolId];

        // Update all policy parameters
        pc.minCap = minCap;
        pc.maxCap = maxCap;
        pc.stepPpm = stepPpm;
        pc.budgetPpm = budgetPpm;
        pc.decayWindow = decayWindow;
        pc.updateInterval = updateInterval;

        _validatePolicy(pc);

        // Ensure current maxTicksPerBlock is within new min/max bounds
        uint24 currentCap = maxTicksPerBlock[poolId];
        if (currentCap < pc.minCap) {
            maxTicksPerBlock[poolId] = pc.minCap;
            emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.minCap, uint32(block.timestamp));
        } else if (currentCap > pc.maxCap) {
            maxTicksPerBlock[poolId] = pc.maxCap;
            emit MaxTicksPerBlockUpdated(poolId, currentCap, pc.maxCap, uint32(block.timestamp));
        }

        emit PolicyCacheRefreshed(poolId);
    }

    /**
     * @notice Enables the oracle for a given pool, initializing its state.
     * @dev Can only be called by the configured hook address.
     * @param key The PoolKey of the pool to enable.
     * @param initialMaxTicksPerBlock User-set initial CAP threshold
     * @param minCap Minimum maxTicksPerBlock value
     * @param maxCap Maximum maxTicksPerBlock value
     * @param stepPpm Auto-tune step size in PPM
     * @param budgetPpm Target CAP frequency in PPM
     * @param decayWindow Frequency decay window in seconds
     * @param updateInterval Minimum time between auto-tune adjustments
     */
    function enableOracleForPool(
        PoolKey calldata key,
        uint24 initialMaxTicksPerBlock,
        uint24 minCap,
        uint24 maxCap,
        uint32 stepPpm,
        uint32 budgetPpm,
        uint32 decayWindow,
        uint32 updateInterval
    ) external {
        if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
        PoolId poolId = key.toId();
        if (states[poolId].cardinality > 0) {
            revert Errors.OracleOperationFailed("enableOracleForPool", "Already enabled");
        }

        /* ------------------------------------------------------------------ *
         * Set policy parameters and validate                                 *
         * ------------------------------------------------------------------ */
        CachedPolicy storage pc = _policy[poolId];
        pc.minCap = minCap;
        pc.maxCap = maxCap;
        pc.stepPpm = stepPpm;
        pc.budgetPpm = budgetPpm;
        pc.decayWindow = decayWindow;
        pc.updateInterval = updateInterval;

        _validatePolicy(pc);

        // ---------- external read last (reduces griefing surface) ----------
        (, int24 initialTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        TruncatedOracle.Observation[PAGE_SIZE] storage first = _pages[poolId][0];
        first.initialize(uint32(block.timestamp), initialTick);
        states[poolId] = ObservationState({index: 0, cardinality: 1, cardinalityNext: 1});

        // Clamp initialMaxTicksPerBlock inside the validated range
        uint24 cappedInitial = initialMaxTicksPerBlock;
        if (cappedInitial < pc.minCap) cappedInitial = pc.minCap;
        if (cappedInitial > pc.maxCap) cappedInitial = pc.maxCap;
        maxTicksPerBlock[poolId] = cappedInitial;

        // --- audit-aid event ----------------------------------------------------
        emit OracleConfigured(poolId, msg.sender, owner, cappedInitial);
    }

    // Internal workhorse
    function _recordObservation(PoolId poolId, int24 preSwapTick) internal returns (bool tickWasCapped) {
        ObservationState storage state = states[poolId];
        uint16 index = state.index;

        int24 currentTick;
        // Scope to drop temporary variables
        {
            (, int24 tick,,) = StateLibrary.getSlot0(poolManager, poolId);
            currentTick = tick;

            uint24 cap = maxTicksPerBlock[poolId];
            int256 tickDelta256 = int256(currentTick) - int256(preSwapTick);
            uint256 absDelta = tickDelta256 >= 0 ? uint256(tickDelta256) : uint256(-tickDelta256);

            if (absDelta >= cap) {
                int256 capped = tickDelta256 > 0
                    ? int256(preSwapTick) + int256(uint256(cap))
                    : int256(preSwapTick) - int256(uint256(cap));
                currentTick = _toInt24(capped);
                tickWasCapped = true;
            }
        }

        uint32 ts = uint32(block.timestamp);
        TruncatedOracle.Observation storage last = _leaf(poolId, index)[index % PAGE_SIZE];
        if (last.blockTimestamp != ts) {
            uint16 cardinalityUpdated = state.cardinality;
            uint16 cardinalityNext = state.cardinalityNext;
            if (cardinalityNext == cardinalityUpdated && cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
                cardinalityNext = cardinalityUpdated + 1;
            }

            if (cardinalityNext > cardinalityUpdated && index == (cardinalityUpdated - 1)) {
                cardinalityUpdated = cardinalityNext;
                if (cardinalityUpdated > TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
                    cardinalityUpdated = TruncatedOracle.MAX_CARDINALITY_ALLOWED;
                }
            }

            unchecked {
                index += 1;
            }
            if (index >= cardinalityUpdated) {
                index = 0;
            }

            uint128 liquidity = StateLibrary.getLiquidity(poolManager, poolId);
            uint32 delta;
            unchecked {
                delta = ts - last.blockTimestamp;
            }
            TruncatedOracle.Observation storage o = _leaf(poolId, index)[index % PAGE_SIZE];
            o.blockTimestamp = ts;
            o.tickCumulative = last.tickCumulative + int56(currentTick) * int56(uint56(delta));
            o.secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128
                + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1));
            o.initialized = true;

            state.index = index;
            state.cardinality = cardinalityUpdated;

            if (
                state.cardinalityNext < cardinalityUpdated + 1
                    && state.cardinalityNext < TruncatedOracle.MAX_CARDINALITY_ALLOWED
            ) {
                state.cardinalityNext = cardinalityUpdated + 1;
            }
        }

        _updateCapFrequency(poolId, tickWasCapped);
    }

    /// -----------------------------------------------------------------------
    /// @notice Record a new observation using the actual pre-swap tick.
    /// -----------------------------------------------------------------------
    function pushObservationAndCheckCap(PoolId poolId, int24 preSwapTick)
        external
        nonReentrant
        returns (bool tickWasCapped)
    {
        if (!authorizedHooks[msg.sender]) revert NotAuthorizedHook();
        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("pushObservationAndCheckCap", "Pool not enabled");
        }
        return _recordObservation(poolId, preSwapTick);
    }

    /* ─────────────────── VIEW FUNCTIONS ──────────────────────── */

    /**
     * @notice Checks if the oracle is enabled for a given pool.
     * @param poolId The PoolId to check.
     * @return True if the oracle is enabled, false otherwise.
     */
    function isOracleEnabled(PoolId poolId) external view returns (bool) {
        return states[poolId].cardinality > 0;
    }

    /**
     * @notice Gets the latest observation for a pool.
     * @param poolId The PoolId of the pool.
     * @return tick The tick from the latest observation.
     * @return blockTimestamp The timestamp of the latest observation.
     */
    function getLatestObservation(PoolId poolId) external view returns (int24 tick, uint32 blockTimestamp) {
        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("getLatestObservation", "Pool not enabled");
        }

        ObservationState storage state = states[poolId];
        TruncatedOracle.Observation storage o = _leaf(poolId, state.index)[state.index % PAGE_SIZE];
        (, int24 liveTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        return (liveTick, o.blockTimestamp);
    }

    /// @notice View helper mirroring the public mapping but typed for tests.
    function getMaxTicksPerBlock(PoolId poolId) external view returns (uint24) {
        return maxTicksPerBlock[poolId];
    }

    /**
     * @notice Returns the saturation threshold for the capFreq counter.
     * @return The maximum value for the capFreq counter before it saturates.
     */
    function getCapFreqMax() external pure returns (uint64) {
        return CAP_FREQ_MAX;
    }

    /// @notice Calculates time-weighted means of tick and liquidity
    /// @param key the key of the pool to consult
    /// @param secondsAgo Number of seconds in the past from which to calculate the time-weighted means
    /// @return arithmeticMeanTick The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp
    /// @return harmonicMeanLiquidity The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp
    function consult(PoolKey calldata key, uint32 secondsAgo)
        external
        view
        returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
    {
        require(secondsAgo != 0, "BP");

        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = secondsAgo;
        secondsAgos[1] = 0;

        (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) =
            observe(key, secondsAgos);

        int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
        uint160 secondsPerLiquidityCumulativesDelta =
            secondsPerLiquidityCumulativeX128s[1] - secondsPerLiquidityCumulativeX128s[0];

        int56 secondsAgoI56 = int56(uint56(secondsAgo));

        arithmeticMeanTick = int24(tickCumulativesDelta / secondsAgoI56);
        // Always round to negative infinity
        if (tickCumulativesDelta < 0 && (tickCumulativesDelta % secondsAgoI56 != 0)) arithmeticMeanTick--;

        // We are multiplying here instead of shifting to ensure that harmonicMeanLiquidity doesn't overflow uint128
        uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
        harmonicMeanLiquidity = uint128(secondsAgoX160 / (uint192(secondsPerLiquidityCumulativesDelta) << 32));
    }

    /**
     * @notice Observe oracle values at specific secondsAgos from the current block timestamp
     * @dev Reverts if observation at or before the desired observation timestamp does not exist
     * @param key The pool key to observe
     * @param secondsAgos The array of seconds ago to observe
     * @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each secondsAgo
     * @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since pool initialized
     */
    function observe(PoolKey calldata key, uint32[] memory secondsAgos)
        public
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
    {
        PoolId poolId = key.toId();

        if (states[poolId].cardinality == 0) {
            revert Errors.OracleOperationFailed("observe", "Pool not enabled");
        }

        ObservationState storage state = states[poolId];
        uint16 gIdx = state.index; // global index of newest obs

        uint256 len = secondsAgos.length;
        tickCumulatives = new int56[](len);
        secondsPerLiquidityCumulativeX128s = new uint160[](len);
        if (len == 0) return (tickCumulatives, secondsPerLiquidityCumulativeX128s);

        ObserveContext memory ctx;
        ctx.time = uint32(block.timestamp);
        (, ctx.currentTick,,) = StateLibrary.getSlot0(poolManager, poolId);
        ctx.liquidity = StateLibrary.getLiquidity(poolManager, poolId);
        ctx.newestLocalIdx = uint16(gIdx % PAGE_SIZE);
        {
            uint16 newestBase = gIdx - ctx.newestLocalIdx;
            uint16 newestCard = state.cardinality > newestBase ? state.cardinality - newestBase : 1;
            if (newestCard > PAGE_SIZE) {
                newestCard = PAGE_SIZE;
            }
            ctx.newestCard = newestCard;
        }

        for (uint256 i = 0; i < len; i++) {
            uint32 secondsAgo = secondsAgos[i];
            if (secondsAgo == 0) {
                TruncatedOracle.Observation[PAGE_SIZE] storage newestPage = _leaf(poolId, gIdx);
                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                    TruncatedOracle.observeSingle(
                        newestPage,
                        ctx.time,
                        0,
                        ctx.currentTick,
                        ctx.newestLocalIdx,
                        ctx.liquidity,
                        ctx.newestCard
                    );
                continue;
            }

            (uint16 leafCursor, uint16 idx, uint16 card) =
                _resolveLeafForSecondsAgo(poolId, state, gIdx, ctx.newestLocalIdx, ctx.time, secondsAgo);
            TruncatedOracle.Observation[PAGE_SIZE] storage obs = _leaf(poolId, leafCursor);
            (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                TruncatedOracle.observeSingle(obs, ctx.time, secondsAgo, ctx.currentTick, idx, ctx.liquidity, card);
        }

        return (tickCumulatives, secondsPerLiquidityCumulativeX128s);
    }

    function _resolveLeafForSecondsAgo(
        PoolId poolId,
        ObservationState storage state,
        uint16 gIdx,
        uint16 newestLocalIdx,
        uint32 time,
        uint32 secondsAgo
    ) internal view returns (uint16 leafCursor, uint16 idx, uint16 card) {
        uint32 target;
        unchecked {
            target = time >= secondsAgo ? time - secondsAgo : time + (type(uint32).max - secondsAgo) + 1;
        }

        uint16 newestBase = gIdx - newestLocalIdx;
        uint16 pageCursor = newestBase;
        if (state.cardinality == TruncatedOracle.MAX_CARDINALITY_ALLOWED) {
            uint16 pageCount = TruncatedOracle.MAX_CARDINALITY_ALLOWED / PAGE_SIZE;
            for (uint16 i = 0; i < pageCount; i++) {
                TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
                uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : PAGE_SIZE - 1;
                uint16 firstSlot = (pageNewestIdx + 1) % PAGE_SIZE;
                uint32 firstTs = page[firstSlot].blockTimestamp;

                if (target >= firstTs || i + 1 == pageCount) {
                    idx = pageNewestIdx;
                    card = PAGE_SIZE;
                    return (pageCursor, idx, card);
                }

                if (pageCursor >= PAGE_SIZE) {
                    pageCursor -= PAGE_SIZE;
                } else {
                    pageCursor = TruncatedOracle.MAX_CARDINALITY_ALLOWED - PAGE_SIZE;
                }
            }
        }

        while (true) {
            TruncatedOracle.Observation[PAGE_SIZE] storage page = _leaf(poolId, pageCursor);
            uint16 pageCardinality = state.cardinality > pageCursor ? state.cardinality - pageCursor : 1;
            if (pageCardinality > PAGE_SIZE) {
                pageCardinality = PAGE_SIZE;
            }

            uint16 pageNewestIdx = pageCursor == newestBase ? newestLocalIdx : pageCardinality - 1;
            uint16 firstSlot = pageCardinality == PAGE_SIZE ? (pageNewestIdx + 1) % PAGE_SIZE : 0;
            uint32 firstTs = page[firstSlot].blockTimestamp;

            if (target >= firstTs || pageCursor == 0) {
                idx = pageNewestIdx;
                card = pageCardinality;
                return (pageCursor, idx, card);
            }
            pageCursor -= PAGE_SIZE;
        }
    }


    /* ────────────────────── INTERNALS ──────────────────────── */

    /**
     * @notice Updates the CAP frequency counter and potentially triggers auto-tuning.
     * @dev Decays the frequency counter based on time elapsed since the last update.
     *      Increments the counter if a CAP occurred.
     *      Triggers auto-tuning if the frequency exceeds the budget or is too low.
     * @param poolId The PoolId of the pool.
     * @param capOccurred True if a CAP event occurred in the current block.
     */
    function _updateCapFrequency(PoolId poolId, bool capOccurred) internal {
        uint32 lastTs = uint32(lastFreqTs[poolId]);
        uint32 nowTs = uint32(block.timestamp);
        uint32 timeElapsed = nowTs - lastTs;

        /* FAST-PATH ────────────────────────────────────────────────────────
           No tick was capped *and* we're still in the same second ⇒ every
           state var is already correct, so we avoid **all** SSTOREs.      */
        if (!capOccurred && timeElapsed == 0) return;

        lastFreqTs[poolId] = uint48(nowTs); // single SSTORE only when needed

        uint64 currentFreq = capFreq[poolId];

        // --------------------------------------------------------------------- //
        //  1️⃣  Add this block's CAP contribution *first* and saturate.         //
        // --------------------------------------------------------------------- //
        if (capOccurred) {
            unchecked {
                currentFreq += uint64(ONE_DAY_PPM);
            }
            if (currentFreq >= CAP_FREQ_MAX || currentFreq < ONE_DAY_PPM) {
                currentFreq = CAP_FREQ_MAX; // clamp one-step-early
            }
        }

        /* -------- cache policy once -------- */
        CachedPolicy storage pc = _policy[poolId];
        uint32 budgetPpm = pc.budgetPpm;
        uint32 decayWindow = pc.decayWindow;
        uint32 updateInterval = pc.updateInterval;

        // 2️⃣  Apply linear decay *only when no CAP in this block*.
        if (!capOccurred && timeElapsed > 0 && currentFreq > 0) {
            // decay factor = (window - elapsed) / window = 1 - elapsed / window
            if (timeElapsed >= decayWindow) {
                currentFreq = 0; // Fully decayed
            } else {
                uint64 decayFactorPpm = PPM - uint64(timeElapsed) * PPM / decayWindow;
                uint128 decayed = uint128(currentFreq) * decayFactorPpm / PPM;
                // ----- overflow-safe down-cast -------------------------
                if (decayed > type(uint64).max) {
                    currentFreq = CAP_FREQ_MAX;
                } else {
                    uint64 d64 = uint64(decayed);
                    currentFreq = d64 > CAP_FREQ_MAX ? CAP_FREQ_MAX : d64;
                }
            }
        }

        capFreq[poolId] = currentFreq; // single SSTORE

        // Only auto-tune if enough time has passed since last update
        if (!_autoTunePaused[poolId] && block.timestamp >= _lastMaxTickUpdate[poolId] + updateInterval) {
            uint64 targetFreq = uint64(budgetPpm) * ONE_DAY_SEC;
            if (currentFreq > targetFreq) {
                // Too frequent caps -> Increase maxTicksPerBlock (loosen cap)
                _autoTuneMaxTicks(poolId, pc, true);
            } else {
                // Caps too rare -> Decrease maxTicksPerBlock (tighten cap)
                _autoTuneMaxTicks(poolId, pc, false);
            }
        }
    }

    /**
     * @notice Adjusts the maxTicksPerBlock based on CAP frequency.
     * @dev Increases the cap if caps are too frequent, decreases otherwise.
     *      Clamps the adjustment based on policy step size and min/max bounds.
     * @param poolId The PoolId of the pool.
     * @param pc Cached policy struct
     * @param increase True to increase the cap, false to decrease.
     */
    function _autoTuneMaxTicks(PoolId poolId, CachedPolicy storage pc, bool increase) internal {
        uint24 currentCap = maxTicksPerBlock[poolId];

        uint32 stepPpm = pc.stepPpm;
        uint24 minCap = pc.minCap;
        uint24 maxCap = pc.maxCap;

        uint24 change = uint24(uint256(currentCap) * stepPpm / PPM);
        if (change == 0) change = 1; // Ensure minimum change of 1 tick

        uint24 newCap;
        if (increase) {
            newCap = currentCap + change > maxCap ? maxCap : currentCap + change;
        } else {
            newCap = currentCap > change + minCap ? currentCap - change : minCap;
        }

        uint24 diff = currentCap > newCap ? currentCap - newCap : newCap - currentCap;

        if (newCap != currentCap) {
            maxTicksPerBlock[poolId] = newCap;
            _lastMaxTickUpdate[poolId] = uint32(block.timestamp);
            if (diff >= EVENT_DIFF) {
                emit MaxTicksPerBlockUpdated(poolId, currentCap, newCap, uint32(block.timestamp));
            }
        }
    }

    /* ────────────────────── INTERNAL HELPERS ───────────────────────── */

    /// @dev bounded cast; reverts on overflow instead of truncating.
    function _toInt24(int256 v) internal pure returns (int24) {
        require(v >= type(int24).min && v <= type(int24).max, "Tick overflow");
        return int24(v);
    }

    /// @dev Validate policy parameters
    function _validatePolicy(CachedPolicy storage pc) internal view {
        require(pc.stepPpm != 0, "stepPpm cannot be 0");
        require(pc.minCap != 0, "minCap cannot be 0");
        require(pc.maxCap >= pc.minCap, "maxCap must be >= minCap");
        require(pc.decayWindow != 0, "decayWindow cannot be 0");
        require(pc.updateInterval != 0, "updateInterval cannot be 0");
    }

    /* ───────────────────── Emergency pause ────────────────────── */
    /// @notice Emitted when the governor toggles the auto-tune circuit-breaker.
    event AutoTunePaused(PoolId indexed poolId, bool paused, uint32 timestamp);

    /// @dev circuit-breaker flag per pool (default: false = auto-tune active)
    mapping(PoolId => bool) private _autoTunePaused;

    /**
     * @notice Pause or un-pause the adaptive cap algorithm for a pool.
     * @param poolId       Target PoolId.
     * @param paused    True to disable auto-tune, false to resume.
     */
    function setAutoTunePaused(PoolId poolId, bool paused) external {
        if (msg.sender != owner) revert OnlyOwner();
        _autoTunePaused[poolId] = paused;
        emit AutoTunePaused(poolId, paused, uint32(block.timestamp));
    }

    /* ─────────────────────── public cardinality grow ─────────────────────── */
    /**
     * @notice Requests the ring buffer to grow to `cardinalityNext` slots.
     * @dev Mirrors Uniswap-V3 behaviour. Callable by anyone; growth is capped
     *      by the TruncatedOracle library's internal MAX_CARDINALITY_ALLOWED.
     * @param key Encoded PoolKey.
     * @param cardinalityNext Desired new cardinality.
     * @return oldNext Previous next-size.
     * @return newNext Updated next-size after grow.
     */
    function increaseCardinalityNext(PoolKey calldata key, uint16 cardinalityNext)
        external
        returns (uint16 oldNext, uint16 newNext)
    {
        // Public function - anyone can grow the observation buffer (like Uniswap V3)
        PoolId poolId = key.toId();

        ObservationState storage state = states[poolId];
        if (state.cardinality == 0) {
            revert Errors.OracleOperationFailed("increaseCardinalityNext", "Pool not enabled");
        }

        oldNext = state.cardinalityNext;
        if (cardinalityNext <= oldNext) {
            return (oldNext, oldNext);
        }

        state.cardinalityNext = TruncatedOracle.grow(
            _leaf(poolId, state.cardinalityNext), // leaf storage slot
            oldNext,
            cardinalityNext
        );

        newNext = state.cardinalityNext;
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {MultiPositionManager} from "./MultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";

/// @title MultiPositionDeployer
/// @notice Deploys MultiPositionManager contracts with CREATE2
contract MultiPositionDeployer {
    address public immutable authorizedFactory;

    error UnauthorizedCaller();

    constructor(address _authorizedFactory) {
        authorizedFactory = _authorizedFactory;
    }

    function deploy(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        address owner,
        address factory,
        string memory name,
        string memory symbol,
        uint16 fee,
        bytes32 salt
    ) external returns (address) {
        if (msg.sender != authorizedFactory) revert UnauthorizedCaller();
        return address(new MultiPositionManager{salt: salt}(poolManager, poolKey, owner, factory, name, symbol, fee));
    }

    function computeAddress(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        address owner,
        address factory,
        string memory name,
        string memory symbol,
        uint16 fee,
        bytes32 salt
    ) external view returns (address predicted) {
        bytes32 hash = keccak256(
            abi.encodePacked(
                type(MultiPositionManager).creationCode,
                abi.encode(poolManager, poolKey, owner, factory, name, symbol, fee)
            )
        );

        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0xff00000000000000000000000000000000000000000000000000000000000000)
            mstore(add(ptr, 0x01), shl(96, address()))
            mstore(add(ptr, 0x15), salt)
            mstore(add(ptr, 0x35), hash)
            predicted := keccak256(ptr, 0x55)
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

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

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

/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.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,
        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,
        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,
        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,
        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, 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,
        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;

/// @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);
}

File 42 of 82 : PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

/// @notice Parameter struct for `ModifyLiquidity` pool operations
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 Parameter struct for `Swap` pool operations
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;
}

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

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

// 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.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 46 of 82 : 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;
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolManagerUtils} from "./PoolManagerUtils.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/**
 * @title DepositRatioLib
 * @notice Internal library for calculating deposit ratios and proportional distributions
 */
library DepositRatioLib {
    /**
     * @notice Calculate amounts that match the vault's current ratio for directDeposit
     * @param total0 Current total amount of token0 in vault
     * @param total1 Current total amount of token1 in vault
     * @param amount0Desired Amount of token0 user wants to deposit
     * @param amount1Desired Amount of token1 user wants to deposit
     * @return amount0ForPositions Amount of token0 that fits the ratio
     * @return amount1ForPositions Amount of token1 that fits the ratio
     */
    function getRatioAmounts(uint256 total0, uint256 total1, uint256 amount0Desired, uint256 amount1Desired)
        internal
        pure
        returns (uint256 amount0ForPositions, uint256 amount1ForPositions)
    {
        if (total0 == 0 && total1 == 0) {
            // No existing positions, can use full amounts
            return (amount0Desired, amount1Desired);
        }

        if (total0 == 0) {
            // Only token1 in positions
            return (0, amount1Desired);
        }

        if (total1 == 0) {
            // Only token0 in positions
            return (amount0Desired, 0);
        }

        // Calculate amounts that fit the current ratio using cross-product
        uint256 cross = Math.min(amount0Desired * total1, amount1Desired * total0);

        if (cross == 0) {
            return (0, 0);
        }

        // Calculate the amounts that maintain the ratio
        amount0ForPositions = (cross - 1) / total1 + 1;
        amount1ForPositions = (cross - 1) / total0 + 1;

        // Ensure we don't try to use more than deposited
        amount0ForPositions = Math.min(amount0ForPositions, amount0Desired);
        amount1ForPositions = Math.min(amount1ForPositions, amount1Desired);

        return (amount0ForPositions, amount1ForPositions);
    }

    /**
     * @notice Calculate how to distribute amounts across positions proportionally based on liquidity
     * @param positionLiquidities Array of liquidities for each position
     * @param totalLiquidity Total liquidity across all positions
     * @param amount0 Total amount of token0 to distribute
     * @param amount1 Total amount of token1 to distribute
     * @return amounts0 Array of token0 amounts for each position
     * @return amounts1 Array of token1 amounts for each position
     */
    function getProportionalAmounts(
        uint128[] memory positionLiquidities,
        uint256 totalLiquidity,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint256[] memory amounts0, uint256[] memory amounts1) {
        uint256 length = positionLiquidities.length;
        amounts0 = new uint256[](length);
        amounts1 = new uint256[](length);

        if (totalLiquidity == 0) {
            return (amounts0, amounts1);
        }

        // Distribute amounts proportionally
        for (uint256 i = 0; i < length; i++) {
            if (positionLiquidities[i] > 0) {
                amounts0[i] = FullMath.mulDiv(amount0, positionLiquidities[i], totalLiquidity);
                amounts1[i] = FullMath.mulDiv(amount1, positionLiquidities[i], totalLiquidity);
            }
        }

        return (amounts0, amounts1);
    }
}

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

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

import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./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, uint128 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, uint128 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, uint128 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, uint128 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(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                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, uint128 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, uint128 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: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

// 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;

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

File 55 of 82 : ImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
    /// @inheritdoc IImmutableState
    IPoolManager public immutable poolManager;

    /// @notice Thrown when the caller is not PoolManager
    error NotPoolManager();

    /// @notice Only allow calls from the PoolManager contract
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }
}

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

import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";

/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
    /// @notice returns the reserves for the synced currency
    /// @param manager The pool manager contract.

    /// @return uint256 The reserves of the currency.
    /// @dev returns 0 if the reserves are not synced or value is 0.
    /// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
    function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
        if (getSyncedCurrency(manager).isAddressZero()) return 0;
        return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
    }

    function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
        return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
    }

    /// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
    function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
        return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
    }

    /// @notice Get the current delta for a caller in the given currency
    /// @param target The credited account address
    /// @param currency The currency for which to lookup the delta
    function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
        bytes32 key;
        assembly ("memory-safe") {
            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            key := keccak256(0, 64)
        }
        return int256(uint256(manager.exttload(key)));
    }

    /// @notice Returns whether the contract is unlocked or not
    function isUnlocked(IPoolManager manager) internal view returns (bool) {
        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
    }
}

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

import {Currency} from "v4-core/types/Currency.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";

/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
    using SafeERC20 for IERC20;
    /// @notice Settle (pay) a currency to the PoolManager
    /// @param currency Currency to settle
    /// @param manager IPoolManager to settle to
    /// @param payer Address of the payer, the token sender
    /// @param amount Amount to send
    /// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
    function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(manager), amount);
            } else {
                IERC20(Currency.unwrap(currency)).safeTransfer(address(manager), amount);
            }
            manager.settle();
        }
    }

    /// @notice Take (receive) a currency from the PoolManager
    /// @param currency Currency to take
    /// @param manager IPoolManager to take from
    /// @param recipient Address of the recipient, the token receiver
    /// @param amount Amount to receive
    /// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
    function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
        claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
    }
}

File 58 of 82 : FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

// 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
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

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

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.26;

/**
 * @title IMulticall
 * @notice Interface for batching multiple calls in a single transaction
 */
interface IMulticall {
    /**
     * @notice Execute multiple calls in a single transaction
     * @param data Array of encoded function calls
     * @return results Array of return data from each call
     */
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

File 62 of 82 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

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

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

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

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

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

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

                // Divide [high low] by twos.
                low := div(low, twos)

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

            // Shift in bits from high into low.
            low |= high * twos;

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

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

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

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

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

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

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

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}

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

import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {BeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ImmutableState} from "../base/ImmutableState.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";

/// @title Base Hook
/// @notice abstract contract for hook implementations
abstract contract BaseHook is IHooks, ImmutableState {
    error HookNotImplemented();

    constructor(IPoolManager _manager) ImmutableState(_manager) {
        validateHookAddress(this);
    }

    /// @notice Returns a struct of permissions to signal which hook functions are to be implemented
    /// @dev Used at deployment to validate the address correctly represents the expected permissions
    /// @return Permissions struct
    function getHookPermissions() public pure virtual returns (Hooks.Permissions memory);

    /// @notice Validates the deployed hook address agrees with the expected permissions of the hook
    /// @dev this function is virtual so that we can override it during testing,
    /// which allows us to deploy an implementation to any address
    /// and then etch the bytecode into the correct address
    function validateHookAddress(BaseHook _this) internal pure virtual {
        Hooks.validateHookPermissions(_this, getHookPermissions());
    }

    /// @inheritdoc IHooks
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _beforeInitialize(sender, key, sqrtPriceX96);
    }

    function _beforeInitialize(address, PoolKey calldata, uint160) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        onlyPoolManager
        returns (bytes4)
    {
        return _afterInitialize(sender, key, sqrtPriceX96, tick);
    }

    function _afterInitialize(address, PoolKey calldata, uint160, int24) internal virtual returns (bytes4) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeAddLiquidity(sender, key, params, hookData);
    }

    function _beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeRemoveLiquidity(sender, key, params, hookData);
    }

    function _beforeRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterAddLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function _afterAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, BalanceDelta) {
        return _afterRemoveLiquidity(sender, key, params, delta, feesAccrued, hookData);
    }

    function _afterRemoveLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) internal virtual returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        onlyPoolManager
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        return _beforeSwap(sender, key, params, hookData);
    }

    function _beforeSwap(address, PoolKey calldata, SwapParams calldata, bytes calldata)
        internal
        virtual
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4, int128) {
        return _afterSwap(sender, key, params, delta, hookData);
    }

    function _afterSwap(address, PoolKey calldata, SwapParams calldata, BalanceDelta, bytes calldata)
        internal
        virtual
        returns (bytes4, int128)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _beforeDonate(sender, key, amount0, amount1, hookData);
    }

    function _beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }

    /// @inheritdoc IHooks
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external onlyPoolManager returns (bytes4) {
        return _afterDonate(sender, key, amount0, amount1, hookData);
    }

    function _afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        virtual
        returns (bytes4)
    {
        revert HookNotImplemented();
    }
}

// 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
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

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

import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";

interface ILimitOrderManager {
    // =========== Structs ===========
    struct PositionTickRange {
        int24 bottomTick;
        int24 topTick;
        bool isToken0;
    }

    struct ClaimableTokens {
        Currency token;  
        uint256 principal;
        uint256 fees;
    }

    struct UserPosition {
        uint128 liquidity;                
        BalanceDelta lastFeePerLiquidity; 
        BalanceDelta claimablePrincipal;  
        BalanceDelta fees;                
    }

    struct PositionState {
        BalanceDelta feePerLiquidity;  
        uint128 totalLiquidity;        
        bool isActive;
        // bool isWaitingKeeper;
        uint256 currentNonce;
    }

    struct PositionInfo {
        uint128 liquidity;
        BalanceDelta fees;
        bytes32 positionKey;
    }

    struct PositionBalances {
        uint256 principal0;
        uint256 principal1;
        uint256 fees0;
        uint256 fees1;
    }

    struct CreateOrderResult {
        uint256 usedAmount;
        bool isToken0;
        int24 bottomTick;
        int24 topTick;
    }

    struct ScaleOrderParams {
        bool isToken0;
        int24 bottomTick;
        int24 topTick;
        uint256 totalAmount;
        uint256 totalOrders;
        uint256 sizeSkew;
    }
    struct OrderInfo {
        int24 bottomTick;
        int24 topTick;
        uint256 amount;
        uint128 liquidity;
    }

    struct CreateOrdersCallbackData {
        PoolKey key;
        OrderInfo[] orders;
        bool isToken0;
        address orderCreator;
    }

    struct CancelOrderCallbackData {
        PoolKey key;
        int24 bottomTick;
        int24 topTick;
        uint128 liquidity;
        address user;
        bool isToken0;
    }

    struct ClaimOrderCallbackData {
        BalanceDelta principal;
        BalanceDelta fees;
        PoolKey key;
        address user;
    }

    // struct KeeperExecuteCallbackData {
    //     PoolKey key;
    //     bytes32[] positions;
    // }

    struct UnlockCallbackData {
        CallbackType callbackType;
        bytes data;
    }

    enum CallbackType {
        CREATE_ORDERS,
        // CREATE_ORDER,
        CLAIM_ORDER,
        CANCEL_ORDER
        // CREATE_SCALE_ORDERS,
        // KEEPER_EXECUTE_ORDERS
    }

    // =========== Errors ===========

    error FeePercentageTooHigh();
    error AmountTooLow();
    error AddressZero();
    error NotAuthorized();
    // error PositionIsWaitingForKeeper();
    error ZeroLimit();
    error NotWhitelistedPool();
    // Removed MinimumAmountNotMet error
    error MaxOrdersExceeded();
    error UnknownCallbackType();

    // =========== Events ===========
    event OrderClaimed(address owner, PoolId indexed poolId, bytes32 positionKey, uint256 principal0, uint256 principal1, uint256 fees0, uint256 fees1, uint256 hookFeePercentage);
    event OrderCreated(address user, PoolId indexed poolId, bytes32 positionKey);
    event OrderCanceled(address orderOwner, PoolId indexed poolId, bytes32 positionKey);
    event OrderExecuted(PoolId indexed poolId, bytes32 positionKey);
    event PositionsLeftOver(PoolId indexed poolId, bytes32[] leftoverPositions);
    // event KeeperWaitingStatusReset(bytes32 positionKey, int24 bottomTick, int24 topTick, int24 currentTick);
    event HookFeePercentageUpdated (uint256 percentage);

    // =========== Functions ===========
    function createLimitOrder(
        bool isToken0,
        int24 targetTick,
        uint256 amount,
        PoolKey calldata key,
        address recipient
    ) external payable returns (CreateOrderResult memory);

    function createScaleOrders(
        bool isToken0,
        int24 bottomTick,
        int24 topTick,
        uint256 totalAmount,
        uint256 totalOrders,
        uint256 sizeSkew,
        PoolKey calldata key,
        address recipient
    ) external payable returns (CreateOrderResult[] memory results);

    // function setHook(address _hook) external;
    function enableHook(address _hook) external;
    function disableHook(address _hook) external;

    function setHookFeePercentage(uint256 _percentage) external;
    
    function executeOrder(
        PoolKey calldata key,
        int24 tickBeforeSwap,
        int24 tickAfterSwap,
        bool zeroForOne
    ) external;

    function cancelOrder(PoolKey calldata key, bytes32 positionKey) external;

    function positionState(PoolId poolId, bytes32 positionKey) 
        external 
        view 
        returns (
            BalanceDelta feePerLiquidity,
            uint128 totalLiquidity,
            bool isActive,
            // bool isWaitingKeeper,
            uint256 currentNonce
        );

    function cancelBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external;

    // /// @notice Emergency function for keepers to cancel orders on behalf of users
    // /// @dev Only callable by keepers to handle emergency situations
    // /// @param key The pool key identifying the specific Uniswap V4 pool
    // /// @param positionKeys Array of position keys to cancel
    // /// @param user The address of the user whose orders to cancel
    // function emergencyCancelOrders(
    //     PoolKey calldata key,
    //     bytes32[] calldata positionKeys,
    //     address user
    // ) external;

    // /// @notice Keeper function to claim positions on behalf of users
    // /// @dev Only callable by keepers to help users claim their executed positions
    // /// @param key The pool key identifying the specific Uniswap V4 pool
    // /// @param positionKeys Array of position keys to claim
    // /// @param user The address of the user whose positions to claim
    // function keeperClaimPositionKeys(
    //     PoolKey calldata key,
    //     bytes32[] calldata positionKeys,
    //     address user
    // ) external;

    function claimOrder(PoolKey calldata key, bytes32 positionKey) external;

    /// @notice Claims multiple positions using direct position keys
    /// @dev This is more robust than using indices as position keys don't shift when other positions are removed
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to claim
    function claimPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external;

    /// @notice Cancels multiple positions using direct position keys
    /// @dev This is more robust than using indices as position keys don't shift when other positions are removed
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to cancel
    function cancelPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external;

    /// @notice Batch claims multiple orders that were executed or canceled
    /// @dev Uses pagination to handle large numbers of orders
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param offset Starting position in the user's position array
    /// @param limit Maximum number of positions to process in this call
    function claimBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external;

    // function executeOrderByKeeper(PoolKey calldata key, bytes32[] memory waitingPositions) external;
    // function setKeeper(address _keeper, bool _isKeeper) external;
    // function setExecutablePositionsLimit(uint256 _limit) external;
    // Removed setMinAmount and setMinAmounts functions

    // View functions
    function getUserPositions(address user, PoolId poolId, uint256 offset, uint256 limit) external view returns (PositionInfo[] memory positions);



    // Additional view functions for state variables
    function currentNonce(PoolId poolId, bytes32 baseKey) external view returns (uint256);
    function treasury() external view returns (address);
    // function executablePositionsLimit() external view returns (uint256);
    // function isKeeper(address) external view returns (bool);
    // function minAmount(Currency currency) external view returns (uint256);

    function getUserPositionCount(address user, PoolId poolId) external view returns (uint256);
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

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

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            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.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, 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(y, 65536))) // A mul() is saved from starting z at 181.

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

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

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

File 70 of 82 : ReentrancyGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

File 71 of 82 : Errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

library Errors {
    error ZeroAddress();
    error UnauthorizedCaller(address caller);
    error NotInitialized();
    error OracleOperationFailed(string operation, string reason);
}

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

/// @title TruncatedOracle
/// @notice Provides observation storage and TWAP queries for paged oracle architecture
/// @dev Designed to work with 512-slot pages, supporting lazy allocation
library TruncatedOracle {
    /// @notice Maximum number of observations across all pages
    /// @dev With PAGE_SIZE=512, this allows 16 full pages (8192 / 512 = 16)
    uint16 public constant MAX_CARDINALITY_ALLOWED = 8192;

    /// @notice Thrown when trying to observe a price that is older than the oldest recorded price
    error TargetPredatesOldestObservation(uint32 oldestTimestamp, uint32 targetTimestamp);

    struct Observation {
        // the block timestamp of the observation
        uint32 blockTimestamp;
        // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized
        int56 tickCumulative;
        // the seconds per liquidity accumulator, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized
        uint160 secondsPerLiquidityCumulativeX128;
        // whether or not the observation is initialized
        bool initialized;
    }

    /// @notice Initialize the first observation in a page
    /// @param self The storage array (512 slots)
    /// @param time The time of the observation
    function initialize(Observation[512] storage self, uint32 time, int24) internal {
        self[0] = Observation({
            blockTimestamp: time,
            tickCumulative: 0,
            secondsPerLiquidityCumulativeX128: 0,
            initialized: true
        });
    }

    /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values
    /// @param last The specified observation to be transformed
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @return Observation The newly populated observation
    function transform(
        Observation memory last,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity
    ) private pure returns (Observation memory) {
        unchecked {
            uint32 delta = blockTimestamp - last.blockTimestamp;

            return Observation({
                blockTimestamp: blockTimestamp,
                tickCumulative: last.tickCumulative + int56(tick) * int56(uint56(delta)),
                secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128
                    + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)),
                initialized: true
            });
        }
    }

    /// @notice Writes an oracle observation to the page
    /// @dev Writable at most once per block within a page
    /// @param self The stored oracle page (512 slots)
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param blockTimestamp The timestamp of the new observation
    /// @param tick The active tick at the time of the new observation
    /// @param liquidity The total in-range liquidity at the time of the new observation
    /// @param cardinality The number of populated observations in this page
    /// @param cardinalityNext The new length of the observations array after this write, capped at page size (512)
    /// @return indexUpdated The new index of the most recently written element in the oracle array
    /// @return cardinalityUpdated The new cardinality of the observations array
    function write(
        Observation[512] storage self,
        uint16 index,
        uint32 blockTimestamp,
        int24 tick,
        uint128 liquidity,
        uint16 cardinality,
        uint16 cardinalityNext
    ) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated) {
        unchecked {
            Observation memory last = self[index];

            // early return if we've already written an observation this block
            if (last.blockTimestamp == blockTimestamp) {
                return (index, cardinality);
            }

            // if the conditions are right, we can bump the cardinality
            if (cardinalityNext > cardinality && index == (cardinality - 1)) {
                cardinalityUpdated = cardinalityNext;
            } else {
                cardinalityUpdated = cardinality;
            }

            // increment index wrapping at page size (512)
            indexUpdated = (index + 1) % 512;
            self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity);
        }
    }

    /// @notice Prepares the page to store observations by setting next-cardinality
    /// @dev Does not allocate storage; cardinality is incremented on first write
    /// @param current The current cardinality
    /// @param next The proposed next cardinality (what we want to grow to)
    /// @return The new cardinality-next value, capped at 512 and MAX_CARDINALITY_ALLOWED
    function grow(
        Observation[512] storage,
        uint16 current,
        uint16 next
    ) internal pure returns (uint16) {
        unchecked {
            if (next <= current) return current;
            // Cap at page size
            if (next > 512) next = 512;
            // Cap at global maximum
            if (next > MAX_CARDINALITY_ALLOWED) next = MAX_CARDINALITY_ALLOWED;
            return next;
        }
    }

    /// @notice comparator for 32-bit timestamps
    /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time
    /// @param time A timestamp truncated to 32 bits
    /// @param a A comparison timestamp from which to determine the relative position of `time`
    /// @param b A comparison timestamp from which to determine the relative position of `time`
    /// @return Whether `a` is chronologically <= `b`
    function lte(
        uint32 time,
        uint32 a,
        uint32 b
    ) private pure returns (bool) {
        unchecked {
            // if there hasn't been overflow, no need to adjust
            if (a <= time && b <= time) return a <= b;

            uint256 aAdjusted = a > time ? a : a + 2 ** 32;
            uint256 bAdjusted = b > time ? b : b + 2 ** 32;

            return aAdjusted <= bAdjusted;
        }
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied
    /// @dev Assumes there is at least 1 initialized observation
    /// @dev Used by observeSingle() to compute time-weighted averages
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param tick The active tick at the time of the returned or simulated observation
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The total pool liquidity at the time of the call
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation recorded before, or at, the target
    /// @return atOrAfter The observation recorded at, or after, the target
    function getSurroundingObservations(
        Observation[512] storage self,
        uint32 time,
        uint32 target,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            // optimistically set before to the newest observation
            beforeOrAt = self[index];

            // if the target is chronologically at or after the newest observation, we can early return
            if (lte(time, beforeOrAt.blockTimestamp, target)) {
                if (beforeOrAt.blockTimestamp == target) {
                    return (beforeOrAt, atOrAfter);
                } else {
                    return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity));
                }
            }

            // now, set before to the oldest observation
            beforeOrAt = self[(index + 1) % cardinality];
            if (!beforeOrAt.initialized) beforeOrAt = self[0];

            // ensure that the target is chronologically at or after the oldest observation
            if (!lte(time, beforeOrAt.blockTimestamp, target)) {
                revert TargetPredatesOldestObservation(beforeOrAt.blockTimestamp, target);
            }

            // perform binary search
            return binarySearch(self, time, target, index, cardinality);
        }
    }

    /// @notice Fetches the observations beforeOrAt and atOrAfter a given target using binary search
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param target The timestamp at which the reserved observation should be for
    /// @param cardinality The number of populated elements in the oracle array
    /// @return beforeOrAt The observation which occurred at, or before, the given timestamp
    /// @return atOrAfter The observation which occurred at, or after, the given timestamp
    function binarySearch(
        Observation[512] storage self,
        uint32 time,
        uint32 target,
        uint16 index,
        uint16 cardinality
    ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
        unchecked {
            uint256 l = (uint256(index) + 1) % cardinality; // oldest observation
            uint256 r = l + cardinality - 1; // newest observation (virtual index)
            uint256 i;

            while (true) {
                i = (l + r) / 2;

                beforeOrAt = self[i % cardinality];

                // we've landed on an uninitialized tick, keep searching higher (more recently)
                if (!beforeOrAt.initialized) {
                    l = i + 1;
                    continue;
                }

                atOrAfter = self[(i + 1) % cardinality];

                bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target);

                // check if we've found the answer!
                if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) {
                    break;
                }

                if (!targetAtOrAfter) r = i - 1;
                else l = i + 1;
            }
        }
    }

    /// @notice Observes a single point in time
    /// @param self The stored oracle array
    /// @param time The current block timestamp
    /// @param secondsAgo The amount of time to look back, in seconds, from the current block timestamp
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo`
    function observeSingle(
        Observation[512] storage self,
        uint32 time,
        uint32 secondsAgo,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) internal view returns (int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) {
        unchecked {
            if (secondsAgo == 0) {
                Observation memory last = self[index];
                if (last.blockTimestamp != time) {
                    last = transform(last, time, tick, liquidity);
                }
                return (last.tickCumulative, last.secondsPerLiquidityCumulativeX128);
            }

            uint32 target = time - secondsAgo;

            (Observation memory beforeOrAt, Observation memory atOrAfter) =
                getSurroundingObservations(self, time, target, tick, index, liquidity, cardinality);

            if (target == beforeOrAt.blockTimestamp) {
                return (beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128);
            } else if (target == atOrAfter.blockTimestamp) {
                return (atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128);
            } else {
                // we're in the middle, interpolate
                uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp;
                uint32 targetDelta = target - beforeOrAt.blockTimestamp;

                tickCumulative = beforeOrAt.tickCumulative
                    + ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / int56(uint56(observationTimeDelta)))
                        * int56(uint56(targetDelta));

                secondsPerLiquidityCumulativeX128 = beforeOrAt.secondsPerLiquidityCumulativeX128
                    + uint160(
                        (uint256(
                            atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128
                        ) * targetDelta) / observationTimeDelta
                    );
            }
        }
    }

    /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos`
    /// @dev Reverts if `secondsAgos` > oldest observation
    /// @param self The stored oracle array
    /// @param time The current block.timestamp
    /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation
    /// @param tick The current tick
    /// @param index The index of the observation that was most recently written to the observations array
    /// @param liquidity The current in-range pool liquidity
    /// @param cardinality The number of populated elements in the oracle array
    /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo`
    /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo`
    function observe(
        Observation[512] storage self,
        uint32 time,
        uint32[] memory secondsAgos,
        int24 tick,
        uint16 index,
        uint128 liquidity,
        uint16 cardinality
    ) internal view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s) {
        require(cardinality > 0, "I");

        tickCumulatives = new int56[](secondsAgos.length);
        secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length);

        unchecked {
            for (uint256 i = 0; i < secondsAgos.length; i++) {
                (tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i]) =
                    observeSingle(self, time, secondsAgos[i], tick, index, liquidity, cardinality);
            }
        }
    }
}

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

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

// 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 75 of 82 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

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

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

library CurrencyReserves {
    using CustomRevert for bytes4;

    /// bytes32(uint256(keccak256("ReservesOf")) - 1)
    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
    /// bytes32(uint256(keccak256("Currency")) - 1)
    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;

    function getSyncedCurrency() internal view returns (Currency currency) {
        assembly ("memory-safe") {
            currency := tload(CURRENCY_SLOT)
        }
    }

    function resetCurrency() internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, 0)
        }
    }

    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            tstore(RESERVES_OF_SLOT, value)
        }
    }

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}

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

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;

    function read() internal view returns (uint256 count) {
        assembly ("memory-safe") {
            count := tload(NONZERO_DELTA_COUNT_SLOT)
        }
    }

    function increment() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := add(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}

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

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;

    function unlock() internal {
        assembly ("memory-safe") {
            // unlock
            tstore(IS_UNLOCKED_SLOT, true)
        }
    }

    function lock() internal {
        assembly ("memory-safe") {
            tstore(IS_UNLOCKED_SLOT, false)
        }
    }

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

Settings
{
  "remappings": [
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/liquidity-launcher/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin-latest/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "@optimism/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/",
    "@solady/=lib/liquidity-launcher/lib/solady/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@uniswap/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
    "blocknumberish/=lib/liquidity-launcher/lib/blocknumberish/",
    "ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/liquidity-launcher/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/liquidity-launcher/lib/openzeppelin-contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solady/=lib/liquidity-launcher/lib/solady/src/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/",
    "scripts/=lib/liquidity-launcher/lib/optimism/packages/contracts-bedrock/scripts/",
    "liquidity-launcher/src/token-factories/uerc20-factory/=lib/liquidity-launcher/lib/uerc20-factory/src/",
    "liquidity-launcher/src/=lib/liquidity-launcher/src/",
    "liquidity-launcher/=lib/liquidity-launcher/",
    "periphery/=lib/liquidity-launcher/src/periphery/",
    "continuous-clearing-auction/=lib/liquidity-launcher/lib/continuous-clearing-auction/",
    "ll/=lib/liquidity-launcher/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {
    "src/Unilaunch/MultiPositionManager/periphery/InitialDepositLens.sol": {
      "PositionLogic": "0xa198f4da67f3b6735f178779673e062ed287ad78",
      "RebalanceLogic": "0x85d9c453d937379d91e986fb48b4bc08d479e958"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CarpetRequired","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidWeights","type":"error"},{"inputs":[],"name":"NoStrategySpecified","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":"poolKey","type":"tuple"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.InitialDepositParams","name":"params","type":"tuple"}],"name":"getAmountsForInitialDeposit","outputs":[{"internalType":"uint256","name":"otherAmount","type":"uint256"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"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":"poolKey","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.InitialDepositParams","name":"params","type":"tuple"}],"name":"getAmountsForInitialDepositUninitialized","outputs":[{"internalType":"uint256","name":"otherAmount","type":"uint256"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"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":"poolKey","type":"tuple"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.InitialDepositWithSwapParams","name":"params","type":"tuple"}],"name":"getAmountsForInitialDepositWithSwap","outputs":[{"internalType":"uint256","name":"finalAmount0","type":"uint256"},{"internalType":"uint256","name":"finalAmount1","type":"uint256"},{"components":[{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"}],"internalType":"struct LensRatioUtils.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"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":"poolKey","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.InitialDepositWithSwapParams","name":"params","type":"tuple"}],"name":"getAmountsForInitialDepositWithSwapUninitialized","outputs":[{"internalType":"uint256","name":"finalAmount0","type":"uint256"},{"internalType":"uint256","name":"finalAmount1","type":"uint256"},{"components":[{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"}],"internalType":"struct LensRatioUtils.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IMultiPositionManager","name":"manager","type":"address"}],"name":"getPositionStats","outputs":[{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"stats","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"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":"poolKey","type":"tuple"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.CustomInitialDepositParams","name":"params","type":"tuple"}],"name":"previewCustomInitialDepositAndRebalance","outputs":[{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"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":"poolKey","type":"tuple"},{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"components":[{"internalType":"address","name":"strategyAddress","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint256","name":"deposit0","type":"uint256"},{"internalType":"uint256","name":"deposit1","type":"uint256"},{"internalType":"uint256","name":"maxSlippageBps","type":"uint256"}],"internalType":"struct InitialDepositLens.CustomInitialDepositParams","name":"params","type":"tuple"}],"name":"previewCustomInitialDepositAndRebalanceUninitialized","outputs":[{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"centerTick","type":"int24"},{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"components":[{"internalType":"int24","name":"lowerTick","type":"int24"},{"internalType":"int24","name":"upperTick","type":"int24"}],"internalType":"struct IMultiPositionManager.Range[]","name":"ranges","type":"tuple[]"},{"internalType":"uint128[]","name":"liquidities","type":"uint128[]"},{"components":[{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint160","name":"sqrtPriceLower","type":"uint160"},{"internalType":"uint160","name":"sqrtPriceUpper","type":"uint160"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"token0Quantity","type":"uint256"},{"internalType":"uint256","name":"token1Quantity","type":"uint256"},{"internalType":"uint256","name":"valueInToken1","type":"uint256"},{"internalType":"bool","name":"isLimit","type":"bool"}],"internalType":"struct LensRatioUtils.PositionStats[]","name":"expectedPositions","type":"tuple[]"},{"internalType":"uint256","name":"expectedTotal0","type":"uint256"},{"internalType":"uint256","name":"expectedTotal1","type":"uint256"}],"internalType":"struct InitialDepositLens.RebalancePreview","name":"preview","type":"tuple"}],"stateMutability":"view","type":"function"}]

60a0604052348015600e575f80fd5b506040516153cf3803806153cf833981016040819052602b91603b565b6001600160a01b03166080526066565b5f60208284031215604a575f80fd5b81516001600160a01b0381168114605f575f80fd5b9392505050565b60805161534a6100855f395f81816101570152610216015261534a5ff3fe608060405234801561000f575f80fd5b5060043610610085575f3560e01c8063a1a6f91a11610058578063a1a6f91a1461010b578063bf8f0d3a1461011e578063c6f6bf021461013f578063dc4c90d314610152575f80fd5b806319b4dc3f146100895780638d88ed9a146100b45780638dcce6eb146100d45780639f30033f146100e7575b5f80fd5b61009c6100973660046146da565b610191565b6040516100ab93929190614988565b60405180910390f35b6100c76100c23660046149b2565b61025a565b6040516100ab91906149cd565b61009c6100e23660046149df565b610644565b6100fa6100f53660046146da565b6106c5565b6040516100ab959493929190614a24565b6100fa6101193660046149df565b6107a2565b61013161012c3660046149df565b610857565b6040516100ab929190614a89565b61013161014d3660046146da565b6108ed565b6101797f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016100ab565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052906101fd60a085013560c08601356101f8610100880160e08901614ac5565b610997565b5f61023c61020c8760a0902090565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690610a16565b505050905061024c868287610ac8565b935093509350509250925092565b60605f826001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610299573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102bd9190614ae0565b90505f6102ce61020c8360a0902090565b50505090505f80856001600160a01b031663802758606040518163ffffffff1660e01b81526004015f60405180830381865afa158015610310573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526103379190810190614c8d565b91509150815167ffffffffffffffff8111156103555761035561453f565b6040519080825280602002602001820160405280156103ca57816020015b60408051610120810182525f8082526020808301829052928201819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015282525f199092019101816103735790505b5094505f866001600160a01b03166303e782816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561040a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061042e9190614d55565b90505f5b83518110156106395783818151811061044d5761044d614d6c565b60200260200101515f015160020b5f148015610488575083818151811061047657610476614d6c565b60200260200101516020015160020b5f145b610631575f6104b28583815181106104a2576104a2614d6c565b60200260200101515f0151610d2a565b90505f6104db8684815181106104ca576104ca614d6c565b602002602001015160200151610d2a565b90505f806105078985858a89815181106104f7576104f7614d6c565b60200260200101515f0151610fef565b90925090505f610543836105246001600160a01b038d1680614d94565b780100000000000000000000000000000000000000000000000061108a565b90505f6105508383614dab565b90506040518061012001604052808b898151811061057057610570614d6c565b60200260200101515f015160020b81526020018b898151811061059557610595614d6c565b60200260200101516020015160020b8152602001876001600160a01b03168152602001866001600160a01b031681526020018a89815181106105d9576105d9614d6c565b60200260200101515f01516001600160801b031681526020018581526020018481526020018281526020018989101515158152508d888151811061061f5761061f614d6c565b60200260200101819052505050505050505b600101610432565b505050505050919050565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052906106ab60a085013560c08601356101f8610100880160e08901614ac5565b6106b6868686610ac8565b92509250925093509350939050565b5f806106f060405180608001604052805f151581526020015f81526020015f81526020015f81525090565b60606107516040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61076f60a087013560c08801356101f86101008a0160e08b01614ac5565b5f61077e61020c8960a0902090565b505050905061078e888289611127565b939c929b5090995097509095509350505050565b5f806107cd60405180608001604052805f151581526020015f81526020015f81526020015f81525090565b606061082e6040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61084c60a087013560c08801356101f86101008a0160e08b01614ac5565b61078e888888611127565b60606108b86040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b6108d660a084013560c08501356101f8610100870160e08801614ac5565b6108e1858585611216565b91509150935093915050565b606061094e6040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61096c60a084013560c08501356101f8610100870160e08801614ac5565b5f61097b61020c8660a0902090565b505050905061098b858286611216565b92509250509250929050565b5f831580156109a4575082155b90505f846706f05b59d3b200001480156109c55750836706f05b59d3b20000145b9050811580156109d3575080155b156109f15760405163108cef9d60e31b815260040160405180910390fd5b82610a0f57604051631b9f988360e11b815260040160405180910390fd5b5050505050565b5f805f805f610a24866114ea565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa158015610a6c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a909190614d55565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052905f610b1f60208601866149b2565b6001600160a01b031603610b4657604051631b6c707960e11b815260040160405180910390fd5b8361012001355f03610b6b5760405163162908e360e11b815260040160405180910390fd5b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528681526001600160a01b0386166020820152610bd486611526565b60020b6060820152610bfe610bef6040870160208801614dbe565b826060015189606001516117c3565b60020b60408201819052610c1690889088908861182e565b9350610c2a61012086016101008701614ac5565b610c345783610c3b565b8461012001355b6080820152610c5261012086016101008701614ac5565b610c6157846101200135610c63565b835b60a08201525f80610c8283610c7d368a90038a018a614dd9565b6119bd565b91509150610c9782828a8a6101400135611e01565b9450610ca660208801886149b2565b6001600160a01b0316845260408084015160020b6020860152610ccf9060608901908901614e9a565b62ffffff166040850152610ce96080880160608901614e9a565b62ffffff166060850152608080850183905260a0808601839052610d1e918a918791610d19918c01908c01614e9a565b611f33565b50505093509350939050565b60020b5f60ff82901d80830118620d89e8811115610d5357610d536345c3193d60e11b846121ca565b7001fffcb933bd6fad37aa2d162d1a5940016001821602700100000000000000000000000000000000186002821615610d9c576ffff97272373d413259a46990580e213a0260801c5b6004821615610dbb576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615610dda576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615610df9576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610e18576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610e37576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610e56576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610e76576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610e96576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610eb6576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610ed6576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610ef6576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610f16576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610f36576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610f56576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610f77576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610f97576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610fb6576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610fd3576b048a170391f7dc42444e8fa20260801c5b5f841315610fdf575f19045b63ffffffff0160201c9392505050565b5f80836001600160a01b0316856001600160a01b0316111561100f579293925b846001600160a01b0316866001600160a01b03161161103a576110338585856121d9565b9150611081565b836001600160a01b0316866001600160a01b031610156110735761105f8685856121d9565b915061106c85878561225c565b9050611081565b61107e85858561225c565b90505b94509492505050565b5f838302815f19858709828110838203039150508084116110a9575f80fd5b805f036110bb57508290049050611120565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b5f8061115260405180608001604052805f151581526020015f81526020015f81526020015f81525090565b60606111b36040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b5f6111c160208801886149b2565b6001600160a01b0316036111e857604051631b6c707960e11b815260040160405180910390fd5b6111f38888886122a5565b909650945092506112078888888888612434565b95999498509296509194505050565b60606112776040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b5f61128560208501856149b2565b6001600160a01b0316036112ac57604051631b6c707960e11b815260040160405180910390fd5b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528581526001600160a01b038516602082015261131585611526565b60020b606082015261133f6113306040860160208701614dbe565b826060015188606001516117c3565b60020b604080830191909152610100850135608083015261012085013560a0830152805161016081019091525f908061137b60208801886149b2565b6001600160a01b0316815260200186602001602081019061139c9190614dbe565b60020b81526020016113b46060880160408901614e9a565b62ffffff1681526020016113ce6080880160608901614e9a565b62ffffff1681526020016113e860a0880160808901614e9a565b62ffffff16815260a0870135602082015260c08701356040820152606001611417610100880160e08901614ac5565b1515815260016020820152610100870135604082015261014087013560609091015290505f8061144784846119bd565b9150915061145c82828a8a6101400135611e01565b955061146b60208801886149b2565b6001600160a01b0316855260408085015160020b60208701526114949060608901908901614e9a565b62ffffff1660408601526114ae6080880160608901614e9a565b62ffffff166060860152608080860183905260a08087018390526114de918a918891610d19918c01908c01614e9a565b50505050935093915050565b6040515f90611509908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b5f73fffd8963efd1fc6a506488495d951d51639616826401000276a21983016001600160a01b03161115611565576115656318521d4960e21b836126c9565b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b16805f61158f826126de565b60ff169050608081106115aa57607f810383901c91506115b4565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146117b457886001600160a01b031661179982610d2a565b6001600160a01b031611156117ae57816117b6565b806117b6565b815b9998505050505050505050565b5f80600285900b627fffff146117d957846117db565b835b90505f6117e88483614ec9565b90505f8260020b12801561180757506118018483614f01565b60020b15155b1561181a578061181681614f22565b9150505b6118248482614f43565b9695505050505050565b5f6118686040518060c001604052806060815260200160608152602001606081526020015f60020b81526020015f81526020015f81525090565b61187185611526565b60020b60608201525f61188760208501856149b2565b90506001600160a01b0381166340b71404866118a96060880160408901614e9a565b6118b96080890160608a01614e9a565b60608c01516118cf6101008b0160e08c01614ac5565b60405160e087901b7fffffffff00000000000000000000000000000000000000000000000000000000168152600295860b600482015262ffffff948516602482015292909316604483015290920b60648301521515608482015260a4015f60405180830381865afa158015611946573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261196d9190810190614fcd565b60208401528252606087015161198a908290849087908990612769565b604083015261199982876128f3565b60a08401819052608084018290526119b2918691612a07565b979650505050505050565b6060805f604051806101400160405280855f01516001600160a01b03168152602001866040015160020b8152602001856040015162ffffff168152602001856060015162ffffff168152602001855f01516001600160a01b031681526020018560a0015181526020018560c0015181526020018560e0015115158152602001856080015162ffffff1681526020018560a001515f148015611a60575060c0860151155b151581525090505f80611a85875f01518489608001518a60a001518b60200151612a62565b6080880151919350915062ffffff1615611df0575f8073a198f4da67f3b6735f178779673e062ed287ad7863522179138960800151868c5f0151606001518d606001516040518563ffffffff1660e01b8152600401611ae79493929190615028565b608060405180830381865af4158015611b02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b2691906150ae565b9150915083516002611b389190614dab565b67ffffffffffffffff811115611b5057611b5061453f565b604051908082528060200260200182016040528015611b9457816020015b604080518082019091525f8082526020820152815260200190600190039081611b6e5790505b50965083516002611ba59190614dab565b67ffffffffffffffff811115611bbd57611bbd61453f565b604051908082528060200260200182016040528015611be6578160200160208202803683370190505b5095505f5b8451811015611c7757848181518110611c0657611c06614d6c565b6020026020010151888281518110611c2057611c20614d6c565b6020026020010181905250838181518110611c3d57611c3d614d6c565b6020026020010151878281518110611c5757611c57614d6c565b6001600160801b0390921660209283029190910190910152600101611beb565b505f80611c9386868d602001518e608001518f60a00151612a92565b915091508389875181518110611cab57611cab614d6c565b6020026020010181905250828987516001611cc69190614dab565b81518110611cd657611cd6614d6c565b6020026020010181905250836020015160020b845f015160020b14158015611cfd57505f81115b15611d5e57611d2a8b60200151611d16865f0151610d2a565b611d238760200151610d2a565b5f85612b49565b88875181518110611d3d57611d3d614d6c565b60200260200101906001600160801b031690816001600160801b0316815250505b826020015160020b835f015160020b14158015611d7a57505f82115b15611de757611da78b60200151611d93855f0151610d2a565b611da08660200151610d2a565b855f612b49565b8887516001611db69190614dab565b81518110611dc657611dc6614d6c565b60200260200101906001600160801b031690816001600160801b0316815250505b50505050611df7565b8194508093505b5050509250929050565b6060845167ffffffffffffffff811115611e1d57611e1d61453f565b604051908082528060200260200182016040528015611e5657816020015b611e43614521565b815260200190600190039081611e3b5790505b5090505f611e66836127106150d8565b90505f5b8651811015611f29575f611e898883815181106104a2576104a2614d6c565b90505f611ea18984815181106104ca576104ca614d6c565b90505f80611eca8985858d8981518110611ebd57611ebd614d6c565b6020026020010151610fef565b915091506040518060400160405280611ee6848961271061108a565b8152602001611ef8838961271061108a565b815250878681518110611f0d57611f0d614d6c565b6020026020010181905250505050508080600101915050611e6a565b5050949350505050565b81608001515167ffffffffffffffff811115611f5157611f5161453f565b604051908082528060200260200182016040528015611fc657816020015b60408051610120810182525f8082526020808301829052928201819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015282525f19909201910181611f6f5790505b5060c08301525f60e08301819052610100830181905262ffffff821615801590611ff65750600283608001515110155b61200557826080015151612017565b600283608001515161201791906150d8565b90505f5b836080015151811015610a0f575f612042856080015183815181106104a2576104a2614d6c565b90505f61205e866080015184815181106104ca576104ca614d6c565b90505f8061207e8985858b60a001518981518110611ebd57611ebd614d6c565b90925090505f61209b836105246001600160a01b038d1680614d94565b6120a59083614dab565b90506040518061012001604052808a6080015188815181106120c9576120c9614d6c565b60200260200101515f015160020b81526020018a6080015188815181106120f2576120f2614d6c565b60200260200101516020015160020b8152602001866001600160a01b03168152602001856001600160a01b031681526020018a60a00151888151811061213a5761213a614d6c565b60200260200101516001600160801b031681526020018481526020018381526020018281526020018888101515158152508960c00151878151811061218157612181614d6c565b6020026020010181905250828960e00181815161219e9190614dab565b905250610100890180518391906121b6908390614dab565b905250506001909401935061201b92505050565b815f528060020b60045260245ffd5b5f826001600160a01b0316846001600160a01b031611156121f8579192915b6001600160a01b03841661224a7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b1661223287876150eb565b6001600160a01b0316866001600160a01b031661108a565b612254919061510a565b949350505050565b5f826001600160a01b0316846001600160a01b0316111561227b579192915b6122546001600160801b03831661229286866150eb565b6001600160a01b0316600160601b61108a565b6122ce60405180608001604052805f151581526020015f81526020015f81526020015f81525090565b5f805f6122da86611526565b90505f6122fb6122f06040880160208901614dbe565b838a606001516117c3565b905061235561230d60208801886149b2565b8261231e60608a0160408b01614e9a565b61232e60808b0160608c01614e9a565b60608d01516123446101008d0160e08e01614ac5565b8d898e60a001358f60c00135612bfe565b6060870181905260408088018390525163103e311760e31b8152610100890135600482015261012089013560248201526001600160a01b038a166044820152606481019290925260848201527385d9c453d937379d91e986fb48b4bc08d479e958906381f188b89060a4016040805180830381865af41580156123da573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123fe919061511d565b6020870181905290151580875261242391610100890135916101208a0135918b612c26565b959990985094965093945050505050565b60606124956040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528781526001600160a01b03871660208201526124fe87611526565b60020b60608201526125286125196040880160208901614dbe565b82606001518a606001516117c3565b60020b6040808301919091526080820186905260a08201859052805161016081019091525f908061255c60208a018a6149b2565b6001600160a01b0316815260200188602001602081019061257d9190614dbe565b60020b815260200161259560608a0160408b01614e9a565b62ffffff1681526020016125af60808a0160608b01614e9a565b62ffffff1681526020016125c960a08a0160808b01614e9a565b62ffffff16815260a0890135602082015260c089013560408201526060016125f86101008a0160e08b01614ac5565b15158152600160208201526040810188905261014089013560609091015290505f8061262484846119bd565b9150915061263982828c8c6101400135611e01565b955061264860208a018a6149b2565b6001600160a01b0316855260408085015160020b60208701526126719060608b01908b01614e9a565b62ffffff16604086015261268b60808a0160608b01614e9a565b62ffffff166060860152608080860183905260a08087018390526126bb918c918891610d19918e01908e01614e9a565b505050509550959350505050565b815f526001600160a01b03811660045260245ffd5b5f8082116126ea575f80fd5b507f0706060506020500060203020504000106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be6001600160801b03841160071b84811c67ffffffffffffffff1060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b60605f60a0850135158015612780575060c0850135155b90505f876001600160a01b0316631b7c6141885f015189602001518a60600151898b60400160208101906127b49190614e9a565b6127c460808e0160608f01614e9a565b8d60a001358e60c001358f60e00160208101906127e19190614ac5565b8e8d6040518c63ffffffff1660e01b81526004016128099b9a9998979695949392919061517c565b5f60405180830381865afa158015612823573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261284a9190810190615211565b875160208901519192507385d9c453d937379d91e986fb48b4bc08d479e9589163db021467918491886128846101008d0160e08e01614ac5565b6040518663ffffffff1660e01b81526004016128a4959493929190615298565b5f60405180830381865af41580156128be573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128e59190810190615211565b925050505b95945050505050565b5f805f5b8451518110156129ff575f612927865f0151838151811061291a5761291a614d6c565b6020026020010151610d2a565b90505f6129438760200151848151811061291a5761291a614d6c565b90505f8061295b888585670de0b6b3a7640000610fef565b91509150670de0b6b3a76400008960400151868151811061297e5761297e614d6c565b6020026020010151836129919190614d94565b61299b919061510a565b6129a59088614dab565b9650670de0b6b3a7640000896040015186815181106129c6576129c6614d6c565b6020026020010151826129d99190614d94565b6129e3919061510a565b6129ed9087614dab565b955050600190930192506128f7915050565b509250929050565b5f612a1a61012085016101008601614ac5565b15612a4457825f03612a2d57505f611120565b612a3d846101200135838561108a565b9050611120565b815f03612a5257505f611120565b612254846101200135848461108a565b6060805f612a71888886612ce1565b805193509050612a85818989898989612f89565b9150509550959350505050565b5f805f805f5b8951811015612b0a575f80612ae38a612abc8e86815181106104a2576104a2614d6c565b612ad18f87815181106104ca576104ca614d6c565b8e8781518110611ebd57611ebd614d6c565b9092509050612af28286614dab565b9450612afe8185614dab565b93505050600101612a98565b50818611612b18575f612b22565b612b2282876150d8565b9350808511612b31575f612b3b565b612b3b81866150d8565b925050509550959350505050565b5f836001600160a01b0316856001600160a01b03161115612b68579293925b846001600160a01b0316866001600160a01b031611612b9357612b8c858585612faf565b90506128ea565b836001600160a01b0316866001600160a01b03161015612bf3575f612bb9878686612faf565b90505f612bc7878986613017565b9050806001600160801b0316826001600160801b031610612be85780612bea565b815b925050506128ea565b611824858584613017565b5f80612c128c8c8c8c8c8c8c8c8c8c61304c565b915091505b9a509a98505050505050505050565b5f80835f03612c39575085905084612cd7565b8415612c8f575f612c6f612c5b86866001600160a01b0316600160601b61108a565b856001600160a01b0316600160601b61108a565b9050612c7b85896150d8565b9250612c878188614dab565b915050612cd7565b5f612cbf612cab86600160601b876001600160a01b031661108a565b600160601b866001600160a01b031661108a565b9050612ccb8189614dab565b9250612a8585886150d8565b9550959350505050565b60408051808201909152606080825260208201525f612cff83611526565b606080870151608087015160208801516040808a0151948a015160e08b0151915163102dc50160e21b8152600293840b600482015262ffffff9687166024820152951660448601529083900b606485015215156084840152929350915f9182916001600160a01b0316906340b714049060a4015f60405180830381865afa158015612d8c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612db39190810190614fcd565b91509150815167ffffffffffffffff811115612dd157612dd161453f565b604051908082528060200260200182016040528015612e1557816020015b604080518082019091525f8082526020820152815260200190600190039081612def5790505b5085525f5b8251811015612e98576040518060400160405280848381518110612e4057612e40614d6c565b602002602001015160020b8152602001838381518110612e6257612e62614d6c565b602002602001015160020b815250865f01518281518110612e8557612e85614d6c565b6020908102919091010152600101612e1a565b5060408051610140810182526060808252602082018190525f92820183905281018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091528281526020808201839052600286810b604080850191909152918a0151810b606080850191909152918a015162ffffff908116608080860191909152928b01511660a0808501919091528a015160c0808501919091528a015160e0808501919091528a0151151561010084015285900b610120808401919091529089015190890151612f779190839061307a565b60208701525093979650505050505050565b60606119b2875f015188602001518686868a61012001518c606001518c60e001516131b9565b5f826001600160a01b0316846001600160a01b03161115612fce579192915b5f612ff0856001600160a01b0316856001600160a01b0316600160601b61108a565b90506128ea613012848361300489896150eb565b6001600160a01b031661108a565b61325a565b5f826001600160a01b0316846001600160a01b03161115613036579192915b61225461301283600160601b61300488886150eb565b5f808315158061305b57508215155b1561306a575082905081612c17565b612c128c8c8c8c8c8c8c8c6132bc565b60605f846001600160a01b0316631b7c6141855f015186602001518760400151886060015189608001518a60a001518b60c001518c60e001518d61010001518e61012001518e6040518c63ffffffff1660e01b81526004016130e69b9a9998979695949392919061517c565b5f60405180830381865afa158015613100573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526131279190810190615211565b8451602086015161012087015161010088015160405163db02146760e01b81529495507385d9c453d937379d91e986fb48b4bc08d479e9589463db0214679461317894889491939092600401615298565b5f60405180830381865af4158015613192573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128ea9190810190615211565b6060885167ffffffffffffffff8111156131d5576131d561453f565b6040519080825280602002602001820160405280156131fe578160200160208202803683370190505b5090505f6040518060c00160405280898152602001888152602001876001600160a01b0316815260200186151581526020018560020b8152602001841515815250905061324d828a8c8461349a565b5098975050505050505050565b806001600160801b03811681146132b75760405162461bcd60e51b815260206004820152601260248201527f6c6971756964697479206f766572666c6f770000000000000000000000000000604482015260640160405180910390fd5b919050565b60408051610100810182526001600160a01b038a811680835260028b810b6020850181905262ffffff8c8116868801819052908c16606087018190528b840b608088018190528b151560a08901819052968b1660c08901529389900b60e0880152965163102dc50160e21b8152600481019290925260248201526044810195909552606485015260848401919091525f9283929183918291906340b714049060a4015f60405180830381865afa158015613378573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261339f9190810190614fcd565b9150915081515f036133c1576706f05b59d3b20000809450945050505061348d565b5f806133ce8585856136a3565b91509150815f1480156133df575080155b156133fc576706f05b59d3b200008096509650505050505061348d565b5f61342c613418848c6001600160a01b0316600160601b61108a565b8b6001600160a01b0316600160601b61108a565b90505f6134398383614dab565b9050805f0361345c576706f05b59d3b2000080985098505050505050505061348d565b61346f82670de0b6b3a76400008361108a565b985061348389670de0b6b3a76400006150d8565b9750505050505050505b9850989650505050505050565b81515f8190036134aa575061369d565b6134ea6040518060e0016040528060608152602001606081526020015f81526020015f81526020015f81526020015f60020b81526020015f151581525090565b8167ffffffffffffffff8111156135035761350361453f565b60405190808252806020026020018201604052801561352c578160200160208202803683370190505b5081528167ffffffffffffffff8111156135485761354861453f565b604051908082528060200260200182016040528015613571578160200160208202803683370190505b506020820152604083015161358590611526565b60020b60a082015260408301516135a4908290869088905f60016137be565b6135bb81845f015185602001518660600151613a14565b826060015180156135cd57508060c001515b156135e1576135e181858560400151613c05565b5f5b82811015613699575f6136018683815181106104a2576104a2614d6c565b90505f6136198784815181106104ca576104ca614d6c565b905061366586604001518383875f0151878151811061363a5761363a614d6c565b60200260200101518860200151888151811061365857613658614d6c565b6020026020010151612b49565b89848151811061367757613677614d6c565b6001600160801b039092166020928302919091019091015250506001016135e3565b5050505b50505050565b5f805f6136b1868686613cb2565b90506136c881868689608001518a60a00151613d51565b60c08701518651919250905f5b818110156114de575f6136f389838151811061291a5761291a614d6c565b90505f61370b89848151811061291a5761291a614d6c565b90505f80613723878585670de0b6b3a7640000610fef565b91509150670de0b6b3a764000088868151811061374257613742614d6c565b6020026020010151836137559190614d94565b61375f919061510a565b613769908b614dab565b9950670de0b6b3a764000088868151811061378657613786614d6c565b6020026020010151826137999190614d94565b6137a3919061510a565b6137ad908a614dab565b9850846001019450505050506136d5565b84515f8084156137df576137d184613ddd565b91506137dc84613dfe565b90505b5f5b83811015613a08575f6137ff8a83815181106104a2576104a2614d6c565b90505f6138178b84815181106104ca576104ca614d6c565b90505f8061382f8b8585670de0b6b3a7640000610fef565b9150915061385f828d878151811061384957613849614d6c565b6020026020010151670de0b6b3a764000061108a565b8e5180518790811061387357613873614d6c565b602002602001018181525050613895818d878151811061384957613849614d6c565b8e6020015186815181106138ab576138ab614d6c565b60209081029190910101528d518051869081106138ca576138ca614d6c565b60200260200101518e6040018181516138e39190614dab565b90525060208e01518051869081106138fd576138fd614d6c565b60200260200101518e6060018181516139169190614dab565b915081815250508d60a0015160020b8d868151811061393757613937614d6c565b60200260200101515f015160020b1315801561397957508c858151811061396057613960614d6c565b60200260200101516020015160020b8e60a0015160020b125b156139f95789801561398b5750600188115b80156139b857508660020b8d86815181106139a8576139a8614d6c565b60200260200101515f015160020b145b80156139e657508560020b8d86815181106139d5576139d5614d6c565b60200260200101516020015160020b145b6139f95760808e01859052600160c08f01525b846001019450505050506137e1565b50505050505050505050565b8351518115613af557604085015115613a85575f5b81811015613a8357613a5c865f01518281518110613a4957613a49614d6c565b602002602001015186886040015161108a565b8651805183908110613a7057613a70614d6c565b6020908102919091010152600101613a29565b505b606085015115613af0575f5b81811015613aee57613ac586602001518281518110613ab257613ab2614d6c565b602002602001015185886060015161108a565b86602001518281518110613adb57613adb614d6c565b6020908102919091010152600101613a91565b505b610a0f565b5f85604001515f03613b08575f19613b1f565b613b1f85670de0b6b3a7640000886040015161108a565b90505f86606001515f03613b34575f19613b4b565b613b4b85670de0b6b3a7640000896060015161108a565b90505f818310613b5b5781613b5d565b825b90505f5b84811015613bfa57613b98895f01518281518110613b8157613b81614d6c565b602002602001015183670de0b6b3a764000061108a565b8951805183908110613bac57613bac614d6c565b602002602001018181525050613bd189602001518281518110613b8157613b81614d6c565b89602001518281518110613be757613be7614d6c565b6020908102919091010152600101613b61565b505050505050505050565b5f613c2e8484866080015181518110613c2057613c20614d6c565b602002602001015184613e16565b90508060400151845f0151856080015181518110613c4e57613c4e614d6c565b60200260200101818152505080606001518460200151856080015181518110613c7957613c79614d6c565b6020908102919091010152805115613c9957613c998484835f015161417b565b60208101511561369d5761369d8484836020015161428c565b6060835f01516001600160a01b0316631b7c614184848760e00151886020015189604001518a606001515f808d60a001518e6080015160016040518c63ffffffff1660e01b8152600401613d109b9a9998979695949392919061517c565b5f60405180830381865afa158015613d2a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526122549190810190615211565b6060811580613d5f57508551155b80613d6c57508351855114155b15613d785750846128ea565b5f613d8284613ddd565b90505f613d8e85613dfe565b90505f613d9d8888858561438c565b90505f198103613db2578893505050506128ea565b8851600103613dc6578893505050506128ea565b613dd08982614409565b5096979650505050505050565b5f81600281900b620d89e71981613df657613df6614eb5565b050292915050565b5f81600281900b620d89e881613df657613df6614eb5565b613e3d60405180608001604052805f81526020015f81526020015f81526020015f81525090565b608084015183515f90613e4f90610d2a565b90505f613e5f8660200151610d2a565b90505f826001600160a01b0316866001600160a01b03161115613eb157613eae88602001518581518110613e9557613e95614d6c565b6020026020010151600160601b858961300491906150eb565b90505b5f836001600160a01b0316876001600160a01b031611613f6c575f895f01518681518110613ee157613ee1614d6c565b6020026020010151118015613f075750836001600160a01b0316836001600160a01b0316115b15613f65575f613f2e846001600160a01b0316866001600160a01b0316600160601b61108a565b9050613f5d8a5f01518781518110613f4857613f48614d6c565b602002602001015182878761300491906150eb565b9150506140ab565b505f6140ab565b5f836001600160a01b0316886001600160a01b0316108015613f8d57505f83115b15614028575f613fb4856001600160a01b03168a6001600160a01b0316600160601b61108a565b9050805f03614006575f613fe485613fcc8c896150eb565b6001600160a01b0316886001600160a01b031661108a565b9050613ffe81600160601b8c6001600160a01b031661108a565b925050614026565b614023846140148b886150eb565b6001600160a01b03168361108a565b91505b505b808a5f0151878151811061403e5761403e614d6c565b602002602001015110156140a5575f61406e856001600160a01b03168a6001600160a01b0316600160601b61108a565b905061409d8b5f0151888151811061408857614088614d6c565b6020026020010151828b8861300491906150eb565b9250506140a9565b8291505b505b6140bf8785856140ba856144fd565b610fef565b60608801526040870181905289518051879081106140df576140df614d6c565b6020026020010151116140f2575f61411d565b6040860151895180518790811061410b5761410b614d6c565b602002602001015161411d91906150d8565b8652606086015160208a015180518790811061413b5761413b614d6c565b60200260200101511161414e575f612f77565b85606001518960200151868151811061416957614169614d6c565b6020026020010151612f7791906150d8565b8251515f90815b818110156141ea578560a0015160020b8582815181106141a4576141a4614d6c565b60200260200101515f015160020b13156141e25785518051829081106141cc576141cc614d6c565b6020026020010151836141df9190614dab565b92505b600101614182565b508115610a0f575f5b81811015614284578560a0015160020b85828151811061421557614215614d6c565b60200260200101515f015160020b131561427c5761425084875f0151838151811061424257614242614d6c565b60200260200101518561108a565b865180518390811061426457614264614d6c565b602002602001018181516142789190614dab565b9052505b6001016141f3565b505050505050565b8251515f90815b818110156142fd578560a0015160020b8582815181106142b5576142b5614d6c565b60200260200101516020015160020b136142f557856020015181815181106142df576142df614d6c565b6020026020010151836142f29190614dab565b92505b600101614293565b508115610a0f575f5b81811015614284578560a0015160020b85828151811061432857614328614d6c565b60200260200101516020015160020b1361438457614356848760200151838151811061424257614242614d6c565b8660200151828151811061436c5761436c614d6c565b602002602001018181516143809190614dab565b9052505b600101614306565b83515f90815b818110156143fc578460020b8782815181106143b0576143b0614d6c565b602002602001015160020b1480156143e657508360020b8682815181106143d9576143d9614d6c565b602002602001015160020b145b156143f45791506122549050565b600101614392565b505f199695505050505050565b81515f03614415575050565b5f805b8351811015614458578083146144505783818151811061443a5761443a614d6c565b60200260200101518261444d9190614dab565b91505b600101614418565b50805f03614484575f83838151811061447357614473614d6c565b602002602001018181525050505050565b5f5b83518110156144e9578083146144e1576144c28482815181106144ab576144ab614d6c565b6020026020010151670de0b6b3a76400008461108a565b8482815181106144d4576144d4614d6c565b6020026020010181815250505b600101614486565b505f83838151811061447357614473614d6c565b5f6001600160801b038211614512578161451b565b6001600160801b035b92915050565b60405180604001604052806002906020820280368337509192915050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff811182821017156145765761457661453f565b60405290565b6040516060810167ffffffffffffffff811182821017156145765761457661453f565b604051610160810167ffffffffffffffff811182821017156145765761457661453f565b604051601f8201601f1916810167ffffffffffffffff811182821017156145ec576145ec61453f565b604052919050565b6001600160a01b0381168114614608575f80fd5b50565b80356132b7816145f4565b62ffffff81168114614608575f80fd5b80356132b781614616565b8060020b8114614608575f80fd5b80356132b781614631565b5f60a0828403121561465a575f80fd5b614662614553565b9050813561466f816145f4565b8152602082013561467f816145f4565b6020820152604082013561469281614616565b604082015260608201356146a581614631565b606082015260808201356146b8816145f4565b608082015292915050565b5f61016082840312156146d4575f80fd5b50919050565b5f8061020083850312156146ec575f80fd5b6146f6848461464a565b91506147058460a085016146c3565b90509250929050565b5f8151808452602084019350602083015f5b82811015614765578151865f5b600281101561474c57825182526020928301929091019060010161472d565b5050506040959095019460209190910190600101614720565b5093949350505050565b5f8151808452602084019350602083015f5b82811015614765576147a7868351805160020b8252602081015160020b60208301525050565b6040959095019460209190910190600101614781565b5f8151808452602084019350602083015f5b828110156147655781516001600160801b03168652602095860195909101906001016147cf565b5f8151808452602084019350602083015f5b828110156147655781515f815160020b8852602082015160020b6020890152604082015161484160408a01826001600160a01b03169052565b50606082015161485c60608a01826001600160a01b03169052565b50608082015161487760808a01826001600160801b03169052565b5060a082015160a089015260c082015160c089015260e082015160e089015261010082015191506148ad61010089018315159052565b5050610120959095019460209190910190600101614808565b80516001600160a01b031682525f60208201516148e8602085018260020b9052565b5060408201516148ff604085018262ffffff169052565b506060820151614916606085018262ffffff169052565b506080820151610120608085015261493261012085018261476f565b905060a083015184820360a086015261494b82826147bd565b91505060c083015184820360c086015261496582826147f6565b91505060e083015160e08501526101008301516101008501528091505092915050565b838152606060208201525f6149a0606083018561470e565b828103604084015261182481856148c6565b5f602082840312156149c2575f80fd5b8135611120816145f4565b602081525f61112060208301846147f6565b5f805f61022084860312156149f2575f80fd5b6149fc858561464a565b925060a0840135614a0c816145f4565b9150614a1b8560c086016146c3565b90509250925092565b8581528460208201528351151560408201526020840151606082015260408401516080820152606084015160a082015261010060c08201525f614a6b61010083018561470e565b82810360e0840152614a7d81856148c6565b98975050505050505050565b604081525f614a9b604083018561470e565b82810360208401526128ea81856148c6565b8015158114614608575f80fd5b80356132b781614aad565b5f60208284031215614ad5575f80fd5b813561112081614aad565b5f60a0828403128015614af1575f80fd5b50614afa614553565b8251614b05816145f4565b81526020830151614b15816145f4565b60208201526040830151614b2881614616565b60408201526060830151614b3b81614631565b60608201526080830151614b4e816145f4565b60808201529392505050565b5f67ffffffffffffffff821115614b7357614b7361453f565b5060051b60200190565b5f60408284031215614b8d575f80fd5b6040805190810167ffffffffffffffff81118282101715614bb057614bb061453f565b80604052508091508251614bc381614631565b81526020830151614bd381614631565b6020919091015292915050565b5f82601f830112614bef575f80fd5b8151614c02614bfd82614b5a565b6145c3565b80828252602082019150602060608402860101925085831115614c23575f80fd5b602085015b83811015614c835760608188031215614c3f575f80fd5b614c4761457c565b81516001600160801b0381168114614c5d575f80fd5b815260208281015181830152604080840151908301529084529290920191606001614c28565b5095945050505050565b5f8060408385031215614c9e575f80fd5b825167ffffffffffffffff811115614cb4575f80fd5b8301601f81018513614cc4575f80fd5b8051614cd2614bfd82614b5a565b8082825260208201915060208360061b850101925087831115614cf3575f80fd5b6020840193505b82841015614d1f57614d0c8885614b7d565b8252602082019150604084019350614cfa565b80955050505050602083015167ffffffffffffffff811115614d3f575f80fd5b614d4b85828601614be0565b9150509250929050565b5f60208284031215614d65575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761451b5761451b614d80565b8082018082111561451b5761451b614d80565b5f60208284031215614dce575f80fd5b813561112081614631565b5f610160828403128015614deb575f80fd5b50614df461459f565b614dfd8361460b565b8152614e0b6020840161463f565b6020820152614e1c60408401614626565b6040820152614e2d60608401614626565b6060820152614e3e60808401614626565b608082015260a0838101359082015260c08084013590820152614e6360e08401614aba565b60e0820152614e756101008401614aba565b6101008201526101208381013590820152610140928301359281019290925250919050565b5f60208284031215614eaa575f80fd5b813561112081614616565b634e487b7160e01b5f52601260045260245ffd5b5f8160020b8360020b80614edf57614edf614eb5565b627fffff1982145f1982141615614ef857614ef8614d80565b90059392505050565b5f8260020b80614f1357614f13614eb5565b808360020b0791505092915050565b5f8160020b627fffff198103614f3a57614f3a614d80565b5f190192915050565b5f8260020b8260020b028060020b9150808214614f6257614f62614d80565b5092915050565b5f82601f830112614f78575f80fd5b8151614f86614bfd82614b5a565b8082825260208201915060208360051b860101925085831115614fa7575f80fd5b602085015b83811015614c83578051614fbf81614631565b835260209283019201614fac565b5f8060408385031215614fde575f80fd5b825167ffffffffffffffff811115614ff4575f80fd5b61500085828601614f69565b925050602083015167ffffffffffffffff81111561501c575f80fd5b614d4b85828601614f69565b5f6080820162ffffff871683526080602084015280865180835260a0850191506020880192505f5b8181101561508c57615076838551805160020b8252602081015160020b60208301525050565b6020939093019260409290920191600101615050565b505080925050508360020b60408301528260020b606083015295945050505050565b5f80608083850312156150bf575f80fd5b6150c98484614b7d565b91506147058460408501614b7d565b8181038181111561451b5761451b614d80565b6001600160a01b03828116828216039081111561451b5761451b614d80565b5f8261511857615118614eb5565b500490565b5f806040838503121561512e575f80fd5b825161513981614aad565b6020939093015192949293505050565b5f8151808452602084019350602083015f5b8281101561476557815160020b86526020958601959091019060010161515b565b61016081525f61519061016083018e615149565b82810360208401526151a2818e615149565b9150508a60020b60408301528960020b606083015262ffffff8916608083015262ffffff881660a08301528660c08301528560e08301526151e861010083018615159052565b6151f861012083018560020b9052565b8215156101408301529c9b505050505050505050505050565b5f60208284031215615221575f80fd5b815167ffffffffffffffff811115615237575f80fd5b8201601f81018413615247575f80fd5b8051615255614bfd82614b5a565b8082825260208201915060208360051b850101925086831115615276575f80fd5b6020840193505b8284101561182457835182526020938401939091019061527d565b60a080825286519082018190525f90602088019060c0840190835b818110156152d15783518352602093840193909201916001016152b3565b505083810360208501526152e58189615149565b91505082810360408401526152fa8187615149565b9150508360020b606083015261182460808301841515905256fea264697066735822122029467c6c040220587f18a4c5765bf2d89282a5cc68702904541513baa2b4745364736f6c634300081a00330000000000000000000000001f98400000000000000000000000000000000004

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610085575f3560e01c8063a1a6f91a11610058578063a1a6f91a1461010b578063bf8f0d3a1461011e578063c6f6bf021461013f578063dc4c90d314610152575f80fd5b806319b4dc3f146100895780638d88ed9a146100b45780638dcce6eb146100d45780639f30033f146100e7575b5f80fd5b61009c6100973660046146da565b610191565b6040516100ab93929190614988565b60405180910390f35b6100c76100c23660046149b2565b61025a565b6040516100ab91906149cd565b61009c6100e23660046149df565b610644565b6100fa6100f53660046146da565b6106c5565b6040516100ab959493929190614a24565b6100fa6101193660046149df565b6107a2565b61013161012c3660046149df565b610857565b6040516100ab929190614a89565b61013161014d3660046146da565b6108ed565b6101797f0000000000000000000000001f9840000000000000000000000000000000000481565b6040516001600160a01b0390911681526020016100ab565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052906101fd60a085013560c08601356101f8610100880160e08901614ac5565b610997565b5f61023c61020c8760a0902090565b6001600160a01b037f0000000000000000000000001f984000000000000000000000000000000000041690610a16565b505050905061024c868287610ac8565b935093509350509250925092565b60605f826001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610299573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102bd9190614ae0565b90505f6102ce61020c8360a0902090565b50505090505f80856001600160a01b031663802758606040518163ffffffff1660e01b81526004015f60405180830381865afa158015610310573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526103379190810190614c8d565b91509150815167ffffffffffffffff8111156103555761035561453f565b6040519080825280602002602001820160405280156103ca57816020015b60408051610120810182525f8082526020808301829052928201819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015282525f199092019101816103735790505b5094505f866001600160a01b03166303e782816040518163ffffffff1660e01b8152600401602060405180830381865afa15801561040a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061042e9190614d55565b90505f5b83518110156106395783818151811061044d5761044d614d6c565b60200260200101515f015160020b5f148015610488575083818151811061047657610476614d6c565b60200260200101516020015160020b5f145b610631575f6104b28583815181106104a2576104a2614d6c565b60200260200101515f0151610d2a565b90505f6104db8684815181106104ca576104ca614d6c565b602002602001015160200151610d2a565b90505f806105078985858a89815181106104f7576104f7614d6c565b60200260200101515f0151610fef565b90925090505f610543836105246001600160a01b038d1680614d94565b780100000000000000000000000000000000000000000000000061108a565b90505f6105508383614dab565b90506040518061012001604052808b898151811061057057610570614d6c565b60200260200101515f015160020b81526020018b898151811061059557610595614d6c565b60200260200101516020015160020b8152602001876001600160a01b03168152602001866001600160a01b031681526020018a89815181106105d9576105d9614d6c565b60200260200101515f01516001600160801b031681526020018581526020018481526020018281526020018989101515158152508d888151811061061f5761061f614d6c565b60200260200101819052505050505050505b600101610432565b505050505050919050565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052906106ab60a085013560c08601356101f8610100880160e08901614ac5565b6106b6868686610ac8565b92509250925093509350939050565b5f806106f060405180608001604052805f151581526020015f81526020015f81526020015f81525090565b60606107516040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61076f60a087013560c08801356101f86101008a0160e08b01614ac5565b5f61077e61020c8960a0902090565b505050905061078e888289611127565b939c929b5090995097509095509350505050565b5f806107cd60405180608001604052805f151581526020015f81526020015f81526020015f81525090565b606061082e6040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61084c60a087013560c08801356101f86101008a0160e08b01614ac5565b61078e888888611127565b60606108b86040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b6108d660a084013560c08501356101f8610100870160e08801614ac5565b6108e1858585611216565b91509150935093915050565b606061094e6040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b61096c60a084013560c08501356101f8610100870160e08801614ac5565b5f61097b61020c8660a0902090565b505050905061098b858286611216565b92509250509250929050565b5f831580156109a4575082155b90505f846706f05b59d3b200001480156109c55750836706f05b59d3b20000145b9050811580156109d3575080155b156109f15760405163108cef9d60e31b815260040160405180910390fd5b82610a0f57604051631b9f988360e11b815260040160405180910390fd5b5050505050565b5f805f805f610a24866114ea565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa158015610a6c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a909190614d55565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b60408051610120810182525f8082526020820181905291810182905260608181018390526080820181905260a0820181905260c0820181905260e082018390526101008201839052905f610b1f60208601866149b2565b6001600160a01b031603610b4657604051631b6c707960e11b815260040160405180910390fd5b8361012001355f03610b6b5760405163162908e360e11b815260040160405180910390fd5b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528681526001600160a01b0386166020820152610bd486611526565b60020b6060820152610bfe610bef6040870160208801614dbe565b826060015189606001516117c3565b60020b60408201819052610c1690889088908861182e565b9350610c2a61012086016101008701614ac5565b610c345783610c3b565b8461012001355b6080820152610c5261012086016101008701614ac5565b610c6157846101200135610c63565b835b60a08201525f80610c8283610c7d368a90038a018a614dd9565b6119bd565b91509150610c9782828a8a6101400135611e01565b9450610ca660208801886149b2565b6001600160a01b0316845260408084015160020b6020860152610ccf9060608901908901614e9a565b62ffffff166040850152610ce96080880160608901614e9a565b62ffffff166060850152608080850183905260a0808601839052610d1e918a918791610d19918c01908c01614e9a565b611f33565b50505093509350939050565b60020b5f60ff82901d80830118620d89e8811115610d5357610d536345c3193d60e11b846121ca565b7001fffcb933bd6fad37aa2d162d1a5940016001821602700100000000000000000000000000000000186002821615610d9c576ffff97272373d413259a46990580e213a0260801c5b6004821615610dbb576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615610dda576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615610df9576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610e18576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610e37576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610e56576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610e76576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610e96576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610eb6576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610ed6576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610ef6576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610f16576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610f36576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610f56576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610f77576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610f97576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610fb6576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610fd3576b048a170391f7dc42444e8fa20260801c5b5f841315610fdf575f19045b63ffffffff0160201c9392505050565b5f80836001600160a01b0316856001600160a01b0316111561100f579293925b846001600160a01b0316866001600160a01b03161161103a576110338585856121d9565b9150611081565b836001600160a01b0316866001600160a01b031610156110735761105f8685856121d9565b915061106c85878561225c565b9050611081565b61107e85858561225c565b90505b94509492505050565b5f838302815f19858709828110838203039150508084116110a9575f80fd5b805f036110bb57508290049050611120565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150505b9392505050565b5f8061115260405180608001604052805f151581526020015f81526020015f81526020015f81525090565b60606111b36040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b5f6111c160208801886149b2565b6001600160a01b0316036111e857604051631b6c707960e11b815260040160405180910390fd5b6111f38888886122a5565b909650945092506112078888888888612434565b95999498509296509194505050565b60606112776040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b5f61128560208501856149b2565b6001600160a01b0316036112ac57604051631b6c707960e11b815260040160405180910390fd5b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528581526001600160a01b038516602082015261131585611526565b60020b606082015261133f6113306040860160208701614dbe565b826060015188606001516117c3565b60020b604080830191909152610100850135608083015261012085013560a0830152805161016081019091525f908061137b60208801886149b2565b6001600160a01b0316815260200186602001602081019061139c9190614dbe565b60020b81526020016113b46060880160408901614e9a565b62ffffff1681526020016113ce6080880160608901614e9a565b62ffffff1681526020016113e860a0880160808901614e9a565b62ffffff16815260a0870135602082015260c08701356040820152606001611417610100880160e08901614ac5565b1515815260016020820152610100870135604082015261014087013560609091015290505f8061144784846119bd565b9150915061145c82828a8a6101400135611e01565b955061146b60208801886149b2565b6001600160a01b0316855260408085015160020b60208701526114949060608901908901614e9a565b62ffffff1660408601526114ae6080880160608901614e9a565b62ffffff166060860152608080860183905260a08087018390526114de918a918891610d19918c01908c01614e9a565b50505050935093915050565b6040515f90611509908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b5f73fffd8963efd1fc6a506488495d951d51639616826401000276a21983016001600160a01b03161115611565576115656318521d4960e21b836126c9565b77ffffffffffffffffffffffffffffffffffffffff00000000602083901b16805f61158f826126de565b60ff169050608081106115aa57607f810383901c91506115b4565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c678000000000000000161760c19b909b1c674000000000000000169a909a1760c29990991c672000000000000000169890981760c39790971c671000000000000000169690961760c49590951c670800000000000000169490941760c59390931c670400000000000000169290921760c69190911c670200000000000000161760c79190911c670100000000000000161760c89190911c6680000000000000161760c99190911c6640000000000000161760ca9190911c6620000000000000161760cb9190911c6610000000000000161760cc9190911c6608000000000000161760cd9190911c66040000000000001617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b146117b457886001600160a01b031661179982610d2a565b6001600160a01b031611156117ae57816117b6565b806117b6565b815b9998505050505050505050565b5f80600285900b627fffff146117d957846117db565b835b90505f6117e88483614ec9565b90505f8260020b12801561180757506118018483614f01565b60020b15155b1561181a578061181681614f22565b9150505b6118248482614f43565b9695505050505050565b5f6118686040518060c001604052806060815260200160608152602001606081526020015f60020b81526020015f81526020015f81525090565b61187185611526565b60020b60608201525f61188760208501856149b2565b90506001600160a01b0381166340b71404866118a96060880160408901614e9a565b6118b96080890160608a01614e9a565b60608c01516118cf6101008b0160e08c01614ac5565b60405160e087901b7fffffffff00000000000000000000000000000000000000000000000000000000168152600295860b600482015262ffffff948516602482015292909316604483015290920b60648301521515608482015260a4015f60405180830381865afa158015611946573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261196d9190810190614fcd565b60208401528252606087015161198a908290849087908990612769565b604083015261199982876128f3565b60a08401819052608084018290526119b2918691612a07565b979650505050505050565b6060805f604051806101400160405280855f01516001600160a01b03168152602001866040015160020b8152602001856040015162ffffff168152602001856060015162ffffff168152602001855f01516001600160a01b031681526020018560a0015181526020018560c0015181526020018560e0015115158152602001856080015162ffffff1681526020018560a001515f148015611a60575060c0860151155b151581525090505f80611a85875f01518489608001518a60a001518b60200151612a62565b6080880151919350915062ffffff1615611df0575f8073a198f4da67f3b6735f178779673e062ed287ad7863522179138960800151868c5f0151606001518d606001516040518563ffffffff1660e01b8152600401611ae79493929190615028565b608060405180830381865af4158015611b02573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611b2691906150ae565b9150915083516002611b389190614dab565b67ffffffffffffffff811115611b5057611b5061453f565b604051908082528060200260200182016040528015611b9457816020015b604080518082019091525f8082526020820152815260200190600190039081611b6e5790505b50965083516002611ba59190614dab565b67ffffffffffffffff811115611bbd57611bbd61453f565b604051908082528060200260200182016040528015611be6578160200160208202803683370190505b5095505f5b8451811015611c7757848181518110611c0657611c06614d6c565b6020026020010151888281518110611c2057611c20614d6c565b6020026020010181905250838181518110611c3d57611c3d614d6c565b6020026020010151878281518110611c5757611c57614d6c565b6001600160801b0390921660209283029190910190910152600101611beb565b505f80611c9386868d602001518e608001518f60a00151612a92565b915091508389875181518110611cab57611cab614d6c565b6020026020010181905250828987516001611cc69190614dab565b81518110611cd657611cd6614d6c565b6020026020010181905250836020015160020b845f015160020b14158015611cfd57505f81115b15611d5e57611d2a8b60200151611d16865f0151610d2a565b611d238760200151610d2a565b5f85612b49565b88875181518110611d3d57611d3d614d6c565b60200260200101906001600160801b031690816001600160801b0316815250505b826020015160020b835f015160020b14158015611d7a57505f82115b15611de757611da78b60200151611d93855f0151610d2a565b611da08660200151610d2a565b855f612b49565b8887516001611db69190614dab565b81518110611dc657611dc6614d6c565b60200260200101906001600160801b031690816001600160801b0316815250505b50505050611df7565b8194508093505b5050509250929050565b6060845167ffffffffffffffff811115611e1d57611e1d61453f565b604051908082528060200260200182016040528015611e5657816020015b611e43614521565b815260200190600190039081611e3b5790505b5090505f611e66836127106150d8565b90505f5b8651811015611f29575f611e898883815181106104a2576104a2614d6c565b90505f611ea18984815181106104ca576104ca614d6c565b90505f80611eca8985858d8981518110611ebd57611ebd614d6c565b6020026020010151610fef565b915091506040518060400160405280611ee6848961271061108a565b8152602001611ef8838961271061108a565b815250878681518110611f0d57611f0d614d6c565b6020026020010181905250505050508080600101915050611e6a565b5050949350505050565b81608001515167ffffffffffffffff811115611f5157611f5161453f565b604051908082528060200260200182016040528015611fc657816020015b60408051610120810182525f8082526020808301829052928201819052606082018190526080820181905260a0820181905260c0820181905260e0820181905261010082015282525f19909201910181611f6f5790505b5060c08301525f60e08301819052610100830181905262ffffff821615801590611ff65750600283608001515110155b61200557826080015151612017565b600283608001515161201791906150d8565b90505f5b836080015151811015610a0f575f612042856080015183815181106104a2576104a2614d6c565b90505f61205e866080015184815181106104ca576104ca614d6c565b90505f8061207e8985858b60a001518981518110611ebd57611ebd614d6c565b90925090505f61209b836105246001600160a01b038d1680614d94565b6120a59083614dab565b90506040518061012001604052808a6080015188815181106120c9576120c9614d6c565b60200260200101515f015160020b81526020018a6080015188815181106120f2576120f2614d6c565b60200260200101516020015160020b8152602001866001600160a01b03168152602001856001600160a01b031681526020018a60a00151888151811061213a5761213a614d6c565b60200260200101516001600160801b031681526020018481526020018381526020018281526020018888101515158152508960c00151878151811061218157612181614d6c565b6020026020010181905250828960e00181815161219e9190614dab565b905250610100890180518391906121b6908390614dab565b905250506001909401935061201b92505050565b815f528060020b60045260245ffd5b5f826001600160a01b0316846001600160a01b031611156121f8579192915b6001600160a01b03841661224a7bffffffffffffffffffffffffffffffff000000000000000000000000606085901b1661223287876150eb565b6001600160a01b0316866001600160a01b031661108a565b612254919061510a565b949350505050565b5f826001600160a01b0316846001600160a01b0316111561227b579192915b6122546001600160801b03831661229286866150eb565b6001600160a01b0316600160601b61108a565b6122ce60405180608001604052805f151581526020015f81526020015f81526020015f81525090565b5f805f6122da86611526565b90505f6122fb6122f06040880160208901614dbe565b838a606001516117c3565b905061235561230d60208801886149b2565b8261231e60608a0160408b01614e9a565b61232e60808b0160608c01614e9a565b60608d01516123446101008d0160e08e01614ac5565b8d898e60a001358f60c00135612bfe565b6060870181905260408088018390525163103e311760e31b8152610100890135600482015261012089013560248201526001600160a01b038a166044820152606481019290925260848201527385d9c453d937379d91e986fb48b4bc08d479e958906381f188b89060a4016040805180830381865af41580156123da573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123fe919061511d565b6020870181905290151580875261242391610100890135916101208a0135918b612c26565b959990985094965093945050505050565b60606124956040518061012001604052805f6001600160a01b031681526020015f60020b81526020015f62ffffff1681526020015f62ffffff1681526020016060815260200160608152602001606081526020015f81526020015f81525090565b60408051610160810182525f60c0820181905260e08201819052610100820181905261012082018190526101408201819052918101829052606081018290526080810182905260a08101919091528781526001600160a01b03871660208201526124fe87611526565b60020b60608201526125286125196040880160208901614dbe565b82606001518a606001516117c3565b60020b6040808301919091526080820186905260a08201859052805161016081019091525f908061255c60208a018a6149b2565b6001600160a01b0316815260200188602001602081019061257d9190614dbe565b60020b815260200161259560608a0160408b01614e9a565b62ffffff1681526020016125af60808a0160608b01614e9a565b62ffffff1681526020016125c960a08a0160808b01614e9a565b62ffffff16815260a0890135602082015260c089013560408201526060016125f86101008a0160e08b01614ac5565b15158152600160208201526040810188905261014089013560609091015290505f8061262484846119bd565b9150915061263982828c8c6101400135611e01565b955061264860208a018a6149b2565b6001600160a01b0316855260408085015160020b60208701526126719060608b01908b01614e9a565b62ffffff16604086015261268b60808a0160608b01614e9a565b62ffffff166060860152608080860183905260a08087018390526126bb918c918891610d19918e01908e01614e9a565b505050509550959350505050565b815f526001600160a01b03811660045260245ffd5b5f8082116126ea575f80fd5b507f0706060506020500060203020504000106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be6001600160801b03841160071b84811c67ffffffffffffffff1060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b60605f60a0850135158015612780575060c0850135155b90505f876001600160a01b0316631b7c6141885f015189602001518a60600151898b60400160208101906127b49190614e9a565b6127c460808e0160608f01614e9a565b8d60a001358e60c001358f60e00160208101906127e19190614ac5565b8e8d6040518c63ffffffff1660e01b81526004016128099b9a9998979695949392919061517c565b5f60405180830381865afa158015612823573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261284a9190810190615211565b875160208901519192507385d9c453d937379d91e986fb48b4bc08d479e9589163db021467918491886128846101008d0160e08e01614ac5565b6040518663ffffffff1660e01b81526004016128a4959493929190615298565b5f60405180830381865af41580156128be573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128e59190810190615211565b925050505b95945050505050565b5f805f5b8451518110156129ff575f612927865f0151838151811061291a5761291a614d6c565b6020026020010151610d2a565b90505f6129438760200151848151811061291a5761291a614d6c565b90505f8061295b888585670de0b6b3a7640000610fef565b91509150670de0b6b3a76400008960400151868151811061297e5761297e614d6c565b6020026020010151836129919190614d94565b61299b919061510a565b6129a59088614dab565b9650670de0b6b3a7640000896040015186815181106129c6576129c6614d6c565b6020026020010151826129d99190614d94565b6129e3919061510a565b6129ed9087614dab565b955050600190930192506128f7915050565b509250929050565b5f612a1a61012085016101008601614ac5565b15612a4457825f03612a2d57505f611120565b612a3d846101200135838561108a565b9050611120565b815f03612a5257505f611120565b612254846101200135848461108a565b6060805f612a71888886612ce1565b805193509050612a85818989898989612f89565b9150509550959350505050565b5f805f805f5b8951811015612b0a575f80612ae38a612abc8e86815181106104a2576104a2614d6c565b612ad18f87815181106104ca576104ca614d6c565b8e8781518110611ebd57611ebd614d6c565b9092509050612af28286614dab565b9450612afe8185614dab565b93505050600101612a98565b50818611612b18575f612b22565b612b2282876150d8565b9350808511612b31575f612b3b565b612b3b81866150d8565b925050509550959350505050565b5f836001600160a01b0316856001600160a01b03161115612b68579293925b846001600160a01b0316866001600160a01b031611612b9357612b8c858585612faf565b90506128ea565b836001600160a01b0316866001600160a01b03161015612bf3575f612bb9878686612faf565b90505f612bc7878986613017565b9050806001600160801b0316826001600160801b031610612be85780612bea565b815b925050506128ea565b611824858584613017565b5f80612c128c8c8c8c8c8c8c8c8c8c61304c565b915091505b9a509a98505050505050505050565b5f80835f03612c39575085905084612cd7565b8415612c8f575f612c6f612c5b86866001600160a01b0316600160601b61108a565b856001600160a01b0316600160601b61108a565b9050612c7b85896150d8565b9250612c878188614dab565b915050612cd7565b5f612cbf612cab86600160601b876001600160a01b031661108a565b600160601b866001600160a01b031661108a565b9050612ccb8189614dab565b9250612a8585886150d8565b9550959350505050565b60408051808201909152606080825260208201525f612cff83611526565b606080870151608087015160208801516040808a0151948a015160e08b0151915163102dc50160e21b8152600293840b600482015262ffffff9687166024820152951660448601529083900b606485015215156084840152929350915f9182916001600160a01b0316906340b714049060a4015f60405180830381865afa158015612d8c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612db39190810190614fcd565b91509150815167ffffffffffffffff811115612dd157612dd161453f565b604051908082528060200260200182016040528015612e1557816020015b604080518082019091525f8082526020820152815260200190600190039081612def5790505b5085525f5b8251811015612e98576040518060400160405280848381518110612e4057612e40614d6c565b602002602001015160020b8152602001838381518110612e6257612e62614d6c565b602002602001015160020b815250865f01518281518110612e8557612e85614d6c565b6020908102919091010152600101612e1a565b5060408051610140810182526060808252602082018190525f92820183905281018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101919091528281526020808201839052600286810b604080850191909152918a0151810b606080850191909152918a015162ffffff908116608080860191909152928b01511660a0808501919091528a015160c0808501919091528a015160e0808501919091528a0151151561010084015285900b610120808401919091529089015190890151612f779190839061307a565b60208701525093979650505050505050565b60606119b2875f015188602001518686868a61012001518c606001518c60e001516131b9565b5f826001600160a01b0316846001600160a01b03161115612fce579192915b5f612ff0856001600160a01b0316856001600160a01b0316600160601b61108a565b90506128ea613012848361300489896150eb565b6001600160a01b031661108a565b61325a565b5f826001600160a01b0316846001600160a01b03161115613036579192915b61225461301283600160601b61300488886150eb565b5f808315158061305b57508215155b1561306a575082905081612c17565b612c128c8c8c8c8c8c8c8c6132bc565b60605f846001600160a01b0316631b7c6141855f015186602001518760400151886060015189608001518a60a001518b60c001518c60e001518d61010001518e61012001518e6040518c63ffffffff1660e01b81526004016130e69b9a9998979695949392919061517c565b5f60405180830381865afa158015613100573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526131279190810190615211565b8451602086015161012087015161010088015160405163db02146760e01b81529495507385d9c453d937379d91e986fb48b4bc08d479e9589463db0214679461317894889491939092600401615298565b5f60405180830381865af4158015613192573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526128ea9190810190615211565b6060885167ffffffffffffffff8111156131d5576131d561453f565b6040519080825280602002602001820160405280156131fe578160200160208202803683370190505b5090505f6040518060c00160405280898152602001888152602001876001600160a01b0316815260200186151581526020018560020b8152602001841515815250905061324d828a8c8461349a565b5098975050505050505050565b806001600160801b03811681146132b75760405162461bcd60e51b815260206004820152601260248201527f6c6971756964697479206f766572666c6f770000000000000000000000000000604482015260640160405180910390fd5b919050565b60408051610100810182526001600160a01b038a811680835260028b810b6020850181905262ffffff8c8116868801819052908c16606087018190528b840b608088018190528b151560a08901819052968b1660c08901529389900b60e0880152965163102dc50160e21b8152600481019290925260248201526044810195909552606485015260848401919091525f9283929183918291906340b714049060a4015f60405180830381865afa158015613378573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261339f9190810190614fcd565b9150915081515f036133c1576706f05b59d3b20000809450945050505061348d565b5f806133ce8585856136a3565b91509150815f1480156133df575080155b156133fc576706f05b59d3b200008096509650505050505061348d565b5f61342c613418848c6001600160a01b0316600160601b61108a565b8b6001600160a01b0316600160601b61108a565b90505f6134398383614dab565b9050805f0361345c576706f05b59d3b2000080985098505050505050505061348d565b61346f82670de0b6b3a76400008361108a565b985061348389670de0b6b3a76400006150d8565b9750505050505050505b9850989650505050505050565b81515f8190036134aa575061369d565b6134ea6040518060e0016040528060608152602001606081526020015f81526020015f81526020015f81526020015f60020b81526020015f151581525090565b8167ffffffffffffffff8111156135035761350361453f565b60405190808252806020026020018201604052801561352c578160200160208202803683370190505b5081528167ffffffffffffffff8111156135485761354861453f565b604051908082528060200260200182016040528015613571578160200160208202803683370190505b506020820152604083015161358590611526565b60020b60a082015260408301516135a4908290869088905f60016137be565b6135bb81845f015185602001518660600151613a14565b826060015180156135cd57508060c001515b156135e1576135e181858560400151613c05565b5f5b82811015613699575f6136018683815181106104a2576104a2614d6c565b90505f6136198784815181106104ca576104ca614d6c565b905061366586604001518383875f0151878151811061363a5761363a614d6c565b60200260200101518860200151888151811061365857613658614d6c565b6020026020010151612b49565b89848151811061367757613677614d6c565b6001600160801b039092166020928302919091019091015250506001016135e3565b5050505b50505050565b5f805f6136b1868686613cb2565b90506136c881868689608001518a60a00151613d51565b60c08701518651919250905f5b818110156114de575f6136f389838151811061291a5761291a614d6c565b90505f61370b89848151811061291a5761291a614d6c565b90505f80613723878585670de0b6b3a7640000610fef565b91509150670de0b6b3a764000088868151811061374257613742614d6c565b6020026020010151836137559190614d94565b61375f919061510a565b613769908b614dab565b9950670de0b6b3a764000088868151811061378657613786614d6c565b6020026020010151826137999190614d94565b6137a3919061510a565b6137ad908a614dab565b9850846001019450505050506136d5565b84515f8084156137df576137d184613ddd565b91506137dc84613dfe565b90505b5f5b83811015613a08575f6137ff8a83815181106104a2576104a2614d6c565b90505f6138178b84815181106104ca576104ca614d6c565b90505f8061382f8b8585670de0b6b3a7640000610fef565b9150915061385f828d878151811061384957613849614d6c565b6020026020010151670de0b6b3a764000061108a565b8e5180518790811061387357613873614d6c565b602002602001018181525050613895818d878151811061384957613849614d6c565b8e6020015186815181106138ab576138ab614d6c565b60209081029190910101528d518051869081106138ca576138ca614d6c565b60200260200101518e6040018181516138e39190614dab565b90525060208e01518051869081106138fd576138fd614d6c565b60200260200101518e6060018181516139169190614dab565b915081815250508d60a0015160020b8d868151811061393757613937614d6c565b60200260200101515f015160020b1315801561397957508c858151811061396057613960614d6c565b60200260200101516020015160020b8e60a0015160020b125b156139f95789801561398b5750600188115b80156139b857508660020b8d86815181106139a8576139a8614d6c565b60200260200101515f015160020b145b80156139e657508560020b8d86815181106139d5576139d5614d6c565b60200260200101516020015160020b145b6139f95760808e01859052600160c08f01525b846001019450505050506137e1565b50505050505050505050565b8351518115613af557604085015115613a85575f5b81811015613a8357613a5c865f01518281518110613a4957613a49614d6c565b602002602001015186886040015161108a565b8651805183908110613a7057613a70614d6c565b6020908102919091010152600101613a29565b505b606085015115613af0575f5b81811015613aee57613ac586602001518281518110613ab257613ab2614d6c565b602002602001015185886060015161108a565b86602001518281518110613adb57613adb614d6c565b6020908102919091010152600101613a91565b505b610a0f565b5f85604001515f03613b08575f19613b1f565b613b1f85670de0b6b3a7640000886040015161108a565b90505f86606001515f03613b34575f19613b4b565b613b4b85670de0b6b3a7640000896060015161108a565b90505f818310613b5b5781613b5d565b825b90505f5b84811015613bfa57613b98895f01518281518110613b8157613b81614d6c565b602002602001015183670de0b6b3a764000061108a565b8951805183908110613bac57613bac614d6c565b602002602001018181525050613bd189602001518281518110613b8157613b81614d6c565b89602001518281518110613be757613be7614d6c565b6020908102919091010152600101613b61565b505050505050505050565b5f613c2e8484866080015181518110613c2057613c20614d6c565b602002602001015184613e16565b90508060400151845f0151856080015181518110613c4e57613c4e614d6c565b60200260200101818152505080606001518460200151856080015181518110613c7957613c79614d6c565b6020908102919091010152805115613c9957613c998484835f015161417b565b60208101511561369d5761369d8484836020015161428c565b6060835f01516001600160a01b0316631b7c614184848760e00151886020015189604001518a606001515f808d60a001518e6080015160016040518c63ffffffff1660e01b8152600401613d109b9a9998979695949392919061517c565b5f60405180830381865afa158015613d2a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526122549190810190615211565b6060811580613d5f57508551155b80613d6c57508351855114155b15613d785750846128ea565b5f613d8284613ddd565b90505f613d8e85613dfe565b90505f613d9d8888858561438c565b90505f198103613db2578893505050506128ea565b8851600103613dc6578893505050506128ea565b613dd08982614409565b5096979650505050505050565b5f81600281900b620d89e71981613df657613df6614eb5565b050292915050565b5f81600281900b620d89e881613df657613df6614eb5565b613e3d60405180608001604052805f81526020015f81526020015f81526020015f81525090565b608084015183515f90613e4f90610d2a565b90505f613e5f8660200151610d2a565b90505f826001600160a01b0316866001600160a01b03161115613eb157613eae88602001518581518110613e9557613e95614d6c565b6020026020010151600160601b858961300491906150eb565b90505b5f836001600160a01b0316876001600160a01b031611613f6c575f895f01518681518110613ee157613ee1614d6c565b6020026020010151118015613f075750836001600160a01b0316836001600160a01b0316115b15613f65575f613f2e846001600160a01b0316866001600160a01b0316600160601b61108a565b9050613f5d8a5f01518781518110613f4857613f48614d6c565b602002602001015182878761300491906150eb565b9150506140ab565b505f6140ab565b5f836001600160a01b0316886001600160a01b0316108015613f8d57505f83115b15614028575f613fb4856001600160a01b03168a6001600160a01b0316600160601b61108a565b9050805f03614006575f613fe485613fcc8c896150eb565b6001600160a01b0316886001600160a01b031661108a565b9050613ffe81600160601b8c6001600160a01b031661108a565b925050614026565b614023846140148b886150eb565b6001600160a01b03168361108a565b91505b505b808a5f0151878151811061403e5761403e614d6c565b602002602001015110156140a5575f61406e856001600160a01b03168a6001600160a01b0316600160601b61108a565b905061409d8b5f0151888151811061408857614088614d6c565b6020026020010151828b8861300491906150eb565b9250506140a9565b8291505b505b6140bf8785856140ba856144fd565b610fef565b60608801526040870181905289518051879081106140df576140df614d6c565b6020026020010151116140f2575f61411d565b6040860151895180518790811061410b5761410b614d6c565b602002602001015161411d91906150d8565b8652606086015160208a015180518790811061413b5761413b614d6c565b60200260200101511161414e575f612f77565b85606001518960200151868151811061416957614169614d6c565b6020026020010151612f7791906150d8565b8251515f90815b818110156141ea578560a0015160020b8582815181106141a4576141a4614d6c565b60200260200101515f015160020b13156141e25785518051829081106141cc576141cc614d6c565b6020026020010151836141df9190614dab565b92505b600101614182565b508115610a0f575f5b81811015614284578560a0015160020b85828151811061421557614215614d6c565b60200260200101515f015160020b131561427c5761425084875f0151838151811061424257614242614d6c565b60200260200101518561108a565b865180518390811061426457614264614d6c565b602002602001018181516142789190614dab565b9052505b6001016141f3565b505050505050565b8251515f90815b818110156142fd578560a0015160020b8582815181106142b5576142b5614d6c565b60200260200101516020015160020b136142f557856020015181815181106142df576142df614d6c565b6020026020010151836142f29190614dab565b92505b600101614293565b508115610a0f575f5b81811015614284578560a0015160020b85828151811061432857614328614d6c565b60200260200101516020015160020b1361438457614356848760200151838151811061424257614242614d6c565b8660200151828151811061436c5761436c614d6c565b602002602001018181516143809190614dab565b9052505b600101614306565b83515f90815b818110156143fc578460020b8782815181106143b0576143b0614d6c565b602002602001015160020b1480156143e657508360020b8682815181106143d9576143d9614d6c565b602002602001015160020b145b156143f45791506122549050565b600101614392565b505f199695505050505050565b81515f03614415575050565b5f805b8351811015614458578083146144505783818151811061443a5761443a614d6c565b60200260200101518261444d9190614dab565b91505b600101614418565b50805f03614484575f83838151811061447357614473614d6c565b602002602001018181525050505050565b5f5b83518110156144e9578083146144e1576144c28482815181106144ab576144ab614d6c565b6020026020010151670de0b6b3a76400008461108a565b8482815181106144d4576144d4614d6c565b6020026020010181815250505b600101614486565b505f83838151811061447357614473614d6c565b5f6001600160801b038211614512578161451b565b6001600160801b035b92915050565b60405180604001604052806002906020820280368337509192915050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff811182821017156145765761457661453f565b60405290565b6040516060810167ffffffffffffffff811182821017156145765761457661453f565b604051610160810167ffffffffffffffff811182821017156145765761457661453f565b604051601f8201601f1916810167ffffffffffffffff811182821017156145ec576145ec61453f565b604052919050565b6001600160a01b0381168114614608575f80fd5b50565b80356132b7816145f4565b62ffffff81168114614608575f80fd5b80356132b781614616565b8060020b8114614608575f80fd5b80356132b781614631565b5f60a0828403121561465a575f80fd5b614662614553565b9050813561466f816145f4565b8152602082013561467f816145f4565b6020820152604082013561469281614616565b604082015260608201356146a581614631565b606082015260808201356146b8816145f4565b608082015292915050565b5f61016082840312156146d4575f80fd5b50919050565b5f8061020083850312156146ec575f80fd5b6146f6848461464a565b91506147058460a085016146c3565b90509250929050565b5f8151808452602084019350602083015f5b82811015614765578151865f5b600281101561474c57825182526020928301929091019060010161472d565b5050506040959095019460209190910190600101614720565b5093949350505050565b5f8151808452602084019350602083015f5b82811015614765576147a7868351805160020b8252602081015160020b60208301525050565b6040959095019460209190910190600101614781565b5f8151808452602084019350602083015f5b828110156147655781516001600160801b03168652602095860195909101906001016147cf565b5f8151808452602084019350602083015f5b828110156147655781515f815160020b8852602082015160020b6020890152604082015161484160408a01826001600160a01b03169052565b50606082015161485c60608a01826001600160a01b03169052565b50608082015161487760808a01826001600160801b03169052565b5060a082015160a089015260c082015160c089015260e082015160e089015261010082015191506148ad61010089018315159052565b5050610120959095019460209190910190600101614808565b80516001600160a01b031682525f60208201516148e8602085018260020b9052565b5060408201516148ff604085018262ffffff169052565b506060820151614916606085018262ffffff169052565b506080820151610120608085015261493261012085018261476f565b905060a083015184820360a086015261494b82826147bd565b91505060c083015184820360c086015261496582826147f6565b91505060e083015160e08501526101008301516101008501528091505092915050565b838152606060208201525f6149a0606083018561470e565b828103604084015261182481856148c6565b5f602082840312156149c2575f80fd5b8135611120816145f4565b602081525f61112060208301846147f6565b5f805f61022084860312156149f2575f80fd5b6149fc858561464a565b925060a0840135614a0c816145f4565b9150614a1b8560c086016146c3565b90509250925092565b8581528460208201528351151560408201526020840151606082015260408401516080820152606084015160a082015261010060c08201525f614a6b61010083018561470e565b82810360e0840152614a7d81856148c6565b98975050505050505050565b604081525f614a9b604083018561470e565b82810360208401526128ea81856148c6565b8015158114614608575f80fd5b80356132b781614aad565b5f60208284031215614ad5575f80fd5b813561112081614aad565b5f60a0828403128015614af1575f80fd5b50614afa614553565b8251614b05816145f4565b81526020830151614b15816145f4565b60208201526040830151614b2881614616565b60408201526060830151614b3b81614631565b60608201526080830151614b4e816145f4565b60808201529392505050565b5f67ffffffffffffffff821115614b7357614b7361453f565b5060051b60200190565b5f60408284031215614b8d575f80fd5b6040805190810167ffffffffffffffff81118282101715614bb057614bb061453f565b80604052508091508251614bc381614631565b81526020830151614bd381614631565b6020919091015292915050565b5f82601f830112614bef575f80fd5b8151614c02614bfd82614b5a565b6145c3565b80828252602082019150602060608402860101925085831115614c23575f80fd5b602085015b83811015614c835760608188031215614c3f575f80fd5b614c4761457c565b81516001600160801b0381168114614c5d575f80fd5b815260208281015181830152604080840151908301529084529290920191606001614c28565b5095945050505050565b5f8060408385031215614c9e575f80fd5b825167ffffffffffffffff811115614cb4575f80fd5b8301601f81018513614cc4575f80fd5b8051614cd2614bfd82614b5a565b8082825260208201915060208360061b850101925087831115614cf3575f80fd5b6020840193505b82841015614d1f57614d0c8885614b7d565b8252602082019150604084019350614cfa565b80955050505050602083015167ffffffffffffffff811115614d3f575f80fd5b614d4b85828601614be0565b9150509250929050565b5f60208284031215614d65575f80fd5b5051919050565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b808202811582820484141761451b5761451b614d80565b8082018082111561451b5761451b614d80565b5f60208284031215614dce575f80fd5b813561112081614631565b5f610160828403128015614deb575f80fd5b50614df461459f565b614dfd8361460b565b8152614e0b6020840161463f565b6020820152614e1c60408401614626565b6040820152614e2d60608401614626565b6060820152614e3e60808401614626565b608082015260a0838101359082015260c08084013590820152614e6360e08401614aba565b60e0820152614e756101008401614aba565b6101008201526101208381013590820152610140928301359281019290925250919050565b5f60208284031215614eaa575f80fd5b813561112081614616565b634e487b7160e01b5f52601260045260245ffd5b5f8160020b8360020b80614edf57614edf614eb5565b627fffff1982145f1982141615614ef857614ef8614d80565b90059392505050565b5f8260020b80614f1357614f13614eb5565b808360020b0791505092915050565b5f8160020b627fffff198103614f3a57614f3a614d80565b5f190192915050565b5f8260020b8260020b028060020b9150808214614f6257614f62614d80565b5092915050565b5f82601f830112614f78575f80fd5b8151614f86614bfd82614b5a565b8082825260208201915060208360051b860101925085831115614fa7575f80fd5b602085015b83811015614c83578051614fbf81614631565b835260209283019201614fac565b5f8060408385031215614fde575f80fd5b825167ffffffffffffffff811115614ff4575f80fd5b61500085828601614f69565b925050602083015167ffffffffffffffff81111561501c575f80fd5b614d4b85828601614f69565b5f6080820162ffffff871683526080602084015280865180835260a0850191506020880192505f5b8181101561508c57615076838551805160020b8252602081015160020b60208301525050565b6020939093019260409290920191600101615050565b505080925050508360020b60408301528260020b606083015295945050505050565b5f80608083850312156150bf575f80fd5b6150c98484614b7d565b91506147058460408501614b7d565b8181038181111561451b5761451b614d80565b6001600160a01b03828116828216039081111561451b5761451b614d80565b5f8261511857615118614eb5565b500490565b5f806040838503121561512e575f80fd5b825161513981614aad565b6020939093015192949293505050565b5f8151808452602084019350602083015f5b8281101561476557815160020b86526020958601959091019060010161515b565b61016081525f61519061016083018e615149565b82810360208401526151a2818e615149565b9150508a60020b60408301528960020b606083015262ffffff8916608083015262ffffff881660a08301528660c08301528560e08301526151e861010083018615159052565b6151f861012083018560020b9052565b8215156101408301529c9b505050505050505050505050565b5f60208284031215615221575f80fd5b815167ffffffffffffffff811115615237575f80fd5b8201601f81018413615247575f80fd5b8051615255614bfd82614b5a565b8082825260208201915060208360051b850101925086831115615276575f80fd5b6020840193505b8284101561182457835182526020938401939091019061527d565b60a080825286519082018190525f90602088019060c0840190835b818110156152d15783518352602093840193909201916001016152b3565b505083810360208501526152e58189615149565b91505082810360408401526152fa8187615149565b9150508360020b606083015261182460808301841515905256fea264697066735822122029467c6c040220587f18a4c5765bf2d89282a5cc68702904541513baa2b4745364736f6c634300081a0033

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

0000000000000000000000001f98400000000000000000000000000000000004

-----Decoded View---------------
Arg [0] : _poolManager (address): 0x1F98400000000000000000000000000000000004

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 0000000000000000000000001f98400000000000000000000000000000000004


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

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.