ETH Price: $2,948.62 (+1.24%)

Contract

0xC67E3b0Df66Eef48aE9f58aCBE9c7399169575Ee

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
384875582026-01-24 6:25:177 hrs ago1769235917
0xC67E3b0D...9169575Ee
 Contract Creation0 ETH

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RebalancerFactory

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

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

import {IRelayerFactory} from "./interfaces/IRelayerFactory.sol";
import {IRelayer} from "./interfaces/IRelayer.sol";
import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {IMultiPositionFactory} from "./interfaces/IMultiPositionFactory.sol";
import {RebalancerDeployer} from "./RebalancerDeployer.sol";
import {MultiPositionManager} from "./MultiPositionManager.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {VolatilityDynamicFeeLimitOrderHook} from "../LimitOrderBook/hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "../LimitOrderBook/libraries/VolatilityOracle.sol";

/**
 * @title RelayerFactory
 * @notice Factory for deploying Relayer contracts
 * @dev Manages role-based access control for automation services
 */
contract RebalancerFactory is IRelayerFactory, Ownable {
    using PoolIdLibrary for PoolKey;

    /// @notice Role identifier for automation services
    bytes32 public constant AUTOMATION_SERVICE_ROLE = keccak256("AUTOMATION_SERVICE");

    /// @notice Reference to MultiPositionFactory for role management
    IMultiPositionFactory public immutable multiPositionFactory;

    /// @notice Deployer contract for Relayer
    RebalancerDeployer public immutable deployer;

    /// @notice Role storage: role => account => hasRole
    mapping(bytes32 => mapping(address => bool)) private _roles;

    /// @notice Deployed relayer info: relayer address => RelayerInfo
    mapping(address => RelayerInfo) public relayers;

    /// @notice Relayer by MultiPositionManager: mpm => relayer address (1:1 mapping)
    mapping(address => address) public relayerByManager;

    /// @notice Relayers by owner: owner => relayer addresses
    mapping(address => address[]) public relayersByOwner;

    /// @notice All deployed rebalancers (for pagination)
    address[] private allRelayers;

    /// @notice Protocol fee for automated management (denominator: 10 = 10%)
    /// @dev Retained for interface compatibility; not applied automatically.
    uint16 public automatedManagementFee = 10;

    /// @notice Minimum ETH balance required for relayer execution
    uint256 public minBalance = 0.00001 ether;

    /**
     * @notice Construct the RelayerFactory
     * @param _owner The factory owner address
     * @param _multiPositionFactory The MultiPositionFactory for role management
     */
    constructor(address _owner, IMultiPositionFactory _multiPositionFactory) Ownable(_owner) {
        if (_owner == address(0)) revert InvalidAddress();
        if (address(_multiPositionFactory) == address(0)) revert InvalidAddress();
        multiPositionFactory = _multiPositionFactory;
        deployer = new RebalancerDeployer(address(this));
    }

    /**
     * @notice Validate TWAP configuration for a pool
     * @param mpm The MultiPositionManager address
     * @param triggerConfig Trigger configuration to validate
     * @param strategyParams Strategy parameters to validate
     * @param twapParams TWAP parameters to validate
     * @dev Reverts if TWAP configuration is invalid or incompatible
     */
    function _validateTwapConfig(
        address mpm,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.TwapParams calldata twapParams
    ) private view {
        // Skip if TWAP not used
        if (!twapParams.useTwapProtection && !twapParams.useTwapCenter && triggerConfig.baseTwapTickTrigger == 0) {
            return;
        }

        // Get poolKey from MPM
        MultiPositionManager manager = MultiPositionManager(payable(mpm));
        PoolKey memory poolKey = manager.poolKey();

        // Check 1: Pool must be managed by Unilaunch volatility hook
        address hookAddress = address(poolKey.hooks);
        if (hookAddress == address(0)) revert IRelayer.PoolNotManagedByVolatilityHook();

        // Try to cast and check managedPools - will revert if not a VolatilityDynamicFeeHook
        try VolatilityDynamicFeeLimitOrderHook(hookAddress).managedPools(poolKey.toId()) returns (bool isManaged) {
            if (!isManaged) revert IRelayer.PoolNotManagedByVolatilityHook();
        } catch {
            revert IRelayer.PoolNotManagedByVolatilityHook();
        }

        // Check 2: Verify TWAP history availability via oracle
        VolatilityDynamicFeeLimitOrderHook hook = VolatilityDynamicFeeLimitOrderHook(hookAddress);
        VolatilityOracle oracle = hook.volatilityOracle();

        // Validate TWAP history exists for requested period
        try oracle.consult(poolKey, twapParams.twapSeconds) returns (int24, uint128) {
            // TWAP data available
        } catch {
            revert IRelayer.TwapHistoryUnavailable();
        }

        // Check 3: Enforce mutual exclusivity between baseTickTrigger and baseTwapTickTrigger
        bool hasBaseTrigger = (triggerConfig.baseLowerTrigger != 0 || triggerConfig.baseUpperTrigger != 0);
        bool hasTwapTrigger = (triggerConfig.baseTwapTickTrigger != 0);
        if (hasBaseTrigger && hasTwapTrigger) revert IRelayer.MutuallyExclusiveTriggers();

        // Check 4: Prevent useTwapCenter when isBaseRatio=true
        if (twapParams.useTwapCenter && strategyParams.isBaseRatio) {
            revert IRelayer.InvalidTwapConfig();
        }

        // Check 5: Prevent baseTwapTickTrigger when isBaseRatio=true
        if (hasTwapTrigger && strategyParams.isBaseRatio) {
            revert IRelayer.InvalidTwapConfig();
        }

        // Validate twapSeconds is reasonable (not 0, not too large)
        if (twapParams.twapSeconds == 0) revert IRelayer.InvalidTwapConfig();
        if (twapParams.twapSeconds > 7 days) revert IRelayer.InvalidTwapConfig();

        // Validate maxTickDeviation if protection enabled
        if (twapParams.useTwapProtection && twapParams.maxTickDeviation == 0) {
            revert IRelayer.InvalidTwapConfig();
        }
    }

    /**
     * @notice Deploy a new Relayer contract
     * @param mpm The MultiPositionManager to automate
     * @param triggerConfig Initial trigger configuration
     * @param strategyParams Initial strategy parameters
     * @param volatilityParams Volatility parameters for this token pair
     * @param withdrawalParams Initial withdrawal trigger parameters
     * @param compoundSwapParams Initial compound swap trigger parameters
     * @param twapParams TWAP-based protection and centering parameters
     * @return relayer Address of the deployed Relayer
     * @dev Creates a new relayer owned by msg.sender
     * @dev Optionally send ETH to fund the relayer for gas reimbursements
     */
    function deployRelayer(
        address mpm,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external payable override returns (address relayer) {
        if (msg.value < minBalance) revert InsufficientPayment();

        if (mpm == address(0)) revert InvalidAddress();

        // Enforce 1:1 relayer per manager for DDOS protection
        if (relayerByManager[mpm] != address(0)) revert RelayerAlreadyExists();

        // Get the owner of the MultiPositionManager (cast to MultiPositionManager to access Ownable.owner())
        address mpmOwner = MultiPositionManager(payable(mpm)).owner();

        // Only the MPM owner can deploy a relayer for their manager
        if (msg.sender != mpmOwner) revert UnauthorizedAccess();

        // Validate weights: either both 0 (proportional) or sum to 1e18
        _validateWeights(strategyParams.weight0, strategyParams.weight1);

        _validateStrategyParams(strategyParams);

        // Validate TWAP configuration
        _validateTwapConfig(mpm, triggerConfig, strategyParams, twapParams);

        // Deploy new Relayer using deployer contract
        relayer = deployer.deploy(
            mpm,
            address(this),
            mpmOwner,
            triggerConfig,
            strategyParams,
            volatilityParams,
            withdrawalParams,
            compoundSwapParams,
            twapParams
        );

        // Fund relayer if ETH was sent
        if (msg.value > 0) {
            (bool success,) = relayer.call{value: msg.value}("");
            if (!success) revert InvalidAddress(); // Reuse existing error
        }

        // Store relayer info
        relayers[relayer] = RelayerInfo({
            relayerAddress: relayer,
            multiPositionManager: mpm,
            owner: mpmOwner,
            deployedAt: block.timestamp
        });

        // Track by manager (1:1 mapping)
        relayerByManager[mpm] = relayer;

        // Track by owner
        relayersByOwner[mpmOwner].push(relayer);

        // Track globally
        allRelayers.push(relayer);

        emit RelayerDeployed(relayer, mpm, mpmOwner);

        return relayer;
    }

    /**
     * @notice Compute the address where a Relayer will be deployed
     * @param mpm The MultiPositionManager to automate
     * @param owner The owner of the new Relayer
     * @param triggerConfig Initial trigger configuration
     * @param strategyParams Initial strategy parameters
     * @param volatilityParams Volatility parameters for this token pair
     * @param withdrawalParams Initial withdrawal trigger parameters
     * @param compoundSwapParams Initial compound swap trigger parameters
     * @param twapParams TWAP-based protection and centering parameters
     * @return predicted The predicted address of the Relayer
     * @dev Useful for granting roles before deployment
     * @dev Uses CREATE2 for deterministic address computation
     */
    function computeRelayerAddress(
        address mpm,
        address owner,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external view returns (address predicted) {
        return deployer.computeAddress(
            mpm,
            address(this),
            owner,
            triggerConfig,
            strategyParams,
            volatilityParams,
            withdrawalParams,
            compoundSwapParams,
            twapParams
        );
    }

    /**
     * @notice Check if an account has a specific role
     * @param role The role identifier
     * @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 Check if an account has a specific role or is the owner
     * @param role The role identifier
     * @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 Grant a role to an account
     * @param role The role to grant
     * @param account The account to grant the role to
     * @dev Only callable by owner
     */
    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 Revoke a role from an account
     * @param role The role to revoke
     * @param account The account to revoke the role from
     * @dev Only callable by owner
     */
    function revokeRole(bytes32 role, address account) external override onlyOwner {
        if (_roles[role][account]) {
            _roles[role][account] = false;
            emit RoleRevoked(role, account, msg.sender);
        }
    }

    function setMinBalance(uint256 newMinBalance) external onlyOwner {
        if (newMinBalance == 0) revert InvalidAddress();
        uint256 oldMinBalance = minBalance;
        minBalance = newMinBalance;
        emit MinBalanceUpdated(oldMinBalance, newMinBalance);
    }

    /**
     * @notice Set the automated management fee for relayers
     * @param _fee The new fee (denominator: 10 = 10%)
     * @dev Retained for interface compatibility; not applied automatically.
     */
    function setAutomatedManagementFee(uint16 _fee) external {
        if (!multiPositionFactory.hasRole(multiPositionFactory.FEE_MANAGER(), msg.sender)) revert UnauthorizedAccess();
        if (_fee == 0) revert InvalidAddress();
        automatedManagementFee = _fee;
    }

    /**
     * @notice Get information about a specific relayer
     * @param relayer The relayer address
     * @return info RelayerInfo struct
     */
    function getRelayerInfo(address relayer) external view override returns (RelayerInfo memory info) {
        info = relayers[relayer];
        if (info.relayerAddress == address(0)) revert InvalidAddress();
        return info;
    }

    /**
     * @notice Get the relayer for a specific MultiPositionManager
     * @param mpm The MultiPositionManager address
     * @return relayerAddress The relayer address (address(0) if none exists)
     */
    function getRelayerByManager(address mpm) external view override returns (address relayerAddress) {
        return relayerByManager[mpm];
    }

    /**
     * @notice Get all relayers owned by a specific address
     * @param ownerAddress The owner address
     * @return relayersArray Array of relayer addresses
     */
    function getRelayersByOwner(address ownerAddress) external view override returns (address[] memory relayersArray) {
        return relayersByOwner[ownerAddress];
    }

    /**
     * @notice Get all deployed relayers with pagination
     * @param offset Starting index
     * @param limit Maximum number to return (0 for all remaining)
     * @return relayersInfo Array of RelayerInfo structs
     * @return totalCount Total number of deployed relayers
     */
    function getAllRelayersPaginated(uint256 offset, uint256 limit)
        external
        view
        override
        returns (RelayerInfo[] memory relayersInfo, uint256 totalCount)
    {
        totalCount = allRelayers.length;

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

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

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

        relayersInfo = new RelayerInfo[](count);

        for (uint256 i = 0; i < count;) {
            address relayerAddr = allRelayers[offset + i];
            relayersInfo[i] = relayers[relayerAddr];
            unchecked {
                ++i;
            }
        }

        return (relayersInfo, totalCount);
    }

    /**
     * @notice Get total count of deployed relayers
     * @return count Total number of relayers
     */
    function getTotalRelayersCount() external view override returns (uint256 count) {
        return allRelayers.length;
    }

    /**
     * @notice Get all unique token pairs from automated MultiPositionManagers with pagination
     * @param offset Starting index
     * @param limit Maximum number to return (0 for all)
     * @return tokenPairs Array of unique TokenPairInfo structs
     * @return totalCount Total number of unique token pairs
     * @dev Iterates through all relayers, extracts unique token pairs from their managers
     */
    function getUniqueTokenPairs(uint256 offset, uint256 limit)
        external
        view
        override
        returns (TokenPairInfo[] memory tokenPairs, uint256 totalCount)
    {
        // First pass: collect all unique token pairs
        // Using a simple approach: store pairs in memory and check for duplicates
        TokenPairInfo[] memory tempPairs = new TokenPairInfo[](allRelayers.length);
        uint256 uniqueCount = 0;

        for (uint256 i = 0; i < allRelayers.length;) {
            address relayerAddr = allRelayers[i];
            IRelayer relayer = IRelayer(payable(relayerAddr));
            IMultiPositionManager mpm = relayer.manager();

            // Get pool key from manager
            PoolKey memory poolKey = mpm.poolKey();
            address token0 = Currency.unwrap(poolKey.currency0);
            address token1 = Currency.unwrap(poolKey.currency1);

            // Check if this pair already exists in our temp array
            bool isDuplicate = false;
            for (uint256 j = 0; j < uniqueCount;) {
                if (tempPairs[j].token0Address == token0 && tempPairs[j].token1Address == token1) {
                    isDuplicate = true;
                    break;
                }
                unchecked {
                    ++j;
                }
            }

            if (!isDuplicate) {
                // Get symbols
                string memory symbol0 = _getTokenSymbol(token0);
                string memory symbol1 = _getTokenSymbol(token1);

                // Get decimals
                uint8 decimals0 = _getTokenDecimals(token0);
                uint8 decimals1 = _getTokenDecimals(token1);

                tempPairs[uniqueCount] = TokenPairInfo({
                    token0Symbol: symbol0,
                    token0Address: token0,
                    token1Symbol: symbol1,
                    token1Address: token1,
                    token0Decimals: decimals0,
                    token1Decimals: decimals1
                });
                unchecked {
                    ++uniqueCount;
                }
            }

            unchecked {
                ++i;
            }
        }

        totalCount = uniqueCount;

        // Handle pagination
        if (limit == 0) {
            limit = totalCount;
        }

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

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

        tokenPairs = new TokenPairInfo[](count);

        for (uint256 i = 0; i < count;) {
            tokenPairs[i] = tempPairs[offset + i];
            unchecked {
                ++i;
            }
        }

        return (tokenPairs, totalCount);
    }

    /**
     * @notice Helper function to get token symbol
     * @param token The token address
     * @return symbol Token symbol
     */
    function _getTokenSymbol(address token) private view returns (string memory symbol) {
        if (token == address(0)) {
            return "ETH";
        }
        return IERC20Metadata(token).symbol();
    }

    /**
     * @notice Helper function to get token decimals
     * @param token The token address
     * @return decimals Token decimals
     */
    function _getTokenDecimals(address token) private view returns (uint8 decimals) {
        if (token == address(0)) {
            return 18;
        }
        return IERC20Metadata(token).decimals();
    }

    /**
     * @notice Validate weight parameters
     * @param w0 Weight for token0
     * @param w1 Weight for token1
     * @dev Weights must either both be 0 (proportional mode) or sum to 1e18
     */
    function _validateWeights(uint256 w0, uint256 w1) private pure {
        // Proportional mode: both weights must be 0
        bool isProportional = (w0 == 0 && w1 == 0);
        bool isFiftyFifty = (w0 == 0.5e18 && w1 == 0.5e18);
        if (!isProportional && !isFiftyFifty) {
            revert InvalidWeightSum();
        }
    }

    /**
     * @notice Validate withdrawal params for invalid combinations
     * @param params The withdrawal params to validate
     * @dev Prevents invalid configurations that would fail or behave incorrectly
     */
    /**
     * @notice Validate strategy params to prevent perpetual rebalancing
     * @param params The strategy params to validate
     * @dev If isBaseRatio=true and proportional mode, must use swap to fix ratio imbalance
     */
    function _validateStrategyParams(IRelayer.StrategyParams calldata params) private pure {
        // If isBaseRatio=true and proportional mode (weight0=0, weight1=0), must use swap
        // Otherwise: perpetual rebalancing (ratio trigger fires, rebalances proportionally, ratio still wrong, triggers again)
        bool isProportional = (params.weight0 == 0 && params.weight1 == 0);
        if (params.isBaseRatio && isProportional && !params.useRebalanceSwap) {
            revert InvalidAddress(); // Reuse existing error
        }
    }
}

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

import {IRelayer} from "./IRelayer.sol";
import {IMultiPositionFactory} from "./IMultiPositionFactory.sol";

interface IRelayerFactory {
    /// @notice Get the automation service role identifier
    /// @return The role hash
    function AUTOMATION_SERVICE_ROLE() external pure returns (bytes32);

    /// @notice Get the MultiPositionFactory address
    /// @return The MultiPositionFactory interface
    function multiPositionFactory() external view returns (IMultiPositionFactory);

    /// @notice Information about a deployed relayer
    struct RelayerInfo {
        address relayerAddress;
        address multiPositionManager;
        address owner;
        uint256 deployedAt;
    }

    /// @notice Token pair information
    struct TokenPairInfo {
        string token0Symbol;
        address token0Address;
        string token1Symbol;
        address token1Address;
        uint8 token0Decimals;
        uint8 token1Decimals;
    }

    // Events
    event RelayerDeployed(address indexed relayer, address indexed multiPositionManager, address indexed owner);
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
    event MinBalanceUpdated(uint256 oldMinBalance, uint256 newMinBalance);

    // Errors
    error InvalidAddress();
    error UnauthorizedAccess();
    error RelayerAlreadyExists();
    error InsufficientPayment();
    error InvalidWeightSum();

    /// @notice Deploy a new Relayer contract
    /// @param mpm The MultiPositionManager to automate
    /// @param triggerConfig Initial trigger configuration
    /// @param strategyParams Initial strategy parameters
    /// @param volatilityParams Volatility parameters for this token pair
    /// @param withdrawalParams Initial withdrawal trigger parameters
    /// @param compoundSwapParams Initial compound swap trigger parameters
    /// @param twapParams TWAP-based protection and centering parameters
    /// @return relayer Address of the deployed Relayer
    /// @dev Optionally send ETH to fund the relayer for gas reimbursements
    function deployRelayer(
        address mpm,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external payable returns (address relayer);

    /// @notice Compute the address where a Relayer will be deployed
    /// @param mpm The MultiPositionManager to automate
    /// @param owner The owner of the new Relayer
    /// @param triggerConfig Initial trigger configuration
    /// @param strategyParams Initial strategy parameters
    /// @param volatilityParams Volatility parameters for this token pair
    /// @param withdrawalParams Initial withdrawal trigger parameters
    /// @param compoundSwapParams Initial compound swap trigger parameters
    /// @param twapParams TWAP-based protection and centering parameters
    /// @return predicted The predicted address of the Relayer
    /// @dev Useful for granting roles before deployment (uses CREATE2)
    function computeRelayerAddress(
        address mpm,
        address owner,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external view returns (address predicted);

    /// @notice Check if an account has a specific role
    /// @param role The role identifier
    /// @param account The account to check
    /// @return True if the account has the role
    function hasRole(bytes32 role, address account) external view returns (bool);

    /// @notice Check if an account has a specific role or is the owner
    /// @param role The role identifier
    /// @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 returns (bool);

    /// @notice Grant a role to an account (owner only)
    /// @param role The role to grant
    /// @param account The account to grant the role to
    function grantRole(bytes32 role, address account) external;

    /// @notice Revoke a role from an account (owner only)
    /// @param role The role to revoke
    /// @param account The account to revoke the role from
    function revokeRole(bytes32 role, address account) external;

    /// @notice Get the automated management fee
    /// @return The fee denominator (10 = 10%)
    function automatedManagementFee() external view returns (uint16);

    /// @notice Get the minimum ETH balance required for relayer execution
    /// @return The minimum balance amount in wei
    function minBalance() external view returns (uint256);

    /// @notice Set the automated management fee
    /// @param _fee The new fee (denominator: 10 = 10%)
    function setAutomatedManagementFee(uint16 _fee) external;

    /// @notice Set the minimum ETH balance required for relayer execution (owner only)
    /// @param newMinBalance The new minimum balance amount in wei
    function setMinBalance(uint256 newMinBalance) external;

    /// @notice Get information about a specific relayer
    /// @param relayer The relayer address
    /// @return info RelayerInfo struct
    function getRelayerInfo(address relayer) external view returns (RelayerInfo memory info);

    /// @notice Get the relayer for a specific MultiPositionManager
    /// @param mpm The MultiPositionManager address
    /// @return relayer The relayer address (address(0) if none exists)
    function getRelayerByManager(address mpm) external view returns (address relayer);

    /// @notice Get all relayers owned by a specific address
    /// @param owner The owner address
    /// @return relayers Array of relayer addresses
    function getRelayersByOwner(address owner) external view returns (address[] memory relayers);

    /// @notice Get all deployed relayers with pagination
    /// @param offset Starting index
    /// @param limit Maximum number to return (0 for all)
    /// @return relayersInfo Array of RelayerInfo structs
    /// @return totalCount Total number of deployed relayers
    function getAllRelayersPaginated(uint256 offset, uint256 limit)
        external
        view
        returns (RelayerInfo[] memory relayersInfo, uint256 totalCount);

    /// @notice Get total count of deployed relayers
    /// @return count Total number of relayers
    function getTotalRelayersCount() external view returns (uint256 count);

    /// @notice Get all unique token pairs from automated MultiPositionManagers with pagination
    /// @param offset Starting index
    /// @param limit Maximum number to return (0 for all)
    /// @return tokenPairs Array of unique TokenPairInfo structs
    /// @return totalCount Total number of unique token pairs
    function getUniqueTokenPairs(uint256 offset, uint256 limit)
        external
        view
        returns (TokenPairInfo[] memory tokenPairs, uint256 totalCount);
}

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

import {IMultiPositionManager} from "./IMultiPositionManager.sol";
import {IRelayerFactory} from "./IRelayerFactory.sol";
import {RebalanceLogic} from "../libraries/RebalanceLogic.sol";

interface IRelayer {
    /// @notice TWAP-based protection and centering parameters
    struct TwapParams {
        bool useTwapProtection; // Check if current price deviates too far from TWAP (revert if exceeded)
        bool useTwapCenter; // Center new positions around TWAP tick instead of current tick
        uint32 twapSeconds; // TWAP period in seconds (e.g., 1800 = 30 minutes)
        uint24 maxTickDeviation; // Maximum allowed tick deviation from TWAP
    }

    /// @notice Configuration for rebalance triggers
    struct TriggerConfig {
        // Tick-based triggers (absolute deviation from centerTick of last rebalance)
        uint24 baseLowerTrigger; // Tick deviation threshold below center for base trigger (e.g., 50 ticks)
        uint24 baseUpperTrigger; // Tick deviation threshold above center for base trigger (e.g., 50 ticks)
        uint24 limitDeltaTicks; // Tick deviation threshold for limit trigger (e.g., 30 ticks)
        uint24 maxDeltaTicks; // Maximum allowed tick deviation (flashloan/depeg protection)
        // TWAP-based base trigger (mutually exclusive with baseLowerTrigger/baseUpperTrigger)
        uint24 baseTwapTickTrigger; // Tick deviation threshold from last rebalance centerTick for TWAP-based trigger
        // Ratio-based triggers
        uint256 baseMinRatio; // Minimum base0Ratio (1e18 = 100%)
        uint256 baseMaxRatio; // Maximum base0Ratio (1e18 = 100%)
        uint256 limitMinRatio; // Minimum conversion ratio to trigger (e.g., 0.8e18 = 80% converted)
        uint256 limitThreshold; // Prerequisite: limitRatio must exceed this (e.g., 0.2e18 = 20%)
        // Global triggers
        uint256 outOfPositionThreshold; // Trigger when outOfPositionRatio exceeds this (e.g., 0.05e18 = 5%)
    }

    /// @notice Strategy parameters for rebalance execution
    struct StrategyParams {
        uint24 ticksLeft; // Left tick range from center
        uint24 ticksRight; // Right tick range from center
        bool useCarpet; // Whether to use full-range floor
        uint24 limitWidth; // Width for limit positions
        address strategy; // Strategy contract address
        uint256 weight0; // Weight for token0 (weight0 = 0, weight1 = 0 means proportional mode)
        uint256 weight1; // Weight for token1 (sum of weights should be 1e18 if not proportional)
        bool isolatedBaseLimitRebalancing; // If true, limit rebalances independently; if false, coupled
        bool useRebalanceSwap; // If true, uses rebalanceSwap; if false, uses rebalance
        bool isBaseRatio; // If true, enables base ratio triggers
        bool compoundFees; // If true, fees compound into positions; if false, fees claimed to owner before rebalance
    }

    /// @notice Statistics tracking for the relayer
    struct RelayerStats {
        uint256 totalGasSpent; // Cumulative gas costs paid out (in wei)
        uint256 ethBalance; // Current ETH balance for reimbursements
    }

    /// @notice Information about which rebalance triggers are currently met
    struct RebalanceTriggerStatus {
        bool baseTickTrigger;
        bool baseTwapTickTrigger; // TWAP-based base trigger
        bool baseRatioTrigger;
        bool limitTickTrigger;
        bool limitRatioTrigger;
        bool outOfPositionTrigger;
        bool anyTriggerMet; // True if any trigger is met
    }

    /// @notice Configuration for withdrawal triggers
    struct WithdrawalParams {
        uint256 pool0RatioThreshold; // Trigger when pool0Ratio >= this (1e18 = 100%, 0 = disabled)
        uint256 pool1RatioThreshold; // Trigger when pool1Ratio >= this (1e18 = 100%, 0 = disabled)
        bool withdrawAll; // If true, withdraw all tokens (full withdrawal)
        bool withdrawToken0Only; // If true, withdraw only token0 and rebalance with token1
        bool withdrawToken1Only; // If true, withdraw only token1 and rebalance with token0
    }

    /// @notice Configuration for compound swap triggers
    struct CompoundSwapParams {
        uint256 outOfPositionRatioThreshold; // Trigger when outOfPositionRatio >= this (1e18 = 100%, 0 = disabled)
    }

    /// @notice Token pair information
    struct TokenInfo {
        string token0Symbol;
        string token1Symbol;
        address token0Address;
        address token1Address;
        uint8 decimals0;
        uint8 decimals1;
        string token0CoingeckoId;
        string token1CoingeckoId;
    }

    /// @notice Volatility parameters for the token pair
    /// @dev Used for monitoring and volatility-aware strategies
    struct VolatilityParams {
        string geckoIdToken0; // Coingecko ID for token0 (empty string if not applicable)
        string geckoIdToken1; // Coingecko ID for token1 (empty string if not applicable)
        uint8 pairType; // 0=stable-stable, 1=forex/LST, 2=narrow volatile, 3=wide volatile
    }

    /// @notice Consolidated state for all relayer configuration and status
    /// @dev Consolidates all config structs and operational state into single storage struct
    struct RelayerState {
        TriggerConfig triggerConfig; // Current trigger configuration
        StrategyParams strategyParams; // Current strategy parameters
        VolatilityParams volatilityParams; // Volatility parameters for this token pair
        WithdrawalParams withdrawalParams; // Withdrawal trigger parameters
        CompoundSwapParams compoundSwapParams; // Compound swap trigger parameters
        TwapParams twapParams; // TWAP parameters for this relayer
        bool isPaused; // Whether the contract is paused
        uint256 totalGasSpent; // Cumulative gas costs paid out (in wei)
    }

    // Events
    // triggerIndex: 0=baseTickTrigger, 1=baseTwapTickTrigger, 2=baseRatioTrigger, 3=limitTickTrigger, 4=limitRatioTrigger, 5=outOfPositionTrigger
    event AutomatedRebalanceExecuted(uint8 triggerIndex, bool isSwap);
    event AutomatedCompoundExecuted(
        uint256 outOfPositionRatio, uint256 outOfPositionRatioThreshold, address indexed mpm
    );
    event AutomatedWithdrawalExecuted(bool pool0Triggered, bool pool1Triggered, address indexed mpm);
    event TriggersUpdated(address indexed updater);
    event Paused(address indexed pauser);
    event Unpaused(address indexed unpauser);
    event VolatilityParamsUpdated(string geckoIdToken0, string geckoIdToken1, uint8 pairType);
    event TwapProtectionTriggered(int24 currentTick, int24 twapTick, uint24 deviation);
    event TwapCenterUsed(int24 twapTick, uint32 twapSeconds);

    // Errors
    error UnauthorizedCaller();
    error ContractPaused();
    error NoTriggersmet();
    error InsufficientFunds();
    error InvalidTriggerConfig();
    error TransferFailed();
    error NotPaused();
    error InvalidPairType();
    error InvalidWithdrawalParams();
    error TwapHistoryUnavailable();
    error TwapDeviationExceeded();
    error InvalidTwapConfig();
    error MutuallyExclusiveTriggers();
    error PoolNotManagedByVolatilityHook();

    // Core execution functions
    function executeRebalance(uint256[2][] memory outMin, uint256[2][] memory inMin) external;

    function executeRebalanceSwap(
        RebalanceLogic.SwapParams calldata swapParams,
        uint256[2][] memory outMin,
        uint256[2][] memory inMin
    ) external payable;

    function executeCompoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
        external
        payable;

    // View functions
    function getRebalanceParams()
        external
        view
        returns (
            TriggerConfig memory triggerConfig,
            StrategyParams memory strategyParams,
            VolatilityParams memory volatilityParams,
            TwapParams memory twapParams
        );
    // function getTriggerConfig() external view returns (TriggerConfig memory);
    // function getStrategyParams() external view returns (StrategyParams memory);
    // function getStats() external view returns (RelayerStats memory);
    // function estimateRebalancesLeft(uint256 estimatedGasPerRebalance) external view returns (uint256);
    // function getVolatilityParams() external view returns (VolatilityParams memory);
    function getWithdrawalParams() external view returns (WithdrawalParams memory);
    function getCompoundSwapParams() external view returns (CompoundSwapParams memory);
    function manager() external view returns (IMultiPositionManager);
    function factory() external view returns (IRelayerFactory);
    function owner() external view returns (address);
    function isPaused() external view returns (bool);
    function minBalance() external view returns (uint256);

    // Owner functions
    // function updateTriggers(TriggerConfig calldata newConfig) external;
    // function updateStrategyParams(StrategyParams calldata newParams) external;
    // function updateVolatilityParams(VolatilityParams calldata newParams) external;
    function setRebalanceParams(
        TriggerConfig calldata triggerConfig,
        StrategyParams calldata strategyParams,
        VolatilityParams calldata volatilityParams,
        TwapParams calldata twapParams
    ) external;
    function setWithdrawalParams(WithdrawalParams calldata newParams) external;
    function setCompoundSwapParams(CompoundSwapParams calldata newParams) external;
    function executeWithdrawal(uint256[2][] memory outMin) external;
    function pause() external;
    function unpause() external;
    function fundContract() external payable;
    function withdrawFunds(uint256 amount) external;
//     function withdrawAllFunds() external;
}

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

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 {Rebalancer} from "./Rebalancer.sol";
import {IRelayer} from "./interfaces/IRelayer.sol";

/// @title RebalancerDeployer
/// @notice Deploys Rebalancer contracts using CREATE2
contract RebalancerDeployer {
    address public immutable authorizedFactory;

    error UnauthorizedCaller();

    constructor(address _authorizedFactory) {
        authorizedFactory = _authorizedFactory;
    }

    function deploy(
        address mpm,
        address factory,
        address owner,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external returns (address) {
        if (msg.sender != authorizedFactory) revert UnauthorizedCaller();
        bytes32 salt = keccak256(abi.encodePacked(mpm, owner));
        return address(
            new Rebalancer{salt: salt}(
                mpm,
                factory,
                owner,
                triggerConfig,
                strategyParams,
                volatilityParams,
                withdrawalParams,
                compoundSwapParams,
                twapParams
            )
        );
    }

    function computeAddress(
        address mpm,
        address factory,
        address owner,
        IRelayer.TriggerConfig calldata triggerConfig,
        IRelayer.StrategyParams calldata strategyParams,
        IRelayer.VolatilityParams calldata volatilityParams,
        IRelayer.WithdrawalParams calldata withdrawalParams,
        IRelayer.CompoundSwapParams calldata compoundSwapParams,
        IRelayer.TwapParams calldata twapParams
    ) external view returns (address predicted) {
        bytes32 hash = keccak256(
            abi.encodePacked(
                type(Rebalancer).creationCode,
                abi.encode(
                    mpm,
                    factory,
                    owner,
                    triggerConfig,
                    strategyParams,
                    volatilityParams,
                    withdrawalParams,
                    compoundSwapParams,
                    twapParams
                )
            )
        );

        predicted = address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), address(this), keccak256(abi.encodePacked(mpm, owner)), hash)))));
    }
}

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

File 10 of 85 : 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 {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 {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 {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: 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;
    }
}

File 16 of 85 : 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: 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 18 of 85 : 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.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;
}

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

import {IRelayer} from "./interfaces/IRelayer.sol";
import {IMultiPositionManager} from "./interfaces/IMultiPositionManager.sol";
import {IRelayerFactory} from "./interfaces/IRelayerFactory.sol";
import {RebalanceLogic} from "./libraries/RebalanceLogic.sol";
import {RelayerLogic} from "./libraries/RelayerLogic.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {VolatilityDynamicFeeLimitOrderHook} from "../LimitOrderBook/hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "../LimitOrderBook/libraries/VolatilityOracle.sol";

/**
 * @title Relayer
 * @notice Automated relayer for MultiPositionManager with trigger-based execution
 * @dev Executes rebalances and withdrawals when configured triggers are met, reimburses automation services in ETH
 */
contract Rebalancer is IRelayer, ReentrancyGuard {
    using PoolIdLibrary for PoolKey;

    /// @notice Role identifier for automation services (must match factory)
    bytes32 private constant AUTOMATION_SERVICE_ROLE = keccak256("AUTOMATION_SERVICE");

    /// @notice Gas overhead for reimbursement calculation (covers ETH transfer and base tx cost)
    uint256 private constant BASE_GAS_OVERHEAD = 21000 + 10000; // Base tx + ETH transfer overhead

    /// @notice Gas buffer multiplier (1.1x = 110/100 = 10% buffer)
    uint256 private constant GAS_BUFFER_NUMERATOR = 110;
    uint256 private constant GAS_BUFFER_DENOMINATOR = 100;

    /// @notice OP Stack GasPriceOracle predeploy (used for L1 data fee)
    address private constant GAS_PRICE_ORACLE = address(0x420000000000000000000000000000000000000F);
    bytes4 private constant GET_L1_FEE_SELECTOR = bytes4(keccak256("getL1Fee(bytes)"));

    /// @notice The MultiPositionManager being automated
    IMultiPositionManager public immutable manager;

    /// @notice The factory that deployed this contract
    IRelayerFactory public immutable factory;

    /// @notice Consolidated state containing all configuration and operational data
    /// @dev Using internal visibility removes auto-generated getters, saving ~800-1,200 bytes
    RelayerState internal state;

    /// @notice Restrict access to current MPM owner only
    modifier onlyOwner() {
        if (msg.sender != _mpmOwner()) revert UnauthorizedCaller();
        _;
    }

    /// @notice Restrict access to automation services only
    modifier onlyAutomationService() {
        if (!factory.hasRole(AUTOMATION_SERVICE_ROLE, msg.sender)) {
            revert UnauthorizedCaller();
        }
        _;
    }

    /// @notice Ensure contract is not paused
    modifier whenNotPaused() {
        if (state.isPaused) revert ContractPaused();
        _;
    }

    /**
     * @notice Construct a new Rebalancer
     * @param _manager The MultiPositionManager to automate
     * @param _factory The factory that deployed this contract
     * @param _owner The owner of this rebalancer
     * @param _triggerConfig Initial trigger configuration
     * @param _strategyParams Initial strategy parameters
     * @param _volatilityParams Volatility parameters for this token pair
     * @param _withdrawalParams Initial withdrawal trigger parameters
     * @param _compoundSwapParams Initial compound swap trigger parameters
     * @param _twapParams TWAP-based protection and centering parameters
     * @dev Automatically rounds delta values UP to nearest tickSpacing multiple for accuracy
     */
    constructor(
        address _manager,
        address _factory,
        address _owner,
        TriggerConfig memory _triggerConfig,
        StrategyParams memory _strategyParams,
        VolatilityParams memory _volatilityParams,
        WithdrawalParams memory _withdrawalParams,
        CompoundSwapParams memory _compoundSwapParams,
        TwapParams memory _twapParams
    ) {
        if (_manager == address(0)) revert InvalidTriggerConfig();
        if (_factory == address(0)) revert InvalidTriggerConfig();
        if (_owner == address(0)) revert InvalidTriggerConfig();

        manager = IMultiPositionManager(_manager);
        factory = IRelayerFactory(_factory);
        // Note: owner is now dynamic via _mpmOwner(), _owner param kept for factory validation

        // Round up delta values to tickSpacing multiples before storing
        int24 tickSpacing = manager.poolKey().tickSpacing;
        _triggerConfig.baseLowerTrigger = _roundUpToTickSpacing(_triggerConfig.baseLowerTrigger, tickSpacing);
        _triggerConfig.baseUpperTrigger = _roundUpToTickSpacing(_triggerConfig.baseUpperTrigger, tickSpacing);
        _triggerConfig.limitDeltaTicks = _roundUpToTickSpacing(_triggerConfig.limitDeltaTicks, tickSpacing);
        _triggerConfig.maxDeltaTicks = _roundUpToTickSpacing(_triggerConfig.maxDeltaTicks, tickSpacing);

        // Validate delta constraints
        _validateDeltas(
            _triggerConfig.baseLowerTrigger,
            _triggerConfig.baseUpperTrigger,
            _triggerConfig.limitDeltaTicks,
            _triggerConfig.maxDeltaTicks
        );

        // Validate weights
        _validateWeights(_strategyParams.weight0, _strategyParams.weight1);
        if (!_strategyParams.useCarpet) revert InvalidTriggerConfig();

        // If isBaseRatio=true and proportional mode (weight0=0, weight1=0), must use swap
        // Otherwise: perpetual rebalancing (ratio trigger fires, rebalances proportionally, ratio still wrong, triggers again)
        bool isProportional = (_strategyParams.weight0 == 0 && _strategyParams.weight1 == 0);
        if (_strategyParams.isBaseRatio && isProportional && !_strategyParams.useRebalanceSwap) {
            revert InvalidTriggerConfig();
        }

        // Validate pairType
        if (_volatilityParams.pairType > 3) revert InvalidPairType();

        // Validate TWAP configuration
        _validateTwapParams(_twapParams, _triggerConfig, _strategyParams);

        // Assign all parameters to consolidated state struct
        state.triggerConfig = _triggerConfig;
        state.strategyParams = _strategyParams;
        state.volatilityParams = _volatilityParams;
        state.withdrawalParams = _withdrawalParams;
        state.compoundSwapParams = _compoundSwapParams;
        state.twapParams = _twapParams;
        // state.isPaused defaults to false
        // state.totalGasSpent defaults to 0
    }

    /**
     * @notice Validate TWAP parameters
     * @param _twapParams TWAP parameters to validate
     * @param _triggerConfig Trigger configuration
     * @param _strategyParams Strategy parameters
     * @dev Mirrors factory validation to prevent post-deploy misconfiguration
     */
    function _validateTwapParams(
        TwapParams memory _twapParams,
        TriggerConfig memory _triggerConfig,
        StrategyParams memory _strategyParams
    ) private view {
        // Skip if TWAP not used
        if (!_twapParams.useTwapProtection && !_twapParams.useTwapCenter && _triggerConfig.baseTwapTickTrigger == 0) {
            return;
        }

        // Check 1: Mutual exclusivity between baseTickTrigger and baseTwapTickTrigger
        bool hasBaseTrigger = (_triggerConfig.baseLowerTrigger != 0 || _triggerConfig.baseUpperTrigger != 0);
        bool hasTwapTrigger = (_triggerConfig.baseTwapTickTrigger != 0);
        if (hasBaseTrigger && hasTwapTrigger) revert InvalidTriggerConfig();

        // Check 2: Prevent useTwapCenter with isBaseRatio
        if (_twapParams.useTwapCenter && _strategyParams.isBaseRatio) {
            revert InvalidTwapConfig();
        }

        // Check 3: Prevent baseTwapTickTrigger with isBaseRatio
        if (hasTwapTrigger && _strategyParams.isBaseRatio) {
            revert InvalidTwapConfig();
        }

        // Check 4: Validate twapSeconds bounds (before external calls)
        if (_twapParams.twapSeconds == 0) revert InvalidTwapConfig();
        if (_twapParams.twapSeconds > 7 days) revert InvalidTwapConfig();

        // Check 5: Validate maxTickDeviation if protection enabled
        if (_twapParams.useTwapProtection && _twapParams.maxTickDeviation == 0) {
            revert InvalidTwapConfig();
        }

        // Get poolKey from manager for hook/oracle checks
        PoolKey memory poolKey = manager.poolKey();

        // Check 6: Pool must be managed by VolatilityDynamicFeeHook
        address hookAddress = address(poolKey.hooks);
        if (hookAddress == address(0)) revert PoolNotManagedByVolatilityHook();

        // Try to cast and check managedPools - will revert if not a VolatilityDynamicFeeHook
        try VolatilityDynamicFeeLimitOrderHook(hookAddress).managedPools(poolKey.toId()) returns (bool isManaged) {
            if (!isManaged) revert PoolNotManagedByVolatilityHook();
        } catch {
            revert PoolNotManagedByVolatilityHook();
        }

        // Check 7: Verify TWAP history availability via oracle
        VolatilityDynamicFeeLimitOrderHook hook = VolatilityDynamicFeeLimitOrderHook(hookAddress);
        VolatilityOracle oracle = hook.volatilityOracle();

        // Validate TWAP history exists for requested period
        try oracle.consult(poolKey, _twapParams.twapSeconds) returns (int24, uint128) {
            // TWAP data available
        } catch {
            revert TwapHistoryUnavailable();
        }
    }

    /// @notice Current MPM owner (dynamic)
    function owner() public view returns (address) {
        return _mpmOwner();
    }

    function _mpmOwner() internal view returns (address) {
        return Ownable(address(manager)).owner();
    }

    /**
     * @notice Get TWAP tick from VolatilityOracle
     * @return twapTick The TWAP tick for the configured period
     */
    function _getTwapTick() private view returns (int24 twapTick) {
        PoolKey memory poolKey = manager.poolKey();
        address hookAddress = address(poolKey.hooks);

        // Get oracle from hook
        VolatilityDynamicFeeLimitOrderHook hook = VolatilityDynamicFeeLimitOrderHook(hookAddress);
        VolatilityOracle oracle = hook.volatilityOracle();

        // Consult oracle for TWAP
        (twapTick,) = oracle.consult(poolKey, state.twapParams.twapSeconds);

        return twapTick;
    }

    /**
     * @notice Check if current tick is within acceptable deviation from TWAP
     * @dev Reverts if deviation exceeds maxTickDeviation
     */
    function _checkTwapProtection() private {
        if (!state.twapParams.useTwapProtection) return;

        int24 twapTick = _getTwapTick();
        int24 currentTick = manager.currentTick();

        int24 tickDelta = currentTick - twapTick;
        uint256 absDelta = tickDelta >= 0 ? uint256(int256(tickDelta)) : uint256(int256(-tickDelta));

        if (absDelta > state.twapParams.maxTickDeviation) {
            emit TwapProtectionTriggered(currentTick, twapTick, uint24(absDelta));
            revert TwapDeviationExceeded();
        }
    }

    /**
     * @notice Internal wrapper to construct rebalance params using library
     * @param status Trigger status from checkTriggers
     * @return params Constructed rebalance parameters
     */
    function _constructRebalanceParams(RebalanceTriggerStatus memory status)
        private
        view
        returns (IMultiPositionManager.RebalanceParams memory params)
    {
        return RelayerLogic.constructRebalanceParams(manager, state.strategyParams, state.twapParams, status);
    }

    /**
     * @notice Execute a rebalance if triggers are met
     * @param outMin Minimum output amounts for burning positions
     * @param inMin Minimum input amounts for new positions
     * @dev Only callable by whitelisted automation services
     * @dev Reverts if no triggers are met or if rebalance fails
     * @dev Reimburses caller with ETH including 10% buffer
     * @dev Automatically constructs RebalanceParams based on which triggers are met
     */
    function executeRebalance(uint256[2][] memory outMin, uint256[2][] memory inMin)
        external
        override
        onlyAutomationService
        whenNotPaused
        nonReentrant
    {
        // Checks: Verify minimum balance
        if (address(this).balance < factory.minBalance()) revert InsufficientFunds();

        uint256 gasBefore = gasleft();

        // Checks: Verify TWAP protection before executing
        _checkTwapProtection();

        // Checks: Verify triggers are met
        RebalanceTriggerStatus memory status = checkTriggers();
        if (!status.anyTriggerMet) revert NoTriggersmet();

        // Checks: Verify this is the correct execution path
        if (state.strategyParams.useRebalanceSwap) revert InvalidTriggerConfig();

        // Construct rebalance params based on triggers
        IMultiPositionManager.RebalanceParams memory params = _constructRebalanceParams(status);

        // Interactions: Claim fees first if compoundFees is false
        if (!state.strategyParams.compoundFees) {
            manager.claimFee();
        }

        // Interactions: Execute rebalance on MultiPositionManager
        // This will revert if the rebalance fails, which is desired behavior
        manager.rebalance(params, outMin, inMin);

        // Determine primary trigger index (priority order) and emit event
        uint8 triggerIndex;
        if (status.baseTickTrigger) {
            triggerIndex = 0;
        } else if (status.baseTwapTickTrigger) {
            triggerIndex = 1;
        } else if (status.baseRatioTrigger) {
            triggerIndex = 2;
        } else if (status.limitTickTrigger) {
            triggerIndex = 3;
        } else if (status.limitRatioTrigger) {
            triggerIndex = 4;
        } else {
            triggerIndex = 5; // outOfPositionTrigger
        }
        emit AutomatedRebalanceExecuted(triggerIndex, false);

        // Calculate gas used and reimburse caller
        _reimburseGas(gasBefore);
    }

    /**
     * @notice Execute a rebalance with swap if triggers are met
     * @param swapParams Swap parameters for the external DEX swap
     * @param outMin Minimum output amounts for burning positions
     * @param inMin Minimum input amounts for new positions
     * @dev Only callable by whitelisted automation services
     * @dev Reverts if no triggers are met or if rebalance fails
     * @dev Reimburses caller with ETH including 10% buffer
     * @dev Automatically constructs RebalanceParams based on which triggers are met
     */
    function executeRebalanceSwap(
        RebalanceLogic.SwapParams calldata swapParams,
        uint256[2][] memory outMin,
        uint256[2][] memory inMin
    ) external payable override onlyAutomationService whenNotPaused nonReentrant {
        // Checks: Verify minimum balance (exclude caller-funded msg.value)
        uint256 prefundedBalance = address(this).balance - msg.value;
        uint256 requiredMinBalance = factory.minBalance();
        if (prefundedBalance < requiredMinBalance) revert InsufficientFunds();

        uint256 gasBefore = gasleft();

        // Checks: Verify TWAP protection before executing
        _checkTwapProtection();

        // Checks: Verify triggers are met
        RebalanceTriggerStatus memory status = checkTriggers();
        if (!status.anyTriggerMet) revert NoTriggersmet();

        // Checks: Verify this is the correct execution path
        if (!state.strategyParams.useRebalanceSwap) revert InvalidTriggerConfig();

        // Construct rebalance params based on triggers
        IMultiPositionManager.RebalanceParams memory rebalanceParams = _constructRebalanceParams(status);

        // Combine rebalance and swap params
        IMultiPositionManager.RebalanceSwapParams memory params =
            IMultiPositionManager.RebalanceSwapParams({rebalanceParams: rebalanceParams, swapParams: swapParams});

        // Interactions: Claim fees first if compoundFees is false
        if (!state.strategyParams.compoundFees) {
            manager.claimFee();
        }

        // Interactions: Execute rebalance swap on MultiPositionManager
        // Forward any ETH sent (may be needed for swap)
        // This will revert if the rebalance fails, which is desired behavior
        manager.rebalanceSwap{value: msg.value}(params, outMin, inMin);

        // Determine primary trigger index (priority order) and emit event
        uint8 triggerIndex;
        if (status.baseTickTrigger) {
            triggerIndex = 0;
        } else if (status.baseTwapTickTrigger) {
            triggerIndex = 1;
        } else if (status.baseRatioTrigger) {
            triggerIndex = 2;
        } else if (status.limitTickTrigger) {
            triggerIndex = 3;
        } else if (status.limitRatioTrigger) {
            triggerIndex = 4;
        } else {
            triggerIndex = 5; // outOfPositionTrigger
        }
        emit AutomatedRebalanceExecuted(triggerIndex, true);

        // Calculate gas used and reimburse caller
        _reimburseGas(gasBefore);
    }

    /**
     * @notice Execute compound swap when trigger conditions are met
     * @param swapParams Parameters for the DEX aggregator swap
     * @param inMin Minimum amounts for adding liquidity to positions
     * @dev Only callable by automation service when not paused
     * @dev Checks compound swap trigger before executing
     * @dev Reimburses caller with ETH for gas costs
     */
    function executeCompoundSwap(RebalanceLogic.SwapParams calldata swapParams, uint256[2][] calldata inMin)
        external
        payable
        override
        onlyAutomationService
        whenNotPaused
        nonReentrant
    {
        swapParams;
        inMin;
        revert InvalidTriggerConfig();
    }

    /**
     * @notice Execute withdrawal when trigger conditions are met
     * @param outMin Minimum output amounts for slippage protection
     * @dev Only callable by automation service when withdrawal triggers are met
     * @dev Reimburses automation service with ETH including 10% buffer
     */
    function executeWithdrawal(uint256[2][] memory outMin)
        external
        override
        onlyAutomationService
        whenNotPaused
        nonReentrant
    {
        outMin;
        revert InvalidTriggerConfig();
    }

    /**
     * @notice Internal wrapper to check triggers using library
     * @return status Trigger status indicating which triggers are met
     */
    function checkTriggers() internal view returns (RebalanceTriggerStatus memory status) {
        return RelayerLogic.checkTriggers(manager, state.triggerConfig, state.strategyParams, state.twapParams);
    }

    // /**
    //  * @notice Get current statistics
    //  * @return stats RelayerStats struct
    //  */
    // function getStats() external view override returns (RelayerStats memory stats) {
    //     stats.totalGasSpent = totalGasSpent;
    //     stats.ethBalance = address(this).balance;
    // }

    // /**
    //  * @notice Estimate how many rebalances can be funded with current ETH balance
    //  * @param estimatedGasPerRebalance Estimated gas per rebalance (e.g., 500000)
    //  * @return count Estimated number of rebalances remaining
    //  */
    // function estimateRebalancesLeft(uint256 estimatedGasPerRebalance) external view override returns (uint256 count) {
    //     uint256 balance = address(this).balance;
    //     if (balance == 0) return 0;

    //     // Calculate estimated cost per rebalance with buffer
    //     // cost = (estimatedGas + overhead) * gasPrice * buffer
    //     uint256 estimatedCost = (estimatedGasPerRebalance + BASE_GAS_OVERHEAD) * tx.gasprice;
    //     estimatedCost = (estimatedCost * GAS_BUFFER_NUMERATOR) / GAS_BUFFER_DENOMINATOR;

    //     if (estimatedCost == 0) return 0;

    //     return balance / estimatedCost;
    // }

    /**
     * @notice Get all rebalance parameters
     * @return triggerConfig Current TriggerConfig
     * @return strategyParams Current StrategyParams
     * @return volatilityParams Current VolatilityParams
     * @return twapParams Current TwapParams
     */
    function getRebalanceParams()
        external
        view
        override
        returns (TriggerConfig memory, StrategyParams memory, VolatilityParams memory, TwapParams memory)
    {
        return (state.triggerConfig, state.strategyParams, state.volatilityParams, state.twapParams);
    }

    /**
     * @notice Get withdrawal trigger parameters
     * @return params Current WithdrawalParams
     */
    function getWithdrawalParams() external view override returns (WithdrawalParams memory params) {
        return state.withdrawalParams;
    }

    /**
     * @notice Get compound swap trigger parameters
     * @return params Current CompoundSwapParams
     */
    function getCompoundSwapParams() external view override returns (CompoundSwapParams memory params) {
        return state.compoundSwapParams;
    }

    /**
     * @notice Check if the contract is paused
     * @return bool True if paused, false otherwise
     */
    function isPaused() external view override returns (bool) {
        return state.isPaused;
    }

    /**
     * @notice Get the minimum ETH balance required for relayer execution
     * @return The minimum balance amount in wei
     */
    function minBalance() external view override returns (uint256) {
        return factory.minBalance();
    }

    /**
     * @notice Check if compound swap trigger conditions are met
     * @return bool True if outOfPositionRatio meets/exceeds threshold
     * @dev Returns false if threshold is 0 (trigger disabled)
     */
    function compoundSwapTriggerStatus() internal view returns (bool) {
        // If threshold is 0, compound swap trigger is disabled
        if (state.compoundSwapParams.outOfPositionRatioThreshold == 0) {
            return false;
        }

        (,,,, uint256 outOfPositionRatio,,,,,,,) = manager.getRatios();

        return outOfPositionRatio >= state.compoundSwapParams.outOfPositionRatioThreshold;
    }

    /**
     * @notice Check if withdrawal trigger conditions are met
     * @return bool True if pool0Ratio or pool1Ratio meets/exceeds thresholds
     * @dev Returns false if both thresholds are 0 (trigger disabled)
     */
    function withdrawalTriggerStatus() internal view returns (bool) {
        // If both are 0, withdrawal trigger is disabled
        if (state.withdrawalParams.pool0RatioThreshold == 0 && state.withdrawalParams.pool1RatioThreshold == 0) {
            return false;
        }

        (uint256 pool0Ratio, uint256 pool1Ratio,,,,,,,,,,) = manager.getRatios();

        bool pool0Triggered =
            state.withdrawalParams.pool0RatioThreshold != 0 && pool0Ratio >= state.withdrawalParams.pool0RatioThreshold;

        bool pool1Triggered =
            state.withdrawalParams.pool1RatioThreshold != 0 && pool1Ratio >= state.withdrawalParams.pool1RatioThreshold;

        return pool0Triggered || pool1Triggered;
    }

    /**
     * @notice Set all rebalance parameters at once
     * @param _triggerConfig New trigger configuration
     * @param _strategyParams New strategy parameters
     * @param _volatilityParams New volatility parameters
     * @param _twapParams New TWAP parameters
     * @dev Only callable by owner. Validates all parameters.
     */
    function setRebalanceParams(
        TriggerConfig calldata _triggerConfig,
        StrategyParams calldata _strategyParams,
        VolatilityParams calldata _volatilityParams,
        TwapParams calldata _twapParams
    ) external override onlyOwner {
        // Validate and set trigger config
        _validateRatios(
            _triggerConfig.baseMinRatio,
            _triggerConfig.baseMaxRatio,
            _triggerConfig.limitMinRatio,
            _triggerConfig.limitThreshold,
            _triggerConfig.outOfPositionThreshold
        );

        int24 tickSpacing = manager.poolKey().tickSpacing;
        TriggerConfig memory roundedConfig = _triggerConfig;
        roundedConfig.baseLowerTrigger = _roundUpToTickSpacing(_triggerConfig.baseLowerTrigger, tickSpacing);
        roundedConfig.baseUpperTrigger = _roundUpToTickSpacing(_triggerConfig.baseUpperTrigger, tickSpacing);
        roundedConfig.limitDeltaTicks = _roundUpToTickSpacing(_triggerConfig.limitDeltaTicks, tickSpacing);
        roundedConfig.maxDeltaTicks = _roundUpToTickSpacing(_triggerConfig.maxDeltaTicks, tickSpacing);

        _validateDeltas(
            roundedConfig.baseLowerTrigger,
            roundedConfig.baseUpperTrigger,
            roundedConfig.limitDeltaTicks,
            roundedConfig.maxDeltaTicks
        );

        state.triggerConfig = roundedConfig;

        // Validate and set strategy params
        if (_strategyParams.strategy == address(0)) revert InvalidTriggerConfig();
        _validateWeights(_strategyParams.weight0, _strategyParams.weight1);
        if (!_strategyParams.useCarpet) revert InvalidTriggerConfig();
        // If isBaseRatio=true and proportional mode (weight0=0, weight1=0), must use swap
        // Otherwise: perpetual rebalancing (ratio trigger fires, rebalances proportionally, ratio still wrong, triggers again)
        bool isProportional = (_strategyParams.weight0 == 0 && _strategyParams.weight1 == 0);
        if (_strategyParams.isBaseRatio && isProportional && !_strategyParams.useRebalanceSwap) {
            revert InvalidTriggerConfig();
        }

        state.strategyParams = _strategyParams;

        // Validate and set volatility params
        if (_volatilityParams.pairType > 3) revert InvalidPairType();
        state.volatilityParams = _volatilityParams;

        // Validate and set TWAP params
        _validateTwapParams(_twapParams, _triggerConfig, _strategyParams);
        state.twapParams = _twapParams;

        emit TriggersUpdated(msg.sender);
        emit VolatilityParamsUpdated(
            _volatilityParams.geckoIdToken0, _volatilityParams.geckoIdToken1, _volatilityParams.pairType
        );
    }

    /**
     * @notice Set withdrawal trigger parameters
     * @param newParams New withdrawal parameters
     * @dev Only callable by owner
     */
    function setWithdrawalParams(WithdrawalParams calldata newParams) external override onlyOwner {
        state.withdrawalParams = newParams;
    }

    /**
     * @notice Set compound swap trigger parameters
     * @param newParams New compound swap parameters
     * @dev Only callable by owner
     */
    function setCompoundSwapParams(CompoundSwapParams calldata newParams) external override onlyOwner {
        state.compoundSwapParams = newParams;
    }

    /**
     * @notice Pause automated rebalancing
     * @dev Only callable by owner
     */
    function pause() external override onlyOwner {
        if (state.isPaused) revert ContractPaused();
        state.isPaused = true;
    }

    /**
     * @notice Unpause automated rebalancing
     * @dev Only callable by owner
     */
    function unpause() external override onlyOwner {
        if (!state.isPaused) revert NotPaused();
        state.isPaused = false;
    }

    /**
     * @notice Fund the contract with ETH for gas reimbursements
     * @dev Anyone can fund the contract
     */
    function fundContract() external payable override {
        if (msg.value == 0) revert InsufficientFunds();
    }

    /**
     * @notice Withdraw ETH from the contract
     * @param amount Amount of ETH to withdraw
     * @dev Only callable by owner
     */
    function withdrawFunds(uint256 amount) external override onlyOwner {
        if (amount == 0) revert InsufficientFunds();
        if (address(this).balance < amount) revert InsufficientFunds();

        // Use low-level call for ETH transfer
        // Assembly for gas-efficient external call with full control
        // Equivalent Solidity: (bool success,) = _mpmOwner().call{value: amount}("");
        // Memory-safe: only reads/writes scratch space
        bool success;
        address ownerAddr = _mpmOwner();
        assembly ("memory-safe") {
            success := call(gas(), ownerAddr, amount, 0, 0, 0, 0)
        }
        if (!success) revert TransferFailed();
    }

    // /**
    //  * @notice Withdraw all ETH from the contract
    //  * @dev Only callable by owner
    //  */
    // function withdrawAllFunds() external override onlyOwner {
    //     uint256 contractBalance = address(this).balance;
    //     if (contractBalance == 0) revert InsufficientFunds();

    //     // Use low-level call for ETH transfer
    //     // Assembly for gas-efficient external call with full control
    //     // Equivalent Solidity: (bool success,) = owner.call{value: contractBalance}("");
    //     // Memory-safe: only reads/writes scratch space
    //     bool success;
    //     address ownerAddr = owner;
    //     assembly ("memory-safe") {
    //         success := call(gas(), ownerAddr, contractBalance, 0, 0, 0, 0)
    //     }
    //     if (!success) revert TransferFailed();
    // }

    /**
     * @notice Reimburse the caller for gas used
     * @param gasBefore Gas remaining before execution
     * @dev Calculates gas used, applies 10% buffer, and transfers ETH to caller
     */
    function _reimburseGas(uint256 gasBefore) private {
        (,, uint256 reimbursement) = _calculateReimbursement(gasBefore, msg.data);

        // Check sufficient balance
        if (address(this).balance < reimbursement) revert InsufficientFunds();

        // Update statistics
        unchecked {
            state.totalGasSpent += reimbursement;
        }

        // Transfer ETH to caller
        // Assembly for gas-efficient external call with full control
        // Equivalent Solidity: (bool success,) = msg.sender.call{value: reimbursement}("");
        // Memory-safe: only reads/writes scratch space
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), caller(), reimbursement, 0, 0, 0, 0)
        }
        if (!success) revert TransferFailed();
    }

    function _calculateReimbursement(uint256 gasBefore, bytes calldata data)
        internal
        view
        returns (uint256 gasUsed, uint256 l1Fee, uint256 reimbursement)
    {
        // Calculate gas used
        gasUsed = gasBefore - gasleft() + BASE_GAS_OVERHEAD;

        // Add OP Stack L1 data fee when available
        l1Fee = _getL1Fee(data);

        // Calculate reimbursement with 10% buffer
        uint256 l2Cost = gasUsed * tx.gasprice;
        reimbursement = ((l2Cost + l1Fee) * GAS_BUFFER_NUMERATOR) / GAS_BUFFER_DENOMINATOR;
    }

    function _getL1Fee(bytes calldata data) private view returns (uint256 l1Fee) {
        (bool success, bytes memory returnData) =
            GAS_PRICE_ORACLE.staticcall(abi.encodeWithSelector(GET_L1_FEE_SELECTOR, data));
        if (success && returnData.length >= 32) {
            l1Fee = abi.decode(returnData, (uint256));
        }
    }

    function _validateRatios(
        uint256 baseMin,
        uint256 baseMax,
        uint256 limitMin,
        uint256 limitThreshold,
        uint256 outOfPos
    ) private pure {
        if (baseMin > 1e18 || baseMax > 1e18 || limitMin > 1e18 || limitThreshold > 1e18 || outOfPos > 1e18) {
            revert InvalidTriggerConfig();
        }
        if (baseMin != 0 && baseMax != 0 && baseMin > baseMax) {
            revert InvalidTriggerConfig();
        }
    }

    function _validateDeltas(uint24 baseLowerTrigger, uint24 baseUpperTrigger, uint24 limitDelta, uint24 maxDelta)
        private
        pure
    {
        // maxDelta = 0 means no circuit breaker, so only validate if maxDelta is set
        if (maxDelta != 0) {
            // If baseLowerTrigger is set, maxDeltaTicks must be greater
            if (baseLowerTrigger != 0 && maxDelta <= baseLowerTrigger) {
                revert InvalidTriggerConfig();
            }
            // If baseUpperTrigger is set, maxDeltaTicks must be greater
            if (baseUpperTrigger != 0 && maxDelta <= baseUpperTrigger) {
                revert InvalidTriggerConfig();
            }
            // If limitDeltaTicks is set, maxDeltaTicks must be greater
            if (limitDelta != 0 && maxDelta <= limitDelta) {
                revert InvalidTriggerConfig();
            }
        }
    }

    /**
     * @notice Round a delta value UP to the nearest tickSpacing multiple
     * @param value The delta value to round
     * @param tickSpacing The tick spacing to align to
     * @return Rounded value (0 stays 0, non-zero rounds up)
     * @dev Always rounds UP to ensure triggers are not more sensitive than intended
     */
    function _roundUpToTickSpacing(uint24 value, int24 tickSpacing) private pure returns (uint24) {
        if (value == 0) return 0;
        uint24 spacing = uint24(uint256(int256(tickSpacing)));
        return ((value + spacing - 1) / spacing) * spacing;
    }

    function _validateWeights(uint256 w0, uint256 w1) private pure {
        // Proportional mode: both weights must be 0
        bool isProportional = (w0 == 0 && w1 == 0);
        bool isFiftyFifty = (w0 == 0.5e18 && w1 == 0.5e18);
        if (!isProportional && !isFiftyFifty) {
            revert InvalidTriggerConfig();
        }
    }

    /**
     * @notice Receive function to accept ETH
     */
    receive() external payable {}
}

File 21 of 85 : 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.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 {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 {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";
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 29 of 85 : 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.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;
            }
        }
    }
}

// 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: 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
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;

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

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

File 39 of 85 : 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: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

import {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
// 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: 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: 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 47 of 85 : 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 48 of 85 : 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;
    }
}

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

File 50 of 85 : 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;

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

File 54 of 85 : 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: 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;

/**
 * @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.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;

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

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

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

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

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

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

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

import {IRelayer} from "../interfaces/IRelayer.sol";
import {IMultiPositionManager} from "../interfaces/IMultiPositionManager.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 {VolatilityDynamicFeeLimitOrderHook} from "../../LimitOrderBook/hooks/VolatilityDynamicFeeLimitOrderHook.sol";
import {VolatilityOracle} from "../../LimitOrderBook/libraries/VolatilityOracle.sol";

/**
 * @title RebalancerLogic
 * @notice Library containing core rebalancing logic for trigger checking and parameter construction
 * @dev Extracted from Rebalancer.sol to conceal implementation details while maintaining reusability
 */
library RelayerLogic {
    using PoolIdLibrary for PoolKey;
    /**
     * @notice Get TWAP tick from VolatilityOracle
     * @param manager The MultiPositionManager
     * @param twapSeconds TWAP period in seconds
     * @return twapTick The TWAP tick
     */
    function _getTwapTick(IMultiPositionManager manager, uint32 twapSeconds)
        private
        view
        returns (int24 twapTick)
    {
        PoolKey memory poolKey = manager.poolKey();
        address hookAddress = address(poolKey.hooks);

        VolatilityDynamicFeeLimitOrderHook hook =
            VolatilityDynamicFeeLimitOrderHook(hookAddress);
        VolatilityOracle oracle = hook.volatilityOracle();

        (twapTick,) = oracle.consult(poolKey, twapSeconds);
        return twapTick;
    }

    /**
     * @notice Validate TWAP parameters
     * @param manager The MultiPositionManager
     * @param twapParams TWAP parameters to validate
     * @param triggerConfig Trigger configuration
     * @param strategyParams Strategy parameters
     * @dev Mirrors factory validation to prevent post-deploy misconfiguration
     */
    function validateTwapParams(
        IMultiPositionManager manager,
        IRelayer.TwapParams memory twapParams,
        IRelayer.TriggerConfig memory triggerConfig,
        IRelayer.StrategyParams memory strategyParams
    ) external view {
        // Skip if TWAP not used
        if (!twapParams.useTwapProtection && !twapParams.useTwapCenter && triggerConfig.baseTwapTickTrigger == 0) {
            return;
        }

        // Check 1: Mutual exclusivity between baseTickTrigger and baseTwapTickTrigger
        bool hasBaseTrigger = (triggerConfig.baseLowerTrigger != 0 || triggerConfig.baseUpperTrigger != 0);
        bool hasTwapTrigger = (triggerConfig.baseTwapTickTrigger != 0);
        if (hasBaseTrigger && hasTwapTrigger) revert IRelayer.InvalidTriggerConfig();

        // Check 2: Prevent useTwapCenter with isBaseRatio
        if (twapParams.useTwapCenter && strategyParams.isBaseRatio) {
            revert IRelayer.InvalidTwapConfig();
        }

        // Check 3: Prevent baseTwapTickTrigger with isBaseRatio
        if (hasTwapTrigger && strategyParams.isBaseRatio) {
            revert IRelayer.InvalidTwapConfig();
        }

        // Check 4: Validate twapSeconds bounds (before external calls)
        if (twapParams.twapSeconds == 0) revert IRelayer.InvalidTwapConfig();
        if (twapParams.twapSeconds > 7 days) revert IRelayer.InvalidTwapConfig();

        // Check 5: Validate maxTickDeviation if protection enabled
        if (twapParams.useTwapProtection && twapParams.maxTickDeviation == 0) {
            revert IRelayer.InvalidTwapConfig();
        }

        // Get poolKey from manager for hook/oracle checks
        PoolKey memory poolKey = manager.poolKey();

        // Check 6: Pool must be managed by VolatilityDynamicFeeLimitOrderHook
        address hookAddress = address(poolKey.hooks);
        if (hookAddress == address(0)) revert IRelayer.PoolNotManagedByVolatilityHook();

        // Try to cast and check managedPools - will revert if not a VolatilityDynamicFeeLimitOrderHook
        try VolatilityDynamicFeeLimitOrderHook(hookAddress).managedPools(poolKey.toId()) returns (bool isManaged) {
            if (!isManaged) revert IRelayer.PoolNotManagedByVolatilityHook();
        } catch {
            revert IRelayer.PoolNotManagedByVolatilityHook();
        }

        // Check 7: Verify TWAP history availability via oracle
        VolatilityDynamicFeeLimitOrderHook hook =
            VolatilityDynamicFeeLimitOrderHook(hookAddress);
        VolatilityOracle oracle = hook.volatilityOracle();

        // Validate TWAP history exists for requested period
        try oracle.consult(poolKey, twapParams.twapSeconds) returns (int24, uint128) {
            // TWAP data available
        } catch {
            revert IRelayer.TwapHistoryUnavailable();
        }
    }

    /**
     * @notice Check if current tick is within acceptable deviation from TWAP
     * @param manager The MultiPositionManager
     * @param twapParams TWAP parameters
     * @dev Reverts if deviation exceeds maxTickDeviation
     */
    function checkTwapProtection(IMultiPositionManager manager, IRelayer.TwapParams memory twapParams) external {
        if (!twapParams.useTwapProtection) return;

        int24 twapTick = _getTwapTick(manager, twapParams.twapSeconds);
        int24 currentTick = manager.currentTick();

        int24 tickDelta = currentTick - twapTick;
        uint256 absDelta = tickDelta >= 0 ? uint256(int256(tickDelta)) : uint256(int256(-tickDelta));

        if (absDelta > twapParams.maxTickDeviation) {
            emit IRelayer.TwapProtectionTriggered(currentTick, twapTick, uint24(absDelta));
            revert IRelayer.TwapDeviationExceeded();
        }
    }

    /**
     * @notice Check all configured triggers to determine if rebalance should execute
     * @param manager The MultiPositionManager to check
     * @param triggerConfig The trigger configuration
     * @param strategyParams The strategy parameters
     * @param twapParams The TWAP parameters
     * @return status Struct indicating which triggers are currently met
     * @dev Optimized to minimize external calls by batching and conditional execution
     */
    function checkTriggers(
        IMultiPositionManager manager,
        IRelayer.TriggerConfig memory triggerConfig,
        IRelayer.StrategyParams memory strategyParams,
        IRelayer.TwapParams memory twapParams
    ) external view returns (IRelayer.RebalanceTriggerStatus memory status) {
        bool isProportional = (strategyParams.weight0 == 0 && strategyParams.weight1 == 0);

        // Check tick-based triggers (pass twapParams for baseTwapTickTrigger)
        status = _checkTickTriggers(manager, triggerConfig, twapParams, isProportional, status);

        // Check ratio-based triggers if not circuit broken
        if (status.baseTickTrigger || status.baseTwapTickTrigger || !_isCircuitBroken(manager, triggerConfig)) {
            status = _checkRatioTriggers(manager, triggerConfig, strategyParams, status);
        }

        status.anyTriggerMet = status.baseTickTrigger || status.baseTwapTickTrigger || status.baseRatioTrigger
            || status.limitTickTrigger || status.limitRatioTrigger || status.outOfPositionTrigger;
    }

    function _isCircuitBroken(IMultiPositionManager manager, IRelayer.TriggerConfig memory triggerConfig)
        private
        view
        returns (bool)
    {
        if (triggerConfig.maxDeltaTicks == 0) return false;

        (, int24 centerTick,,,,,,,,) = manager.lastStrategyParams();
        int24 rawCurrentTick = manager.currentTick();
        int24 tickSpacing = manager.poolKey().tickSpacing;
        int24 currentTick = rawCurrentTick >= 0
            ? (rawCurrentTick / tickSpacing) * tickSpacing
            : ((rawCurrentTick - tickSpacing + 1) / tickSpacing) * tickSpacing;

        int24 tickDelta = currentTick - centerTick;
        uint256 absDelta = tickDelta >= 0 ? uint256(int256(tickDelta)) : uint256(int256(-tickDelta));

        return absDelta > triggerConfig.maxDeltaTicks;
    }

    function _checkTickTriggers(
        IMultiPositionManager manager,
        IRelayer.TriggerConfig memory triggerConfig,
        IRelayer.TwapParams memory twapParams,
        bool isProportional,
        IRelayer.RebalanceTriggerStatus memory status
    ) private view returns (IRelayer.RebalanceTriggerStatus memory) {
        bool needTickChecks = (triggerConfig.baseLowerTrigger != 0 || triggerConfig.baseUpperTrigger != 0)
            || triggerConfig.baseTwapTickTrigger != 0
            || (!isProportional && (triggerConfig.limitDeltaTicks != 0 || triggerConfig.limitMinRatio != 0));

        if (!needTickChecks) return status;

        (, int24 centerTick,,,,,,,,) = manager.lastStrategyParams();
        int24 rawCurrentTick = manager.currentTick();
        int24 tickSpacing = manager.poolKey().tickSpacing;
        int24 currentTick = rawCurrentTick >= 0
            ? (rawCurrentTick / tickSpacing) * tickSpacing
            : ((rawCurrentTick - tickSpacing + 1) / tickSpacing) * tickSpacing;

        int24 tickDelta = currentTick - centerTick;
        uint256 absDelta = tickDelta >= 0 ? uint256(int256(tickDelta)) : uint256(int256(-tickDelta));

        // Circuit breaker check
        if (triggerConfig.maxDeltaTicks != 0) {
            if (absDelta > triggerConfig.maxDeltaTicks) {
                return status;
            }
        }

        // Check base tick trigger with asymmetric thresholds
        if (triggerConfig.baseLowerTrigger != 0 || triggerConfig.baseUpperTrigger != 0) {
            bool triggered = false;

            if (tickDelta > 0) {
                // Price moved up (above center) - check upper trigger
                triggered = (
                    triggerConfig.baseUpperTrigger != 0 && uint256(int256(tickDelta)) >= triggerConfig.baseUpperTrigger
                );
            } else if (tickDelta < 0) {
                // Price moved down (below center) - check lower trigger
                triggered = (triggerConfig.baseLowerTrigger != 0 && absDelta >= triggerConfig.baseLowerTrigger);
            }

            // Also check against circuit breaker if set
            status.baseTickTrigger =
                triggered && (triggerConfig.maxDeltaTicks == 0 || absDelta <= triggerConfig.maxDeltaTicks);
        }

        // Check TWAP-based base trigger
        if (triggerConfig.baseTwapTickTrigger != 0) {
            int24 twapTick = _getTwapTick(manager, twapParams.twapSeconds);
            int24 twapDelta = twapTick - centerTick;
            uint256 absTwapDelta = twapDelta >= 0 ? uint256(int256(twapDelta)) : uint256(int256(-twapDelta));

            status.baseTwapTickTrigger = absTwapDelta >= triggerConfig.baseTwapTickTrigger
                && (triggerConfig.maxDeltaTicks == 0 || absDelta <= triggerConfig.maxDeltaTicks);
        }

        return status;
    }

    function _checkRatioTriggers(
        IMultiPositionManager manager,
        IRelayer.TriggerConfig memory triggerConfig,
        IRelayer.StrategyParams memory strategyParams,
        IRelayer.RebalanceTriggerStatus memory status
    ) private view returns (IRelayer.RebalanceTriggerStatus memory) {
        bool needRatios = (
            strategyParams.isBaseRatio && (triggerConfig.baseMinRatio != 0 || triggerConfig.baseMaxRatio != 0)
        ) || triggerConfig.limitMinRatio != 0 || triggerConfig.limitDeltaTicks != 0
            || triggerConfig.outOfPositionThreshold != 0;

        if (!needRatios) return status;

        (
            ,
            ,
            ,
            ,
            ,
            uint256 outOfPositionRatio,
            ,
            uint256 limitRatio,
            uint256 base0Ratio,
            ,
            uint256 limit0Ratio,
            uint256 limit1Ratio
        ) = manager.getRatios();

        // Check base ratio trigger
        if (strategyParams.isBaseRatio && (triggerConfig.baseMinRatio != 0 || triggerConfig.baseMaxRatio != 0)) {
            status.baseRatioTrigger = base0Ratio < triggerConfig.baseMinRatio || base0Ratio > triggerConfig.baseMaxRatio;
        }

        // Check limit tick trigger
        if (triggerConfig.limitDeltaTicks != 0) {
            status.limitTickTrigger = _checkLimitTickTrigger(manager, triggerConfig);
        }

        // Check limit ratio trigger
        if (triggerConfig.limitMinRatio != 0 && limitRatio > triggerConfig.limitThreshold) {
            status.limitRatioTrigger =
                checkLimitRatioTrigger(manager, limit0Ratio, limit1Ratio, triggerConfig.limitMinRatio);
        }

        // Check out of position trigger
        if (triggerConfig.outOfPositionThreshold != 0) {
            status.outOfPositionTrigger = outOfPositionRatio > triggerConfig.outOfPositionThreshold;
        }

        return status;
    }

    /**
     * @notice Check limit tick trigger based on active limit position boundaries
     * @param manager The MultiPositionManager to check
     * @param triggerConfig The trigger configuration
     * @return triggered True if limit tick trigger is met
     */
    function _checkLimitTickTrigger(IMultiPositionManager manager, IRelayer.TriggerConfig memory triggerConfig)
        private
        view
        returns (bool triggered)
    {
        uint256 limitLength = manager.limitPositionsLength();
        if (limitLength == 0) return false;

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

        // Determine which limit position has more liquidity and use it
        IMultiPositionManager.Range memory activeLimitRange;
        if (
            limitLength == 2 && positionData[ranges.length - 2].liquidity > positionData[ranges.length - 1].liquidity
                && positionData[ranges.length - 2].liquidity > 0
        ) {
            activeLimitRange = ranges[ranges.length - 2];
        } else if (positionData[ranges.length - 1].liquidity > 0) {
            activeLimitRange = ranges[ranges.length - 1];
        } else {
            return false;
        }

        int24 currentTick = manager.currentTick();

        // Check if current tick is inside the limit position range
        if (currentTick >= activeLimitRange.lowerTick && currentTick < activeLimitRange.upperTick) {
            return false;
        } else if (currentTick < activeLimitRange.lowerTick) {
            // Below limit position: trigger if distance > limitDeltaTicks
            triggered = uint256(int256(activeLimitRange.lowerTick - currentTick)) > triggerConfig.limitDeltaTicks;
        } else {
            // At or above limit position: trigger if distance >= limitDeltaTicks
            triggered = uint256(int256(currentTick - activeLimitRange.upperTick)) >= triggerConfig.limitDeltaTicks;
        }

        // Apply circuit breaker (maxDeltaTicks) if set
        if (triggered && triggerConfig.maxDeltaTicks != 0) {
            int24 tickDelta;
            (, tickDelta,,,,,,,,) = manager.lastStrategyParams();
            tickDelta = currentTick - tickDelta;
            triggered = (tickDelta >= 0 ? uint256(int256(tickDelta)) : uint256(int256(-tickDelta)))
                <= triggerConfig.maxDeltaTicks;
        }
    }

    /// @dev Position ID used for all MPM positions in Uniswap V4
    bytes32 private constant POSITION_ID = bytes32(uint256(1));

    /**
     * @notice Check limit ratio trigger based on position with higher liquidity
     * @param manager The MultiPositionManager to check
     * @param limit0Ratio Current limit0Ratio
     * @param limit1Ratio Current limit1Ratio
     * @param limitMinRatio Minimum ratio threshold
     * @return triggered True if limit ratio trigger is met
     * @dev Uses position index to determine direction (limitPos0=below, limitPos1=above by design)
     */
    function checkLimitRatioTrigger(
        IMultiPositionManager manager,
        uint256 limit0Ratio,
        uint256 limit1Ratio,
        uint256 limitMinRatio
    ) public view returns (bool triggered) {
        if (manager.limitPositionsLength() == 0) return false;

        // Get limit positions and determine which to check
        IMultiPositionManager.Range memory limitPos0 = manager.limitPositions(0);
        IMultiPositionManager.Range memory limitPos1 = manager.limitPositions(1);

        bool hasLimit0 = limitPos0.lowerTick < limitPos0.upperTick;
        bool hasLimit1 = limitPos1.lowerTick < limitPos1.upperTick;

        bool checkLimit0;
        if (hasLimit0 && !hasLimit1) {
            checkLimit0 = true;
        } else if (!hasLimit0 && hasLimit1) {
            checkLimit0 = false;
        } else {
            // Both exist - query liquidity via StateLibrary
            checkLimit0 = _getLimitWithMoreLiquidity(manager, limitPos0, limitPos1);
        }

        // By design (PositionLogic.sol): limitPos0 is below center, limitPos1 is above center
        // - limitPos0 (below): originally token1, converts to token0 → check limit0Ratio
        // - limitPos1 (above): originally token0, converts to token1 → check limit1Ratio
        return checkLimit0 ? limit0Ratio >= limitMinRatio : limit1Ratio >= limitMinRatio;
    }

    function _getLimitWithMoreLiquidity(
        IMultiPositionManager manager,
        IMultiPositionManager.Range memory limitPos0,
        IMultiPositionManager.Range memory limitPos1
    ) private view returns (bool isLimit0) {
        PoolId poolId = manager.poolKey().toId();
        address mpmAddr = address(manager);
        (uint128 liq0,,) = StateLibrary.getPositionInfo(
            manager.poolManager(), poolId, mpmAddr, limitPos0.lowerTick, limitPos0.upperTick, POSITION_ID
        );
        (uint128 liq1,,) = StateLibrary.getPositionInfo(
            manager.poolManager(), poolId, mpmAddr, limitPos1.lowerTick, limitPos1.upperTick, POSITION_ID
        );
        return liq0 >= liq1;
    }

    /**
     * @notice Construct rebalance parameters based on trigger status
     * @param manager The MultiPositionManager
     * @param strategyParams The strategy parameters
     * @param twapParams The TWAP parameters
     * @param status The trigger status from checkTriggers
     * @return params The constructed RebalanceParams for execution
     * @dev Determines whether to use current tick (sentinel), TWAP tick, or previous center tick
     */
    function constructRebalanceParams(
        IMultiPositionManager manager,
        IRelayer.StrategyParams memory strategyParams,
        IRelayer.TwapParams memory twapParams,
        IRelayer.RebalanceTriggerStatus memory status
    ) external view returns (IMultiPositionManager.RebalanceParams memory params) {
        // Determine if using TWAP tick as center
        bool useTwapCenterValue = status.baseTwapTickTrigger || twapParams.useTwapCenter;

        // Determine if using SENTINEL_VALUE or previous centerTick
        bool useSentinelValue = status.baseTickTrigger || status.baseRatioTrigger
            || (status.limitTickTrigger && !strategyParams.isolatedBaseLimitRebalancing);

        // Set centerTick (priority: TWAP > Sentinel > Previous)
        if (useTwapCenterValue) {
            // Use TWAP tick as center
            params.center = _getTwapTick(manager, twapParams.twapSeconds);
        } else if (useSentinelValue) {
            params.center = type(int24).max;
        } else {
            (, params.center,,,,,,,,) = manager.lastStrategyParams();
        }

        // Set weights - always use strategy params
        // Proportional weights (0,0) signal to use current position ratios
        if (strategyParams.weight0 == 0 && strategyParams.weight1 == 0) {
            params.weight0 = 0;
            params.weight1 = 0;
        } else {
            params.weight0 = strategyParams.weight0;
            params.weight1 = strategyParams.weight1;
        }

        // Set other params from strategyParams (inline to save stack)
        params.strategy = strategyParams.strategy;
        params.tLeft = strategyParams.ticksLeft;
        params.tRight = strategyParams.ticksRight;
        params.limitWidth = strategyParams.limitWidth;
        params.useCarpet = strategyParams.useCarpet;
    }

    /**
     * @notice Withdraw a single token type and rebalance with the remaining token
     * @param manager The MultiPositionManager to interact with
     * @param isToken0 True to withdraw token0, false to withdraw token1
     * @param outMin Slippage protection for withdrawCustom
     */
    function withdrawSingleToken(
        IMultiPositionManager manager,
        bool isToken0,
        uint256[2][] memory outMin
    ) public {
        // Withdraw the specified token (tokens go to owner)
        {
            (uint256 total0, uint256 total1,,) = manager.getTotalAmounts();
            if (isToken0) {
                manager.withdrawCustom(total0, 0, outMin);
            } else {
                manager.withdrawCustom(0, total1, outMin);
            }
        }

        // Check if rebalance needed based on remaining token
        {
            (uint256 pool0Ratio, uint256 pool1Ratio,,,,,,,,,,) = manager.getRatios();
            // If withdrawing token0, check if token1 remains (pool1Ratio > 0)
            // If withdrawing token1, check if token0 remains (pool0Ratio > 0)
            if (isToken0 ? (pool1Ratio == 0) : (pool0Ratio == 0)) {
                return; // No remaining token, no rebalance needed
            }
        }

        // Retrieve strategy params and execute rebalance
        {
            (
                address lastStrategy,
                int24 lastCenterTick,
                uint24 lastTicksLeft,
                uint24 lastTicksRight,
                uint24 lastLimitWidth,
                , // weight0 - ignore, use 0 for proportional
                , // weight1 - ignore, use 0 for proportional
                bool lastUseCarpet,
                , // useSwap - ignore
                // useAssetWeights - ignore
            ) = manager.lastStrategyParams();

            manager.rebalance(
                IMultiPositionManager.RebalanceParams({
                    strategy: lastStrategy,
                    center: lastCenterTick,
                    tLeft: lastTicksLeft,
                    tRight: lastTicksRight,
                    limitWidth: lastLimitWidth,
                    weight0: 0,
                    weight1: 0,
                    useCarpet: lastUseCarpet
                }),
                new uint256[2][](manager.basePositionsLength() + manager.limitPositionsLength()), // rebalanceOutMin (all zeros)
                new uint256[2][](0) // inMin (empty -> zero-filled for new baseRanges)
            );
        }
    }

    /**
     * @notice Validate withdrawal params for invalid combinations
     * @param params The withdrawal params to validate
     * @dev Reverts if params have invalid flag combinations
     */
    function validateWithdrawalParams(IRelayer.WithdrawalParams memory params) public pure {
        if (
            // Cannot have withdrawAll=true with either token-specific flag
            (params.withdrawAll && (params.withdrawToken0Only || params.withdrawToken1Only))
            // Cannot set both withdrawToken0Only and withdrawToken1Only (mutually exclusive)
            || (params.withdrawToken0Only && params.withdrawToken1Only)
            // Cannot set both pool0RatioThreshold and pool1RatioThreshold (mutually exclusive)
            || (params.pool0RatioThreshold != 0 && params.pool1RatioThreshold != 0)
            // If all flags are false and both ratio thresholds are 0, no trigger is possible
            || (!params.withdrawAll && !params.withdrawToken0Only && !params.withdrawToken1Only
                && params.pool0RatioThreshold == 0 && params.pool1RatioThreshold == 0)
            // Logic validation: pool0RatioThreshold should pair with withdrawToken0Only or withdrawAll
            // If pool is 95% token0, you should withdraw token0 (not token1 which doesn't exist)
            || (params.pool0RatioThreshold != 0 && params.withdrawToken1Only)
            // Logic validation: pool1RatioThreshold should pair with withdrawToken1Only or withdrawAll
            // If pool is 95% token1, you should withdraw token1 (not token0 which doesn't exist)
            || (params.pool1RatioThreshold != 0 && params.withdrawToken0Only)
        ) {
            revert IRelayer.InvalidWithdrawalParams();
        }
    }
}

// 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: 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;

/// @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 66 of 85 : 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 69 of 85 : 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
// 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 72 of 85 : 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: 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: 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
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
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 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 79 of 85 : 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: 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: 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
// 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/RebalancerFactory.sol": {
      "RelayerLogic": "0x23dd9c89038a9ade8128f0601e74ab0610f5c043"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract IMultiPositionFactory","name":"_multiPositionFactory","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InsufficientPayment","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidTwapConfig","type":"error"},{"inputs":[],"name":"InvalidWeightSum","type":"error"},{"inputs":[],"name":"MutuallyExclusiveTriggers","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PoolNotManagedByVolatilityHook","type":"error"},{"inputs":[],"name":"RelayerAlreadyExists","type":"error"},{"inputs":[],"name":"TwapHistoryUnavailable","type":"error"},{"inputs":[],"name":"UnauthorizedAccess","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldMinBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newMinBalance","type":"uint256"}],"name":"MinBalanceUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"relayer","type":"address"},{"indexed":true,"internalType":"address","name":"multiPositionManager","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"}],"name":"RelayerDeployed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"inputs":[],"name":"AUTOMATION_SERVICE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"automatedManagementFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"mpm","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"components":[{"internalType":"uint24","name":"baseLowerTrigger","type":"uint24"},{"internalType":"uint24","name":"baseUpperTrigger","type":"uint24"},{"internalType":"uint24","name":"limitDeltaTicks","type":"uint24"},{"internalType":"uint24","name":"maxDeltaTicks","type":"uint24"},{"internalType":"uint24","name":"baseTwapTickTrigger","type":"uint24"},{"internalType":"uint256","name":"baseMinRatio","type":"uint256"},{"internalType":"uint256","name":"baseMaxRatio","type":"uint256"},{"internalType":"uint256","name":"limitMinRatio","type":"uint256"},{"internalType":"uint256","name":"limitThreshold","type":"uint256"},{"internalType":"uint256","name":"outOfPositionThreshold","type":"uint256"}],"internalType":"struct IRelayer.TriggerConfig","name":"triggerConfig","type":"tuple"},{"components":[{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"isolatedBaseLimitRebalancing","type":"bool"},{"internalType":"bool","name":"useRebalanceSwap","type":"bool"},{"internalType":"bool","name":"isBaseRatio","type":"bool"},{"internalType":"bool","name":"compoundFees","type":"bool"}],"internalType":"struct IRelayer.StrategyParams","name":"strategyParams","type":"tuple"},{"components":[{"internalType":"string","name":"geckoIdToken0","type":"string"},{"internalType":"string","name":"geckoIdToken1","type":"string"},{"internalType":"uint8","name":"pairType","type":"uint8"}],"internalType":"struct IRelayer.VolatilityParams","name":"volatilityParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"pool0RatioThreshold","type":"uint256"},{"internalType":"uint256","name":"pool1RatioThreshold","type":"uint256"},{"internalType":"bool","name":"withdrawAll","type":"bool"},{"internalType":"bool","name":"withdrawToken0Only","type":"bool"},{"internalType":"bool","name":"withdrawToken1Only","type":"bool"}],"internalType":"struct IRelayer.WithdrawalParams","name":"withdrawalParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"outOfPositionRatioThreshold","type":"uint256"}],"internalType":"struct IRelayer.CompoundSwapParams","name":"compoundSwapParams","type":"tuple"},{"components":[{"internalType":"bool","name":"useTwapProtection","type":"bool"},{"internalType":"bool","name":"useTwapCenter","type":"bool"},{"internalType":"uint32","name":"twapSeconds","type":"uint32"},{"internalType":"uint24","name":"maxTickDeviation","type":"uint24"}],"internalType":"struct IRelayer.TwapParams","name":"twapParams","type":"tuple"}],"name":"computeRelayerAddress","outputs":[{"internalType":"address","name":"predicted","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"mpm","type":"address"},{"components":[{"internalType":"uint24","name":"baseLowerTrigger","type":"uint24"},{"internalType":"uint24","name":"baseUpperTrigger","type":"uint24"},{"internalType":"uint24","name":"limitDeltaTicks","type":"uint24"},{"internalType":"uint24","name":"maxDeltaTicks","type":"uint24"},{"internalType":"uint24","name":"baseTwapTickTrigger","type":"uint24"},{"internalType":"uint256","name":"baseMinRatio","type":"uint256"},{"internalType":"uint256","name":"baseMaxRatio","type":"uint256"},{"internalType":"uint256","name":"limitMinRatio","type":"uint256"},{"internalType":"uint256","name":"limitThreshold","type":"uint256"},{"internalType":"uint256","name":"outOfPositionThreshold","type":"uint256"}],"internalType":"struct IRelayer.TriggerConfig","name":"triggerConfig","type":"tuple"},{"components":[{"internalType":"uint24","name":"ticksLeft","type":"uint24"},{"internalType":"uint24","name":"ticksRight","type":"uint24"},{"internalType":"bool","name":"useCarpet","type":"bool"},{"internalType":"uint24","name":"limitWidth","type":"uint24"},{"internalType":"address","name":"strategy","type":"address"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"isolatedBaseLimitRebalancing","type":"bool"},{"internalType":"bool","name":"useRebalanceSwap","type":"bool"},{"internalType":"bool","name":"isBaseRatio","type":"bool"},{"internalType":"bool","name":"compoundFees","type":"bool"}],"internalType":"struct IRelayer.StrategyParams","name":"strategyParams","type":"tuple"},{"components":[{"internalType":"string","name":"geckoIdToken0","type":"string"},{"internalType":"string","name":"geckoIdToken1","type":"string"},{"internalType":"uint8","name":"pairType","type":"uint8"}],"internalType":"struct IRelayer.VolatilityParams","name":"volatilityParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"pool0RatioThreshold","type":"uint256"},{"internalType":"uint256","name":"pool1RatioThreshold","type":"uint256"},{"internalType":"bool","name":"withdrawAll","type":"bool"},{"internalType":"bool","name":"withdrawToken0Only","type":"bool"},{"internalType":"bool","name":"withdrawToken1Only","type":"bool"}],"internalType":"struct IRelayer.WithdrawalParams","name":"withdrawalParams","type":"tuple"},{"components":[{"internalType":"uint256","name":"outOfPositionRatioThreshold","type":"uint256"}],"internalType":"struct IRelayer.CompoundSwapParams","name":"compoundSwapParams","type":"tuple"},{"components":[{"internalType":"bool","name":"useTwapProtection","type":"bool"},{"internalType":"bool","name":"useTwapCenter","type":"bool"},{"internalType":"uint32","name":"twapSeconds","type":"uint32"},{"internalType":"uint24","name":"maxTickDeviation","type":"uint24"}],"internalType":"struct IRelayer.TwapParams","name":"twapParams","type":"tuple"}],"name":"deployRelayer","outputs":[{"internalType":"address","name":"relayer","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"deployer","outputs":[{"internalType":"contract RebalancerDeployer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getAllRelayersPaginated","outputs":[{"components":[{"internalType":"address","name":"relayerAddress","type":"address"},{"internalType":"address","name":"multiPositionManager","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"deployedAt","type":"uint256"}],"internalType":"struct IRelayerFactory.RelayerInfo[]","name":"relayersInfo","type":"tuple[]"},{"internalType":"uint256","name":"totalCount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"mpm","type":"address"}],"name":"getRelayerByManager","outputs":[{"internalType":"address","name":"relayerAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"relayer","type":"address"}],"name":"getRelayerInfo","outputs":[{"components":[{"internalType":"address","name":"relayerAddress","type":"address"},{"internalType":"address","name":"multiPositionManager","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"deployedAt","type":"uint256"}],"internalType":"struct IRelayerFactory.RelayerInfo","name":"info","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"ownerAddress","type":"address"}],"name":"getRelayersByOwner","outputs":[{"internalType":"address[]","name":"relayersArray","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalRelayersCount","outputs":[{"internalType":"uint256","name":"count","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getUniqueTokenPairs","outputs":[{"components":[{"internalType":"string","name":"token0Symbol","type":"string"},{"internalType":"address","name":"token0Address","type":"address"},{"internalType":"string","name":"token1Symbol","type":"string"},{"internalType":"address","name":"token1Address","type":"address"},{"internalType":"uint8","name":"token0Decimals","type":"uint8"},{"internalType":"uint8","name":"token1Decimals","type":"uint8"}],"internalType":"struct IRelayerFactory.TokenPairInfo[]","name":"tokenPairs","type":"tuple[]"},{"internalType":"uint256","name":"totalCount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRoleOrOwner","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"multiPositionFactory","outputs":[{"internalType":"contract IMultiPositionFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"relayerByManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"relayers","outputs":[{"internalType":"address","name":"relayerAddress","type":"address"},{"internalType":"address","name":"multiPositionManager","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"deployedAt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"relayersByOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_fee","type":"uint16"}],"name":"setAutomatedManagementFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMinBalance","type":"uint256"}],"name":"setMinBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60c06040526006805461ffff1916600a1790556509184e72a000600755348015610027575f80fd5b5060405161856b38038061856b83398101604081905261004691610198565b816001600160a01b03811661007457604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61007d81610125565b506001600160a01b0382166100a55760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0381166100cc5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b03811660805260405130906100e790610174565b6001600160a01b039091168152602001604051809103905ff080158015610110573d5f803e3d5ffd5b506001600160a01b031660a052506101d09050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b615bb9806129b283390190565b6001600160a01b0381168114610195575f80fd5b50565b5f80604083850312156101a9575f80fd5b82516101b481610181565b60208401519092506101c581610181565b809150509250929050565b60805160a0516127a561020d5f395f81816104e2015281816108e5015261128601525f818161059901528181610737015261076601526127a55ff3fe60806040526004361061018e575f3560e01c806391d14854116100dc578063d547741f11610087578063e8ae2b6911610062578063e8ae2b6914610537578063ed90116014610556578063f2fde38b14610569578063fc3d920e14610588575f80fd5b8063d547741f146104b2578063d5f39488146104d1578063dcf4cf9614610504575f80fd5b8063c4edff84116100b7578063c4edff8414610451578063c5bb87581461047e578063c91d956c14610493575f80fd5b806391d14854146103c95780639c9d5d68146103f8578063af7f84fe14610424575f80fd5b80635df654951161013c5780637614b4cd116101175780637614b4cd1461037057806381509e601461038f5780638da5cb5b146103ad575f80fd5b80635df65495146103105780635e0000a01461033d578063715018a61461035c575f80fd5b80632f2ff15d1161016c5780632f2ff15d1461024a5780634e7284cd1461026b5780635300f8411461028a575f80fd5b806306bfd20b146101925780631b048054146101c75780631dd2e68f14610213575b5f80fd5b34801561019d575f80fd5b506101b16101ac366004611c14565b6105bb565b6040516101be9190611c2f565b60405180910390f35b3480156101d2575f80fd5b506101fb6101e1366004611c14565b60036020525f90815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016101be565b34801561021e575f80fd5b506101fb61022d366004611c14565b6001600160a01b039081165f908152600360205260409020541690565b348015610255575f80fd5b50610269610264366004611c79565b61064c565b005b348015610276575f80fd5b506101fb610285366004611ca7565b610701565b348015610295575f80fd5b506102db6102a4366004611c14565b600260208190525f918252604090912080546001820154928201546003909201546001600160a01b03918216938216929091169084565b6040516101be94939291906001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b34801561031b575f80fd5b5060065461032a9061ffff1681565b60405161ffff90911681526020016101be565b348015610348575f80fd5b50610269610357366004611cd1565b610735565b348015610367575f80fd5b506102696108b9565b34801561037b575f80fd5b506101fb61038a366004611d5a565b6108cc565b34801561039a575f80fd5b506005545b6040519081526020016101be565b3480156103b8575f80fd5b505f546001600160a01b03166101fb565b3480156103d4575f80fd5b506103e86103e3366004611c79565b610976565b60405190151581526020016101be565b348015610403575f80fd5b50610417610412366004611c14565b6109a2565b6040516101be9190611e14565b34801561042f575f80fd5b5061044361043e366004611e5f565b610a15565b6040516101be929190611e7f565b34801561045c575f80fd5b5061047061046b366004611e5f565b610bc2565b6040516101be929190611f40565b348015610489575f80fd5b5061039f60075481565b34801561049e575f80fd5b506102696104ad366004612018565b611000565b3480156104bd575f80fd5b506102696104cc366004611c79565b61106d565b3480156104dc575f80fd5b506101fb7f000000000000000000000000000000000000000000000000000000000000000081565b34801561050f575f80fd5b5061039f7ff688e31edd11ef8893fafe7d794fed44b1d68e9104656ba21c2bc086e624b6c481565b348015610542575f80fd5b506103e8610551366004611c79565b6110f6565b6101fb61056436600461202f565b61113a565b348015610574575f80fd5b50610269610583366004611c14565b6114b9565b348015610593575f80fd5b506101fb7f000000000000000000000000000000000000000000000000000000000000000081565b60408051608080820183525f808352602080840182905283850182905260609384018290526001600160a01b038681168352600280835292869020865194850187528054821680865260018201548316938601939093529283015416948301949094526003015491810191909152906106475760405163e6c4247b60e01b815260040160405180910390fd5b919050565b6106546114fb565b6001600160a01b03811661067b5760405163e6c4247b60e01b815260040160405180910390fd5b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff166106fd575f8281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45b5050565b6004602052815f5260405f20818154811061071a575f80fd5b5f918252602090912001546001600160a01b03169150829050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166391d148547f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ea26266c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e491906120d7565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526004810191909152336024820152604401602060405180830381865afa15801561083c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061086091906120fb565b61087d57604051631a27eac360e11b815260040160405180910390fd5b8061ffff165f036108a15760405163e6c4247b60e01b815260040160405180910390fd5b6006805461ffff191661ffff92909216919091179055565b6108c16114fb565b6108ca5f611527565b565b60405163169ade0360e31b81525f906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063b4d6f0189061092a908c9030908d908d908d908d908d908d908d906004016123b4565b602060405180830381865afa158015610945573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096991906124de565b9998505050505050505050565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff165b92915050565b6001600160a01b0381165f90815260046020908152604091829020805483518184028101840190945280845260609392830182828015610a0957602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116109eb575b50505050509050919050565b6005546060905f839003610a27578092505b808410610a7d57604080515f8082526020820190925290610a75565b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610a435790505b509150610bbb565b5f81610a898587612521565b11610a945783610a9e565b610a9e8583612534565b90508067ffffffffffffffff811115610ab957610ab96124f9565b604051908082528060200260200182016040528015610b0957816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610ad75790505b5092505f5b81811015610bb8575f6005610b238389612521565b81548110610b3357610b33612547565b5f9182526020808320909101546001600160a01b039081168084526002808452604094859020855160808101875281548516815260018201548516958101959095529081015490921693830193909352600301546060820152865191925090869084908110610ba457610ba4612547565b602090810291909101015250600101610b0e565b50505b9250929050565b60605f8060058054905067ffffffffffffffff811115610be457610be46124f9565b604051908082528060200260200182016040528015610c4357816020015b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610c025790505b5090505f805b600554811015610e8f575f60058281548110610c6757610c67612547565b5f9182526020808320909101546040805163481c6a7560e01b815290516001600160a01b039092169450849392849263481c6a759260048082019392918290030181865afa158015610cbb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cdf91906124de565b90505f816001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610d1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d42919061259d565b80516020820151919250905f805b89811015610dda57836001600160a01b03168b8281518110610d7457610d74612547565b6020026020010151602001516001600160a01b0316148015610dc45750826001600160a01b03168b8281518110610dad57610dad612547565b6020026020010151606001516001600160a01b0316145b15610dd25760019150610dda565b600101610d50565b5080610e7d575f610dea84611583565b90505f610df684611583565b90505f610e0286611614565b90505f610e0e86611614565b90506040518060c00160405280858152602001886001600160a01b03168152602001848152602001876001600160a01b031681526020018360ff1681526020018260ff168152508e8e81518110610e6757610e67612547565b60200260200101819052508c6001019c50505050505b87600101975050505050505050610c49565b50809250845f03610e9e578294505b828610610f0557604080515f8082526020820190925290610efb565b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610eba5790505b5093505050610bbb565b5f83610f118789612521565b11610f1c5785610f26565b610f268785612534565b90508067ffffffffffffffff811115610f4157610f416124f9565b604051908082528060200260200182016040528015610fa057816020015b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610f5f5790505b5094505f5b81811015610ff55783610fb8828a612521565b81518110610fc857610fc8612547565b6020026020010151868281518110610fe257610fe2612547565b6020908102919091010152600101610fa5565b505050509250929050565b6110086114fb565b805f036110285760405163e6c4247b60e01b815260040160405180910390fd5b600780549082905560408051828152602081018490527f65d057080f4c8634a11330806ded4bb764a6416376e126938311cf1cda7f1081910160405180910390a15050565b6110756114fb565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff16156106fd575f8281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b5f80546001600160a01b038381169116148061113357505f8381526001602090815260408083206001600160a01b038616845290915290205460ff165b9392505050565b5f60075434101561115e5760405163cd1c886760e01b815260040160405180910390fd5b6001600160a01b0388166111855760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b038881165f9081526003602052604090205416156111bc576040516205738360ea1b815260040160405180910390fd5b5f886001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061121d91906124de565b9050336001600160a01b0382161461124857604051631a27eac360e11b815260040160405180910390fd5b61125a8760a001358860c0013561168b565b611263876116eb565b61126f89898986611756565b6040516352907b9d60e01b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906352907b9d906112cb908c90309086908e908e908e908e908e908e906004016123b4565b6020604051808303815f875af11580156112e7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061130b91906124de565b91503415611385575f826001600160a01b0316346040515f6040518083038185875af1925050503d805f811461135c576040519150601f19603f3d011682016040523d82523d5f602084013e611361565b606091505b50509050806113835760405163e6c4247b60e01b815260040160405180910390fd5b505b604080516080810182526001600160a01b038085168083528c8216602080850182815287851686880181815242606089019081525f87815260028087528b82209a518b54908b1673ffffffffffffffffffffffffffffffffffffffff19918216178c5595516001808d018054928d16928916929092179091559351908b01805491909a16908616179098555160039889015584875296835287862080548316861790558086526004835287862080548089018255908752928620909201805482168517905560058054968701815585527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db090950180549095168317909455935192939290917f7693e4b27904de2418f1de7feb4e3e3e0aa788e2262b3b4eae57f4c9623cb13691a450979650505050505050565b6114c16114fb565b6001600160a01b0381166114ef57604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b6114f881611527565b50565b5f546001600160a01b031633146108ca5760405163118cdaa760e01b81523360048201526024016114e6565b5f80546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60606001600160a01b0382166115b257505060408051808201909152600381526208aa8960eb1b602082015290565b816001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa1580156115ed573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261099c9190810190612633565b5f6001600160a01b03821661162b57506012919050565b816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611667573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061099c91906126c7565b5f82158015611698575081155b90505f836706f05b59d3b200001480156116b95750826706f05b59d3b20000145b9050811580156116c7575080155b156116e55760405163940addc760e01b815260040160405180910390fd5b50505050565b5f60a0820135158015611700575060c0820135155b9050611714610140830161012084016126e2565b801561171d5750805b80156117385750611736610120830161010084016126e2565b155b156106fd5760405163e6c4247b60e01b815260040160405180910390fd5b61176360208201826126e2565b15801561177d575061177b60408201602083016126e2565b155b801561179b575061179460a08401608085016126fd565b62ffffff16155b6116e5575f8490505f816001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156117e0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611804919061259d565b60808101519091506001600160a01b0381166118325760405162f61f7960e41b815260040160405180910390fd5b806001600160a01b03166326a1161761184c8460a0902090565b6040518263ffffffff1660e01b815260040161186a91815260200190565b602060405180830381865afa9250505080156118a3575060408051601f3d908101601f191682019092526118a0918101906120fb565b60015b6118bf5760405162f61f7960e41b815260040160405180910390fd5b806118dc5760405162f61f7960e41b815260040160405180910390fd5b505f8190505f816001600160a01b03166355b13a4f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561191e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061194291906124de565b90506001600160a01b0381166362aaf2668561196460608a0160408b01612718565b604080517fffffffff0000000000000000000000000000000000000000000000000000000060e086901b16815283516001600160a01b0390811660048301526020850151811660248301529184015162ffffff166044820152606084015160020b606482015260809093015116608483015263ffffffff1660a482015260c4016040805180830381865afa925050508015611a1c575060408051601f3d908101601f19168201909252611a1991810190612731565b60015b611a3957604051635d2c8bcb60e11b815260040160405180910390fd5b50505f611a4960208a018a6126fd565b62ffffff16151580611a6e5750611a6660408a0160208b016126fd565b62ffffff1615155b90505f611a8160a08b0160808c016126fd565b62ffffff1615159050818015611a945750805b15611ab2576040516318964e4d60e21b815260040160405180910390fd5b611ac26040890160208a016126e2565b8015611adb5750611adb6101408a016101208b016126e2565b15611af95760405163b24184b760e01b815260040160405180910390fd5b808015611b135750611b136101408a016101208b016126e2565b15611b315760405163b24184b760e01b815260040160405180910390fd5b611b416060890160408a01612718565b63ffffffff165f03611b665760405163b24184b760e01b815260040160405180910390fd5b62093a80611b7a60608a0160408b01612718565b63ffffffff161115611b9f5760405163b24184b760e01b815260040160405180910390fd5b611bac60208901896126e2565b8015611bca5750611bc36080890160608a016126fd565b62ffffff16155b15611be85760405163b24184b760e01b815260040160405180910390fd5b5050505050505050505050565b6001600160a01b03811681146114f8575f80fd5b803561064781611bf5565b5f60208284031215611c24575f80fd5b813561113381611bf5565b6080810161099c82846001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b036040820151166040830152606081015160608301525050565b5f8060408385031215611c8a575f80fd5b823591506020830135611c9c81611bf5565b809150509250929050565b5f8060408385031215611cb8575f80fd5b8235611cc381611bf5565b946020939093013593505050565b5f60208284031215611ce1575f80fd5b813561ffff81168114611133575f80fd5b5f6101408284031215611d03575f80fd5b50919050565b5f6101608284031215611d03575f80fd5b5f60608284031215611d03575f80fd5b5f60a08284031215611d03575f80fd5b5f60208284031215611d03575f80fd5b5f60808284031215611d03575f80fd5b5f805f805f805f80610440898b031215611d72575f80fd5b8835611d7d81611bf5565b97506020890135611d8d81611bf5565b9650611d9c8a60408b01611cf2565b9550611dac8a6101808b01611d09565b94506102e089013567ffffffffffffffff811115611dc8575f80fd5b611dd48b828c01611d1a565b945050611de58a6103008b01611d2a565b9250611df58a6103a08b01611d3a565b9150611e058a6103c08b01611d4a565b90509295985092959890939650565b602080825282518282018190525f918401906040840190835b81811015611e545783516001600160a01b0316835260209384019390920191600101611e2d565b509095945050505050565b5f8060408385031215611e70575f80fd5b50508035926020909101359150565b604080825283519082018190525f9060208501906060840190835b81811015611eff57611ee98385516001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b036040820151166040830152606081015160608301525050565b6020939093019260809290920191600101611e9a565b5050602093909301939093525092915050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f604082016040835280855180835260608501915060608160051b8601019250602087015f5b8281101561200457605f198786030184528151805160c08752611f8c60c0880182611f12565b90506001600160a01b03602083015116602088015260408201518782036040890152611fb88282611f12565b9150506001600160a01b03606083015116606088015260ff608083015116608088015260ff60a08301511660a08801528096505050602082019150602084019350600181019050611f66565b505050506020929092019290925292915050565b5f60208284031215612028575f80fd5b5035919050565b5f805f805f805f610420888a031215612046575f80fd5b873561205181611bf5565b96506120608960208a01611cf2565b9550612070896101608a01611d09565b94506102c088013567ffffffffffffffff81111561208c575f80fd5b6120988a828b01611d1a565b9450506120a9896102e08a01611d2a565b92506120b9896103808a01611d3a565b91506120c9896103a08a01611d4a565b905092959891949750929550565b5f602082840312156120e7575f80fd5b5051919050565b80151581146114f8575f80fd5b5f6020828403121561210b575f80fd5b8151611133816120ee565b62ffffff811681146114f8575f80fd5b803561064781612116565b8035610647816120ee565b6121528261214983612126565b62ffffff169052565b61215e60208201612126565b62ffffff16602083015261217460408201612131565b1515604083015261218760608201612126565b62ffffff16606083015261219d60808201611c09565b6001600160a01b0316608083015260a0818101359083015260c080820135908301526121cb60e08201612131565b151560e08301526121df6101008201612131565b15156101008301526121f46101208201612131565b15156101208301526122096101408201612131565b801515610140840152505050565b5f808335601e1984360301811261222c575f80fd5b830160208101925035905067ffffffffffffffff81111561224b575f80fd5b803603821315610bbb575f80fd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60ff811681146114f8575f80fd5b5f61229a8283612217565b606085526122ac606086018284612259565b9150506122bc6020840184612217565b85830360208701526122cf838284612259565b9250505060408301356122e181612281565b60ff81166040860152508091505092915050565b80358252602080820135908301526040810135612311816120ee565b151560408301526060810135612326816120ee565b15156060830152608081013561233b816120ee565b8015156080840152505050565b803563ffffffff81168114610647575f80fd5b8035612366816120ee565b151582526020810135612378816120ee565b1515602083015263ffffffff61239060408301612348565b16604083015260608101356123a481612116565b62ffffff81166060840152505050565b6001600160a01b038a1681526001600160a01b03891660208201526001600160a01b03881660408201526123ee6060820161214989612126565b5f6123fb60208901612126565b62ffffff16608083015261241160408901612126565b62ffffff1660a083015261242760608901612126565b62ffffff1660c083015261243d60808901612126565b62ffffff811660e08401525060a08801356101008381019190915260c08901356101208085019190915260e08a0135610140850152908901356101608401528801356101808301526124936101a083018861213c565b6104606103008301526124aa61046083018761228f565b90506124ba6103208301866122f5565b83356103c08301526124d06103e083018461235b565b9a9950505050505050505050565b5f602082840312156124ee575f80fd5b815161113381611bf5565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082018082111561099c5761099c61250d565b8181038181111561099c5761099c61250d565b634e487b7160e01b5f52603260045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715612584576125846124f9565b604052919050565b8051600281900b8114610647575f80fd5b5f60a08284031280156125ae575f80fd5b5060405160a0810167ffffffffffffffff811182821017156125d2576125d26124f9565b60405282516125e081611bf5565b815260208301516125f081611bf5565b6020820152604083015161260381612116565b60408201526126146060840161258c565b6060820152608083015161262781611bf5565b60808201529392505050565b5f60208284031215612643575f80fd5b815167ffffffffffffffff811115612659575f80fd5b8201601f81018413612669575f80fd5b805167ffffffffffffffff811115612683576126836124f9565b612696601f8201601f191660200161255b565b8181528560208385010111156126aa575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f602082840312156126d7575f80fd5b815161113381612281565b5f602082840312156126f2575f80fd5b8135611133816120ee565b5f6020828403121561270d575f80fd5b813561113381612116565b5f60208284031215612728575f80fd5b61113382612348565b5f8060408385031215612742575f80fd5b61274b8361258c565b915060208301516fffffffffffffffffffffffffffffffff81168114611c9c575f80fdfea26469706673582212203def67b279757228ad81130f322be91e2ee54a87b3dbee5ed2efe681d3f0a9e564736f6c634300081a003360a0604052348015600e575f80fd5b50604051615bb9380380615bb9833981016040819052602b91603b565b6001600160a01b03166080526066565b5f60208284031215604a575f80fd5b81516001600160a01b0381168114605f575f80fd5b9392505050565b608051615b366100835f395f81816048015260b80152615b365ff3fe608060405234801561000f575f80fd5b506004361061003f575f3560e01c80630852f9f31461004357806352907b9d14610086578063b4d6f01814610099575b5f80fd5b61006a7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200160405180910390f35b61006a610094366004610323565b6100ac565b61006a6100a7366004610323565b61018e565b5f336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146100f657604051635c427cd960e01b815260040160405180910390fd5b6040516bffffffffffffffffffffffff1960608c811b821660208401528a901b1660348201525f90604801604051602081830303815290604052805190602001209050808b8b8b8b8b8b8b8b8b60405161014f906102b5565b61016199989796959493929190610675565b8190604051809103905ff590508015801561017e573d5f803e3d5ffd5b509b9a5050505050505050505050565b5f80604051806020016101a0906102b5565b601f1982820381018352601f9091011660408190526101d3908d908d908d908d908d908d908d908d908d90602001610675565b60408051601f19818403018152908290526101f192916020016107b6565b60408051808303601f19018152828252805160209182012060608f811b6bffffffffffffffffffffffff19908116848701528e821b811660348701528451602881880301815260488701909552845194909301939093207fff0000000000000000000000000000000000000000000000000000000000000060688601523090931b9091166069840152607d830191909152609d8201819052915060bd0160408051601f1981840301815291905280516020909101209b9a5050505050505050505050565b61532e806107d383390190565b80356001600160a01b03811681146102d8575f80fd5b919050565b5f606082840312156102ed575f80fd5b50919050565b5f60a082840312156102ed575f80fd5b5f602082840312156102ed575f80fd5b5f608082840312156102ed575f80fd5b5f805f805f805f805f898b0361046081121561033d575f80fd5b6103468b6102c2565b995061035460208c016102c2565b985061036260408c016102c2565b9750610140605f1982011215610376575f80fd5b60608b01965061016061019f198201121561038f575f80fd5b506101a08a0194506103008a013567ffffffffffffffff8111156103b1575f80fd5b6103bd8c828d016102dd565b9450506103ce8b6103208c016102f3565b92506103de8b6103c08c01610303565b91506103ee8b6103e08c01610313565b90509295985092959850929598565b803562ffffff811681146102d8575f80fd5b803580151581146102d8575f80fd5b6104348261042b836103fd565b62ffffff169052565b610440602082016103fd565b62ffffff1660208301526104566040820161040f565b15156040830152610469606082016103fd565b62ffffff16606083015261047f608082016102c2565b6001600160a01b0316608083015260a0818101359083015260c080820135908301526104ad60e0820161040f565b151560e08301526104c1610100820161040f565b15156101008301526104d6610120820161040f565b15156101208301526104eb610140820161040f565b801515610140840152505050565b5f808335601e1984360301811261050e575f80fd5b830160208101925035905067ffffffffffffffff81111561052d575f80fd5b80360382131561053b575f80fd5b9250929050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b5f61057582836104f9565b60608552610587606086018284610542565b91505061059760208401846104f9565b85830360208701526105aa838284610542565b92505050604083013560ff81168082146105c2575f80fd5b604095909501949094529392505050565b80358252602080820135908301526105ed6040820161040f565b151560408301526106006060820161040f565b151560608301526106136080820161040f565b151560808301525050565b6106278161040f565b151582526106376020820161040f565b15156020830152604081013563ffffffff8116808214610655575f80fd5b60408401525062ffffff61066b606083016103fd565b1660608301525050565b6001600160a01b038a1681526001600160a01b03891660208201526001600160a01b03881660408201526106af6060820161042b896103fd565b5f6106bc602089016103fd565b62ffffff1660808301526106d2604089016103fd565b62ffffff1660a08301526106e8606089016103fd565b62ffffff1660c08301526106fe608089016103fd565b62ffffff811660e08401525060a08801356101008381019190915260c08901356101208085019190915260e08a0135610140850152908901356101608401528801356101808301526107546101a083018861041e565b61046061030083015261076b61046083018761056a565b905061077b6103208301866105d3565b83356103c08301526107916103e083018461061e565b9a9950505050505050505050565b5f81518060208401855e5f93019283525090919050565b5f6107ca6107c4838661079f565b8461079f565b94935050505056fe60c060405234801561000f575f80fd5b5060405161532e38038061532e83398101604081905261002e91610ef1565b60015f556001600160a01b03891661005957604051632e205f8760e01b815260040160405180910390fd5b6001600160a01b03881661008057604051632e205f8760e01b815260040160405180910390fd5b6001600160a01b0387166100a757604051632e205f8760e01b815260040160405180910390fd5b6001600160a01b03808a16608081905290891660a09081526040805163182148ef60e01b815290515f939263182148ef92600480820193918290030181865afa1580156100f6573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061011a919061106a565b60600151875190915061012d90826105b4565b62ffffff168752602087015161014390826105b4565b62ffffff166020880152604087015161015c90826105b4565b62ffffff166040880152606087015161017590826105b4565b62ffffff16606088018190528751602089015160408a015161019693610603565b6101ae8660a001518760c001516106c860201b60201c565b85604001516101d057604051632e205f8760e01b815260040160405180910390fd5b5f8660a001515f1480156101e6575060c0870151155b905086610120015180156101f75750805b80156102065750866101000151155b1561022457604051632e205f8760e01b815260040160405180910390fd5b6003866040015160ff16111561024d5760405163cff7bdd160e01b815260040160405180910390fd5b61025883898961071f565b8760015f015f820151815f015f6101000a81548162ffffff021916908362ffffff1602179055506020820151815f0160036101000a81548162ffffff021916908362ffffff1602179055506040820151815f0160066101000a81548162ffffff021916908362ffffff1602179055506060820151815f0160096101000a81548162ffffff021916908362ffffff1602179055506080820151815f01600c6101000a81548162ffffff021916908362ffffff16021790555060a0820151816001015560c0820151816002015560e08201518160030155610100820151816004015561012082015181600501559050508660016006015f820151815f015f6101000a81548162ffffff021916908362ffffff1602179055506020820151815f0160036101000a81548162ffffff021916908362ffffff1602179055506040820151815f0160066101000a81548160ff0219169083151502179055506060820151815f0160076101000a81548162ffffff021916908362ffffff1602179055506080820151815f01600a6101000a8154816001600160a01b0302191690836001600160a01b0316021790555060a0820151816001015560c0820151816002015560e0820151816003015f6101000a81548160ff0219169083151502179055506101008201518160030160016101000a81548160ff0219169083151502179055506101208201518160030160026101000a81548160ff0219169083151502179055506101408201518160030160036101000a81548160ff021916908315150217905550905050856001600a015f820151815f0190816104b39190611164565b50602082015160018201906104c89082611164565b506040918201516002909101805460ff90921660ff199092169190911790558551600e55602080870151600f5586820151601080546060808b01516080909b015115156201000090810262ff0000199c151561010090810261ff0019971515881661ffff1996871617179d909d16179093559851601155875160128054958a0151968a015199909a015162ffffff1666010000000000000262ffffff60301b1963ffffffff909a169093029890981668ffffffffffffff000019951515909a029715159092169290911691909117949094171694909417919091179091555061133a9650505050505050565b5f8262ffffff165f036105c857505f6105fd565b600282900b808060016105db8288611232565b6105e5919061124d565b6105ef9190611268565b6105f99190611299565b9150505b92915050565b62ffffff8116156106c25762ffffff84161580159061062c57508362ffffff168162ffffff1611155b1561064a57604051632e205f8760e01b815260040160405180910390fd5b62ffffff83161580159061066857508262ffffff168162ffffff1611155b1561068657604051632e205f8760e01b815260040160405180910390fd5b62ffffff8216158015906106a457508162ffffff168162ffffff1611155b156106c257604051632e205f8760e01b815260040160405180910390fd5b50505050565b5f821580156106d5575081155b90505f836706f05b59d3b200001480156106f65750826706f05b59d3b20000145b9050811580156106a45750806106c257604051632e205f8760e01b815260040160405180910390fd5b825115801561073057508260200151155b80156107435750608082015162ffffff16155b1561074d57505050565b81515f9062ffffff1615158061076b5750602083015162ffffff1615155b608084015190915062ffffff1615158180156107845750805b156107a257604051632e205f8760e01b815260040160405180910390fd5b846020015180156107b557508261012001515b156107d35760405163b24184b760e01b815260040160405180910390fd5b8080156107e257508261012001515b156108005760405163b24184b760e01b815260040160405180910390fd5b846040015163ffffffff165f0361082a5760405163b24184b760e01b815260040160405180910390fd5b62093a80856040015163ffffffff1611156108585760405163b24184b760e01b815260040160405180910390fd5b8451801561086d5750606085015162ffffff16155b1561088b5760405163b24184b760e01b815260040160405180910390fd5b5f6080516001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156108ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ee919061106a565b60808101519091506001600160a01b03811661091c5760405162f61f7960e41b815260040160405180910390fd5b6001600160a01b0381166326a116176109368460a0902090565b6040518263ffffffff1660e01b815260040161095491815260200190565b602060405180830381865afa92505050801561098d575060408051601f3d908101601f1916820190925261098a918101906112be565b60015b6109a95760405162f61f7960e41b815260040160405180910390fd5b806109c65760405162f61f7960e41b815260040160405180910390fd5b505f8190505f816001600160a01b03166355b13a4f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a08573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a2c91906112de565b6040808b01518151633155793360e11b815287516001600160a01b0390811660048301526020890151811660248301529288015162ffffff166044820152606088015160020b606482015260808801518316608482015263ffffffff90911660a48201529192508216906362aaf2669060c4016040805180830381865afa925050508015610ad7575060408051601f3d908101601f19168201909252610ad4918101906112f9565b60015b610af457604051635d2c8bcb60e11b815260040160405180910390fd5b5050505050505050505050565b6001600160a01b0381168114610b15575f80fd5b50565b8051610b2381610b01565b919050565b634e487b7160e01b5f52604160045260245ffd5b60405161016081016001600160401b0381118282101715610b5f57610b5f610b28565b60405290565b60405160a081016001600160401b0381118282101715610b5f57610b5f610b28565b60405161014081016001600160401b0381118282101715610b5f57610b5f610b28565b805162ffffff81168114610b23575f80fd5b80518015158114610b23575f80fd5b5f6101608284031215610bdc575f80fd5b610be4610b3c565b9050610bef82610baa565b8152610bfd60208301610baa565b6020820152610c0e60408301610bbc565b6040820152610c1f60608301610baa565b6060820152610c3060808301610b18565b608082015260a0828101519082015260c08083015190820152610c5560e08301610bbc565b60e0820152610c676101008301610bbc565b610100820152610c7a6101208301610bbc565b610120820152610c8d6101408301610bbc565b61014082015292915050565b5f82601f830112610ca8575f80fd5b81516001600160401b03811115610cc157610cc1610b28565b604051601f8201601f19908116603f011681016001600160401b0381118282101715610cef57610cef610b28565b604052818152838201602001851015610d06575f80fd5b8160208501602083015e5f918101602001919091529392505050565b5f60608284031215610d32575f80fd5b604051606081016001600160401b0381118282101715610d5457610d54610b28565b604052825190915081906001600160401b03811115610d71575f80fd5b610d7d85828601610c99565b82525060208301516001600160401b03811115610d98575f80fd5b610da485828601610c99565b602083015250604083015160ff81168114610dbd575f80fd5b6040919091015292915050565b5f60a08284031215610dda575f80fd5b610de2610b65565b82518152602080840151908201529050610dfe60408301610bbc565b6040820152610e0f60608301610bbc565b6060820152610e2060808301610bbc565b608082015292915050565b5f60208284031215610e3b575f80fd5b604051602081016001600160401b0381118282101715610e5d57610e5d610b28565b6040529151825250919050565b5f60808284031215610e7a575f80fd5b604051608081016001600160401b0381118282101715610e9c57610e9c610b28565b604052905080610eab83610bbc565b8152610eb960208401610bbc565b6020820152604083015163ffffffff81168114610ed4575f80fd5b6040820152610ee560608401610baa565b60608201525092915050565b5f805f805f805f805f898b03610460811215610f0b575f80fd5b8a51610f1681610b01565b60208c0151909a50610f2781610b01565b60408c0151909950610f3881610b01565b9750610140605f1982011215610f4c575f80fd5b50610f55610b87565b610f6160608c01610baa565b8152610f6f60808c01610baa565b6020820152610f8060a08c01610baa565b6040820152610f9160c08c01610baa565b6060820152610fa260e08c01610baa565b60808201526101008b81015160a0830152610120808d015160c08401526101408d015160e08401526101608d0151918301919091526101808c0151908201529550610ff18b6101a08c01610bcb565b6103008b01519095506001600160401b0381111561100d575f80fd5b6110198c828d01610d22565b94505061102a8b6103208c01610dca565b925061103a8b6103c08c01610e2b565b915061104a8b6103e08c01610e6a565b90509295985092959850929598565b8051600281900b8114610b23575f80fd5b5f60a082840312801561107b575f80fd5b50611084610b65565b825161108f81610b01565b8152602083015161109f81610b01565b60208201526110b060408401610baa565b60408201526110c160608401611059565b606082015260808301516110d481610b01565b60808201529392505050565b600181811c908216806110f457607f821691505b60208210810361111257634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111561115f57805f5260205f20601f840160051c8101602085101561113d5750805b601f840160051c820191505b8181101561115c575f8155600101611149565b50505b505050565b81516001600160401b0381111561117d5761117d610b28565b6111918161118b84546110e0565b84611118565b6020601f8211600181146111c3575f83156111ac5750848201515b5f19600385901b1c1916600184901b17845561115c565b5f84815260208120601f198516915b828110156111f257878501518255602094850194600190920191016111d2565b508482101561120f57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b634e487b7160e01b5f52601160045260245ffd5b62ffffff81811683821601908111156105fd576105fd61121e565b62ffffff82811682821603908111156105fd576105fd61121e565b5f62ffffff83168061128857634e487b7160e01b5f52601260045260245ffd5b8062ffffff84160491505092915050565b62ffffff81811683821602908116908181146112b7576112b761121e565b5092915050565b5f602082840312156112ce575f80fd5b6112d782610bbc565b9392505050565b5f602082840312156112ee575f80fd5b81516112d781610b01565b5f806040838503121561130a575f80fd5b61131383611059565b60208401519092506001600160801b038116811461132f575f80fd5b809150509250929050565b60805160a051613f5c6113d25f395f81816103b4015281816104900152818161055a0152818161087b01528181610a7d01528181610b39015261136101525f81816101f50152818161069c0152818161072001528181610c5901528181610cdd01528181610ebc0152818161192001528181611ab601528181611b9101528181611c6c0152818161206b01526123000152613f5c5ff3fe608060405260043610610140575f3560e01c80638456cb59116100bb578063c45a015511610071578063ddae5dbb11610057578063ddae5dbb146103f8578063de23b78614610412578063edbcc59914610431575f80fd5b8063c45a0155146103a3578063c5bb8758146103d6575f80fd5b8063b0e699b3116100a1578063b0e699b314610345578063b187bd2614610379578063bd097e211461039b575f80fd5b80638456cb591461031d5780638da5cb5b14610331575f80fd5b80633d54621811610110578063481c6a75116100f6578063481c6a75146101e45780634aabce801461023457806356db3be314610253575f80fd5b80633d546218146101b15780633f4ba83a146101d0575f80fd5b806311ad711d1461014b578063145a919614610160578063155dd5ee146101735780632f46d48014610192575f80fd5b3661014757005b5f80fd5b61015e610159366004612836565b610455565b005b61015e61016e3660046128c4565b610840565b34801561017e575f80fd5b5061015e61018d36600461295f565b61094e565b34801561019d575f80fd5b5061015e6101ac366004612976565b6109fc565b3480156101bc575f80fd5b5061015e6101cb36600461298f565b610a42565b3480156101db575f80fd5b5061015e610df5565b3480156101ef575f80fd5b506102177f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b34801561023f575f80fd5b5061015e61024e3660046129f4565b610e5d565b34801561025e575f80fd5b506102d66040805160a0810182525f80825260208201819052918101829052606081018290526080810191909152506040805160a081018252600e548152600f54602082015260105460ff80821615159383019390935261010081048316151560608301526201000090049091161515608082015290565b60405161022b91905f60a082019050825182526020830151602083015260408301511515604083015260608301511515606083015260808301511515608083015292915050565b348015610328575f80fd5b5061015e6112c2565b34801561033c575f80fd5b5061021761132e565b348015610350575f80fd5b5060408051602080820183525f909152815180820183526011549081905291519182520161022b565b348015610384575f80fd5b5060135460ff16604051901515815260200161022b565b61015e61133c565b3480156103ae575f80fd5b506102177f000000000000000000000000000000000000000000000000000000000000000081565b3480156103e1575f80fd5b506103ea61135e565b60405190815260200161022b565b348015610403575f80fd5b5061015e61016e366004612a82565b34801561041d575f80fd5b5061015e61042c366004612ab4565b6113e2565b34801561043c575f80fd5b50610445611429565b60405161022b9493929190612c09565b604051632474521560e21b81527ff688e31edd11ef8893fafe7d794fed44b1d68e9104656ba21c2bc086e624b6c460048201523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906391d1485490604401602060405180830381865afa1580156104dd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105019190612d2b565b61051e57604051635c427cd960e01b815260040160405180910390fd5b60135460ff16156105425760405163ab35696f60e01b815260040160405180910390fd5b61054a6118de565b5f6105553447612d61565b90505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c5bb87586040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105b4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105d89190612d74565b9050808210156105fb5760405163356680b760e01b815260040160405180910390fd5b5f5a9050610607611906565b5f610610611a53565b90508060c00151610634576040516371b3254360e01b815260040160405180910390fd5b600a54610100900460ff1661065c57604051632e205f8760e01b815260040160405180910390fd5b5f61066682611b26565b90505f60405180604001604052808381526020018a61068490612e21565b9052600a549091506301000000900460ff16610709577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166399d32fc46040518163ffffffff1660e01b81526004015f604051808303815f87803b1580156106f2575f80fd5b505af1158015610704573d5f803e3d5ffd5b505050505b6040516303e8bba760e11b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906307d1774e90349061075b9085908d908d90600401612f90565b5f604051808303818588803b158015610772575f80fd5b505af1158015610784573d5f803e3d5ffd5b50505050505f835f01511561079a57505f6107e6565b8360200151156107ac575060016107e6565b8360400151156107be575060026107e6565b8360600151156107d0575060036107e6565b8360800151156107e2575060046107e6565b5060055b6040805160ff83168152600160208201527f543def41c1f273c4721f97c7251254611652d7bd872f672559eeccc42a06664b910160405180910390a161082b85611c07565b5050505050505061083b60015f55565b505050565b604051632474521560e21b81527ff688e31edd11ef8893fafe7d794fed44b1d68e9104656ba21c2bc086e624b6c460048201523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906391d1485490604401602060405180830381865afa1580156108c8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ec9190612d2b565b61090957604051635c427cd960e01b815260040160405180910390fd5b60135460ff161561092d5760405163ab35696f60e01b815260040160405180910390fd5b6109356118de565b604051632e205f8760e01b815260040160405180910390fd5b610956611c69565b6001600160a01b0316336001600160a01b03161461098757604051635c427cd960e01b815260040160405180910390fd5b805f036109a75760405163356680b760e01b815260040160405180910390fd5b804710156109c85760405163356680b760e01b815260040160405180910390fd5b5f806109d2611c69565b90505f805f8086855af191508161083b576040516312171d8360e31b815260040160405180910390fd5b610a04611c69565b6001600160a01b0316336001600160a01b031614610a3557604051635c427cd960e01b815260040160405180910390fd5b80600e61083b828261306e565b604051632474521560e21b81527ff688e31edd11ef8893fafe7d794fed44b1d68e9104656ba21c2bc086e624b6c460048201523360248201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906391d1485490604401602060405180830381865afa158015610aca573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610aee9190612d2b565b610b0b57604051635c427cd960e01b815260040160405180910390fd5b60135460ff1615610b2f5760405163ab35696f60e01b815260040160405180910390fd5b610b376118de565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c5bb87586040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b93573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bb79190612d74565b471015610bd75760405163356680b760e01b815260040160405180910390fd5b5f5a9050610be3611906565b5f610bec611a53565b90508060c00151610c10576040516371b3254360e01b815260040160405180910390fd5b600a54610100900460ff1615610c3957604051632e205f8760e01b815260040160405180910390fd5b5f610c4382611b26565b600a549091506301000000900460ff16610cc6577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166399d32fc46040518163ffffffff1660e01b81526004015f604051808303815f87803b158015610caf575f80fd5b505af1158015610cc1573d5f803e3d5ffd5b505050505b604051637e1fec2f60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063fc3fd85e90610d16908490899089906004016130ea565b5f604051808303815f87803b158015610d2d575f80fd5b505af1158015610d3f573d5f803e3d5ffd5b505050505f825f015115610d5457505f610da0565b826020015115610d6657506001610da0565b826040015115610d7857506002610da0565b826060015115610d8a57506003610da0565b826080015115610d9c57506004610da0565b5060055b6040805160ff831681525f60208201527f543def41c1f273c4721f97c7251254611652d7bd872f672559eeccc42a06664b910160405180910390a1610de484611c07565b50505050610df160015f55565b5050565b610dfd611c69565b6001600160a01b0316336001600160a01b031614610e2e57604051635c427cd960e01b815260040160405180910390fd5b60135460ff16610e5157604051636cd6020160e01b815260040160405180910390fd5b6013805460ff19169055565b610e65611c69565b6001600160a01b0316336001600160a01b031614610e9657604051635c427cd960e01b815260040160405180910390fd5b610eb98460a001358560c001358660e00135876101000135886101200135611cea565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610f16573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f3a919061314b565b6060015190505f610f50368790038701876131ec565b9050610f68610f626020880188613293565b83611d99565b62ffffff168152610f82610f626040880160208901613293565b62ffffff166020820152610f9f610f626060880160408901613293565b62ffffff166040820152610fbc610f626080880160608901613293565b62ffffff1660608201819052815160208301516040840151610fdd93611de6565b80516001805460208401516040850151606086015160808088015162ffffff9081166c01000000000000000000000000026effffff000000000000000000000000199382166901000000000000000000026bffffff00000000000000000019958316660100000000000002959095166bffffffffffff0000000000001996831663010000000265ffffffffffff199098169290991691909117959095179390931695909517179390931617905560a08083015160025560c083015160035560e08301516004556101008301516005556101208301516006555f916110c59188019088016132ae565b6001600160a01b0316036110ec57604051632e205f8760e01b815260040160405180910390fd5b6110fe8560a001358660c00135611ea5565b61110e60608601604087016132c9565b61112b57604051632e205f8760e01b815260040160405180910390fd5b5f60a0860135158015611140575060c0860135155b9050611154610140870161012088016132c9565b801561115d5750805b80156111785750611176610120870161010088016132c9565b155b1561119657604051632e205f8760e01b815260040160405180910390fd5b8560076111a382826132fc565b50600390506111b860608701604088016134dd565b60ff1611156111da5760405163cff7bdd160e01b815260040160405180910390fd5b84600b6111e7828261367e565b5061121f90506111fc36869003860186613792565b61120b368a90038a018a6131ec565b61121a368a90038a018a613817565b611efc565b83601261122c82826138e6565b505060405133907f36856dac67e0c80ce641d223cf8262765a352675d9842335b277fae990f06b7a905f90a27fc35c2b90126d4a8d9c3aa49d69726011fc796c5a28a1eeda36ce37b2570bb9aa61128386806134f8565b61129060208901896134f8565b6112a060608b0160408c016134dd565b6040516112b19594939291906139ae565b60405180910390a150505050505050565b6112ca611c69565b6001600160a01b0316336001600160a01b0316146112fb57604051635c427cd960e01b815260040160405180910390fd5b60135460ff161561131f5760405163ab35696f60e01b815260040160405180910390fd5b6013805460ff19166001179055565b5f611337611c69565b905090565b345f0361135c5760405163356680b760e01b815260040160405180910390fd5b565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c5bb87586040518163ffffffff1660e01b8152600401602060405180830381865afa1580156113bb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113379190612d74565b50565b6113ea611c69565b6001600160a01b0316336001600160a01b03161461141b57604051635c427cd960e01b815260040160405180910390fd5b80601161083b828290359055565b60408051610140810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081019190915260408051610160810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101829052610140810191909152604080516060808201835280825260208201525f91810191909152604080516080810182525f80825260208201819052918101829052606081019190915260015f0160016006016001600a01600160110183604051806101400160405290815f82015f9054906101000a900462ffffff1662ffffff1662ffffff1681526020015f820160039054906101000a900462ffffff1662ffffff1662ffffff1681526020015f820160069054906101000a900462ffffff1662ffffff1662ffffff1681526020015f820160099054906101000a900462ffffff1662ffffff1662ffffff1681526020015f8201600c9054906101000a900462ffffff1662ffffff1662ffffff16815260200160018201548152602001600282015481526020016003820154815260200160048201548152602001600582015481525050935082604051806101600160405290815f82015f9054906101000a900462ffffff1662ffffff1662ffffff1681526020015f820160039054906101000a900462ffffff1662ffffff1662ffffff1681526020015f820160069054906101000a900460ff161515151581526020015f820160079054906101000a900462ffffff1662ffffff1662ffffff1681526020015f8201600a9054906101000a90046001600160a01b03166001600160a01b03166001600160a01b031681526020016001820154815260200160028201548152602001600382015f9054906101000a900460ff161515151581526020016003820160019054906101000a900460ff161515151581526020016003820160029054906101000a900460ff161515151581526020016003820160039054906101000a900460ff1615151515815250509250816040518060600160405290815f8201805461176290613542565b80601f016020809104026020016040519081016040528092919081815260200182805461178e90613542565b80156117d95780601f106117b0576101008083540402835291602001916117d9565b820191905f5260205f20905b8154815290600101906020018083116117bc57829003601f168201915b505050505081526020016001820180546117f290613542565b80601f016020809104026020016040519081016040528092919081815260200182805461181e90613542565b80156118695780601f1061184057610100808354040283529160200191611869565b820191905f5260205f20905b81548152906001019060200180831161184c57829003601f168201915b50505091835250506002919091015460ff90811660209283015260408051608081018252945480831615158652610100810490921615159285019290925262010000810463ffffffff16918401919091526601000000000000900462ffffff1660608301529398929750929550919350915050565b60025f540361190057604051633ee5aeb560e01b815260040160405180910390fd5b60025f55565b60125460ff1661191257565b5f61191b6122fc565b90505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663065e53606040518163ffffffff1660e01b8152600401602060405180830381865afa15801561197a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199e91906139ea565b90505f6119ab8383613a03565b90505f808260020b12156119ca576119c282613a28565b60020b6119cf565b8160020b5b6012549091506601000000000000900462ffffff16811115611a4d5760408051600285810b825286900b602082015262ffffff83168183015290517f5dd60ed064040c386227d2be54c6c27d8b9a76d2576c2756d7b5f77724ebc1f09181900360600190a1604051636aba994b60e11b815260040160405180910390fd5b50505050565b6040805160e0810182525f80825260208201819052818301819052606082018190526080820181905260a0820181905260c0820152905163f18371b960e01b81527323dd9c89038a9ade8128f0601e74ab0610f5c0439063f18371b990611ae7907f000000000000000000000000000000000000000000000000000000000000000090600190600790601290600401613afb565b60e060405180830381865af4158015611b02573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113379190613bda565b60408051610100810182525f80825260208201819052818301819052606082018190526080820181905260a0820181905260c0820181905260e08201529051639fa5afdb60e01b81527323dd9c89038a9ade8128f0601e74ab0610f5c04390639fa5afdb90611bc1907f0000000000000000000000000000000000000000000000000000000000000000906007906012908890600401613c74565b61010060405180830381865af4158015611bdd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c019190613d30565b92915050565b5f611c13825f366124ad565b9250505080471015611c385760405163356680b760e01b815260040160405180910390fd5b60148054820190555f8080808085335af190508061083b576040516312171d8360e31b815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611cc6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113379190613dc8565b670de0b6b3a7640000851180611d075750670de0b6b3a764000084115b80611d195750670de0b6b3a764000083115b80611d2b5750670de0b6b3a764000082115b80611d3d5750670de0b6b3a764000081115b15611d5b57604051632e205f8760e01b815260040160405180910390fd5b8415801590611d6957508315155b8015611d7457508385115b15611d9257604051632e205f8760e01b815260040160405180910390fd5b5050505050565b5f8262ffffff165f03611dad57505f611c01565b600282900b80806001611dc08288613de3565b611dca9190613dfe565b611dd49190613e2d565b611dde9190613e52565b949350505050565b62ffffff811615611a4d5762ffffff841615801590611e0f57508362ffffff168162ffffff1611155b15611e2d57604051632e205f8760e01b815260040160405180910390fd5b62ffffff831615801590611e4b57508262ffffff168162ffffff1611155b15611e6957604051632e205f8760e01b815260040160405180910390fd5b62ffffff821615801590611e8757508162ffffff168162ffffff1611155b15611a4d57604051632e205f8760e01b815260040160405180910390fd5b5f82158015611eb2575081155b90505f836706f05b59d3b20000148015611ed35750826706f05b59d3b20000145b905081158015611e87575080611a4d57604051632e205f8760e01b815260040160405180910390fd5b8251158015611f0d57508260200151155b8015611f205750608082015162ffffff16155b15611f2a57505050565b81515f9062ffffff16151580611f485750602083015162ffffff1615155b608084015190915062ffffff161515818015611f615750805b15611f7f57604051632e205f8760e01b815260040160405180910390fd5b84602001518015611f9257508261012001515b15611fb05760405163b24184b760e01b815260040160405180910390fd5b808015611fbf57508261012001515b15611fdd5760405163b24184b760e01b815260040160405180910390fd5b846040015163ffffffff165f036120075760405163b24184b760e01b815260040160405180910390fd5b62093a80856040015163ffffffff1611156120355760405163b24184b760e01b815260040160405180910390fd5b8451801561204a5750606085015162ffffff16155b156120685760405163b24184b760e01b815260040160405180910390fd5b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156120c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120e9919061314b565b60808101519091506001600160a01b0381166121175760405162f61f7960e41b815260040160405180910390fd5b806001600160a01b03166326a116176121318460a0902090565b6040518263ffffffff1660e01b815260040161214f91815260200190565b602060405180830381865afa925050508015612188575060408051601f3d908101601f1916820190925261218591810190612d2b565b60015b6121a45760405162f61f7960e41b815260040160405180910390fd5b806121c15760405162f61f7960e41b815260040160405180910390fd5b505f8190505f816001600160a01b03166355b13a4f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612203573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906122279190613dc8565b6040808b01518151633155793360e11b815287516001600160a01b0390811660048301526020890151811660248301529288015162ffffff166044820152606088015160020b606482015260808801518316608482015263ffffffff90911660a48201529192508216906362aaf2669060c4016040805180830381865afa9250505080156122d2575060408051601f3d908101601f191682019092526122cf91810190613e77565b60015b6122ef57604051635d2c8bcb60e11b815260040160405180910390fd5b5050505050505050505050565b5f807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa15801561235a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061237e919061314b565b90505f816080015190505f8190505f816001600160a01b03166355b13a4f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156123c9573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123ed9190613dc8565b60125460408051633155793360e11b815287516001600160a01b0390811660048301526020890151811660248301529188015162ffffff166044820152606088015160020b60648201526080880151821660848201526201000090920463ffffffff1660a4830152919250908216906362aaf2669060c4016040805180830381865afa15801561247f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124a39190613e77565b5095945050505050565b5f805f6179185a6124be9088612d61565b6124c89190613ec0565b92506124d48585612511565b91505f6124e13a85613ed3565b90506064606e6124f18584613ec0565b6124fb9190613ed3565b6125059190613eea565b91505093509350939050565b5f805f73420000000000000000000000000000000000000f6001600160a01b03167f49948e0eea3a61833d802630e547ce1678911adc8c2c9347dfea3fa5dbb623998686604051602401612566929190613efd565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff000000000000000000000000000000000000000000000000000000009094169390931790925290516125d19190613f10565b5f60405180830381855afa9150503d805f8114612609576040519150601f19603f3d011682016040523d82523d5f602084013e61260e565b606091505b509150915081801561262257506020815110155b1561263e578080602001905181019061263b9190612d74565b92505b505092915050565b5f60c08284031215612656575f80fd5b50919050565b634e487b7160e01b5f52604160045260245ffd5b6040805190810167ffffffffffffffff811182821017156126935761269361265c565b60405290565b60405160c0810167ffffffffffffffff811182821017156126935761269361265c565b604051610140810167ffffffffffffffff811182821017156126935761269361265c565b604051610160810167ffffffffffffffff811182821017156126935761269361265c565b60405160e0810167ffffffffffffffff811182821017156126935761269361265c565b604051610100810167ffffffffffffffff811182821017156126935761269361265c565b604051601f8201601f1916810167ffffffffffffffff811182821017156127745761277461265c565b604052919050565b5f82601f83011261278b575f80fd5b813567ffffffffffffffff8111156127a5576127a561265c565b6127b460208260051b0161274b565b8082825260208201915060208360061b8601019250858311156127d5575f80fd5b602085015b838110156124a35786601f8201126127f0575f80fd5b6127f8612670565b806040830189811115612809575f80fd5b835b8181101561282357803584526020938401930161280b565b50508452506020909201916040016127da565b5f805f60608486031215612848575f80fd5b833567ffffffffffffffff81111561285e575f80fd5b61286a86828701612646565b935050602084013567ffffffffffffffff811115612886575f80fd5b6128928682870161277c565b925050604084013567ffffffffffffffff8111156128ae575f80fd5b6128ba8682870161277c565b9150509250925092565b5f805f604084860312156128d6575f80fd5b833567ffffffffffffffff8111156128ec575f80fd5b6128f886828701612646565b935050602084013567ffffffffffffffff811115612914575f80fd5b8401601f81018613612924575f80fd5b803567ffffffffffffffff81111561293a575f80fd5b8660208260061b840101111561294e575f80fd5b939660209190910195509293505050565b5f6020828403121561296f575f80fd5b5035919050565b5f60a0828403128015612987575f80fd5b509092915050565b5f80604083850312156129a0575f80fd5b823567ffffffffffffffff8111156129b6575f80fd5b6129c28582860161277c565b925050602083013567ffffffffffffffff8111156129de575f80fd5b6129ea8582860161277c565b9150509250929050565b5f805f80848603610340811215612a09575f80fd5b610140811215612a17575f80fd5b85945061016061013f1982011215612a2d575f80fd5b610140860193506102a086013567ffffffffffffffff811115612a4e575f80fd5b860160608189031215612a5f575f80fd5b925060806102bf1982011215612a73575f80fd5b509295919450926102c0019150565b5f60208284031215612a92575f80fd5b813567ffffffffffffffff811115612aa8575f80fd5b611dde8482850161277c565b5f6020828403128015612987575f80fd5b805162ffffff1682526020810151612ae4602084018262ffffff169052565b506040810151612af8604084018215159052565b506060810151612b0f606084018262ffffff169052565b506080810151612b2a60808401826001600160a01b03169052565b5060a081015160a083015260c081015160c083015260e0810151612b5260e084018215159052565b50610100810151612b6861010084018215159052565b50610120810151612b7e61012084018215159052565b5061014081015161083b61014084018215159052565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f815160608452612bd66060850182612b94565b905060208301518482036020860152612bef8282612b94565b91505060ff60408401511660408501528091505092915050565b845162ffffff1681525f6020860151612c29602084018262ffffff169052565b506040860151612c40604084018262ffffff169052565b506060860151612c57606084018262ffffff169052565b506080860151612c6e608084018262ffffff169052565b5060a086015160a083015260c086015160c083015260e086015160e0830152610100860151610100830152610120860151610120830152612cb3610140830186612ac5565b6103406102a0830152612cca610340830185612bc2565b835115156102c0840152602084015115156102e0840152604084015163ffffffff16610300840152606084015162ffffff1661032084015290505b95945050505050565b80151581146113df575f80fd5b8051612d2681612d0e565b919050565b5f60208284031215612d3b575f80fd5b8151612d4681612d0e565b9392505050565b634e487b7160e01b5f52601160045260245ffd5b81810381811115611c0157611c01612d4d565b5f60208284031215612d84575f80fd5b5051919050565b6001600160a01b03811681146113df575f80fd5b8035612d2681612d8b565b5f82601f830112612db9575f80fd5b813567ffffffffffffffff811115612dd357612dd361265c565b612de6601f8201601f191660200161274b565b818152846020838601011115612dfa575f80fd5b816020850160208301375f918101602001919091529392505050565b8035612d2681612d0e565b5f60c08236031215612e31575f80fd5b612e39612699565b823560048110612e47575f80fd5b8152612e5560208401612d9f565b6020820152604083013567ffffffffffffffff811115612e73575f80fd5b612e7f36828601612daa565b604083015250612e9160608401612e16565b60608201526080838101359082015260a092830135928101929092525090565b6001600160a01b038151168252602081015160020b602083015262ffffff60408201511660408301526060810151612ef0606084018262ffffff169052565b506080810151612f07608084018262ffffff169052565b5060a081015160a083015260c081015160c083015260e081015161083b60e084018215159052565b5f8151808452602084019350602083015f5b82811015612f86578151865f5b6002811015612f6d578251825260209283019290910190600101612f4e565b5050506040959095019460209190910190600101612f41565b5093949350505050565b60608152612fa2606082018551612eb1565b5f6020850151610120610160840152805160048110612fcf57634e487b7160e01b5f52602160045260245ffd5b61018084015260208101516001600160a01b03166101a0840152604081015160c06101c0850152613004610240850182612b94565b9050606082015161301a6101e086018215159052565b50608082015161020085015260a082015161022085015283810360208501526130438187612f2f565b91505082810360408401526130588185612f2f565b9695505050505050565b5f8135611c0181612d0e565b813581556020820135600182015560028101604083013561308e81612d0e565b815460ff191660ff821515161782555060608301356130ac81612d0e565b815461ff00191681151560081b61ff00161782555060808301356130cf81612d0e565b815462ff0000191681151560101b62ff000016178255611a4d565b6130f48185612eb1565b6101406101008201525f61310c610140830185612f2f565b8281036101208401526130588185612f2f565b62ffffff811681146113df575f80fd5b8051612d268161311f565b8051600281900b8114612d26575f80fd5b5f60a082840312801561315c575f80fd5b5060405160a0810167ffffffffffffffff811182821017156131805761318061265c565b604052825161318e81612d8b565b8152602083015161319e81612d8b565b602082015260408301516131b18161311f565b60408201526131c26060840161313a565b606082015260808301516131d581612d8b565b60808201529392505050565b8035612d268161311f565b5f6101408284031280156131fe575f80fd5b506132076126bc565b613210836131e1565b815261321e602084016131e1565b602082015261322f604084016131e1565b6040820152613240606084016131e1565b6060820152613251608084016131e1565b608082015260a0838101359082015260c0808401359082015260e080840135908201526101008084013590820152610120928301359281019290925250919050565b5f602082840312156132a3575f80fd5b8135612d468161311f565b5f602082840312156132be575f80fd5b8135612d4681612d8b565b5f602082840312156132d9575f80fd5b8135612d4681612d0e565b5f8135611c018161311f565b5f8135611c0181612d8b565b61331d613308836132e4565b825462ffffff191662ffffff91909116178255565b61334a61332c602084016132e4565b825465ffffff000000191660189190911b65ffffff00000016178255565b61337d61335960408401613062565b82805466ff000000000000191691151560301b66ff00000000000016919091179055565b6133b261338c606084016132e4565b825469ffffff00000000000000191660389190911b69ffffff0000000000000016178255565b6134106133c1608084016132f0565b82547fffff0000000000000000000000000000000000000000ffffffffffffffffffff1660509190911b7dffffffffffffffffffffffffffffffffffffffff0000000000000000000016178255565b60a0820135600182015560c082013560028201556003810161344b61343760e08501613062565b825490151560ff1660ff1991909116178255565b61347561345b6101008501613062565b82805461ff00191691151560081b61ff0016919091179055565b6134a16134856101208501613062565b82805462ff0000191691151560101b62ff000016919091179055565b61083b6134b16101408501613062565b82805463ff000000191691151560181b63ff00000016919091179055565b60ff811681146113df575f80fd5b5f602082840312156134ed575f80fd5b8135612d46816134cf565b5f808335601e1984360301811261350d575f80fd5b83018035915067ffffffffffffffff821115613527575f80fd5b60200191503681900382131561353b575f80fd5b9250929050565b600181811c9082168061355657607f821691505b60208210810361265657634e487b7160e01b5f52602260045260245ffd5b601f82111561083b57805f5260205f20601f840160051c810160208510156135995750805b601f840160051c820191505b81811015611d92575f81556001016135a5565b67ffffffffffffffff8311156135d0576135d061265c565b6135e4836135de8354613542565b83613574565b5f601f841160018114613615575f85156135fe5750838201355b5f19600387901b1c1916600186901b178355611d92565b5f83815260208120601f198716915b828110156136445786850135825560209485019460019092019101613624565b5086821015613660575f1960f88860031b161c19848701351681555b505060018560011b0183555050505050565b5f8135611c01816134cf565b61368882836134f8565b67ffffffffffffffff8111156136a0576136a061265c565b6136b4816136ae8554613542565b85613574565b5f601f8211600181146136e5575f83156136ce5750838201355b5f19600385901b1c1916600184901b17855561373c565b5f85815260208120601f198516915b8281101561371457868501358255602094850194600190920191016136f4565b5084821015613730575f1960f88660031b161c19848701351681555b505060018360011b0185555b5050505061374d60208301836134f8565b61375b8183600186016135b8565b5050610df161376c60408401613672565b6002830160ff821660ff198254161781555050565b63ffffffff811681146113df575f80fd5b5f60808284031280156137a3575f80fd5b506040516080810167ffffffffffffffff811182821017156137c7576137c761265c565b60405282356137d581612d0e565b815260208301356137e581612d0e565b602082015260408301356137f881613781565b6040820152606083013561380b8161311f565b60608201529392505050565b5f610160828403128015613829575f80fd5b506138326126e0565b61383b836131e1565b8152613849602084016131e1565b602082015261385a60408401612e16565b604082015261386b606084016131e1565b606082015261387c60808401612d9f565b608082015260a0838101359082015260c080840135908201526138a160e08401612e16565b60e08201526138b36101008401612e16565b6101008201526138c66101208401612e16565b6101208201526138d96101408401612e16565b6101408201529392505050565b81356138f181612d0e565b815460ff191660ff8215151617825550602082013561390f81612d0e565b815461ff00191681151560081b61ff001617825550604082013561393281613781565b815465ffffffff00008260101b1691508165ffffffff0000198216178355606084013561395e8161311f565b68ffffff0000000000008160301b168368ffffffffffffff0000198416171784555050505050565b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b606081525f6139c1606083018789613986565b82810360208401526139d4818688613986565b91505060ff831660408301529695505050505050565b5f602082840312156139fa575f80fd5b612d468261313a565b600282810b9082900b03627fffff198112627fffff82131715611c0157611c01612d4d565b5f8160020b627fffff198103613a4057613a40612d4d565b5f0392915050565b805462ffffff81168352601881901c62ffffff166020840152613a756040840160ff8360301c1615159052565b603881901c62ffffff166060840152605081901c6001600160a01b0316608084015250600181015460a0830152600281015460c0830152600381015460ff8116151560e0840152613ad1610100840160ff8360081c1615159052565b613ae6610120840160ff8360101c1615159052565b61083b610140840160ff8360181c1615159052565b6001600160a01b0385168152835462ffffff81166020830152610340820190601881901c62ffffff166040840152603081901c62ffffff166060840152604881901c62ffffff166080840152606081901c62ffffff1660a084015250600185015460c0830152600285015460e0830152600385015461010083015260048501546101208301526005850154610140830152613b9a610160830185613a48565b612d056102c08301845460ff80821615158352600882901c1615156020830152601081901c63ffffffff16604083015260301c62ffffff16606090910152565b5f60e0828403128015613beb575f80fd5b50613bf4612704565b8251613bff81612d0e565b81526020830151613c0f81612d0e565b60208201526040830151613c2281612d0e565b60408201526060830151613c3581612d0e565b6060820152613c4660808401612d1b565b6080820152613c5760a08401612d1b565b60a0820152613c6860c08401612d1b565b60c08201529392505050565b6001600160a01b03851681526102e08101613c926020830186613a48565b613cd26101808301855460ff80821615158352600882901c1615156020830152601081901c63ffffffff16604083015260301c62ffffff16606090910152565b825115156102008301526020830151151561022083015260408301511515610240830152606083015115156102608301526080830151151561028083015260a083015115156102a083015260c08301518015156102c08401526124a3565b5f610100828403128015613d42575f80fd5b50613d4b612727565b8251613d5681612d8b565b8152613d646020840161313a565b6020820152613d756040840161312f565b6040820152613d866060840161312f565b6060820152613d976080840161312f565b608082015260a0838101519082015260c08084015190820152613dbc60e08401612d1b565b60e08201529392505050565b5f60208284031215613dd8575f80fd5b8151612d4681612d8b565b62ffffff8181168382160190811115611c0157611c01612d4d565b62ffffff8281168282160390811115611c0157611c01612d4d565b634e487b7160e01b5f52601260045260245ffd5b5f62ffffff831680613e4157613e41613e19565b8062ffffff84160491505092915050565b62ffffff8181168382160290811690818114613e7057613e70612d4d565b5092915050565b5f8060408385031215613e88575f80fd5b613e918361313a565b915060208301516fffffffffffffffffffffffffffffffff81168114613eb5575f80fd5b809150509250929050565b80820180821115611c0157611c01612d4d565b8082028115828204841417611c0157611c01612d4d565b5f82613ef857613ef8613e19565b500490565b602081525f611dde602083018486613986565b5f82518060208501845e5f92019182525091905056fea26469706673582212204280f5f6f4601cddac138d914fcbdd757f3293fba4a1101c6b3025553a0d56f864736f6c634300081a0033a26469706673582212208316be437352a9bf9c967b4f15cbb2ef7842f7b31bc486db467c18386bbf783464736f6c634300081a0033000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1000000000000000000000000f2d7660ae1a70794fdc3fbc48a16406688953446

Deployed Bytecode

0x60806040526004361061018e575f3560e01c806391d14854116100dc578063d547741f11610087578063e8ae2b6911610062578063e8ae2b6914610537578063ed90116014610556578063f2fde38b14610569578063fc3d920e14610588575f80fd5b8063d547741f146104b2578063d5f39488146104d1578063dcf4cf9614610504575f80fd5b8063c4edff84116100b7578063c4edff8414610451578063c5bb87581461047e578063c91d956c14610493575f80fd5b806391d14854146103c95780639c9d5d68146103f8578063af7f84fe14610424575f80fd5b80635df654951161013c5780637614b4cd116101175780637614b4cd1461037057806381509e601461038f5780638da5cb5b146103ad575f80fd5b80635df65495146103105780635e0000a01461033d578063715018a61461035c575f80fd5b80632f2ff15d1161016c5780632f2ff15d1461024a5780634e7284cd1461026b5780635300f8411461028a575f80fd5b806306bfd20b146101925780631b048054146101c75780631dd2e68f14610213575b5f80fd5b34801561019d575f80fd5b506101b16101ac366004611c14565b6105bb565b6040516101be9190611c2f565b60405180910390f35b3480156101d2575f80fd5b506101fb6101e1366004611c14565b60036020525f90815260409020546001600160a01b031681565b6040516001600160a01b0390911681526020016101be565b34801561021e575f80fd5b506101fb61022d366004611c14565b6001600160a01b039081165f908152600360205260409020541690565b348015610255575f80fd5b50610269610264366004611c79565b61064c565b005b348015610276575f80fd5b506101fb610285366004611ca7565b610701565b348015610295575f80fd5b506102db6102a4366004611c14565b600260208190525f918252604090912080546001820154928201546003909201546001600160a01b03918216938216929091169084565b6040516101be94939291906001600160a01b039485168152928416602084015292166040820152606081019190915260800190565b34801561031b575f80fd5b5060065461032a9061ffff1681565b60405161ffff90911681526020016101be565b348015610348575f80fd5b50610269610357366004611cd1565b610735565b348015610367575f80fd5b506102696108b9565b34801561037b575f80fd5b506101fb61038a366004611d5a565b6108cc565b34801561039a575f80fd5b506005545b6040519081526020016101be565b3480156103b8575f80fd5b505f546001600160a01b03166101fb565b3480156103d4575f80fd5b506103e86103e3366004611c79565b610976565b60405190151581526020016101be565b348015610403575f80fd5b50610417610412366004611c14565b6109a2565b6040516101be9190611e14565b34801561042f575f80fd5b5061044361043e366004611e5f565b610a15565b6040516101be929190611e7f565b34801561045c575f80fd5b5061047061046b366004611e5f565b610bc2565b6040516101be929190611f40565b348015610489575f80fd5b5061039f60075481565b34801561049e575f80fd5b506102696104ad366004612018565b611000565b3480156104bd575f80fd5b506102696104cc366004611c79565b61106d565b3480156104dc575f80fd5b506101fb7f0000000000000000000000000d5bf374306eef436416dd8900f61997c2ef93df81565b34801561050f575f80fd5b5061039f7ff688e31edd11ef8893fafe7d794fed44b1d68e9104656ba21c2bc086e624b6c481565b348015610542575f80fd5b506103e8610551366004611c79565b6110f6565b6101fb61056436600461202f565b61113a565b348015610574575f80fd5b50610269610583366004611c14565b6114b9565b348015610593575f80fd5b506101fb7f000000000000000000000000f2d7660ae1a70794fdc3fbc48a1640668895344681565b60408051608080820183525f808352602080840182905283850182905260609384018290526001600160a01b038681168352600280835292869020865194850187528054821680865260018201548316938601939093529283015416948301949094526003015491810191909152906106475760405163e6c4247b60e01b815260040160405180910390fd5b919050565b6106546114fb565b6001600160a01b03811661067b5760405163e6c4247b60e01b815260040160405180910390fd5b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff166106fd575f8281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45b5050565b6004602052815f5260405f20818154811061071a575f80fd5b5f918252602090912001546001600160a01b03169150829050565b7f000000000000000000000000f2d7660ae1a70794fdc3fbc48a164066889534466001600160a01b03166391d148547f000000000000000000000000f2d7660ae1a70794fdc3fbc48a164066889534466001600160a01b031663ea26266c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107e491906120d7565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526004810191909152336024820152604401602060405180830381865afa15801561083c573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061086091906120fb565b61087d57604051631a27eac360e11b815260040160405180910390fd5b8061ffff165f036108a15760405163e6c4247b60e01b815260040160405180910390fd5b6006805461ffff191661ffff92909216919091179055565b6108c16114fb565b6108ca5f611527565b565b60405163169ade0360e31b81525f906001600160a01b037f0000000000000000000000000d5bf374306eef436416dd8900f61997c2ef93df169063b4d6f0189061092a908c9030908d908d908d908d908d908d908d906004016123b4565b602060405180830381865afa158015610945573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061096991906124de565b9998505050505050505050565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff165b92915050565b6001600160a01b0381165f90815260046020908152604091829020805483518184028101840190945280845260609392830182828015610a0957602002820191905f5260205f20905b81546001600160a01b031681526001909101906020018083116109eb575b50505050509050919050565b6005546060905f839003610a27578092505b808410610a7d57604080515f8082526020820190925290610a75565b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610a435790505b509150610bbb565b5f81610a898587612521565b11610a945783610a9e565b610a9e8583612534565b90508067ffffffffffffffff811115610ab957610ab96124f9565b604051908082528060200260200182016040528015610b0957816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610ad75790505b5092505f5b81811015610bb8575f6005610b238389612521565b81548110610b3357610b33612547565b5f9182526020808320909101546001600160a01b039081168084526002808452604094859020855160808101875281548516815260018201548516958101959095529081015490921693830193909352600301546060820152865191925090869084908110610ba457610ba4612547565b602090810291909101015250600101610b0e565b50505b9250929050565b60605f8060058054905067ffffffffffffffff811115610be457610be46124f9565b604051908082528060200260200182016040528015610c4357816020015b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610c025790505b5090505f805b600554811015610e8f575f60058281548110610c6757610c67612547565b5f9182526020808320909101546040805163481c6a7560e01b815290516001600160a01b039092169450849392849263481c6a759260048082019392918290030181865afa158015610cbb573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cdf91906124de565b90505f816001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610d1e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d42919061259d565b80516020820151919250905f805b89811015610dda57836001600160a01b03168b8281518110610d7457610d74612547565b6020026020010151602001516001600160a01b0316148015610dc45750826001600160a01b03168b8281518110610dad57610dad612547565b6020026020010151606001516001600160a01b0316145b15610dd25760019150610dda565b600101610d50565b5080610e7d575f610dea84611583565b90505f610df684611583565b90505f610e0286611614565b90505f610e0e86611614565b90506040518060c00160405280858152602001886001600160a01b03168152602001848152602001876001600160a01b031681526020018360ff1681526020018260ff168152508e8e81518110610e6757610e67612547565b60200260200101819052508c6001019c50505050505b87600101975050505050505050610c49565b50809250845f03610e9e578294505b828610610f0557604080515f8082526020820190925290610efb565b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610eba5790505b5093505050610bbb565b5f83610f118789612521565b11610f1c5785610f26565b610f268785612534565b90508067ffffffffffffffff811115610f4157610f416124f9565b604051908082528060200260200182016040528015610fa057816020015b6040805160c08101825260608082525f60208084018290529383018290529082018190526080820181905260a082015282525f19909201910181610f5f5790505b5094505f5b81811015610ff55783610fb8828a612521565b81518110610fc857610fc8612547565b6020026020010151868281518110610fe257610fe2612547565b6020908102919091010152600101610fa5565b505050509250929050565b6110086114fb565b805f036110285760405163e6c4247b60e01b815260040160405180910390fd5b600780549082905560408051828152602081018490527f65d057080f4c8634a11330806ded4bb764a6416376e126938311cf1cda7f1081910160405180910390a15050565b6110756114fb565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff16156106fd575f8281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b5f80546001600160a01b038381169116148061113357505f8381526001602090815260408083206001600160a01b038616845290915290205460ff165b9392505050565b5f60075434101561115e5760405163cd1c886760e01b815260040160405180910390fd5b6001600160a01b0388166111855760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b038881165f9081526003602052604090205416156111bc576040516205738360ea1b815260040160405180910390fd5b5f886001600160a01b0316638da5cb5b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061121d91906124de565b9050336001600160a01b0382161461124857604051631a27eac360e11b815260040160405180910390fd5b61125a8760a001358860c0013561168b565b611263876116eb565b61126f89898986611756565b6040516352907b9d60e01b81526001600160a01b037f0000000000000000000000000d5bf374306eef436416dd8900f61997c2ef93df16906352907b9d906112cb908c90309086908e908e908e908e908e908e906004016123b4565b6020604051808303815f875af11580156112e7573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061130b91906124de565b91503415611385575f826001600160a01b0316346040515f6040518083038185875af1925050503d805f811461135c576040519150601f19603f3d011682016040523d82523d5f602084013e611361565b606091505b50509050806113835760405163e6c4247b60e01b815260040160405180910390fd5b505b604080516080810182526001600160a01b038085168083528c8216602080850182815287851686880181815242606089019081525f87815260028087528b82209a518b54908b1673ffffffffffffffffffffffffffffffffffffffff19918216178c5595516001808d018054928d16928916929092179091559351908b01805491909a16908616179098555160039889015584875296835287862080548316861790558086526004835287862080548089018255908752928620909201805482168517905560058054968701815585527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db090950180549095168317909455935192939290917f7693e4b27904de2418f1de7feb4e3e3e0aa788e2262b3b4eae57f4c9623cb13691a450979650505050505050565b6114c16114fb565b6001600160a01b0381166114ef57604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b6114f881611527565b50565b5f546001600160a01b031633146108ca5760405163118cdaa760e01b81523360048201526024016114e6565b5f80546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60606001600160a01b0382166115b257505060408051808201909152600381526208aa8960eb1b602082015290565b816001600160a01b03166395d89b416040518163ffffffff1660e01b81526004015f60405180830381865afa1580156115ed573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261099c9190810190612633565b5f6001600160a01b03821661162b57506012919050565b816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611667573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061099c91906126c7565b5f82158015611698575081155b90505f836706f05b59d3b200001480156116b95750826706f05b59d3b20000145b9050811580156116c7575080155b156116e55760405163940addc760e01b815260040160405180910390fd5b50505050565b5f60a0820135158015611700575060c0820135155b9050611714610140830161012084016126e2565b801561171d5750805b80156117385750611736610120830161010084016126e2565b155b156106fd5760405163e6c4247b60e01b815260040160405180910390fd5b61176360208201826126e2565b15801561177d575061177b60408201602083016126e2565b155b801561179b575061179460a08401608085016126fd565b62ffffff16155b6116e5575f8490505f816001600160a01b031663182148ef6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156117e0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611804919061259d565b60808101519091506001600160a01b0381166118325760405162f61f7960e41b815260040160405180910390fd5b806001600160a01b03166326a1161761184c8460a0902090565b6040518263ffffffff1660e01b815260040161186a91815260200190565b602060405180830381865afa9250505080156118a3575060408051601f3d908101601f191682019092526118a0918101906120fb565b60015b6118bf5760405162f61f7960e41b815260040160405180910390fd5b806118dc5760405162f61f7960e41b815260040160405180910390fd5b505f8190505f816001600160a01b03166355b13a4f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561191e573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061194291906124de565b90506001600160a01b0381166362aaf2668561196460608a0160408b01612718565b604080517fffffffff0000000000000000000000000000000000000000000000000000000060e086901b16815283516001600160a01b0390811660048301526020850151811660248301529184015162ffffff166044820152606084015160020b606482015260809093015116608483015263ffffffff1660a482015260c4016040805180830381865afa925050508015611a1c575060408051601f3d908101601f19168201909252611a1991810190612731565b60015b611a3957604051635d2c8bcb60e11b815260040160405180910390fd5b50505f611a4960208a018a6126fd565b62ffffff16151580611a6e5750611a6660408a0160208b016126fd565b62ffffff1615155b90505f611a8160a08b0160808c016126fd565b62ffffff1615159050818015611a945750805b15611ab2576040516318964e4d60e21b815260040160405180910390fd5b611ac26040890160208a016126e2565b8015611adb5750611adb6101408a016101208b016126e2565b15611af95760405163b24184b760e01b815260040160405180910390fd5b808015611b135750611b136101408a016101208b016126e2565b15611b315760405163b24184b760e01b815260040160405180910390fd5b611b416060890160408a01612718565b63ffffffff165f03611b665760405163b24184b760e01b815260040160405180910390fd5b62093a80611b7a60608a0160408b01612718565b63ffffffff161115611b9f5760405163b24184b760e01b815260040160405180910390fd5b611bac60208901896126e2565b8015611bca5750611bc36080890160608a016126fd565b62ffffff16155b15611be85760405163b24184b760e01b815260040160405180910390fd5b5050505050505050505050565b6001600160a01b03811681146114f8575f80fd5b803561064781611bf5565b5f60208284031215611c24575f80fd5b813561113381611bf5565b6080810161099c82846001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b036040820151166040830152606081015160608301525050565b5f8060408385031215611c8a575f80fd5b823591506020830135611c9c81611bf5565b809150509250929050565b5f8060408385031215611cb8575f80fd5b8235611cc381611bf5565b946020939093013593505050565b5f60208284031215611ce1575f80fd5b813561ffff81168114611133575f80fd5b5f6101408284031215611d03575f80fd5b50919050565b5f6101608284031215611d03575f80fd5b5f60608284031215611d03575f80fd5b5f60a08284031215611d03575f80fd5b5f60208284031215611d03575f80fd5b5f60808284031215611d03575f80fd5b5f805f805f805f80610440898b031215611d72575f80fd5b8835611d7d81611bf5565b97506020890135611d8d81611bf5565b9650611d9c8a60408b01611cf2565b9550611dac8a6101808b01611d09565b94506102e089013567ffffffffffffffff811115611dc8575f80fd5b611dd48b828c01611d1a565b945050611de58a6103008b01611d2a565b9250611df58a6103a08b01611d3a565b9150611e058a6103c08b01611d4a565b90509295985092959890939650565b602080825282518282018190525f918401906040840190835b81811015611e545783516001600160a01b0316835260209384019390920191600101611e2d565b509095945050505050565b5f8060408385031215611e70575f80fd5b50508035926020909101359150565b604080825283519082018190525f9060208501906060840190835b81811015611eff57611ee98385516001600160a01b0381511682526001600160a01b0360208201511660208301526001600160a01b036040820151166040830152606081015160608301525050565b6020939093019260809290920191600101611e9a565b5050602093909301939093525092915050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f604082016040835280855180835260608501915060608160051b8601019250602087015f5b8281101561200457605f198786030184528151805160c08752611f8c60c0880182611f12565b90506001600160a01b03602083015116602088015260408201518782036040890152611fb88282611f12565b9150506001600160a01b03606083015116606088015260ff608083015116608088015260ff60a08301511660a08801528096505050602082019150602084019350600181019050611f66565b505050506020929092019290925292915050565b5f60208284031215612028575f80fd5b5035919050565b5f805f805f805f610420888a031215612046575f80fd5b873561205181611bf5565b96506120608960208a01611cf2565b9550612070896101608a01611d09565b94506102c088013567ffffffffffffffff81111561208c575f80fd5b6120988a828b01611d1a565b9450506120a9896102e08a01611d2a565b92506120b9896103808a01611d3a565b91506120c9896103a08a01611d4a565b905092959891949750929550565b5f602082840312156120e7575f80fd5b5051919050565b80151581146114f8575f80fd5b5f6020828403121561210b575f80fd5b8151611133816120ee565b62ffffff811681146114f8575f80fd5b803561064781612116565b8035610647816120ee565b6121528261214983612126565b62ffffff169052565b61215e60208201612126565b62ffffff16602083015261217460408201612131565b1515604083015261218760608201612126565b62ffffff16606083015261219d60808201611c09565b6001600160a01b0316608083015260a0818101359083015260c080820135908301526121cb60e08201612131565b151560e08301526121df6101008201612131565b15156101008301526121f46101208201612131565b15156101208301526122096101408201612131565b801515610140840152505050565b5f808335601e1984360301811261222c575f80fd5b830160208101925035905067ffffffffffffffff81111561224b575f80fd5b803603821315610bbb575f80fd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b60ff811681146114f8575f80fd5b5f61229a8283612217565b606085526122ac606086018284612259565b9150506122bc6020840184612217565b85830360208701526122cf838284612259565b9250505060408301356122e181612281565b60ff81166040860152508091505092915050565b80358252602080820135908301526040810135612311816120ee565b151560408301526060810135612326816120ee565b15156060830152608081013561233b816120ee565b8015156080840152505050565b803563ffffffff81168114610647575f80fd5b8035612366816120ee565b151582526020810135612378816120ee565b1515602083015263ffffffff61239060408301612348565b16604083015260608101356123a481612116565b62ffffff81166060840152505050565b6001600160a01b038a1681526001600160a01b03891660208201526001600160a01b03881660408201526123ee6060820161214989612126565b5f6123fb60208901612126565b62ffffff16608083015261241160408901612126565b62ffffff1660a083015261242760608901612126565b62ffffff1660c083015261243d60808901612126565b62ffffff811660e08401525060a08801356101008381019190915260c08901356101208085019190915260e08a0135610140850152908901356101608401528801356101808301526124936101a083018861213c565b6104606103008301526124aa61046083018761228f565b90506124ba6103208301866122f5565b83356103c08301526124d06103e083018461235b565b9a9950505050505050505050565b5f602082840312156124ee575f80fd5b815161113381611bf5565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b8082018082111561099c5761099c61250d565b8181038181111561099c5761099c61250d565b634e487b7160e01b5f52603260045260245ffd5b604051601f8201601f1916810167ffffffffffffffff81118282101715612584576125846124f9565b604052919050565b8051600281900b8114610647575f80fd5b5f60a08284031280156125ae575f80fd5b5060405160a0810167ffffffffffffffff811182821017156125d2576125d26124f9565b60405282516125e081611bf5565b815260208301516125f081611bf5565b6020820152604083015161260381612116565b60408201526126146060840161258c565b6060820152608083015161262781611bf5565b60808201529392505050565b5f60208284031215612643575f80fd5b815167ffffffffffffffff811115612659575f80fd5b8201601f81018413612669575f80fd5b805167ffffffffffffffff811115612683576126836124f9565b612696601f8201601f191660200161255b565b8181528560208385010111156126aa575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f602082840312156126d7575f80fd5b815161113381612281565b5f602082840312156126f2575f80fd5b8135611133816120ee565b5f6020828403121561270d575f80fd5b813561113381612116565b5f60208284031215612728575f80fd5b61113382612348565b5f8060408385031215612742575f80fd5b61274b8361258c565b915060208301516fffffffffffffffffffffffffffffffff81168114611c9c575f80fdfea26469706673582212203def67b279757228ad81130f322be91e2ee54a87b3dbee5ed2efe681d3f0a9e564736f6c634300081a0033

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

000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1000000000000000000000000f2d7660ae1a70794fdc3fbc48a16406688953446

-----Decoded View---------------
Arg [0] : _owner (address): 0xe911f518449ba0011D84b047B4cde50dAA081eC1
Arg [1] : _multiPositionFactory (address): 0xF2D7660aE1A70794fdc3fBC48a16406688953446

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1
Arg [1] : 000000000000000000000000f2d7660ae1a70794fdc3fbc48a16406688953446


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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