ETH Price: $3,557.24 (-1.35%)

Contract

0x4ED675a684528aa315f8742013e2ff198B368d36

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
297545242025-10-15 4:34:4327 days ago1760502883
0x4ED675a6...98B368d36
 Contract Creation0 ETH

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultiPositionFactory

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT
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 { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { RebalanceLogic } from "./lib/RebalanceLogic.sol";

contract MultiPositionFactory is IMultiPositionFactory, Ownable {
    // Role constants
    bytes32 public constant override CLAIM_MANAGER = keccak256("CLAIM_MANAGER");

    // Role storage
    mapping(bytes32 => mapping(address => bool)) private _roles;

    // 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 used names to prevent duplicates
    mapping(string => bool) public usedNames;

    // Protocol fee recipient
    address public feeRecipient;

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

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

    // Deployer contract for MultiPositionManager
    MultiPositionDeployer public immutable deployer;
    
    // Custom errors
    error UnauthorizedAccess();
    error ManagerAlreadyExists();
    error InvalidAddress();
    error InitializationFailed();
    error InvalidFee();
    error InsufficientMsgValue();
    error NameAlreadyUsed(string name);
    
    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();
    }

    /**
     * @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 returns (address) {
        if (managerOwner == address(0)) revert InvalidAddress();

        // Check if name is already used
        if (usedNames[name]) revert NameAlreadyUsed(name);

        // 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 = "GAMMA-LP";

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

        // Mark name as used
        usedNames[name] = true;

        // 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);
        
        emit MultiPositionManagerDeployed(
            managerAddress,
            managerOwner,
            poolKey
        );
        
        return managerAddress;
    }

    /**
     * @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
     * @param name The name for the LP token
     * @param deposit0Desired Amount of token0 to deposit
     * @param deposit1Desired Amount of token1 to deposit
     * @param to Address to receive LP shares
     * @param inMin Minimum amounts for slippage protection
     * @param rebalanceParams Strategy and rebalance parameters
     * @return mpm The address of the deployed and initialized MultiPositionManager
     */
    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 returns (address mpm) {
        // Input validation
        if (managerOwner == address(0)) revert InvalidAddress();
        if (to == address(0)) revert InvalidAddress();

        // Deploy MPM (call external function using 'this')
        mpm = this.deployMultiPositionManager(poolKey, managerOwner, name);

        // Deposit liquidity (Factory can call because it's s.factory in MPM)
        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
     * @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 to Address to receive the LP shares
     * @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
     */
    function deployDepositAndRebalanceSwap(
        PoolKey memory poolKey,
        address managerOwner,
        string memory name,
        uint256 deposit0Desired,
        uint256 deposit1Desired,
        address to,
        RebalanceLogic.SwapParams calldata swapParams,
        uint256[2][] memory inMin,
        IMultiPositionManager.RebalanceParams memory rebalanceParams
    ) external payable returns (address mpm) {
        // Input validation
        if (managerOwner == address(0)) revert InvalidAddress();
        if (to == address(0)) revert InvalidAddress();
        if (swapParams.aggregatorAddress == address(0)) revert InvalidAddress();

        // Deploy MPM (call external function using 'this')
        mpm = this.deployMultiPositionManager(poolKey, managerOwner, name);

        // Deposit liquidity (tokens will sit idle in MPM, no positions yet)
        MultiPositionManager(payable(mpm)).deposit{value: msg.value}(
            deposit0Desired,
            deposit1Desired,
            to,
            msg.sender  // from = msg.sender (the user calling this function)
        );

        // RebalanceSwap: swaps to target ratio + creates positions
        MultiPositionManager(payable(mpm)).rebalanceSwap(
            IMultiPositionManager.RebalanceSwapParams({
                rebalanceParams: rebalanceParams,
                swapParams: swapParams
            }),
            new uint256[2][](0),  // outMin empty (no positions to burn)
            inMin                 // inMin for new positions after swap
        );

        return mpm;
    }

    /**
     * @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) {
        // Use fixed symbol for all deployments
        string memory symbol = "GAMMA-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
        );
    }

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

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

// SPDX-License-Identifier: MIT
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;
    }

    // Roles
    function CLAIM_MANAGER() external view 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);
    
    // 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 {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IHooks } from "v4-core/interfaces/IHooks.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 "../lib/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;
    int24 limitWidth;
    uint256 weight0;
    uint256 weight1;
    bool useCarpet;
  }

  struct RebalanceSwapParams {
    RebalanceParams rebalanceParams;
    RebalanceLogic.SwapParams swapParams;
  }
  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 basePositionsLength() external view returns (uint256);
  function limitPositionsLength() external view returns (uint256);
  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;
  function rebalanceSwap(
    RebalanceSwapParams calldata params,
    uint256[2][] memory outMin,
    uint256[2][] memory inMin
  ) external payable;
  function claimFee() external;
  function setFee(uint16 fee) external;
  function factory() external view returns (address);
  // 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;

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

  // Role management functions
  function grantRebalancerRole(address account) external;
  function revokeRebalancerRole(address account) external;
  function isRebalancer(address account) external view returns (bool);

}

// SPDX-License-Identifier: MIT
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
 * @dev Separated from factory to reduce factory contract size
 */
contract MultiPositionDeployer {
    /**
     * @notice Deploys a new MultiPositionManager contract
     * @param poolManager The Uniswap V4 pool manager
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param owner The owner of the new MultiPositionManager
     * @param factory The factory contract address
     * @param name The name of the LP token
     * @param symbol The symbol of the LP token
     * @param fee The protocol fee
     * @param salt The salt for CREATE2 deployment
     * @return The address of the deployed MultiPositionManager
     */
    function deploy(
        IPoolManager poolManager,
        PoolKey memory poolKey,
        address owner,
        address factory,
        string memory name,
        string memory symbol,
        uint16 fee,
        bytes32 salt
    ) external returns (address) {
        return address(new MultiPositionManager{salt: salt}(
            poolManager,
            poolKey,
            owner,
            factory,
            name,
            symbol,
            fee
        ));
    }

    /**
     * @notice Computes the address where a MultiPositionManager will be deployed
     * @param poolManager The Uniswap V4 pool manager
     * @param poolKey The pool key for the Uniswap V4 pool
     * @param owner The owner of the new MultiPositionManager
     * @param factory The factory contract address
     * @param name The name of the LP token
     * @param symbol The symbol of the LP token
     * @param fee The protocol fee
     * @param salt The salt for CREATE2 deployment
     * @return predicted The address where the MultiPositionManager will be deployed
     */
    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)
        ));

        /// @solidity memory-safe-assembly
        assembly {
            // Load free memory pointer
            let ptr := mload(0x40)

            // Store 0xff at the correct position (byte 0 of our 85-byte data)
            mstore(ptr, 0xff00000000000000000000000000000000000000000000000000000000000000)

            // Store address at byte 1 (shift right by 96 bits = 12 bytes to right-align in 20 bytes)
            mstore(add(ptr, 0x01), shl(96, address()))

            // Store salt at byte 21
            mstore(add(ptr, 0x15), salt)

            // Store hash at byte 53
            mstore(add(ptr, 0x35), hash)

            // Hash 85 bytes starting from ptr
            predicted := keccak256(ptr, 0x55)
        }
    }
}

// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.26;

import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { ERC20, ERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.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 { TransientStateLibrary } from "v4-core/libraries/TransientStateLibrary.sol";
import { SafeCast } from "v4-core/libraries/SafeCast.sol";
import { SafeCallback } from "v4-periphery/src/base/SafeCallback.sol";
import { CurrencySettler } from "v4-periphery/lib/v4-core/test/utils/CurrencySettler.sol";

import { IMultiPositionManager } from "./interfaces/IMultiPositionManager.sol";
import { IMultiPositionFactory } from "./interfaces/IMultiPositionFactory.sol";
import { PoolManagerUtils } from "./PoolManagerUtils.sol";
import { Multicall } from "./base/Multicall.sol";
import { SharedStructs } from "./base/SharedStructs.sol";
import { RebalanceLogic } from "./lib/RebalanceLogic.sol";
import { WithdrawLogic } from "./lib/WithdrawLogic.sol";
import { DepositLogic } from "./lib/DepositLogic.sol";
import { PositionLogic } from "./lib/PositionLogic.sol";


contract MultiPositionManager is
  IMultiPositionManager,
  Initializable,
  ERC20Permit,
  ReentrancyGuard,
  Ownable,
  SafeCallback,
  Multicall
{
  using SafeERC20 for IERC20;
  using StateLibrary for IPoolManager;
  using TransientStateLibrary for IPoolManager;
  using SignedMath for int256;
  using Math for uint256;
  using PoolIdLibrary for PoolKey;
  using SafeCast for *;
  using CurrencySettler for Currency;

  uint256 public constant PRECISION = 1e36;

  int24 public constant CENTER_AT_CURRENT_TICK = type(int24).max;

  // Events for role management
  event RebalancerGranted(address indexed account);
  event RebalancerRevoked(address indexed account);

  // Single storage struct
  SharedStructs.ManagerStorage internal s;

  error InvalidFee();
  error ZeroAddress();
  error ZeroValue();
  error InvalidTickRange();
  error InvalidAction();
  error InvalidRebalanceParams();
  error InvalidPoolKeyTokens();
  error InvalidDepositAmount(uint256 amount);
  error CurrencyDeltaError();
  error DuplicatedRange(Range range);
  error NotANativeTokenPair();
  error InsufficientShares(uint256 shares, uint256 minShares);
  error UnauthorizedCaller();
  error InvalidRecipient();
  error NoSharesMinted();
  error InvalidInMinLength();
  error OutMinLengthMismatch();
  error AmountMustBePositive();
  error InsufficientBalance();
  error SlippageProtection();
  error NoStrategySpecified();
  error InvalidWeightSum();
  error WeightBelowMinimum();
  error RegistryNotSet();
  error NoSharesExist();
  error StrategyNotApproved();
  error CannotSendETHForERC20Pair();
  error CarpetRequiresBothTokens();
  error InsufficientLiquidityForCarpet();
  error SwapFailed();
  error InsufficientSwapOutput();

  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 Rebalance(Position[]);
  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
  ) ERC20Permit(_name) ERC20(_name, _symbol) Ownable(_owner) SafeCallback(_poolManager) {

    // Initialize storage struct
    s.poolKey = _poolKey;
    s.poolId = _poolKey.toId();
    s.currency0 = _poolKey.currency0;
    s.currency1 = _poolKey.currency1;
    s.factory = _factory;
    s.fee = _fee;
  }

  // ============ Public Getters for Storage ============

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


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

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

  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
  ) {
    SharedStructs.StrategyParams memory params = s.lastStrategyParams;
    return (
      params.strategy,
      params.centerTick,
      params.ticksLeft,
      params.ticksRight,
      params.limitWidth,
      params.weight0,
      params.weight1,
      params.useCarpet
    );
  }

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


  modifier onlyOwnerOrFactory() {
    if (msg.sender != owner() && msg.sender != s.factory) revert UnauthorizedCaller();
    _;
  }

  modifier onlyOwnerOrRebalancerOrFactory() {
    if (msg.sender != owner() && !s.rebalancers[msg.sender] && msg.sender != s.factory) revert UnauthorizedCaller();
    _;
  }

  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 which liquidity tokens are minted
   * @param from Address from which asset tokens are transferred
   * @return shares Number of shares minted
   * @return deposit0 Actual amount of token0 deposited
   * @return deposit1 Actual amount of token1 deposited
   */
  function deposit(
    uint256 deposit0Desired,
    uint256 deposit1Desired,
    address to,
    address from
  ) external payable onlyOwnerOrFactory returns (
    uint256 shares,
    uint256 deposit0,
    uint256 deposit1
  ) {
    // Delegate to DepositLogic library
    (shares, deposit0, deposit1) = DepositLogic.processDeposit(
      s,
      poolManager,
      deposit0Desired,
      deposit1Desired,
      to,
      from,
      totalSupply(),
      msg.value
    );

    // Effects: Mint shares first (checks-effects-interactions pattern)
    _mint(to, shares);

    // Interactions: Transfer tokens to vault
    _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
   * @param inMin Minimum amounts for each position (slippage protection)
   */
  function compound(uint256[2][] calldata inMin) external onlyOwnerOrFactory {
    poolManager.unlock(abi.encode(IMultiPositionManager.Action.COMPOUND, abi.encode(inMin)));
  }

  /**
   * @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 onlyOwnerOrFactory {
    // 1. Collect fees via ZERO_BURN (inside unlock)
    if (s.basePositionsLength > 0) {
      poolManager.unlock(abi.encode(IMultiPositionManager.Action.ZERO_BURN));
    }

    // 2. Execute swap (outside unlock)
    RebalanceLogic.executeCompoundSwap(s, swapParams);

    // 3. Compound - add liquidity back to positions (inside unlock)
    poolManager.unlock(
      abi.encode(IMultiPositionManager.Action.COMPOUND, abi.encode(inMin))
    );
  }

  /**
   *
   * @param shares Number of liquidity tokens to redeem as pool assets
   * @param to Address to which redeemed pool assets are sent (ignored if withdrawToWallet is false)
   * @param outMin min amount returned for shares of liq
   * @param withdrawToWallet If true, transfers tokens to 'to' 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
   */
  function withdraw(
    uint256 shares,
    address to,
    uint256[2][] memory outMin,
    bool withdrawToWallet
  ) nonReentrant external returns (uint256 amount0, uint256 amount1) {
    // Delegate to WithdrawLogic library
    (amount0, amount1) = WithdrawLogic.processWithdraw(
      s,
      poolManager,
      shares,
      to,
      outMin,
      totalSupply(),
      msg.sender,
      withdrawToWallet
    );

    // Only burn shares if withdrawing to wallet
    if (withdrawToWallet) {
      _burn(msg.sender, shares);
    }
  }


  /**
   * @notice Withdraw custom amounts of both tokens
   * @param amount0Desired Amount of token0 to withdraw
   * @param amount1Desired Amount of token1 to withdraw
   * @param to Address to receive the tokens
   * @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
   */
  function withdrawCustom(
    uint256 amount0Desired,
    uint256 amount1Desired,
    address to,
    uint256[2][] memory outMin
  ) external nonReentrant returns (uint256 amount0Out, uint256 amount1Out, uint256 sharesBurned) {
    // Delegate to WithdrawLogic library
    WithdrawLogic.CustomWithdrawParams memory params = WithdrawLogic.CustomWithdrawParams({
      amount0Desired: amount0Desired,
      amount1Desired: amount1Desired,
      to: to,
      outMin: outMin,
      totalSupply: totalSupply(),
      senderBalance: balanceOf(msg.sender),
      sender: msg.sender
    });

    (amount0Out, amount1Out, sharesBurned) = WithdrawLogic.processWithdrawCustom(s, poolManager, params);

    // Burn shares after successful withdrawal
    _burn(msg.sender, sharesBurned);
  }


  /**
   * @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
   */
  function rebalance(
    IMultiPositionManager.RebalanceParams calldata params,
    uint256[2][] memory outMin,
    uint256[2][] memory inMin
  ) public onlyOwnerOrRebalancerOrFactory {
    // Delegate to RebalanceLogic library
    (
      IMultiPositionManager.Range[] memory baseRanges,
      uint128[] memory liquidities,
      int24 limitWidth
    ) = RebalanceLogic.rebalance(s, poolManager, params, outMin, inMin);

    // Execute rebalance with calculated parameters
    bytes memory encodedParams = abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin);
    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 onlyOwnerOrRebalancerOrFactory {
    // 1. Burn all existing positions first (inside unlock)
    if (totalSupply() > 0 && (s.basePositionsLength > 0 || s.limitPositionsLength > 0)) {
      poolManager.unlock(
        abi.encode(IMultiPositionManager.Action.BURN_ALL, abi.encode(outMin))
      );
    }

    // 2. Execute swap (if needed) and calculate ranges (outside unlock)
    (
      IMultiPositionManager.Range[] memory baseRanges,
      uint128[] memory liquidities,
      int24 limitWidth
    ) = RebalanceLogic.executeSwapAndCalculateRanges(s, poolManager, params);

    // 4. Rebalance with new ranges (inside unlock)
    bytes memory encodedParams = abi.encode(baseRanges, liquidities, limitWidth, inMin, outMin);
    poolManager.unlock(
      abi.encode(IMultiPositionManager.Action.REBALANCE, encodedParams)
    );
  }

  /**
   * @notice Claims fees
   * @dev If called by owner, performs zeroBurn and claims both owner and protocol fees
   * @dev If called by factory owner or CLAIM_MANAGER, only claims existing protocol fees
   */
  function claimFee() external {
    // Check if caller is the owner
    if (msg.sender == owner()) {
      // Owner can claim their portion + trigger protocol fee transfer
      poolManager.unlock(
        abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(msg.sender))
      );
    } else if (IMultiPositionFactory(s.factory).hasRoleOrOwner(
      IMultiPositionFactory(s.factory).CLAIM_MANAGER(),
      msg.sender
    )) {
      // Factory owner or CLAIM_MANAGER can only claim protocol fees (no zeroBurn)
      poolManager.unlock(
        abi.encode(IMultiPositionManager.Action.CLAIM_FEE, abi.encode(address(0)))
      );
    } else {
      revert UnauthorizedCaller();
    }
  }


  function setFee(uint16 newFee) external {
    require(msg.sender == Ownable(s.factory).owner());
    s.fee = newFee;
  }

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

  /**
   * @notice Revoke rebalancer role from an address
   * @param account The address to revoke the role from
   */
  function revokeRebalancerRole(address account) external onlyOwner {
    if (s.rebalancers[account]) {
      s.rebalancers[account] = false;
      emit RebalancerRevoked(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 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) {
      WithdrawLogic.zeroBurnAllWithoutUnlock(s, poolManager);
      (
        uint256 shares,
        uint256[2][] memory outMin
      ) = abi.decode(params, (uint256, uint256[2][]));
      (uint256 amountOut0, uint256 amountOut1) = PositionLogic.burnLiquidities(poolManager, s, shares, totalSupply(), outMin);
      return abi.encode(amountOut0, amountOut1);
    } else if (selector == IMultiPositionManager.Action.REBALANCE) {
      // Delegate entirely to RebalanceLogic
      return RebalanceLogic.processRebalanceInCallback(s, poolManager, params, totalSupply());
    } else if (selector == IMultiPositionManager.Action.ZERO_BURN) {
      // Collect fees into vault via zeroBurn
      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) {
      // Delegate entirely to WithdrawLogic
      return WithdrawLogic.processBurnAllInCallback(s, poolManager, totalSupply(), params);
    } else if (selector == IMultiPositionManager.Action.COMPOUND) {
      // Delegate to DepositLogic
      uint256[2][] memory inMin = abi.decode(params, (uint256[2][]));
      DepositLogic.processCompound(s, poolManager, inMin);
      return "";
    } else revert InvalidAction();
  }


  /**
   * @notice Close both currency deltas with pool manager
   */
  function _closePair() internal {
    PoolManagerUtils.close(poolManager, s.currency1);
    PoolManagerUtils.close(poolManager, s.currency0);
  }

  /**
   * @notice Internal function to handle token transfers
   * @param from Address to transfer from
   * @param currency The currency to transfer
   * @param amount Amount to transfer
   */
  function _transferIn(address from, Currency currency, uint256 amount) internal {
    if (currency.isAddressZero()) {
      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
pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

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

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

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

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

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

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

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

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

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

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

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

File 7 of 70 : 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
// 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);
    }
}

File 9 of 70 : RebalanceLogic.sol
// SPDX-License-Identifier: UNLICENSED
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 { Currency } from "v4-core/types/Currency.sol";
import { TickMath } from "v4-core/libraries/TickMath.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 { 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 { 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;
    using SafeERC20 for IERC20;

    uint256 constant PRECISION = 1e18;

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

    // Events
    event Rebalance(IMultiPositionManager.Position[] positions);
    event LogTotalAmounts(uint256 totalAmount0, uint256 totalAmount1);
    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;
        int24 limitWidth;
        bool weightsAreProportional;
    }

    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
        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
     * @param inMin Minimum input amounts for new positions (slippage protection)
     * @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,
        uint256[2][] memory inMin
    ) external returns (
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory liquidities,
        int24 limitWidth
    ) {
        if (outMin.length != s.basePositionsLength + s.limitPositionsLength) {
            revert OutMinLengthMismatch();
        }

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

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

        ctx.weight0 = params.weight0;
        ctx.weight1 = params.weight1;
        ctx.weightsAreProportional = (ctx.weight0 == 0 && ctx.weight1 == 0);
        if (ctx.weightsAreProportional) {
            (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 {
            ctx.center = params.center;
        }

        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
        baseRanges = new IMultiPositionManager.Range[](lowerTicks.length);
        for (uint i = 0; i < lowerTicks.length; i++) {
            baseRanges[i] = IMultiPositionManager.Range(lowerTicks[i], upperTicks[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,
            outMin,
            inMin
        );
    }

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

        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 {}

            // Use default weights if needed
            if (!params.useCarpet && !supportsWeightedDist &&
                (params.weight0 != 0.5e18 || params.weight1 != 0.5e18)) {
                params.weight0 = 0.5e18;
                params.weight1 = 0.5e18;
            }
        }

        return ctx.strategy.calculateDensities(
            params.lowerTicks,
            params.upperTicks,
            params.tick,
            params.center,
            params.tLeft,
            params.tRight,
            params.weight0,
            params.weight1,
            params.useCarpet,
            params.tickSpacing,
            weightsAreProportional
        );
    }

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

        // Store flag early to avoid stack too deep
        bool weightsAreProportional = ctx.weightsAreProportional;

        // Process in separate scope to reduce stack
        {
            // Get current pool state
            (uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(s.poolKey.toId());

            // Get total available amounts (will be calculated by caller)
            (uint256 available0, uint256 available1) = _getTotalAvailable(s, poolManager);

            // Carpet mode requires both tokens to create base layer across all positions
            if (ctx.useCarpet && (available0 == 0 || available1 == 0)) {
                revert CarpetRequiresBothTokens();
            }

            // Use existing helper to calculate liquidities from weights
            _calculateLiquiditiesFromWeights(
                liquidities,
                weights,
                baseRanges,
                available0,
                available1,
                sqrtPriceX96,
                weightsAreProportional
            );
        }

        // Verify carpet positions have sufficient liquidity
        if (ctx.useCarpet) {
            _validateCarpetLiquidity(baseRanges, liquidities, s.poolKey.tickSpacing);
        }

        // Store the parameters for future use
        _updateStrategyParams(s, ctx);

        // Emit event using helper
        _emitRebalanceEvent(baseRanges, s.poolKey);

        // Return the data needed for the unlock
        return (baseRanges, liquidities, ctx.limitWidth);
    }

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

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

    /**
     * @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 weightsAreProportional
    ) internal pure {
        if (!weightsAreProportional) {
            // For explicit weights, use direct liquidity calculation (old approach)
            calculateLiquiditiesDirectly(liquidities, weights, baseRanges, total0, total1, sqrtPriceX96);
            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);

        // Step 2: Scale allocations proportionally to available tokens
        scaleAllocations(data, total0, total1, 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);
    }

    /**
     * @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 = 0;
        uint256 totalWeightedToken1 = 0;

        for (uint i = 0; i < rangesLength; i++) {
            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);
        }

        // 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 (uint i = 0; i < rangesLength; i++) {
            liquidities[i] = uint128(FullMath.mulDiv(weights[i], totalLiquidity, 1e18));
        }
    }

    /**
     * @notice Calculate initial token allocations based on weights
     */
    function calculateInitialAllocations(
        AllocationData memory data,
        IMultiPositionManager.Range[] memory baseRanges,
        uint256[] memory weights,
        uint160 sqrtPriceX96
    ) internal pure {
        uint256 rangesLength = baseRanges.length;

        for (uint i = 0; i < rangesLength; i++) {
            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) {
                data.currentRangeIndex = i;
                data.hasCurrentRange = true;
            }
        }
    }

    /**
     * @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 weightsAreProportional
    ) internal pure {
        uint256 rangesLength = data.token0Allocations.length;

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

            if (data.totalToken1Needed > 0) {
                for (uint i = 0; i < rangesLength; i++) {
                    data.token1Allocations[i] = FullMath.mulDiv(
                        data.token1Allocations[i],
                        available1,
                        data.totalToken1Needed
                    );
                }
            }
        } 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 (uint i = 0; i < rangesLength; i++) {
                data.token0Allocations[i] = FullMath.mulDiv(
                    data.token0Allocations[i],
                    scaleFactor,
                    1e18
                );
                data.token1Allocations[i] = FullMath.mulDiv(
                    data.token1Allocations[i],
                    scaleFactor,
                    1e18
                );
            }
        }
    }

    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))
        uint128 liquidityFrom1 = 0;
        if (sqrtPriceX96 > sqrtPriceLower) {
            // Direct division as Python does: liquidity = amount1 / (sqrtPrice - sqrtPriceLower)
            liquidityFrom1 = uint128(
                FullMath.mulDiv(
                    data.token1Allocations[idx],
                    FixedPoint96.Q96,
                    sqrtPriceX96 - sqrtPriceLower
                )
            );
        }

        // 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
            token0Needed = FullMath.mulDiv(
                liquidityFrom1,
                sqrtPriceUpper - sqrtPriceX96,
                FullMath.mulDiv(sqrtPriceUpper, sqrtPriceX96, FixedPoint96.Q96)
            );
        }

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

        // Calculate actual usage with the determined liquidity
        (excess.actualToken0, excess.actualToken1) = LiquidityAmounts.getAmountsForLiquidity(
            sqrtPriceX96,
            sqrtPriceLower,
            sqrtPriceUpper,
            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 = 0;
        uint256 rangesLength = data.token0Allocations.length;

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

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

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

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

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

    /**
     * @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 (uint i = 0; i < rangesLength; i++) {
            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) {
                    liquidities[i] = uint128(
                        FullMath.mulDiv(
                            data.token1Allocations[i],
                            FixedPoint96.Q96,
                            sqrtPriceUpper - sqrtPriceLower
                        )
                    );
                } 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);
                    liquidities[i] = uint128(
                        FullMath.mulDiv(
                            data.token0Allocations[i],
                            intermediate,
                            sqrtPriceUpper - sqrtPriceLower
                        )
                    );
                } else {
                    liquidities[i] = 0;
                }
            } else {
                // Current range - use Python's exact logic
                // First assume token1 is limiting
                uint128 liquidityFrom1 = 0;
                if (sqrtPriceX96 > sqrtPriceLower && data.token1Allocations[i] > 0) {
                    liquidityFrom1 = uint128(
                        FullMath.mulDiv(
                            data.token1Allocations[i],
                            FixedPoint96.Q96,
                            sqrtPriceX96 - sqrtPriceLower
                        )
                    );
                }

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

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

    function _validateCarpetLiquidity(
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory liquidities,
        int24 tickSpacing
    ) internal pure {
        int24 minUsable = TickMath.minUsableTick(tickSpacing);
        int24 maxUsable = TickMath.maxUsableTick(tickSpacing);

        if (baseRanges[0].lowerTick == minUsable && liquidities[0] == 0) {
            revert InsufficientLiquidityForCarpet();
        }

        uint256 lastIdx = baseRanges.length - 1;
        if (baseRanges[lastIdx].upperTick == maxUsable && liquidities[lastIdx] == 0) {
            revert InsufficientLiquidityForCarpet();
        }
    }

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

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

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

        // 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 Helper to emit rebalance event
     */
    function _emitRebalanceEvent(
        IMultiPositionManager.Range[] memory baseRanges,
        PoolKey memory poolKey
    ) internal {
        IMultiPositionManager.Position[] memory positions = new IMultiPositionManager.Position[](baseRanges.length);
        for (uint i = 0; i < baseRanges.length; i++) {
            positions[i] = IMultiPositionManager.Position({
                poolKey: poolKey,
                lowerTick: baseRanges[i].lowerTick,
                upperTick: baseRanges[i].upperTick
            });
        }
        emit Rebalance(positions);
        // Note: LogTotalAmounts will be emitted by the main contract
    }

    /**
     * @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) {
        // Perform zeroBurn if there are active positions
        _performZeroBurnIfNeeded(s, poolManager);

        // Decode parameters
        (
            IMultiPositionManager.Range[] memory baseRanges,
            uint128[] memory liquidities,
            int24 limitWidth,
            uint256[2][] memory inMin,
            uint256[2][] memory outMin
        ) = abi.decode(params, (IMultiPositionManager.Range[], uint128[], int24, uint256[2][], uint256[2][]));

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

        // Ensure inMin has correct length for slippage protection
        if (inMin.length != baseRanges.length) {
            revert InMinLengthMismatch(inMin.length, baseRanges.length);
        }

        // Mint new positions
        PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin);

        return "";
    }

    /**
     * @notice Perform zeroBurn if there are active positions
     */
    function _performZeroBurnIfNeeded(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager
    ) private {
        if (s.basePositionsLength > 0 ||
            s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick ||
            s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {

            // Get ranges for zeroBurn
            IMultiPositionManager.Range[] memory baseRangesArray = new IMultiPositionManager.Range[](s.basePositionsLength);
            for (uint8 i = 0; i < s.basePositionsLength; i++) {
                baseRangesArray[i] = s.basePositions[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,
        int24 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
        IMultiPositionManager.Range[] memory allRanges = new IMultiPositionManager.Range[](baseRanges.length + 2);
        s.basePositionsLength = baseRanges.length;
        for (uint8 i = 0; i < baseRanges.length; ) {
            s.basePositions[i] = baseRanges[i];
            allRanges[i] = baseRanges[i];
            unchecked {
                i = i + 1;
            }
        }

        // 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 Process rebalance after a single token withdrawal
     * @dev This function handles the rebalance logic when there are remaining tokens after withdrawal
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param remainingToken0 Amount of token0 remaining after withdrawal
     * @param remainingToken1 Amount of token1 remaining after withdrawal
     */
    function processRebalanceAfterWithdraw(
        SharedStructs.ManagerStorage storage s,
        IPoolManager poolManager,
        uint256 remainingToken0,
        uint256 remainingToken1
    ) external {
        // Check if we need to rebalance - need remaining tokens and a strategy
        if ((remainingToken0 == 0 && remainingToken1 == 0) || s.lastStrategyParams.strategy == address(0)) {
            return;
        }

        // Create rebalance params from stored strategy
        IMultiPositionManager.RebalanceParams memory rebalanceParams = IMultiPositionManager.RebalanceParams({
            strategy: s.lastStrategyParams.strategy,
            center: s.lastStrategyParams.centerTick,
            tLeft: s.lastStrategyParams.ticksLeft,
            tRight: s.lastStrategyParams.ticksRight,
            limitWidth: int24(uint24(s.lastStrategyParams.limitWidth)),
            weight0: uint256(s.lastStrategyParams.weight0),
            weight1: uint256(s.lastStrategyParams.weight1),
            useCarpet: s.lastStrategyParams.useCarpet
        });

        // Empty outMin for internal rebalance (no withdrawal happening)
        uint256[2][] memory outMin = new uint256[2][](0);

        // Rebalance using the remaining amounts
        (IMultiPositionManager.Range[] memory baseRanges, uint128[] memory liquidities, ) =
            _processRebalance(s, poolManager, rebalanceParams, outMin, new uint256[2][](0));

        // Set positions
        for (uint256 i = 0; i < baseRanges.length; i++) {
            s.basePositions[i] = baseRanges[i];
        }
        s.basePositionsLength = baseRanges.length;

        // Create empty inMin for internal deposit (no slippage protection needed for internal calls)
        uint256[2][] memory inMin = new uint256[2][](baseRanges.length);

        // Mint positions
        PositionLogic.mintLiquidities(poolManager, s, liquidities, inMin);

        // Emit rebalance event
        IMultiPositionManager.Position[] memory positions = new IMultiPositionManager.Position[](baseRanges.length);
        for (uint i = 0; i < baseRanges.length; i++) {
            positions[i] = IMultiPositionManager.Position({
                poolKey: s.poolKey,
                lowerTick: baseRanges[i].lowerTick,
                upperTick: baseRanges[i].upperTick
            });
        }
        emit Rebalance(positions);
    }

    /**
     * @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) {
        if (amount0 == 0 && amount1 == 0) {
            return (0.5e18, 0.5e18);
        }

        // 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 view 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 view returns (uint256 totalAmount0, uint256 totalAmount1) {
        uint256[] memory densities = _getDensities(params, lowerTicks, upperTicks);

        uint160 sqrtPrice = params.sqrtPriceX96;
        for (uint256 i = 0; i < lowerTicks.length; i++) {
            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;
        }
    }

    function calculateWeightsFromStrategy(
        ILiquidityStrategy strategy,
        int24 center,
        uint24 tLeft,
        uint24 tRight,
        int24 tickSpacing,
        bool useCarpet,
        uint160 sqrtPriceX96,
        int24 currentTick
    ) internal view 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 Rebalance with token swap through aggregator
     * @param s Storage struct
     * @param poolManager Pool manager contract
     * @param params Rebalance parameters
     * @param aggregator Aggregator contract address
     * @param swapData Encoded swap calldata
     * @param minAmountOut Minimum amount expected from swap
     * @param outMin Minimum output amounts for withdrawals
     * @param inMin Minimum input amounts for new positions (slippage protection)
     * @param totalSupply Current total supply of shares
     * @return baseRanges The base ranges to rebalance to
     * @return liquidities The liquidity amounts for each range
     * @return limitWidth The limit width for limit positions
     */
    /**
     * @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,
        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
        );

        emit SwapExecuted(swapParams.aggregatorAddress, 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 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,
        int24 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,
        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 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(
        SwapParams calldata params,
        uint256 amount0,
        uint256 amount1,
        address currency0,
        address currency1
    ) private returns (uint256 amountOut) {
        // Validate aggregator type (prevents arbitrary contract calls)
        if (uint8(params.aggregator) > 3) 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(params.aggregatorAddress, 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,) = params.aggregatorAddress.call{ value: ethValue }(params.swapData);

        // Reset approval for security (skip if native ETH)
        if (!isETHIn) {
            IERC20(inputToken).forceApprove(params.aggregatorAddress, 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,
        int24 limitWidth
    ) {
        (uint160 sqrtPriceX96, int24 currentTick, , ) = poolManager.getSlot0(s.poolKey.toId());
        StrategyContext memory ctx = _buildStrategyContext(s, params, amount0, amount1, sqrtPriceX96, currentTick);

        (baseRanges, liquidities) = generateRangesAndLiquidities(
            s,
            poolManager,
            ctx,
            amount0,
            amount1
        );

        _updateStrategyParams(s, ctx);

        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 (StrategyContext memory ctx) {
        ctx.weightsAreProportional = (params.weight0 == 0 && params.weight1 == 0);
        if (ctx.weightsAreProportional) {
            (ctx.weight0, ctx.weight1) = calculateWeightsFromAmounts(amount0, amount1, sqrtPriceX96);
        } else {
            ctx.weight0 = params.weight0;
            ctx.weight1 = params.weight1;
        }

        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 {
            ctx.center = params.center;
        }

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

        if (ctx.resolvedStrategy == address(0)) revert NoStrategySpecified();
        ctx.strategy = ILiquidityStrategy(ctx.resolvedStrategy);
    }

    /**
     * @notice Generate ranges and calculate liquidities
     */
    /**
     * @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
        );
    }

    /**
     * @notice Generate ranges and calculate liquidities (pure version for SimpleLens)
     * @dev Accepts poolKey as parameter instead of reading from storage
     */
    function generateRangesAndLiquiditiesWithPoolKey(
        PoolKey memory poolKey,
        IPoolManager poolManager,
        StrategyContext memory ctx,
        uint256 amount0,
        uint256 amount1
    ) public view returns (
        IMultiPositionManager.Range[] memory baseRanges,
        uint128[] memory liquidities
    ) {
        // Generate tick ranges
        (int24[] memory lowerTicks, int24[] memory upperTicks) = ctx.strategy.generateRanges(
            ctx.center,
            ctx.tLeft,
            ctx.tRight,
            poolKey.tickSpacing,
            ctx.useCarpet
        );

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

        // Calculate weights using pure version
        uint256[] memory weights = calculateWeightsWithPoolKey(poolKey, poolManager, ctx, lowerTicks, upperTicks);

        // Initialize liquidities array
        liquidities = new uint128[](baseRanges.length);

        // Get current sqrt price
        (uint160 sqrtPriceX96Current, , , ) = poolManager.getSlot0(poolKey.toId());

        // Calculate liquidities using global limiting factor approach
        _calculateLiquiditiesFromWeights(
            liquidities,
            weights,
            baseRanges,
            amount0,
            amount1,
            sqrtPriceX96Current,
            ctx.weightsAreProportional
        );
    }

}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the 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);
}

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

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

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

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

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

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

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

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

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

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

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

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

File 12 of 70 : IImmutableState.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;

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

/// @title Interface for ImmutableState
interface IImmutableState {
    /// @notice The Uniswap v4 PoolManager contract
    function poolManager() external view returns (IPoolManager);
}

File 13 of 70 : 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.0.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.20;

import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Permit deadline has expired.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev Mismatched signature.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @inheritdoc IERC20Permit
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
        return super.nonces(owner);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 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 Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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.
     */
    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.
     */
    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 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).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            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 silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return 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 {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

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

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

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

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

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

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

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

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

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

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

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

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

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

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

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

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

            // Invert denominator mod 2^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 for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // 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 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

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

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

    /**
     * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// 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.
     */
    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 {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.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: 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: GPL-3.0-or-later
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 {
    /// @notice Thrown when calling unlockCallback where the caller is not PoolManager
    error NotPoolManager();

    constructor(IPoolManager _poolManager) ImmutableState(_poolManager) {}

    /// @notice Only allow calls from the PoolManager contract
    modifier onlyPoolManager() {
        if (msg.sender != address(poolManager)) revert NotPoolManager();
        _;
    }

    /// @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: MIT
pragma solidity ^0.8.20;

import {Currency} from "../../src/types/Currency.sol";
import {IERC20Minimal} from "../../src/interfaces/external/IERC20Minimal.sol";
import {IPoolManager} from "../../src/interfaces/IPoolManager.sol";

/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// To settle a positive delta (a credit to the user), a user may take or mint.
/// To settle a negative delta (a debt on the user), a user make transfer or burn to pay off a debt.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
    /// @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 {
        // for native currencies or burns, calling sync is not required
        // short circuit for ERC-6909 burns to support ERC-6909-wrapped native tokens
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20Minimal(Currency.unwrap(currency)).transferFrom(payer, address(manager), amount);
            } else {
                IERC20Minimal(Currency.unwrap(currency)).transfer(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);
    }
}

// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.26;

import { IPoolManager } from "v4-core/interfaces/IPoolManager.sol";
import { PoolKey } from "v4-core/types/PoolKey.sol";
import { BalanceDelta } from "v4-core/types/BalanceDelta.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 "v4-periphery/lib/v4-core/test/utils/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 { 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 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
  );
  event LiquidityMinted(
    IMultiPositionManager.Position position,
    uint128 liquidity
  );
  event LiquidityBurnt(
    IMultiPositionManager.Position position,
    uint256 liquidity
  );
  
  error PSC();
  error InvalidPositionData(
    IMultiPositionManager.Position position
  );
  error PoolNotInitialized(
    PoolKey poolKey
  );
  error DuplicatedPosition(
    IMultiPositionManager.Position position
  );
  error ZeroLiquidityAmount(
    IMultiPositionManager.Position position
  );

  function mintLiquidities(
    IPoolManager poolManager,
    PoolKey memory poolKey,
    IMultiPositionManager.Range[] memory baseRanges,
    IMultiPositionManager.Range[2] memory limitRanges,
    uint128[] memory liquidities,
    uint256[2][] memory inMin
  ) external {
    for (uint8 i = 0; i < baseRanges.length; ) {
      (
        uint256 currencyDelta0,
        uint256 currencyDelta1
      ) = _getCurrencyDeltas(
        poolManager,
        poolKey.currency0,
        poolKey.currency1
      );
      (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(
        poolManager,
        poolKey,
        baseRanges[i],
        liquidities[i]
      );
      if (amount0 > currencyDelta0) {
        amount0 = currencyDelta0;
      }
      if (amount1 > currencyDelta1) {
        amount1 = currencyDelta1;
      }

      _mintLiquidityForAmounts(
        poolManager,
        poolKey,
        baseRanges[i],
        amount0,
        amount1,
        inMin[i]
      );

      unchecked {
        i = i + 1;
      }
    }

    // mint limit positions if they are defined (checked inside the function)
    _mintLimitPositions(
      poolManager,
      poolKey,
      limitRanges
    );
  }

  // 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
  ) internal {
    if (limitRanges[0].lowerTick != limitRanges[0].upperTick) {
      uint256 currencyDelta1 = _getCurrencyDelta(
        poolManager,
        poolKey.currency1
      );
      
      if (currencyDelta1 > 0) {
        _mintLiquidityForAmounts(
          poolManager,
          poolKey,
          limitRanges[0],
          0,
          currencyDelta1,
          [uint256(0), uint256(0)]
        );
      }
    }

    if (limitRanges[1].lowerTick != limitRanges[1].upperTick) {
      uint256 currencyDelta0 = _getCurrencyDelta(
        poolManager,
        poolKey.currency0
      );

      if (currencyDelta0 > 0) {
        _mintLiquidityForAmounts(
          poolManager,
          poolKey,
          limitRanges[1],
          currencyDelta0,
          0,
          [uint256(0), uint256(0)]
        );
      }
    }
  }

  function _mintLiquidityForAmounts(
    IPoolManager poolManager,
    PoolKey memory poolKey,
    IMultiPositionManager.Range memory range,
    uint256 amount0,
    uint256 amount1,
    uint256[2] memory inMin
  ) internal {
    (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
    );

    if (liquidity > 0) {
      (BalanceDelta callerDelta, ) = poolManager.modifyLiquidity(
        poolKey,
        IPoolManager.ModifyLiquidityParams({
          tickLower: range.lowerTick,
          tickUpper: range.upperTick,
          liquidityDelta: liquidity.toInt128(),
          salt: POSITION_ID
        }),
        HOOK_DATA
      );

      /// callerDelta.amount0() and callerDelta.amount0() are all negative
      if (
        int256(callerDelta.amount0()).abs() < inMin[0] ||
        int256(callerDelta.amount1()).abs() < inMin[1]
      ) {
        revert PSC();
      }
      emit LiquidityMinted(
        IMultiPositionManager.Position(poolKey, range.lowerTick, range.upperTick),
        liquidity
      );
    }
  }

  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 amountOut0;
    uint256 amountOut1;
    uint256 baseRangesLength = baseRanges.length;

    // Burn base positions
    for (uint8 i = 0; i < baseRangesLength; ) {
      (amountOut0, amountOut1) = burnLiquidityForShare(
        poolManager,
        poolKey,
        baseRanges[i],
        shares,
        totalSupply,
        outMin[i]
      );

      amount0 = amount0 + amountOut0;
      amount1 = amount1 + amountOut1;

      unchecked {
        i = i + 1;
      }
    }

    // Burn limit positions with their specific outMin
    (amountOut0, amountOut1) = _burnLimitPositions(
      poolManager,
      poolKey,
      limitRanges,
      shares,
      totalSupply,
      outMin,
      baseRangesLength
    );
    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);

    for (uint8 i = 0; i < 2; ) {
      // Skip empty limit positions
      if (limitRanges[i].lowerTick != limitRanges[i].upperTick) {
        uint256 outMinIndex = baseRangesLength + i;
        // 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
        );

        amount0 = amount0 + amountOut0;
        amount1 = amount1 + amountOut1;
      }

      unchecked {
        i = i + 1;
      }
    }
  }

  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, ) = poolManager.modifyLiquidity(
        poolKey,
        IPoolManager.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`)
      amountOut0 = callerDelta.amount0().toUint128();
      amountOut1 = callerDelta.amount1().toUint128();
      
      if (
        amountOut0 < outMin[0] ||
        amountOut1 < outMin[1]
      ) {
        revert PSC();
      }
      
      emit LiquidityBurnt(
        IMultiPositionManager.Position(poolKey, range.lowerTick, range.upperTick),
        liquidityForShares
      );
    }
  }

  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 fee0;
    uint256 fee1;
    for (uint8 i = 0; i < baseRanges.length; ) {
      (fee0, fee1) = _zeroBurnWithoutUnlock(
        poolManager,
        poolKey,
        baseRanges[i]
      );
      totalFee0 = totalFee0 + fee0;
      totalFee1 = totalFee1 + fee1;
      
      unchecked {
        i++;
      }
    }

    (fee0, fee1) = _zeroBurnWithoutUnlock(
      poolManager,
      poolKey,
      limitRanges[0]
    );
    totalFee0 = totalFee0 + fee0;
    totalFee1 = totalFee1 + fee1;
    (fee0, fee1) = _zeroBurnWithoutUnlock(
      poolManager,
      poolKey,
      limitRanges[1]
    );
    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 _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,
          IPoolManager.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 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);
    }
    (liquidity, , ) = poolManager.getPositionInfo(
      poolKey.toId(),
      address(this),
      range.lowerTick,
      range.upperTick,
      POSITION_ID
    );

    (uint160 sqrtPriceX96, , , ) = poolManager.getSlot0(poolKey.toId());

    (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 (uint i = 0; i < totalPositionsLength; ++i) {
      (uint256 amount0, uint256 amount1) = getAmountsForLiquidity(
        poolManager,
        poolKey,
        ranges[i],
        uint128(positionData[i].liquidity)
      );

      unchecked {
        outMin[i] = [
          amount0 * slippageMultiplier / 10000,
          amount1 * slippageMultiplier / 10000
        ];
      }
    }

    return outMin;
  }
}

// SPDX-License-Identifier: MIT
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
 */
abstract contract Multicall is IMulticall {
    error DeadlineExpired();
    error MulticallFailed(uint256 index, bytes reason);
    
    /**
     * @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) {
        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) {
                // 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;
        }
    }
    
    /**
     * @notice Execute multiple calls with a deadline
     * @param deadline Timestamp after which the transaction reverts
     * @param data Array of encoded function calls
     * @return results Array of return data from each call
     */
    function multicallWithDeadline(
        uint256 deadline,
        bytes[] calldata data
    ) external payable override returns (bytes[] memory results) {
        if (block.timestamp > deadline) revert DeadlineExpired();
        return multicall(data);
    }
    
    /**
     * @notice Helper to get current block timestamp
     * @return Current block timestamp
     */
    function getCurrentTimestamp() external view returns (uint256) {
        return block.timestamp;
    }
}

File 29 of 70 : SharedStructs.sol
// SPDX-License-Identifier: UNLICENSED
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) rebalancers;

        // 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
        // Total: 31 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: UNLICENSED
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) {
                    amount0 = amount0 + unusedAmount0;
                    s.currency0.transfer(to, unusedAmount0);
                }
                if (unusedAmount1 > 0) {
                    amount1 = 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);

                amount0 = amount0 + unusedAmount0;
                amount1 = 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 then transfer
            zeroBurnAllWithoutUnlock(s, poolManager);
            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);
        bytes memory result = 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 = 0;
        uint256 sharesForToken1 = 0;

        if (amount0Desired > 0 && total0 > 0) {
            // Ceiling division
            sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
        }

        if (amount1Desired > 0 && total1 > 0) {
            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 = withdrawalValue0InToken1 + amount1Desired;

        // Calculate pool value in token1 terms
        uint256 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 = withdrawalValue0InToken1 + amount1Desired;

        // Calculate pool value in token1 terms
        uint256 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 = 0;
        uint256 sharesForToken1 = 0;

        if (amount0Desired > 0 && total0 > 0) {
            // Ceiling division
            sharesForToken0 = (amount0Desired * totalSupply + total0 - 1) / total0;
        }

        if (amount1Desired > 0 && total1 > 0) {
            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 = totalFee0 / s.fee;
                uint256 treasuryFee1 = totalFee1 / s.fee;
                uint256 ownerFee0 = totalFee0 - treasuryFee0;
                uint256 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]
            );
            total0 = total0 + amount0;
            total1 = total1 + amount1;
            totalFee0 = totalFee0 + feesOwed0;
            totalFee1 = totalFee1 + feesOwed1;

            unchecked {
                i++;
            }
        }

        // Get amounts from limit positions
        for (uint8 i = 0; i < s.limitPositionsLength; ) {
            (
                ,
                uint256 amount0,
                uint256 amount1,
                uint256 feesOwed0,
                uint256 feesOwed1
            ) = PoolManagerUtils.getAmountsOf(
                poolManager,
                s.poolKey,
                s.limitPositions[i]
            );
            total0 = total0 + amount0;
            total1 = total1 + amount1;
            totalFee0 = totalFee0 + feesOwed0;
            totalFee1 = totalFee1 + feesOwed1;

            unchecked {
                i++;
            }
        }

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

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

        // Add unused balances
        total0 = total0 + s.currency0.balanceOfSelf();
        total1 = 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][]));

        // Burn all positions
        (uint256 amount0, uint256 amount1) = PositionLogic.burnLiquidities(
            poolManager,
            s,
            totalSupply,
            totalSupply,
            outMin
        );

        // 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) {
        // Get position arrays directly from PositionLogic
        IMultiPositionManager.Range[] memory baseRangesArray = PositionLogic.getBasePositionsArray(s);
        IMultiPositionManager.Range[2] memory limitRangesArray = PositionLogic.getLimitPositionsArray(s);

        // Collect fees from all positions
        (totalFee0, totalFee1) = PoolManagerUtils.zeroBurnAll(
            poolManager,
            s.poolKey,
            baseRangesArray,
            limitRangesArray,
            s.currency0,
            s.currency1,
            s.fee
        );
    }

}

// SPDX-License-Identifier: UNLICENSED
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 "../libraries/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();
    error SwapFailed();
    error InsufficientSwapOutput();

    // Events
    event Deposit(
        address indexed from,
        address indexed to,
        uint256 shares,
        uint256 deposit0,
        uint256 deposit1
    );

    /**
     * @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, shares, deposit0, deposit1);

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

    /**
     * @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
        });
        // Get current token amounts in each position
        uint256 totalToken0InPositions;
        uint256 totalToken1InPositions;
        uint256[] memory positionToken0 = new uint256[](params.basePositionsLength + 2);
        uint256[] memory positionToken1 = new uint256[](params.basePositionsLength + 2);

        // Get token amounts for base positions
        for (uint8 i = 0; i < params.basePositionsLength; i++) {
            IMultiPositionManager.Range memory range = s.basePositions[i];
            (, uint256 amount0InPos, uint256 amount1InPos, , ) = PoolManagerUtils.getAmountsOf(
                params.poolManager,
                params.poolKey,
                range
            );
            positionToken0[i] = amount0InPos;
            positionToken1[i] = amount1InPos;
            totalToken0InPositions += amount0InPos;
            totalToken1InPositions += amount1InPos;
        }

        // Get token amounts for limit positions if they exist
        for (uint8 i = 0; i < 2; i++) {
            uint256 idx = params.basePositionsLength + i;
            IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
            if (limitRange.lowerTick != limitRange.upperTick) {
                (, uint256 amount0InPos, uint256 amount1InPos, , ) = PoolManagerUtils.getAmountsOf(
                    params.poolManager,
                    params.poolKey,
                    limitRange
                );
                positionToken0[idx] = amount0InPos;
                positionToken1[idx] = amount1InPos;
                totalToken0InPositions += amount0InPos;
                totalToken1InPositions += amount1InPos;
            }
        }

        // If no tokens in positions, fall back to liquidity-based distribution
        if (totalToken0InPositions == 0 && totalToken1InPositions == 0) {
            // Get total liquidity for fallback
            uint256 totalLiquidity;
            for (uint8 i = 0; i < params.basePositionsLength; i++) {
                IMultiPositionManager.Range memory range = s.basePositions[i];
                (uint128 liquidity, , , , ) = PoolManagerUtils.getAmountsOf(
                    params.poolManager,
                    params.poolKey,
                    range
                );
                totalLiquidity += liquidity;
            }

            // Check limit positions
            for (uint8 i = 0; i < 2; i++) {
                IMultiPositionManager.Range memory limitRange = s.limitPositions[i];
                if (limitRange.lowerTick != limitRange.upperTick) {
                    (uint128 liquidity, , , , ) = PoolManagerUtils.getAmountsOf(
                        params.poolManager,
                        params.poolKey,
                        limitRange
                    );
                    totalLiquidity += liquidity;
                }
            }

            if (totalLiquidity == 0) {
                // No positions to add to
                amounts0 = new uint256[](params.basePositionsLength + 2);
                amounts1 = new uint256[](params.basePositionsLength + 2);
                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.basePositionsLength + 2);
            amounts1 = new uint256[](params.basePositionsLength + 2);
            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
        (uint256 amount0ToDistribute, uint256 amount1ToDistribute) = DepositRatioLib.getRatioAmounts(
            totalToken0InPositions,
            totalToken1InPositions,
            params.amount0,
            params.amount1
        );

        // Now distribute these amounts proportionally based on current holdings
        amounts0 = new uint256[](params.basePositionsLength + 2);
        amounts1 = new uint256[](params.basePositionsLength + 2);

        // Distribute token0 to positions that hold token0
        if (totalToken0InPositions > 0 && amount0ToDistribute > 0) {
            for (uint256 i = 0; i < params.basePositionsLength + 2; i++) {
                if (positionToken0[i] > 0) {
                    amounts0[i] = FullMath.mulDiv(
                        amount0ToDistribute,
                        positionToken0[i],
                        totalToken0InPositions
                    );
                }
            }
        }

        // Distribute token1 to positions that hold token1
        if (totalToken1InPositions > 0 && amount1ToDistribute > 0) {
            for (uint256 i = 0; i < params.basePositionsLength + 2; i++) {
                if (positionToken1[i] > 0) {
                    amounts1[i] = FullMath.mulDiv(
                        amount1ToDistribute,
                        positionToken1[i],
                        totalToken1InPositions
                    );
                }
            }
        }
    }

    /**
     * @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
        for (uint8 i = 0; i < s.basePositionsLength; i++) {
            if (amounts0[i] > 0 || amounts1[i] > 0) {
                PoolManagerUtils._mintLiquidityForAmounts(
                    poolManager,
                    s.poolKey,
                    s.basePositions[i],
                    amounts0[i],
                    amounts1[i],
                    inMin[i]
                );
            }
        }

        // Add liquidity to limit positions if they exist
        for (uint8 i = 0; i < s.limitPositionsLength; i++) {
            uint256 idx = s.basePositionsLength + i;
            if (s.limitPositions[i].lowerTick != s.limitPositions[i].upperTick &&
                (amounts0[idx] > 0 || amounts1[idx] > 0)) {
                PoolManagerUtils._mintLiquidityForAmounts(
                    poolManager,
                    s.poolKey,
                    s.limitPositions[i],
                    amounts0[idx],
                    amounts1[idx],
                    inMin[idx]
                );
            }
        }
    }

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

}

// SPDX-License-Identifier: UNLICENSED
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,
        int24 limitWidth,
        IMultiPositionManager.Range[] memory baseRanges,
        int24 tickSpacing,
        int24 currentTick
    ) external {
        if (limitWidth == 0) {
            delete s.limitPositions;
            s.limitPositionsLength = 0;
            return;
        }

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

        // Check against NEW base ranges (not historical ones)
        for (uint256 i = 0; i < baseRanges.length; i++) {
            int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
            if (rangeWidth == limitWidth) {
                limitWidth = limitWidth + tickSpacing;
                break;
            }
        }

        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 - limitWidth, baseTick, tickSpacing);
        (
            s.limitPositions[1].lowerTick,
            s.limitPositions[1].upperTick
        ) = roundUp(baseTick + tickSpacing, baseTick + tickSpacing + limitWidth, tickSpacing);

        // Update limitPositionsLength based on non-empty positions
        s.limitPositionsLength = 0;
        if (s.limitPositions[0].lowerTick != s.limitPositions[0].upperTick) {
            s.limitPositionsLength++;
        }
        if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
            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(
        int24 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 (limitWidth % tickSpacing != 0) {
            // increase `limitWidth` to round up multiple of tickSpacing
            limitWidth = (limitWidth / tickSpacing + 1) * tickSpacing;
        }

        // Check against NEW base ranges (not historical ones)
        for (uint256 i = 0; i < baseRanges.length; i++) {
            int24 rangeWidth = baseRanges[i].upperTick - baseRanges[i].lowerTick;
            if (rangeWidth == limitWidth) {
                limitWidth = limitWidth + tickSpacing;
                break;
            }
        }

        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 - limitWidth, baseTick, tickSpacing);
        (
            upperLimit.lowerTick,
            upperLimit.upperTick
        ) = roundUp(baseTick + tickSpacing, baseTick + tickSpacing + 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 {
        for (uint256 i = 0; i < allRanges.length; i++) {
            for (uint256 j = i + 1; j < allRanges.length; j++) {
                // Skip empty ranges
                if (allRanges[j].lowerTick == allRanges[j].upperTick) continue;

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

    /**
     * @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) {
        ranges = new IMultiPositionManager.Range[](s.basePositionsLength);
        for (uint8 i = 0; i < s.basePositionsLength; i++) {
            ranges[i] = s.basePositions[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
    ) external {
        IMultiPositionManager.Range[] memory baseRangesArray = getBasePositionsArray(s);
        IMultiPositionManager.Range[2] memory limitRangesArray = getLimitPositionsArray(s);

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

    /**
     * @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 = i + 1;
            }
        }
    }

    /**
     * @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) {
            nonEmptyLimitPositions++;
        }
        if (s.limitPositions[1].lowerTick != s.limitPositions[1].upperTick) {
            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 = i + 1;
            }
        }

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

                limitIndex++;
            }

            unchecked {
                i = i + 1;
            }
        }
    }

    /**
     * @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) {
        for (uint8 i = 0; i < s.basePositionsLength; ) {
            if (s.basePositions[i].lowerTick != s.basePositions[i].upperTick) {
                (, uint256 amt0, uint256 amt1, , ) = PoolManagerUtils.getAmountsOf(
                    poolManager,
                    s.poolKey,
                    s.basePositions[i]
                );
                base0 += amt0;
                base1 += amt1;
            }
            unchecked {
                i = i + 1;
            }
        }
    }

    /**
     * @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]
                );
                limit0 += amt0;
                limit1 += amt1;
            }
            unchecked {
                i = i + 1;
            }
        }
    }

    /**
     * @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 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 = base0 + limit0;
        uint256 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: MIT
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 price = uint256(sqrtPriceX96) << 32;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 41 of 70 : 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: MIT
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 carpet positions
     * @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 carpet positions at extreme ticks for TWAP support
     * @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 view 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 view returns (string memory strategyType);
    
    /**
     * @notice Get a description of the strategy
     * @return description Human-readable description of the distribution pattern
     */
    function getDescription() external view 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 carpet options
     * @dev Comprehensive function that supports both token weights and carpet liquidity
     * @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 to add carpet liquidity at extremes (0.01% each)
     * @param tickSpacing The tick spacing of the pool
     * @param weightsAreProportional 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 weightsAreProportional
    ) external view returns (uint256[] memory weights);
}

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
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}.
     *
     * All two of these 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}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * 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:
     * ```
     * 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.0.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

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

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

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

/// @title 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: 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
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 58 of 70 : ImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
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;

    constructor(IPoolManager _poolManager) {
        poolManager = _poolManager;
    }
}

File 59 of 70 : FixedPoint128.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.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);
    
    /**
     * @notice Execute multiple calls with a deadline
     * @param deadline Timestamp after which the transaction reverts
     * @param data Array of encoded function calls
     * @return results Array of return data from each call
     */
    function multicallWithDeadline(
        uint256 deadline,
        bytes[] calldata data
    ) external payable returns (bytes[] memory results);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.26;

import { IMultiPositionManager } from "../interfaces/IMultiPositionManager.sol";
import { IPoolManager } from "v4-core/interfaces/IPoolManager.sol";
import { PoolManagerUtils } from "../PoolManagerUtils.sol";
import { FullMath } from "v4-core/libraries/FullMath.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

/**
 * @title DepositRatioLib
 * @notice Internal library for calculating deposit ratios and proportional distributions
 */
library DepositRatioLib {
    /**
     * @notice Calculate amounts that match the vault's current ratio for directDeposit
     * @param total0 Current total amount of token0 in vault
     * @param total1 Current total amount of token1 in vault
     * @param amount0Desired Amount of token0 user wants to deposit
     * @param amount1Desired Amount of token1 user wants to deposit
     * @return amount0ForPositions Amount of token0 that fits the ratio
     * @return amount1ForPositions Amount of token1 that fits the ratio
     */
    function getRatioAmounts(
        uint256 total0,
        uint256 total1,
        uint256 amount0Desired,
        uint256 amount1Desired
    ) internal pure returns (
        uint256 amount0ForPositions,
        uint256 amount1ForPositions
    ) {
        if (total0 == 0 && total1 == 0) {
            // No existing positions, can use full amounts
            return (amount0Desired, amount1Desired);
        }
        
        if (total0 == 0) {
            // Only token1 in positions
            return (0, amount1Desired);
        }
        
        if (total1 == 0) {
            // Only token0 in positions  
            return (amount0Desired, 0);
        }
        
        // Calculate amounts that fit the current ratio using cross-product
        uint256 cross = Math.min(amount0Desired * total1, amount1Desired * total0);
        
        if (cross == 0) {
            return (0, 0);
        }
        
        // Calculate the amounts that maintain the ratio
        amount0ForPositions = (cross - 1) / total1 + 1;
        amount1ForPositions = (cross - 1) / total0 + 1;
        
        // Ensure we don't try to use more than deposited
        amount0ForPositions = Math.min(amount0ForPositions, amount0Desired);
        amount1ForPositions = Math.min(amount1ForPositions, amount1Desired);
        
        return (amount0ForPositions, amount1ForPositions);
    }

    /**
     * @notice Calculate how to distribute amounts across positions proportionally based on liquidity
     * @param positionLiquidities Array of liquidities for each position
     * @param totalLiquidity Total liquidity across all positions
     * @param amount0 Total amount of token0 to distribute
     * @param amount1 Total amount of token1 to distribute
     * @return amounts0 Array of token0 amounts for each position
     * @return amounts1 Array of token1 amounts for each position
     */
    function getProportionalAmounts(
        uint128[] memory positionLiquidities,
        uint256 totalLiquidity,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (
        uint256[] memory amounts0,
        uint256[] memory amounts1
    ) {
        uint256 length = positionLiquidities.length;
        amounts0 = new uint256[](length);
        amounts1 = new uint256[](length);
        
        if (totalLiquidity == 0) {
            return (amounts0, amounts1);
        }
        
        // Distribute amounts proportionally
        for (uint256 i = 0; i < length; i++) {
            if (positionLiquidities[i] > 0) {
                amounts0[i] = FullMath.mulDiv(
                    amount0,
                    positionLiquidities[i],
                    totalLiquidity
                );
                amounts1[i] = FullMath.mulDiv(
                    amount1,
                    positionLiquidities[i],
                    totalLiquidity
                );
            }
        }
        
        return (amounts0, amounts1);
    }
}

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

/// @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
// OpenZeppelin Contracts (last updated v5.0.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 ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 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 ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-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 ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 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.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

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

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

File 67 of 70 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

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

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

Settings
{
  "remappings": [
    "@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "ds-test/=lib/v4-periphery/lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-periphery/lib/v4-core/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/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/"
  ],
  "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/MultiPositionFactory.sol": {
      "PoolManagerUtils": "0x1143c3b269071b0e3733d369daeba6a1992136a3",
      "DepositLogic": "0x11723b5c668a615eedd8a555e16507cd589ac4a0",
      "PositionLogic": "0x300413dc4d8de395e5b3d9aa7fbb533d74f2b848",
      "RebalanceLogic": "0xa1addf0299fa54137d09a68b67d40c3d70e4148d",
      "WithdrawLogic": "0x49d866ace6f38e2b0b91ab0589536a16c92d5c31"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract IPoolManager","name":"_poolManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"InitializationFailed","type":"error"},{"inputs":[],"name":"InsufficientMsgValue","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidFee","type":"error"},{"inputs":[],"name":"ManagerAlreadyExists","type":"error"},{"inputs":[{"internalType":"string","name":"name","type":"string"}],"name":"NameAlreadyUsed","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":"UnauthorizedAccess","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"multiPositionManager","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"indexed":false,"internalType":"struct PoolKey","name":"poolKey","type":"tuple"}],"name":"MultiPositionManagerDeployed","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":"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":"CLAIM_MANAGER","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"}],"name":"computeAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"int24","name":"limitWidth","type":"int24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"}],"name":"deployDepositAndRebalance","outputs":[{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"uint256","name":"deposit0Desired","type":"uint256"},{"internalType":"uint256","name":"deposit1Desired","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"components":[{"internalType":"enum RebalanceLogic.Aggregator","name":"aggregator","type":"uint8"},{"internalType":"address","name":"aggregatorAddress","type":"address"},{"internalType":"bytes","name":"swapData","type":"bytes"},{"internalType":"bool","name":"swapToken0","type":"bool"},{"internalType":"uint256","name":"swapAmount","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"internalType":"struct RebalanceLogic.SwapParams","name":"swapParams","type":"tuple"},{"internalType":"uint256[2][]","name":"inMin","type":"uint256[2][]"},{"components":[{"internalType":"address","name":"strategy","type":"address"},{"internalType":"int24","name":"center","type":"int24"},{"internalType":"uint24","name":"tLeft","type":"uint24"},{"internalType":"uint24","name":"tRight","type":"uint24"},{"internalType":"int24","name":"limitWidth","type":"int24"},{"internalType":"uint256","name":"weight0","type":"uint256"},{"internalType":"uint256","name":"weight1","type":"uint256"},{"internalType":"bool","name":"useCarpet","type":"bool"}],"internalType":"struct IMultiPositionManager.RebalanceParams","name":"rebalanceParams","type":"tuple"}],"name":"deployDepositAndRebalanceSwap","outputs":[{"internalType":"address","name":"mpm","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"address","name":"managerOwner","type":"address"},{"internalType":"string","name":"name","type":"string"}],"name":"deployMultiPositionManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"deployer","outputs":[{"internalType":"contract MultiPositionDeployer","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getAllManagersPaginated","outputs":[{"components":[{"internalType":"address","name":"managerAddress","type":"address"},{"internalType":"address","name":"managerOwner","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"string","name":"name","type":"string"}],"internalType":"struct IMultiPositionFactory.ManagerInfo[]","name":"managersInfo","type":"tuple[]"},{"internalType":"uint256","name":"totalCount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"managerOwner","type":"address"}],"name":"getManagersByOwner","outputs":[{"components":[{"internalType":"address","name":"managerAddress","type":"address"},{"internalType":"address","name":"managerOwner","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"string","name":"name","type":"string"}],"internalType":"struct IMultiPositionFactory.ManagerInfo[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalManagersCount","outputs":[{"internalType":"uint256","name":"","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":[{"internalType":"address","name":"","type":"address"}],"name":"managers","outputs":[{"internalType":"address","name":"managerAddress","type":"address"},{"internalType":"address","name":"managerOwner","type":"address"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"poolKey","type":"tuple"},{"internalType":"string","name":"name","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"managersByOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"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":"address","name":"_feeRecipient","type":"address"}],"name":"setFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_fee","type":"uint16"}],"name":"setProtocolFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"","type":"string"}],"name":"usedNames","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

60c06040526006805461ffff60a01b1916600560a11b179055348015610023575f80fd5b506040516188d23803806188d28339810160408190526100429161019a565b816001600160a01b03811661007057604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61007981610127565b506001600160a01b0382166100a15760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0381166100c85760405163e6c4247b60e01b815260040160405180910390fd5b600680546001600160a01b0319166001600160a01b038481169190911790915581166080526040516100f990610176565b604051809103905ff080158015610112573d5f803e3d5ffd5b506001600160a01b031660a052506101d29050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b61600a806128c883390190565b6001600160a01b0381168114610197575f80fd5b50565b5f80604083850312156101ab575f80fd5b82516101b681610183565b60208401519092506101c781610183565b809150509250929050565b60805160a0516126b961020f5f395f81816104120152818161065001526107f501525f81816104450152818161067f015261082a01526126b95ff3fe608060405260043610610183575f3560e01c806391d14854116100d1578063dc4c90d31161007c578063e8ae2b6911610057578063e8ae2b69146104a5578063f2fde38b146104c4578063fdff9b4d146104e3575f80fd5b8063dc4c90d314610434578063e4467f3514610467578063e74b981b14610486575f80fd5b8063c836bfb9116100ac578063c836bfb9146103ce578063d547741f146103e2578063d5f3948814610401575f80fd5b806391d1485414610331578063b0e21e8a14610360578063b85b99c914610394575f80fd5b8063715018a6116101315780638be6bbb21161010c5780638be6bbb2146102a85780638c3bf9b9146102d45780638da5cb5b14610315575f80fd5b8063715018a614610254578063730df06714610268578063871fa6f814610295575f80fd5b80634690484011610161578063469048401461020357806347686a82146102225780634b86230c14610241575f80fd5b806327d2bbd7146101875780632f2ff15d146101c35780632f6b4b0e146101e4575b5f80fd5b348015610192575f80fd5b506101a66101a1366004611845565b610512565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101ce575f80fd5b506101e26101dd36600461186f565b610546565b005b3480156101ef575f80fd5b506101a66101fe366004611a7d565b6105fb565b34801561020e575f80fd5b506006546101a6906001600160a01b031681565b34801561022d575f80fd5b506101a661023c366004611a7d565b610721565b6101a661024f366004611c44565b610abe565b34801561025f575f80fd5b506101e2610c97565b348015610273575f80fd5b50610287610282366004611d06565b610caa565b6040516101ba929190611e41565b6101a66102a3366004611e78565b610fb4565b3480156102b3575f80fd5b506102c76102c2366004611f60565b6111df565b6040516101ba9190611f7b565b3480156102df575f80fd5b506103077f24d766ec0f1bfbd75ff2bcd2034fbf5cbb00e3d6a7a59d2b365558f2842a463081565b6040519081526020016101ba565b348015610320575f80fd5b505f546001600160a01b03166101a6565b34801561033c575f80fd5b5061035061034b36600461186f565b611491565b60405190151581526020016101ba565b34801561036b575f80fd5b5060065461038190600160a01b900461ffff1681565b60405161ffff90911681526020016101ba565b34801561039f575f80fd5b506103506103ae366004611f8d565b805160208183018101805160058252928201919093012091525460ff1681565b3480156103d9575f80fd5b50600454610307565b3480156103ed575f80fd5b506101e26103fc36600461186f565b6114bd565b34801561040c575f80fd5b506101a67f000000000000000000000000000000000000000000000000000000000000000081565b34801561043f575f80fd5b506101a67f000000000000000000000000000000000000000000000000000000000000000081565b348015610472575f80fd5b506101e2610481366004611fc7565b611546565b348015610491575f80fd5b506101e26104a0366004611f60565b6115ae565b3480156104b0575f80fd5b506103506104bf36600461186f565b6115ff565b3480156104cf575f80fd5b506101e26104de366004611f60565b611643565b3480156104ee575f80fd5b506105026104fd366004611f60565b611680565b6040516101ba9493929190611fe8565b6003602052815f5260405f20818154811061052b575f80fd5b5f918252602090912001546001600160a01b03169150829050565b61054e611788565b6001600160a01b0381166105755760405163e6c4247b60e01b815260040160405180910390fd5b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff166105f7575f8281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45b5050565b5f8060405180604001604052806008815260200167047414d4d412d4c560c41b81525090505f85858560405160200161063693929190612075565b6040516020818303038152906040528051906020012090507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663eaf1ecd87f00000000000000000000000000000000000000000000000000000000000000008888308988600660149054906101000a900461ffff16896040518963ffffffff1660e01b81526004016106d89897969594939291906120fa565b602060405180830381865afa1580156106f3573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061071791906121c8565b9695505050505050565b5f6001600160a01b0383166107495760405163e6c4247b60e01b815260040160405180910390fd5b60058260405161075991906121e3565b9081526040519081900360200190205460ff16156107955781604051632875deb960e11b815260040161078c91906121f9565b60405180910390fd5b5f8484846040516020016107ab93929190612075565b60408051808303601f19018152828252805160209182012083830183526008845267047414d4d412d4c560c41b918401919091526006549151631edb071b60e31b81529093505f917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169163f6d838d89161086b917f0000000000000000000000000000000000000000000000000000000000000000918c918c9130918d918b91600160a01b90910461ffff16908d906004016120fa565b6020604051808303815f875af1158015610887573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ab91906121c8565b905060016005866040516108bf91906121e3565b9081526040805160209281900383018120805460ff191694151594909417909355608080840182526001600160a01b038581168086528b82168587019081528685018e815260608089018e81525f9485526002808a52948890208a5181546001600160a01b0319908116918916919091178255945160018201805487169189169190911790559251805195840180548616968816969096179095559784015160038301805498860151928601519187167fffffffffffffffffff000000000000000000000000000000000000000000000090991698909817600160a01b62ffffff93841602177fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b9290911691909102179095559201516004840180549093169116179055905160058201906109fa9082612289565b5050506001600160a01b038087165f81815260036020908152604080832080546001818101835591855292842090920180549587166001600160a01b031996871681179091556004805493840181559093527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b9091018054909416821790935591519091907f35f19687cb41dc3bc33596333ef672f611fa71e0114deb2ed84abe96b74a4d2f90610aac908b90612344565b60405180910390a39695505050505050565b5f6001600160a01b038816610ae65760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b038416610b0d5760405163e6c4247b60e01b815260040160405180910390fd5b6040516323b4354160e11b815230906347686a8290610b34908c908c908c90600401612075565b6020604051808303815f875af1158015610b50573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b7491906121c8565b6040516384715b1160e01b815260048101889052602481018790526001600160a01b038681166044830152336064830152919250908216906384715b1190349060840160606040518083038185885af1158015610bd3573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190610bf891906123a0565b5050604080515f808252602082019092526001600160a01b038416925063c0147edc91859190610c3e565b610c2b611803565b815260200190600190039081610c235790505b50866040518463ffffffff1660e01b8152600401610c5e939291906124a8565b5f604051808303815f87803b158015610c75575f80fd5b505af1158015610c87573d5f803e3d5ffd5b5050505098975050505050505050565b610c9f611788565b610ca85f6117b4565b565b6004546060905f839003610cbc578092505b808410610d4157604080515f8082526020820190925290610d39565b610d2660408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b815260200190600190039081610cd85790505b509150610fad565b5f81610d4d85876124f1565b11610d585783610d62565b610d628583612504565b90508067ffffffffffffffff811115610d7d57610d7d61189d565b604051908082528060200260200182016040528015610dfc57816020015b610de960408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b815260200190600190039081610d9b5790505b5092505f5b81811015610faa575f6004610e1683896124f1565b81548110610e2657610e26612517565b5f9182526020808320909101546001600160a01b0390811680845260028084526040948590208551608080820188528254861682526001830154861682880152875160a081018952838501548716815260038401548088169882019890985262ffffff600160a01b890416818a0152600160b81b90970490930b606080880191909152600483015490951692860192909252948101939093526005840180549195509293929184019190610ed99061220b565b80601f0160208091040260200160405190810160405280929190818152602001828054610f059061220b565b8015610f505780601f10610f2757610100808354040283529160200191610f50565b820191905f5260205f20905b815481529060010190602001808311610f3357829003601f168201915b505050505081525050858381518110610f6b57610f6b612517565b602002602001018190525080858381518110610f8957610f89612517565b60209081029190910101516001600160a01b03909116905250600101610e01565b50505b9250929050565b5f6001600160a01b038916610fdc5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0385166110035760405163e6c4247b60e01b815260040160405180910390fd5b5f6110146040860160208701611f60565b6001600160a01b03160361103b5760405163e6c4247b60e01b815260040160405180910390fd5b6040516323b4354160e11b815230906347686a8290611062908d908d908d90600401612075565b6020604051808303815f875af115801561107e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a291906121c8565b6040516384715b1160e01b815260048101899052602481018890526001600160a01b038781166044830152336064830152919250908216906384715b1190349060840160606040518083038185885af1158015611101573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061112691906123a0565b505050806001600160a01b03166307f46d3f6040518060400160405280858152602001876111539061252b565b9052604080515f8082526020820190925290611185565b611172611803565b81526020019060019003908161116a5790505b50866040518463ffffffff1660e01b81526004016111a5939291906125bb565b5f604051808303815f87803b1580156111bc575f80fd5b505af11580156111ce573d5f803e3d5ffd5b505050509998505050505050505050565b6001600160a01b0381165f90815260036020908152604080832080548251818502810185019093528083526060949383018282801561124557602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611227575b505050505090505f815167ffffffffffffffff8111156112675761126761189d565b6040519080825280602002602001820160405280156112e657816020015b6112d360408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b8152602001906001900390816112855790505b5090505f5b8251811015611489575f83828151811061130757611307612517565b6020908102919091018101516001600160a01b038082165f90815260028085526040918290208251608080820185528254861682526001830154861682890152845160a081018652838501548716815260038401548088169982019990995262ffffff600160a01b8a041681870152600160b81b90980490930b606080890191909152600483015490951692870192909252918101949094526005810180549395509092918401916113b89061220b565b80601f01602080910402602001604051908101604052809291908181526020018280546113e49061220b565b801561142f5780601f106114065761010080835404028352916020019161142f565b820191905f5260205f20905b81548152906001019060200180831161141257829003601f168201915b50505050508152505083838151811061144a5761144a612517565b60200260200101819052508083838151811061146857611468612517565b60209081029190910101516001600160a01b039091169052506001016112eb565b509392505050565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff165b92915050565b6114c5611788565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff16156105f7575f8281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b61154e611788565b8061ffff165f03611572576040516358d620b360e01b815260040160405180910390fd5b6006805461ffff909216600160a01b027fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff909216919091179055565b6115b6611788565b6001600160a01b0381166115dd5760405163e6c4247b60e01b815260040160405180910390fd5b600680546001600160a01b0319166001600160a01b0392909216919091179055565b5f80546001600160a01b038381169116148061163c57505f8381526001602090815260408083206001600160a01b038616845290915290205460ff165b9392505050565b61164b611788565b6001600160a01b03811661167457604051631e4fbdf760e01b81525f600482015260240161078c565b61167d816117b4565b50565b600260208181525f92835260409283902080546001820154855160a081018752838601546001600160a01b039081168252600385015480821696830196909652600160a01b860462ffffff1697820197909752600160b81b90940490940b60608401526004820154851660808401526005820180549186169590941693906117079061220b565b80601f01602080910402602001604051908101604052809291908181526020018280546117339061220b565b801561177e5780601f106117555761010080835404028352916020019161177e565b820191905f5260205f20905b81548152906001019060200180831161176157829003601f168201915b5050505050905084565b5f546001600160a01b03163314610ca85760405163118cdaa760e01b815233600482015260240161078c565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60405180604001604052806002906020820280368337509192915050565b6001600160a01b038116811461167d575f80fd5b803561184081611821565b919050565b5f8060408385031215611856575f80fd5b823561186181611821565b946020939093013593505050565b5f8060408385031215611880575f80fd5b82359150602083013561189281611821565b809150509250929050565b634e487b7160e01b5f52604160045260245ffd5b6040805190810167ffffffffffffffff811182821017156118d4576118d461189d565b60405290565b604051610100810167ffffffffffffffff811182821017156118d4576118d461189d565b60405160c0810167ffffffffffffffff811182821017156118d4576118d461189d565b604051601f8201601f1916810167ffffffffffffffff8111828210171561194a5761194a61189d565b604052919050565b803562ffffff81168114611840575f80fd5b8035600281900b8114611840575f80fd5b5f60a08284031215611985575f80fd5b60405160a0810167ffffffffffffffff811182821017156119a8576119a861189d565b60405290508082356119b981611821565b815260208301356119c981611821565b60208201526119da60408401611952565b60408201526119eb60608401611964565b606082015260808301356119fe81611821565b6080919091015292915050565b5f82601f830112611a1a575f80fd5b8135602083015f8067ffffffffffffffff841115611a3a57611a3a61189d565b50601f8301601f1916602001611a4f81611921565b915050828152858383011115611a63575f80fd5b828260208301375f92810160200192909252509392505050565b5f805f60e08486031215611a8f575f80fd5b611a998585611975565b925060a0840135611aa981611821565b915060c084013567ffffffffffffffff811115611ac4575f80fd5b611ad086828701611a0b565b9150509250925092565b5f82601f830112611ae9575f80fd5b813567ffffffffffffffff811115611b0357611b0361189d565b611b1260208260051b01611921565b8082825260208201915060208360061b860101925085831115611b33575f80fd5b602085015b83811015611b945786601f820112611b4e575f80fd5b611b566118b1565b806040830189811115611b67575f80fd5b835b81811015611b81578035845260209384019301611b69565b5050845250602090920191604001611b38565b5095945050505050565b80358015158114611840575f80fd5b5f6101008284031215611bbe575f80fd5b611bc66118da565b90508135611bd381611821565b8152611be160208301611964565b6020820152611bf260408301611952565b6040820152611c0360608301611952565b6060820152611c1460808301611964565b608082015260a0828101359082015260c08083013590820152611c3960e08301611b9e565b60e082015292915050565b5f805f805f805f80610260898b031215611c5c575f80fd5b611c668a8a611975565b975060a0890135611c7681611821565b965060c089013567ffffffffffffffff811115611c91575f80fd5b611c9d8b828c01611a0b565b96505060e089013594506101008901359350610120890135611cbe81611821565b925061014089013567ffffffffffffffff811115611cda575f80fd5b611ce68b828c01611ada565b925050611cf78a6101608b01611bad565b90509295985092959890939650565b5f8060408385031215611d17575f80fd5b50508035926020909101359150565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f82825180855260208501945060208160051b830101602085015f5b83811015611e3557601f1985840301885281516001600160a01b0381511684526001600160a01b0360208201511660208501526040810151611e0360408601826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b506060015161010060e08501819052611e1e90850182611d26565b6020998a0199909450929092019150600101611d70565b50909695505050505050565b604081525f611e536040830185611d54565b90508260208301529392505050565b5f60c08284031215611e72575f80fd5b50919050565b5f805f805f805f805f6102808a8c031215611e91575f80fd5b611e9b8b8b611975565b9850611ea960a08b01611835565b975060c08a013567ffffffffffffffff811115611ec4575f80fd5b611ed08c828d01611a0b565b97505060e08a013595506101008a01359450611eef6101208b01611835565b93506101408a013567ffffffffffffffff811115611f0b575f80fd5b611f178c828d01611e62565b9350506101608a013567ffffffffffffffff811115611f34575f80fd5b611f408c828d01611ada565b925050611f518b6101808c01611bad565b90509295985092959850929598565b5f60208284031215611f70575f80fd5b813561163c81611821565b602081525f61163c6020830184611d54565b5f60208284031215611f9d575f80fd5b813567ffffffffffffffff811115611fb3575f80fd5b611fbf84828501611a0b565b949350505050565b5f60208284031215611fd7575f80fd5b813561ffff8116811461163c575f80fd5b6001600160a01b03851681526001600160a01b038416602082015261205e60408201846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b61010060e08201525f610717610100830184611d26565b6120cd81856001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b6001600160a01b03831660a082015260e060c08201525f6120f160e0830184611d26565b95945050505050565b6001600160a01b038916815261216160208201896001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b6001600160a01b03871660c08201526001600160a01b03861660e08201526101806101008201525f612197610180830187611d26565b8281036101208401526121aa8187611d26565b61ffff95909516610140840152505061016001529695505050505050565b5f602082840312156121d8575f80fd5b815161163c81611821565b5f82518060208501845e5f920191825250919050565b602081525f61163c6020830184611d26565b600181811c9082168061221f57607f821691505b602082108103611e7257634e487b7160e01b5f52602260045260245ffd5b601f82111561228457805f5260205f20601f840160051c810160208510156122625750805b601f840160051c820191505b81811015612281575f815560010161226e565b50505b505050565b815167ffffffffffffffff8111156122a3576122a361189d565b6122b7816122b1845461220b565b8461223d565b6020601f8211600181146122e9575f83156122d25750848201515b5f19600385901b1c1916600184901b178455612281565b5f84815260208120601f198516915b8281101561231857878501518255602094850194600190920191016122f8565b508482101561233557868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b60a081016114b782846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b5f805f606084860312156123b2575f80fd5b5050815160208301516040909301519094929350919050565b6001600160a01b038151168252602081015160020b602083015262ffffff6040820151166040830152606081015161240a606084018262ffffff169052565b50608081015161241f608084018260020b9052565b5060a081015160a083015260c081015160c083015260e081015161228460e084018215159052565b5f8151808452602084019350602083015f5b8281101561249e578151865f5b6002811015612485578251825260209283019290910190600101612466565b5050506040959095019460209190910190600101612459565b5093949350505050565b6124b281856123cb565b6101406101008201525f6124ca610140830185612447565b8281036101208401526107178185612447565b634e487b7160e01b5f52601160045260245ffd5b808201808211156114b7576114b76124dd565b818103818111156114b7576114b76124dd565b634e487b7160e01b5f52603260045260245ffd5b5f60c0823603121561253b575f80fd5b6125436118fe565b823560048110612551575f80fd5b815261255f60208401611835565b6020820152604083013567ffffffffffffffff81111561257d575f80fd5b61258936828601611a0b565b60408301525061259b60608401611b9e565b60608201526080838101359082015260a092830135928101929092525090565b606081526125cd6060820185516123cb565b5f60208501516101206101608401528051600481106125fa57634e487b7160e01b5f52602160045260245ffd5b61018084015260208101516001600160a01b03166101a0840152604081015160c06101c085015261262f610240850182611d26565b905060608201516126456101e086018215159052565b50608082015161020085015260a0820151610220850152838103602085015261266e8187612447565b9150508281036040840152610717818561244756fea26469706673582212203fc0b258f905c20d1217deffe7285fea16b1f80ebcf572c47c741193027e3f0464736f6c634300081a00336080604052348015600e575f80fd5b50615fee8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610034575f3560e01c8063eaf1ecd814610038578063f6d838d814610067575b5f80fd5b61004b61004636600461029f565b61007a565b6040516001600160a01b03909116815260200160405180910390f35b61004b61007536600461029f565b610140565b5f806040518060200161008c90610192565b601f1982820381018352601f9091011660408190526100bb908c908c908c908c908c908c908c9060200161040a565b60408051601f19818403018152908290526100d992916020016104e2565b6040516020818303038152906040528051906020012090506040517fff0000000000000000000000000000000000000000000000000000000000000081523060601b6001820152836015820152816035820152605581209250505098975050505050505050565b5f818989898989898960405161015590610192565b610165979695949392919061040a565b8190604051809103905ff5905080158015610182573d5f803e3d5ffd5b5090505b98975050505050505050565b615aba806104ff83390190565b6001600160a01b03811681146101b3575f80fd5b50565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff811182821017156101ed576101ed6101b6565b60405290565b80356101fe8161019f565b919050565b5f82601f830112610212575f80fd5b813567ffffffffffffffff81111561022c5761022c6101b6565b604051601f8201601f19908116603f0116810167ffffffffffffffff8111828210171561025b5761025b6101b6565b604052818152838201602001851015610272575f80fd5b816020850160208301375f918101602001919091529392505050565b803561ffff811681146101fe575f80fd5b5f805f805f805f80888a036101808112156102b8575f80fd5b89356102c38161019f565b985060a0601f19820112156102d6575f80fd5b506102df6101ca565b60208a01356102ed8161019f565b815260408a01356102fd8161019f565b602082015260608a013562ffffff81168114610317575f80fd5b604082015260808a0135600281900b8114610330575f80fd5b606082015261034160a08b016101f3565b6080820152965061035460c08a016101f3565b955061036260e08a016101f3565b945061010089013567ffffffffffffffff81111561037e575f80fd5b61038a8b828c01610203565b94505061012089013567ffffffffffffffff8111156103a7575f80fd5b6103b38b828c01610203565b9350506103c36101408a0161028e565b979a969950949793969295919450919261016001359150565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b03881681526001600160a01b0387511660208201526001600160a01b03602088015116604082015262ffffff6040880151166060820152606087015160020b60808201526001600160a01b0360808801511660a082015261047d60c08201876001600160a01b03169052565b6001600160a01b03851660e08201526101606101008201525f6104a46101608301866103dc565b8281036101208401526104b781866103dc565b91505061018661014083018461ffff169052565b5f81518060208401855e5f93019283525090919050565b5f6104f66104f083866104cb565b846104cb565b94935050505056fe610180604052348015610010575f80fd5b50604051615aba380380615aba83398101604081905261002f916103f7565b8680868580604051806040016040528060018152602001603160f81b8152508888816003908161005f91906105ad565b50600461006c82826105ad565b5061007c9150839050600561023a565b6101205261008b81600661023a565b61014052815160208084019190912060e052815190820120610100524660a05261011760e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b60805250503060c0525060016008556001600160a01b03811661015457604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b61015d8161026c565b506001600160a01b03908116610160528751600a80549183166001600160a01b0319928316811790915560208a0151600b805460408d015160608e015162ffffff908116600160b81b0262ffffff60b81b1991909216600160a01b9081026001600160b81b031990941695891695861793909317161790915560808c0151600c805491871691861691909117905560a0909b20600d55600e80548416909217909155600f805490921617905560158054969091166001600160b01b03199096169590951761ffff9290921690960217909255506106bf9350505050565b5f6020835110156102555761024e836102bd565b9050610266565b8161026084826105ad565b5060ff90505b92915050565b600980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b5f80829050601f815111156102e7578260405163305a27a960e01b815260040161014b9190610667565b80516102f28261069c565b179392505050565b6001600160a01b038116811461030e575f80fd5b50565b634e487b7160e01b5f52604160045260245ffd5b60405160a081016001600160401b038111828210171561034757610347610311565b60405290565b8051610358816102fa565b919050565b5f82601f83011261036c575f80fd5b81516001600160401b0381111561038557610385610311565b604051601f8201601f19908116603f011681016001600160401b03811182821017156103b3576103b3610311565b6040528181528382016020018510156103ca575f80fd5b8160208501602083015e5f918101602001919091529392505050565b805161ffff81168114610358575f80fd5b5f805f805f805f87890361016081121561040f575f80fd5b885161041a816102fa565b975060a0601f198201121561042d575f80fd5b50610436610325565b6020890151610444816102fa565b81526040890151610454816102fa565b6020820152606089015162ffffff8116811461046e575f80fd5b60408201526080890151600281900b8114610487575f80fd5b606082015261049860a08a0161034d565b608082015295506104ab60c0890161034d565b94506104b960e0890161034d565b6101008901519094506001600160401b038111156104d5575f80fd5b6104e18a828b0161035d565b6101208a015190945090506001600160401b038111156104ff575f80fd5b61050b8a828b0161035d565b92505061051b61014089016103e6565b905092959891949750929550565b600181811c9082168061053d57607f821691505b60208210810361055b57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f8211156105a857805f5260205f20601f840160051c810160208510156105865750805b601f840160051c820191505b818110156105a5575f8155600101610592565b50505b505050565b81516001600160401b038111156105c6576105c6610311565b6105da816105d48454610529565b84610561565b6020601f82116001811461060c575f83156105f55750848201515b5f19600385901b1c1916600184901b1784556105a5565b5f84815260208120601f198516915b8281101561063b578785015182556020948501946001909201910161061b565b508482101561065857868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b8051602080830151919081101561055b575f1960209190910360031b1b16919050565b60805160a05160c05160e051610100516101205161014051610160516152e36107d75f395f8181610aa101528181610c0e01528181610d5601528181610e4401528181610ef601528181611091015281816111dc0152818161133d015281816113fd015281816114cb01528181611596015281816117af0152818161182c015281816119d401528181611b9001528181611d0601528181611d5301528181611dd301528181611efd01528181612d2301528181612ddf01528181612ecf01528181612f8f01528181613077015281816131610152818161320c01528181613258015261328f01525f61264e01525f61262101525f61245b01525f61243301525f61238e01525f6123b801525f6123e201526152e35ff3fe6080604052600436106102fb575f3560e01c80637c2c9c7a11610191578063ac9650d8116100dc578063d505accf11610087578063ddca3f4311610062578063ddca3f4314610b07578063e98d8c3a14610b34578063f2fde38b14610b53575f80fd5b8063d505accf14610a71578063dc4c90d314610a90578063dd62ed3e14610ac3575f80fd5b8063c45a0155116100b7578063c45a015514610a0d578063c4a7761e14610a2a578063c82813d714610a5e575f80fd5b8063ac9650d81461096e578063b13c86a314610981578063c0147edc146109ee575f80fd5b80638e0055531161013c57806399d32fc41161011757806399d32fc414610919578063a9059cbb1461092d578063aaf5eb681461094c575f80fd5b80638e005553146108c757806391dd7346146108e657806395d89b4114610905575f80fd5b806384715b111161016c57806384715b111461085c57806384b0196e1461086f5780638da5cb5b14610896575f80fd5b80637c2c9c7a146108075780637ecebe00146108295780638027586014610848575f80fd5b806323b872dd11610251578063689b5f4f116101fc5780636c9230db116101d75780636c9230db146107ad57806370a08231146107bf578063715018a6146107f3575f80fd5b8063689b5f4f14610728578063695ab14e146107545780636bcc5c4f14610773575f80fd5b80634141d61a1161022c5780634141d61a146106a7578063467c9eff146106bd5780635fc01fae146106f4575f80fd5b806323b872dd14610659578063313ce567146106785780633644e51514610693575f80fd5b8063095ea7b3116102b157806318160ddd1161028c57806318160ddd1461053d578063182148ef146105515780631b4a723b14610645575f80fd5b8063095ea7b3146103a6578063108d636a146103d557806315e2b6cd1461051e575f80fd5b8063065e5360116102e1578063065e53601461034957806306fdde031461037057806307f46d3f14610391575f80fd5b806303e78281146103065780630533e0f314610329575f80fd5b3661030257005b5f80fd5b348015610311575f80fd5b506011545b6040519081526020015b60405180910390f35b61033c610337366004613b80565b610b72565b6040516103209190613bf6565b348015610354575f80fd5b5061035d610ba9565b60405160029190910b8152602001610320565b34801561037b575f80fd5b50610384610c3d565b6040516103209190613c59565b6103a461039f366004613df6565b610ccd565b005b3480156103b1575f80fd5b506103c56103c0366004613e9d565b610fae565b6040519015158152602001610320565b3480156103e0575f80fd5b506104b760408051610100810182526017546001600160a01b038116808352600160a01b820460020b60208401819052600160b81b830462ffffff9081169585018690527a0100000000000000000000000000000000000000000000000000008404811660608601819052600160e81b90940416608085018190526018546effffffffffffffffffffffffffffff80821660a088018190526f01000000000000000000000000000000830490911660c08801819052600160f01b90920460ff16151560e09097018790529397929695919392909190565b604080516001600160a01b03909916895260029790970b602089015262ffffff958616968801969096529284166060870152921660808501526effffffffffffffffffffffffffffff91821660a08501521660c0830152151560e082015261010001610320565b348015610529575f80fd5b506103a4610538366004613ec7565b610fc7565b348015610548575f80fd5b50600254610316565b34801561055c575f80fd5b506105e16040805160a0810182525f80825260208201819052918101829052606081018290526080810191909152506040805160a081018252600a546001600160a01b039081168252600b54808216602084015262ffffff600160a01b82041693830193909352600160b81b90920460020b6060820152600c54909116608082015290565b60405161032091905f60a0820190506001600160a01b0383511682526001600160a01b03602084015116602083015262ffffff6040840151166040830152606083015160020b60608301526001600160a01b03608084015116608083015292915050565b348015610650575f80fd5b50601454610316565b348015610664575f80fd5b506103c5610673366004613ee2565b611038565b348015610683575f80fd5b5060405160128152602001610320565b34801561069e575f80fd5b5061031661105b565b3480156106b2575f80fd5b5061035d627fffff81565b3480156106c8575f80fd5b506103c56106d7366004613ec7565b6001600160a01b03165f9081526016602052604090205460ff1690565b3480156106ff575f80fd5b5061071361070e366004613f38565b611069565b60408051928352602083019190915201610320565b348015610733575f80fd5b50610747610742366004613fa0565b611147565b6040516103209190613fb7565b34801561075f575f80fd5b506103a461076e366004614019565b611196565b34801561077e575f80fd5b5061079261078d366004614058565b6112ae565b60408051938452602084019290925290820152606001610320565b3480156107b8575f80fd5b5042610316565b3480156107ca575f80fd5b506103166107d9366004613ec7565b6001600160a01b03165f9081526020819052604090205490565b3480156107fe575f80fd5b506103a46113cc565b348015610812575f80fd5b5061081b6113df565b60405161032092919061410f565b348015610834575f80fd5b50610316610843366004613ec7565b611490565b348015610853575f80fd5b5061081b6114ad565b61079261086a366004614189565b611519565b34801561087a575f80fd5b5061088361169c565b60405161032097969594939291906141c5565b3480156108a1575f80fd5b506009546001600160a01b03165b6040516001600160a01b039091168152602001610320565b3480156108d2575f80fd5b506103a46108e136600461425b565b6116de565b3480156108f1575f80fd5b5061038461090036600461427c565b6117a2565b348015610910575f80fd5b506103846117f7565b348015610924575f80fd5b506103a4611806565b348015610938575f80fd5b506103c5610947366004613e9d565b611a1d565b348015610957575f80fd5b506103166ec097ce7bc90715b34b9f100000000081565b61033c61097c3660046142ea565b611a2a565b34801561098c575f80fd5b50610995611b65565b604080519c8d5260208d019b909b52998b019890985260608a0196909652608089019490945260a088019290925260c087015260e086015261010085015261012084015261014083015261016082015261018001610320565b3480156109f9575f80fd5b506103a4610a0836600461431d565b611c86565b348015610a18575f80fd5b506015546001600160a01b03166108af565b348015610a35575f80fd5b50610a3e611d48565b604080519485526020850193909352918301526060820152608001610320565b6103a4610a6c366004614386565b611d85565b348015610a7c575f80fd5b506103a4610a8b3660046143e6565b611fd0565b348015610a9b575f80fd5b506108af7f000000000000000000000000000000000000000000000000000000000000000081565b348015610ace575f80fd5b50610316610add366004614457565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b348015610b12575f80fd5b50601554600160a01b900461ffff1660405161ffff9091168152602001610320565b348015610b3f575f80fd5b506103a4610b4e366004613ec7565b612106565b348015610b5e575f80fd5b506103a4610b6d366004613ec7565b61218a565b606083421115610b9557604051631ab7da6b60e01b815260040160405180910390fd5b610b9f8383611a2a565b90505b9392505050565b6040805160a08082018352600a546001600160a01b039081168352600b548082166020850152600160a01b810462ffffff1694840194909452600160b81b90930460020b6060830152600c549092166080820152205f90610c34906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906121c4565b50909392505050565b606060038054610c4c9061448e565b80601f0160208091040260200160405190810160405280929190818152602001828054610c789061448e565b8015610cc35780601f10610c9a57610100808354040283529160200191610cc3565b820191905f5260205f20905b815481529060010190602001808311610ca657829003601f168201915b5050505050905090565b6009546001600160a01b03163314801590610cf75750335f9081526016602052604090205460ff16155b8015610d0e57506015546001600160a01b03163314155b15610d2c57604051635c427cd960e01b815260040160405180910390fd5b5f610d3660025490565b118015610d4f5750601154151580610d4f575060145415155b15610e23577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c89491600484604051602001610d96919061451d565b60408051601f1981840301815290829052610db49291602001614563565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610ddf9190613c59565b5f604051808303815f875af1158015610dfa573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610e2191908101906145a9565b505b5f805f73a1addf0299fa54137d09a68b67d40c3d70e4148d63816f6d79600a7f0000000000000000000000000000000000000000000000000000000000000000896040518463ffffffff1660e01b8152600401610e82939291906147d9565b5f60405180830381865af4158015610e9c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610ec391908101906148fa565b9250925092505f8383838789604051602001610ee39594939291906149cd565b60405160208183030381529060405290507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c89491600183604051602001610f37929190614563565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401610f629190613c59565b5f604051808303815f875af1158015610f7d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610fa491908101906145a9565b5050505050505050565b5f33610fbb818585612276565b60019150505b92915050565b610fcf612283565b6001600160a01b0381165f9081526016602052604090205460ff1615611035576001600160a01b0381165f81815260166020526040808220805460ff19169055517fcaf92444a1394370243e8971ce81be80e609e85e617e7a8f3a5ec1bfb7f7efaf9190a25b50565b5f336110458582856122b0565b611050858585612325565b506001949350505050565b5f611064612382565b905090565b5f806110736124ab565b7349d866ace6f38e2b0b91ab0589536a16c92d5c3163ee3c71c5600a7f00000000000000000000000000000000000000000000000000000000000000008989896110bc60025490565b338b6040518963ffffffff1660e01b81526004016110e1989796959493929190614ac8565b6040805180830381865af41580156110fb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061111f9190614b31565b909250905082156111345761113433876124d5565b61113e6001600855565b94509492505050565b604080518082019091525f80825260208201526012826002811061116d5761116d614b53565b60408051808201909152910154600281810b83526301000000909104900b602082015292915050565b6009546001600160a01b031633148015906111bc57506015546001600160a01b03163314155b156111da57604051635c427cd960e01b815260040160405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894916005848460405160200161121e929190614b67565b60408051601f198184030181529082905261123c9291602001614563565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016112679190613c59565b5f604051808303815f875af1158015611282573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526112a991908101906145a9565b505050565b5f805f6112b96124ab565b5f6040518060e00160405280898152602001888152602001876001600160a01b031681526020018681526020016112ef60025490565b8152335f8181526020818152604091829020549084015291820152516337009bed60e11b81529091507349d866ace6f38e2b0b91ab0589536a16c92d5c3190636e0137da9061136790600a907f0000000000000000000000000000000000000000000000000000000000000000908690600401614b99565b606060405180830381865af4158015611382573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113a69190614c28565b919550935091506113b733836124d5565b506113c26001600855565b9450945094915050565b6113d4612283565b6113dd5f61250d565b565b604051630969c6db60e41b8152600a60048201526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166024820152606090819073300413dc4d8de395e5b3d9aa7fbb533d74f2b8489063969c6db0906044015b5f60405180830381865af4158015611461573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526114889190810190614c53565b915091509091565b6001600160a01b0381165f90815260076020526040812054610fc1565b604051631ce65fa960e01b8152600a60048201526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166024820152606090819073300413dc4d8de395e5b3d9aa7fbb533d74f2b84890631ce65fa990604401611447565b5f805f61152e6009546001600160a01b031690565b6001600160a01b0316336001600160a01b03161415801561155a57506015546001600160a01b03163314155b1561157857604051635c427cd960e01b815260040160405180910390fd5b7311723b5c668a615eedd8a555e16507cd589ac4a063a0d368af600a7f00000000000000000000000000000000000000000000000000000000000000008a8a8a8a6115c260025490565b60405160e089901b6001600160e01b031916815260048101979097526001600160a01b039586166024880152604487019490945260648601929092528316608485015290911660a483015260c48201523460e482015261010401606060405180830381865af4158015611637573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061165b9190614c28565b9194509250905061166c8584612576565b600e546116849085906001600160a01b0316846125aa565b600f546113c29085906001600160a01b0316836125aa565b5f6060805f805f60606116ad61261a565b6116b5612647565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b60155460408051638da5cb5b60e01b815290516001600160a01b0390921691638da5cb5b916004808201926020929091908290030181865afa158015611726573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061174a9190614d47565b6001600160a01b0316336001600160a01b031614611766575f80fd5b6015805461ffff909216600160a01b027fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff909216919091179055565b6060336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146117ed5760405163570c108560e11b815260040160405180910390fd5b610ba28383612674565b606060048054610c4c9061448e565b6009546001600160a01b031633036118e357604080513360208201526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016916348c8949191600391015b60408051601f19818403018152908290526118769291602001614563565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016118a19190613c59565b5f604051808303815f875af11580156118bc573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261103591908101906145a9565b60155460408051638c3bf9b960e01b815290516001600160a01b039092169163e8ae2b69918391638c3bf9b9916004808201926020929091908290030181865afa158015611933573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119579190614d62565b6040516001600160e01b031960e084901b1681526004810191909152336024820152604401602060405180830381865afa158015611997573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906119bb9190614d79565b15611a0457604080515f60208201526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016916348c894919160039101611858565b604051635c427cd960e01b815260040160405180910390fd5b5f33610fbb818585612325565b60608167ffffffffffffffff811115611a4557611a45613c6b565b604051908082528060200260200182016040528015611a7857816020015b6060815260200190600190039081611a635790505b5090505f5b82811015611b5e575f8030868685818110611a9a57611a9a614b53565b9050602002810190611aac9190614d94565b604051611aba929190614dd7565b5f60405180830381855af49150503d805f8114611af2576040519150601f19603f3d011682016040523d82523d5f602084013e611af7565b606091505b509150915081611b3657805115611b1057805181602001fd5b8281604051631b3dcf4560e21b8152600401611b2d929190614de6565b60405180910390fd5b80848481518110611b4957611b49614b53565b60209081029190910101525050600101611a7d565b5092915050565b5f805f805f805f805f805f805f73300413dc4d8de395e5b3d9aa7fbb533d74f2b848633b150fdf600a7f00000000000000000000000000000000000000000000000000000000000000006040518363ffffffff1660e01b8152600401611bde9291909182526001600160a01b0316602082015260400190565b61018060405180830381865af4158015611bfa573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c1e9190614dfe565b9050805f015181602001518260400151836060015184608001518560a001518660c001518760e001518861010001518961012001518a61014001518b61016001519c509c509c509c509c509c509c509c509c509c509c509c5050909192939495969798999a9b565b6009546001600160a01b03163314801590611cb05750335f9081526016602052604090205460ff16155b8015611cc757506015546001600160a01b03163314155b15611ce557604051635c427cd960e01b815260040160405180910390fd5b5f805f73a1addf0299fa54137d09a68b67d40c3d70e4148d6304219722600a7f00000000000000000000000000000000000000000000000000000000000000008989896040518663ffffffff1660e01b8152600401610e82959493929190614e98565b5f805f80611d77600a7f00000000000000000000000000000000000000000000000000000000000000006126a6565b935093509350935090919293565b6009546001600160a01b03163314801590611dab57506015546001600160a01b03163314155b15611dc957604051635c427cd960e01b815260040160405180910390fd5b60115415611e81577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894916002604051602001611e129190614ee2565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611e3d9190613c59565b5f604051808303815f875af1158015611e58573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611e7f91908101906145a9565b505b604051637238097160e01b815273a1addf0299fa54137d09a68b67d40c3d70e4148d90637238097190611ebb90600a908790600401614ef0565b6040805180830381865af4158015611ed5573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ef99190614b31565b50507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c8949160058484604051602001611f3f929190614b67565b60408051601f1981840301815290829052611f5d9291602001614563565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611f889190613c59565b5f604051808303815f875af1158015611fa3573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611fca91908101906145a9565b50505050565b83421115611ff45760405163313c898160e11b815260048101859052602401611b2d565b5f7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988888861203f8c6001600160a01b03165f90815260076020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090505f61209982612945565b90505f6120a882878787612971565b9050896001600160a01b0316816001600160a01b0316146120ef576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401611b2d565b6120fa8a8a8a612276565b50505050505050505050565b61210e612283565b6001600160a01b038116612120575f80fd5b6001600160a01b0381165f9081526016602052604090205460ff16611035576001600160a01b0381165f81815260166020526040808220805460ff19166001179055517f2fdbc602265e61159b9ca311b0f2a21b2f39999153264f4359d82b0c82ad21c49190a250565b612192612283565b6001600160a01b0381166121bb57604051631e4fbdf760e01b81525f6004820152602401611b2d565b6110358161250d565b5f805f805f6121d28661299f565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa15801561221a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061223e9190614d62565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b6112a983838360016129db565b6009546001600160a01b031633146113dd5760405163118cdaa760e01b8152336004820152602401611b2d565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f198114611fca578181101561231757604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611b2d565b611fca84848484035f6129db565b6001600160a01b03831661234e57604051634b637e8f60e11b81525f6004820152602401611b2d565b6001600160a01b0382166123775760405163ec442f0560e01b81525f6004820152602401611b2d565b6112a9838383612aad565b5f306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480156123da57507f000000000000000000000000000000000000000000000000000000000000000046145b1561240457507f000000000000000000000000000000000000000000000000000000000000000090565b611064604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b6002600854036124ce57604051633ee5aeb560e01b815260040160405180910390fd5b6002600855565b6001600160a01b0382166124fe57604051634b637e8f60e11b81525f6004820152602401611b2d565b612509825f83612aad565b5050565b600980546001600160a01b038381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b03821661259f5760405163ec442f0560e01b81525f6004820152602401611b2d565b6125095f8383612aad565b6001600160a01b0382166125ff57803410156125c4575f80fd5b803411156112a957336108fc6125da8334614f1c565b6040518115909202915f818181858888f19350505050158015611fca573d5f803e3d5ffd5b80156112a9576112a96001600160a01b038316843084612bd3565b60606110647f00000000000000000000000000000000000000000000000000000000000000006005612c42565b60606110647f00000000000000000000000000000000000000000000000000000000000000006006612c42565b60605f8061268484860186614f2f565b915091505f6126938383612ceb565b905061269d61324f565b95945050505050565b5f805f805f5b86600701548160ff16101561279b575f805f80731143c3b269071b0e3733d369daeba6a1992136a363aa3847598b8d5f018e6006015f8a60ff1681526020019081526020015f206040518463ffffffff1660e01b815260040161271193929190614fba565b60a060405180830381865af415801561272c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127509190615025565b94509450945094505083896127659190615068565b98506127718389615068565b975061277d8288615068565b96506127898187615068565b955050600190930192506126ac915050565b505f5b86600a01548160ff16101561288e575f808080731143c3b269071b0e3733d369daeba6a1992136a363aa3847598b8d6008810160ff8a16600281106127e5576127e5614b53565b016040518463ffffffff1660e01b815260040161280493929190614fba565b60a060405180830381865af415801561281f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128439190615025565b94509450945094505083896128589190615068565b98506128648389615068565b97506128708288615068565b965061287c8187615068565b9550506001909301925061279e915050565b50600b8601546128a990600160a01b900461ffff168361507b565b6128b39083614f1c565b600b8701549092506128d090600160a01b900461ffff168261507b565b6128da9082614f1c565b90506128e68285615068565b93506128f28184615068565b600487015490935061290c906001600160a01b03166132bd565b6129169085615068565b6005870154909450612930906001600160a01b03166132bd565b61293a9084615068565b925092959194509250565b5f610fc1612951612382565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f806129818888888861333e565b9250925092506129918282613402565b50909150505b949350505050565b6040515f906129be908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b6001600160a01b038416612a045760405163e602df0560e01b81525f6004820152602401611b2d565b6001600160a01b038316612a2d57604051634a1406b160e11b81525f6004820152602401611b2d565b6001600160a01b038085165f9081526001602090815260408083209387168352929052208290558015611fca57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051612a9f91815260200190565b60405180910390a350505050565b6001600160a01b038316612ad7578060025f828254612acc9190615068565b90915550612b479050565b6001600160a01b0383165f9081526020819052604090205481811015612b295760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401611b2d565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216612b6357600280548290039055612b81565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051612bc691815260200190565b60405180910390a3505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166323b872dd60e01b179052611fca9085906134ba565b606060ff8314612c5c57612c558361351b565b9050610fc1565b818054612c689061448e565b80601f0160208091040260200160405190810160405280929190818152602001828054612c949061448e565b8015612cdf5780601f10612cb657610100808354040283529160200191612cdf565b820191905f5260205f20905b815481529060010190602001808311612cc257829003601f168201915b50505050509050610fc1565b60605f836005811115612d0057612d0061452f565b03612e9857604051631b0b434d60e01b8152600a60048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001660248201527349d866ace6f38e2b0b91ab0589536a16c92d5c3190631b0b434d906044016040805180830381865af4158015612d81573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612da59190614b31565b50505f8083806020019051810190612dbd919061513c565b915091505f8073300413dc4d8de395e5b3d9aa7fbb533d74f2b848632c7b7fe07f0000000000000000000000000000000000000000000000000000000000000000600a87612e0a60025490565b886040518663ffffffff1660e01b8152600401612e2b959493929190615181565b6040805180830381865af4158015612e45573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e699190614b31565b60408051602081019390935282810191909152805180830382018152606090920190529450610fc19350505050565b6001836005811115612eac57612eac61452f565b03612f585773a1addf0299fa54137d09a68b67d40c3d70e4148d63081cd184600a7f000000000000000000000000000000000000000000000000000000000000000085612ef860025490565b6040518563ffffffff1660e01b8152600401612f1794939291906151bf565b5f60405180830381865af4158015612f31573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612c5591908101906145a9565b6002836005811115612f6c57612f6c61452f565b0361302957604051631b0b434d60e01b8152600a60048201526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001660248201527349d866ace6f38e2b0b91ab0589536a16c92d5c3190631b0b434d906044016040805180830381865af4158015612fed573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906130119190614b31565b505060405180602001604052805f8152509050610fc1565b600383600581111561303d5761303d61452f565b0361312a575f828060200190518101906130579190614d47565b90507349d866ace6f38e2b0b91ab0589536a16c92d5c31632e2d1b85600a7f0000000000000000000000000000000000000000000000000000000000000000846130a96009546001600160a01b031690565b6040516001600160e01b031960e087901b16815260048101949094526001600160a01b03928316602485015290821660448401521660648201526084015b5f6040518083038186803b1580156130fd575f80fd5b505af415801561310f573d5f803e3d5ffd5b5050505060405180602001604052805f815250915050610fc1565b600483600581111561313e5761313e61452f565b036131a9577349d866ace6f38e2b0b91ab0589536a16c92d5c3163245010a3600a7f000000000000000000000000000000000000000000000000000000000000000061318960025490565b866040518563ffffffff1660e01b8152600401612f1794939291906151f7565b60058360058111156131bd576131bd61452f565b03613236575f828060200190518101906131d79190615224565b60405163c896ac7560e01b81529091507311723b5c668a615eedd8a555e16507cd589ac4a09063c896ac75906130e790600a907f0000000000000000000000000000000000000000000000000000000000000000908690600401615256565b604051634a7f394f60e01b815260040160405180910390fd5b600f54613286907f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b0316613558565b600e546113dd907f0000000000000000000000000000000000000000000000000000000000000000906001600160a01b0316613558565b5f6001600160a01b0382166132d3575047919050565b6040516370a0823160e01b81523060048201526001600160a01b038316906370a0823190602401602060405180830381865afa158015613315573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fc19190614d62565b919050565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561337757505f915060039050826113c2565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa1580156133c8573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b0381166133f357505f9250600191508290506113c2565b975f9750879650945050505050565b5f8260038111156134155761341561452f565b0361341e575050565b60018260038111156134325761343261452f565b036134505760405163f645eedf60e01b815260040160405180910390fd5b60028260038111156134645761346461452f565b036134855760405163fce698f760e01b815260048101829052602401611b2d565b60038260038111156134995761349961452f565b03612509576040516335e2f38360e21b815260048101829052602401611b2d565b5f6134ce6001600160a01b038416836135ba565b905080515f141580156134f25750808060200190518101906134f09190614d79565b155b156112a957604051635274afe760e01b81526001600160a01b0384166004820152602401611b2d565b60605f613527836135c7565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f61356d6001600160a01b03841630846135ee565b9050805f0361357b57505050565b5f8112156135a4576112a983306135918461527d565b6001600160a01b0386169291905f61367c565b6112a96001600160a01b0383168430845f613948565b6060610ba283835f613a1a565b5f60ff8216601f811115610fc157604051632cd44ac360e21b815260040160405180910390fd5b5f806001600160a01b0384165f526001600160a01b03831660205260405f209050846001600160a01b031663f135baaa826040518263ffffffff1660e01b815260040161363d91815260200190565b602060405180830381865afa158015613658573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061269d9190614d62565b801561371157836001600160a01b031663f5298aca846136ab886001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018590526064015b5f604051808303815f87803b1580156136f6575f80fd5b505af1158015613708573d5f803e3d5ffd5b50505050613941565b6001600160a01b03851661378857836001600160a01b03166311da60b4836040518263ffffffff1660e01b815260040160206040518083038185885af115801561375d573d5f803e3d5ffd5b50505050506040513d601f19601f820116820180604052508101906137829190614d62565b50613941565b604051632961046560e21b81526001600160a01b03868116600483015285169063a5841194906024015f604051808303815f87803b1580156137c8575f80fd5b505af11580156137da573d5f803e3d5ffd5b505050506001600160a01b038316301461386c576040516323b872dd60e01b81526001600160a01b0384811660048301528581166024830152604482018490528616906323b872dd906064016020604051808303815f875af1158015613842573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138669190614d79565b506138de565b60405163a9059cbb60e01b81526001600160a01b0385811660048301526024820184905286169063a9059cbb906044016020604051808303815f875af11580156138b8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906138dc9190614d79565b505b836001600160a01b03166311da60b46040518163ffffffff1660e01b81526004016020604051808303815f875af115801561391b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061393f9190614d62565b505b5050505050565b8061398a57604051630b0d9c0960e01b81526001600160a01b038681166004830152848116602483015260448201849052851690630b0d9c09906064016136df565b836001600160a01b031663156e29f6846139b3886001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018590526064015f604051808303815f87803b1580156139fd575f80fd5b505af1158015613a0f573d5f803e3d5ffd5b505050505050505050565b606081471015613a3f5760405163cd78605960e01b8152306004820152602401611b2d565b5f80856001600160a01b03168486604051613a5a9190615297565b5f6040518083038185875af1925050503d805f8114613a94576040519150601f19603f3d011682016040523d82523d5f602084013e613a99565b606091505b5091509150613aa9868383613ab3565b9695505050505050565b606082613ac857613ac382613b0f565b610ba2565b8151158015613adf57506001600160a01b0384163b155b15613b0857604051639996b31560e01b81526001600160a01b0385166004820152602401611b2d565b5080610ba2565b805115613b1f5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f8083601f840112613b48575f80fd5b50813567ffffffffffffffff811115613b5f575f80fd5b6020830191508360208260051b8501011115613b79575f80fd5b9250929050565b5f805f60408486031215613b92575f80fd5b83359250602084013567ffffffffffffffff811115613baf575f80fd5b613bbb86828701613b38565b9497909650939450505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f602082016020835280845180835260408501915060408160051b8601019250602086015f5b82811015613c4d57603f19878603018452613c38858351613bc8565b94506020938401939190910190600101613c1c565b50929695505050505050565b602081525f610ba26020830184613bc8565b634e487b7160e01b5f52604160045260245ffd5b6040805190810167ffffffffffffffff81118282101715613ca257613ca2613c6b565b60405290565b6040516060810167ffffffffffffffff81118282101715613ca257613ca2613c6b565b604051610180810167ffffffffffffffff81118282101715613ca257613ca2613c6b565b604051601f8201601f1916810167ffffffffffffffff81118282101715613d1857613d18613c6b565b604052919050565b5f67ffffffffffffffff821115613d3957613d39613c6b565b5060051b60200190565b5f82601f830112613d52575f80fd5b8135613d65613d6082613d20565b613cef565b8082825260208201915060208360061b860101925085831115613d86575f80fd5b6020850160405b84821015613dea5787601f830112613da3575f80fd5b613dac81613cef565b808284018a811115613dbc575f80fd5b845b81811015613dd6578035845260209384019301613dbe565b505085525060209093019290810190613d8d565b50909695505050505050565b5f805f60608486031215613e08575f80fd5b833567ffffffffffffffff811115613e1e575f80fd5b84016101208187031215613e30575f80fd5b9250602084013567ffffffffffffffff811115613e4b575f80fd5b613e5786828701613d43565b925050604084013567ffffffffffffffff811115613e73575f80fd5b613e7f86828701613d43565b9150509250925092565b6001600160a01b0381168114611035575f80fd5b5f8060408385031215613eae575f80fd5b8235613eb981613e89565b946020939093013593505050565b5f60208284031215613ed7575f80fd5b8135610ba281613e89565b5f805f60608486031215613ef4575f80fd5b8335613eff81613e89565b92506020840135613f0f81613e89565b929592945050506040919091013590565b8015158114611035575f80fd5b803561333981613f20565b5f805f8060808587031215613f4b575f80fd5b843593506020850135613f5d81613e89565b9250604085013567ffffffffffffffff811115613f78575f80fd5b613f8487828801613d43565b9250506060850135613f9581613f20565b939692955090935050565b5f60208284031215613fb0575f80fd5b5035919050565b60408101610fc18284805160020b8252602081015160020b60208301525050565b5f8083601f840112613fe8575f80fd5b50813567ffffffffffffffff811115613fff575f80fd5b6020830191508360208260061b8501011115613b79575f80fd5b5f806020838503121561402a575f80fd5b823567ffffffffffffffff811115614040575f80fd5b61404c85828601613fd8565b90969095509350505050565b5f805f806080858703121561406b575f80fd5b8435935060208501359250604085013561408481613e89565b9150606085013567ffffffffffffffff81111561409f575f80fd5b6140ab87828801613d43565b91505092959194509250565b5f8151808452602084019350602083015f5b82811015614105576140ef868351805160020b8252602081015160020b60208301525050565b60409590950194602091909101906001016140c9565b5093949350505050565b604081525f61412160408301856140b7565b82810360208401528084518083526020830191506020860192505f5b81811015613dea5783516fffffffffffffffffffffffffffffffff815116845260208101516020850152604081015160408501525060608301925060208401935060018101905061413d565b5f805f806080858703121561419c575f80fd5b843593506020850135925060408501356141b581613e89565b91506060850135613f9581613e89565b60ff60f81b8816815260e060208201525f6141e360e0830189613bc8565b82810360408401526141f58189613bc8565b606084018890526001600160a01b038716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b8181101561424a57835183526020938401939092019160010161422c565b50909b9a5050505050505050505050565b5f6020828403121561426b575f80fd5b813561ffff81168114610ba2575f80fd5b5f806020838503121561428d575f80fd5b823567ffffffffffffffff8111156142a3575f80fd5b8301601f810185136142b3575f80fd5b803567ffffffffffffffff8111156142c9575f80fd5b8560208284010111156142da575f80fd5b6020919091019590945092505050565b5f80602083850312156142fb575f80fd5b823567ffffffffffffffff811115614311575f80fd5b61404c85828601613b38565b5f805f838503610140811215614331575f80fd5b61010081121561433f575f80fd5b5083925061010084013567ffffffffffffffff81111561435d575f80fd5b61436986828701613d43565b92505061012084013567ffffffffffffffff811115613e73575f80fd5b5f805f60408486031215614398575f80fd5b833567ffffffffffffffff8111156143ae575f80fd5b840160c081870312156143bf575f80fd5b9250602084013567ffffffffffffffff8111156143da575f80fd5b613bbb86828701613fd8565b5f805f805f805f60e0888a0312156143fc575f80fd5b873561440781613e89565b9650602088013561441781613e89565b95506040880135945060608801359350608088013560ff8116811461443a575f80fd5b9699959850939692959460a0840135945060c09093013592915050565b5f8060408385031215614468575f80fd5b823561447381613e89565b9150602083013561448381613e89565b809150509250929050565b600181811c908216806144a257607f821691505b6020821081036144c057634e487b7160e01b5f52602260045260245ffd5b50919050565b5f8151808452602084019350602083015f5b82811015614105578151865f5b60028110156145045782518252602092830192909101906001016144e5565b50505060409590950194602091909101906001016144d8565b602081525f610ba260208301846144c6565b634e487b7160e01b5f52602160045260245ffd5b6006811061455f57634e487b7160e01b5f52602160045260245ffd5b9052565b61456d8184614543565b604060208201525f610b9f6040830184613bc8565b5f67ffffffffffffffff82111561459b5761459b613c6b565b50601f01601f191660200190565b5f602082840312156145b9575f80fd5b815167ffffffffffffffff8111156145cf575f80fd5b8201601f810184136145df575f80fd5b80516145ed613d6082614582565b818152856020838501011115614601575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b8060020b8114611035575f80fd5b80356133398161461e565b803562ffffff81168114613339575f80fd5b803561465481613e89565b6001600160a01b03168252602081013561466d8161461e565b60020b602083015261468160408201614637565b62ffffff16604083015261469760608201614637565b62ffffff1660608301526146ad6080820161462c565b6146bc608084018260020b9052565b5060a0818101359083015260c080820135908301526146dd60e08201613f2d565b80151560e0840152505050565b5f808335601e198436030181126146ff575f80fd5b830160208101925035905067ffffffffffffffff81111561471e575f80fd5b803603821315613b79575f80fd5b81835281816020850137505f828201602090810191909152601f909101601f19169091010190565b5f813560048110158015614766575f80fd5b508352602082013561477781613e89565b6001600160a01b0316602084015261479260408301836146ea565b60c060408601526147a760c08601828461472c565b9150506147b660608401613f2d565b151560608501526080838101359085015260a09283013592909301919091525090565b8381526001600160a01b0383166020820152606060408201526147ff6060820183614649565b5f61010083013560be19843603018112614817575f80fd5b610120610160840152613aa96101808401858301614754565b80516133398161461e565b5f82601f83011261484a575f80fd5b8151614858613d6082613d20565b8082825260208201915060208360061b860101925085831115614879575f80fd5b602085015b838110156148d15760408188031215614895575f80fd5b61489d613c7f565b81516148a88161461e565b815260208201516148b88161461e565b602082810191909152908452929092019160400161487e565b5095945050505050565b80516fffffffffffffffffffffffffffffffff81168114613339575f80fd5b5f805f6060848603121561490c575f80fd5b835167ffffffffffffffff811115614922575f80fd5b61492e8682870161483b565b935050602084015167ffffffffffffffff81111561494a575f80fd5b8401601f8101861361495a575f80fd5b8051614968613d6082613d20565b8082825260208201915060208360051b850101925088831115614989575f80fd5b6020840193505b828410156149b2576149a1846148db565b825260209384019390910190614990565b94506149c49250505060408501614830565b90509250925092565b60a081525f6149df60a08301886140b7565b82810360208401528087518083526020830191506020890192505f5b81811015614a2b5783516fffffffffffffffffffffffffffffffff168352602093840193909201916001016149fb565b5050614a3c604085018860020b9052565b8381036060850152614a4e81876144c6565b9150508281036080840152614a6381856144c6565b98975050505050505050565b5f8151808452602084019350602083015f5b828110156141055781515f87815b6002811015614aae578351825260209384019390910190600101614a8f565b505050604096909601955060209190910190600101614a81565b8881526001600160a01b03881660208201528660408201526001600160a01b038616606082015261010060808201525f614b06610100830187614a6f565b60a0830195909552506001600160a01b039290921660c0830152151560e09091015295945050505050565b5f8060408385031215614b42575f80fd5b505080516020909101519092909150565b634e487b7160e01b5f52603260045260245ffd5b602080825281018290525f8360408301825b858110156148d15760408383376040928301929190910190600101614b79565b8381526001600160a01b03831660208201526060604082015281516060820152602082015160808201526001600160a01b0360408301511660a08201525f606083015160e060c0840152614bf1610140840182614a6f565b9050608084015160e084015260a08401516101008401526001600160a01b0360c08501511661012084015280915050949350505050565b5f805f60608486031215614c3a575f80fd5b5050815160208301516040909301519094929350919050565b5f8060408385031215614c64575f80fd5b825167ffffffffffffffff811115614c7a575f80fd5b614c868582860161483b565b925050602083015167ffffffffffffffff811115614ca2575f80fd5b8301601f81018513614cb2575f80fd5b8051614cc0613d6082613d20565b80828252602082019150602060608402850101925087831115614ce1575f80fd5b6020840193505b82841015614d395760608489031215614cff575f80fd5b614d07613ca8565b614d10856148db565b815260208581015181830152604080870151908301529083526060909401939190910190614ce8565b809450505050509250929050565b5f60208284031215614d57575f80fd5b8151610ba281613e89565b5f60208284031215614d72575f80fd5b5051919050565b5f60208284031215614d89575f80fd5b8151610ba281613f20565b5f808335601e19843603018112614da9575f80fd5b83018035915067ffffffffffffffff821115614dc3575f80fd5b602001915036819003821315613b79575f80fd5b818382375f9101908152919050565b828152604060208201525f610b9f6040830184613bc8565b5f610180828403128015614e10575f80fd5b50614e19613ccb565b825181526020808401519082015260408084015190820152606080840151908201526080808401519082015260a0808401519082015260c0808401519082015260e08084015190820152610100808401519082015261012080840151908201526101408084015190820152610160928301519281019290925250919050565b8581526001600160a01b0385166020820152614eb76040820185614649565b6101806101408201525f614ecf610180830185614a6f565b828103610160840152614a638185614a6f565b60208101610fc18284614543565b828152604060208201525f610b9f6040830184614754565b634e487b7160e01b5f52601160045260245ffd5b81810381811115610fc157610fc1614f08565b5f8060408385031215614f40575f80fd5b823560068110614f4e575f80fd5b9150602083013567ffffffffffffffff811115614f69575f80fd5b8301601f81018513614f79575f80fd5b8035614f87613d6082614582565b818152866020838501011115614f9b575f80fd5b816020840160208301375f602083830101528093505050509250929050565b6001600160a01b0384811682528354811660208301526001840154808216604084015260a081811c62ffffff16606085015260b89190911c600290810b60808501528086015490921690830152825480820b60c084015260181c900b60e08201526101008101612997565b5f805f805f60a08688031215615039575f80fd5b615042866148db565b602087015160408801516060890151608090990151929a91995097965090945092505050565b80820180821115610fc157610fc1614f08565b5f8261509557634e487b7160e01b5f52601260045260245ffd5b500490565b5f82601f8301126150a9575f80fd5b81516150b7613d6082613d20565b8082825260208201915060208360061b8601019250858311156150d8575f80fd5b6020850160405b84821015613dea5787601f8301126150f5575f80fd5b6150fe81613cef565b808284018a81111561510e575f80fd5b845b81811015615128578051845260209384019301615110565b5050855250602090930192908101906150df565b5f806040838503121561514d575f80fd5b8251602084015190925067ffffffffffffffff81111561516b575f80fd5b6151778582860161509a565b9150509250929050565b6001600160a01b038616815284602082015283604082015282606082015260a060808201525f6151b460a0830184614a6f565b979650505050505050565b8481526001600160a01b0384166020820152608060408201525f6151e66080830185613bc8565b905082606083015295945050505050565b8481526001600160a01b0384166020820152826040820152608060608201525f613aa96080830184613bc8565b5f60208284031215615234575f80fd5b815167ffffffffffffffff81111561524a575f80fd5b6129978482850161509a565b8381526001600160a01b0383166020820152606060408201525f61269d6060830184614a6f565b5f600160ff1b820161529157615291614f08565b505f0390565b5f82518060208501845e5f92019182525091905056fea2646970667358221220a54e83a1a62d20e08e55329ff0c94daedaf05863f14029b01e00de1f810ce8f164736f6c634300081a0033a2646970667358221220813e5ceda331a17fdf035d379e5b380fb6a6df3a0a43007f3c0931cdd9b7356664736f6c634300081a0033000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec10000000000000000000000001f98400000000000000000000000000000000004

Deployed Bytecode

0x608060405260043610610183575f3560e01c806391d14854116100d1578063dc4c90d31161007c578063e8ae2b6911610057578063e8ae2b69146104a5578063f2fde38b146104c4578063fdff9b4d146104e3575f80fd5b8063dc4c90d314610434578063e4467f3514610467578063e74b981b14610486575f80fd5b8063c836bfb9116100ac578063c836bfb9146103ce578063d547741f146103e2578063d5f3948814610401575f80fd5b806391d1485414610331578063b0e21e8a14610360578063b85b99c914610394575f80fd5b8063715018a6116101315780638be6bbb21161010c5780638be6bbb2146102a85780638c3bf9b9146102d45780638da5cb5b14610315575f80fd5b8063715018a614610254578063730df06714610268578063871fa6f814610295575f80fd5b80634690484011610161578063469048401461020357806347686a82146102225780634b86230c14610241575f80fd5b806327d2bbd7146101875780632f2ff15d146101c35780632f6b4b0e146101e4575b5f80fd5b348015610192575f80fd5b506101a66101a1366004611845565b610512565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156101ce575f80fd5b506101e26101dd36600461186f565b610546565b005b3480156101ef575f80fd5b506101a66101fe366004611a7d565b6105fb565b34801561020e575f80fd5b506006546101a6906001600160a01b031681565b34801561022d575f80fd5b506101a661023c366004611a7d565b610721565b6101a661024f366004611c44565b610abe565b34801561025f575f80fd5b506101e2610c97565b348015610273575f80fd5b50610287610282366004611d06565b610caa565b6040516101ba929190611e41565b6101a66102a3366004611e78565b610fb4565b3480156102b3575f80fd5b506102c76102c2366004611f60565b6111df565b6040516101ba9190611f7b565b3480156102df575f80fd5b506103077f24d766ec0f1bfbd75ff2bcd2034fbf5cbb00e3d6a7a59d2b365558f2842a463081565b6040519081526020016101ba565b348015610320575f80fd5b505f546001600160a01b03166101a6565b34801561033c575f80fd5b5061035061034b36600461186f565b611491565b60405190151581526020016101ba565b34801561036b575f80fd5b5060065461038190600160a01b900461ffff1681565b60405161ffff90911681526020016101ba565b34801561039f575f80fd5b506103506103ae366004611f8d565b805160208183018101805160058252928201919093012091525460ff1681565b3480156103d9575f80fd5b50600454610307565b3480156103ed575f80fd5b506101e26103fc36600461186f565b6114bd565b34801561040c575f80fd5b506101a67f0000000000000000000000008860211615db2bff56d9f06ca6adb8654eb5a5ea81565b34801561043f575f80fd5b506101a67f0000000000000000000000001f9840000000000000000000000000000000000481565b348015610472575f80fd5b506101e2610481366004611fc7565b611546565b348015610491575f80fd5b506101e26104a0366004611f60565b6115ae565b3480156104b0575f80fd5b506103506104bf36600461186f565b6115ff565b3480156104cf575f80fd5b506101e26104de366004611f60565b611643565b3480156104ee575f80fd5b506105026104fd366004611f60565b611680565b6040516101ba9493929190611fe8565b6003602052815f5260405f20818154811061052b575f80fd5b5f918252602090912001546001600160a01b03169150829050565b61054e611788565b6001600160a01b0381166105755760405163e6c4247b60e01b815260040160405180910390fd5b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff166105f7575f8281526001602081815260408084206001600160a01b0386168086529252808420805460ff19169093179092559051339285917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9190a45b5050565b5f8060405180604001604052806008815260200167047414d4d412d4c560c41b81525090505f85858560405160200161063693929190612075565b6040516020818303038152906040528051906020012090507f0000000000000000000000008860211615db2bff56d9f06ca6adb8654eb5a5ea6001600160a01b031663eaf1ecd87f0000000000000000000000001f984000000000000000000000000000000000048888308988600660149054906101000a900461ffff16896040518963ffffffff1660e01b81526004016106d89897969594939291906120fa565b602060405180830381865afa1580156106f3573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061071791906121c8565b9695505050505050565b5f6001600160a01b0383166107495760405163e6c4247b60e01b815260040160405180910390fd5b60058260405161075991906121e3565b9081526040519081900360200190205460ff16156107955781604051632875deb960e11b815260040161078c91906121f9565b60405180910390fd5b5f8484846040516020016107ab93929190612075565b60408051808303601f19018152828252805160209182012083830183526008845267047414d4d412d4c560c41b918401919091526006549151631edb071b60e31b81529093505f917f0000000000000000000000008860211615db2bff56d9f06ca6adb8654eb5a5ea6001600160a01b03169163f6d838d89161086b917f0000000000000000000000001f98400000000000000000000000000000000004918c918c9130918d918b91600160a01b90910461ffff16908d906004016120fa565b6020604051808303815f875af1158015610887573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108ab91906121c8565b905060016005866040516108bf91906121e3565b9081526040805160209281900383018120805460ff191694151594909417909355608080840182526001600160a01b038581168086528b82168587019081528685018e815260608089018e81525f9485526002808a52948890208a5181546001600160a01b0319908116918916919091178255945160018201805487169189169190911790559251805195840180548616968816969096179095559784015160038301805498860151928601519187167fffffffffffffffffff000000000000000000000000000000000000000000000090991698909817600160a01b62ffffff93841602177fffffffffffff000000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b9290911691909102179095559201516004840180549093169116179055905160058201906109fa9082612289565b5050506001600160a01b038087165f81815260036020908152604080832080546001818101835591855292842090920180549587166001600160a01b031996871681179091556004805493840181559093527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b9091018054909416821790935591519091907f35f19687cb41dc3bc33596333ef672f611fa71e0114deb2ed84abe96b74a4d2f90610aac908b90612344565b60405180910390a39695505050505050565b5f6001600160a01b038816610ae65760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b038416610b0d5760405163e6c4247b60e01b815260040160405180910390fd5b6040516323b4354160e11b815230906347686a8290610b34908c908c908c90600401612075565b6020604051808303815f875af1158015610b50573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b7491906121c8565b6040516384715b1160e01b815260048101889052602481018790526001600160a01b038681166044830152336064830152919250908216906384715b1190349060840160606040518083038185885af1158015610bd3573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190610bf891906123a0565b5050604080515f808252602082019092526001600160a01b038416925063c0147edc91859190610c3e565b610c2b611803565b815260200190600190039081610c235790505b50866040518463ffffffff1660e01b8152600401610c5e939291906124a8565b5f604051808303815f87803b158015610c75575f80fd5b505af1158015610c87573d5f803e3d5ffd5b5050505098975050505050505050565b610c9f611788565b610ca85f6117b4565b565b6004546060905f839003610cbc578092505b808410610d4157604080515f8082526020820190925290610d39565b610d2660408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b815260200190600190039081610cd85790505b509150610fad565b5f81610d4d85876124f1565b11610d585783610d62565b610d628583612504565b90508067ffffffffffffffff811115610d7d57610d7d61189d565b604051908082528060200260200182016040528015610dfc57816020015b610de960408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b815260200190600190039081610d9b5790505b5092505f5b81811015610faa575f6004610e1683896124f1565b81548110610e2657610e26612517565b5f9182526020808320909101546001600160a01b0390811680845260028084526040948590208551608080820188528254861682526001830154861682880152875160a081018952838501548716815260038401548088169882019890985262ffffff600160a01b890416818a0152600160b81b90970490930b606080880191909152600483015490951692860192909252948101939093526005840180549195509293929184019190610ed99061220b565b80601f0160208091040260200160405190810160405280929190818152602001828054610f059061220b565b8015610f505780601f10610f2757610100808354040283529160200191610f50565b820191905f5260205f20905b815481529060010190602001808311610f3357829003601f168201915b505050505081525050858381518110610f6b57610f6b612517565b602002602001018190525080858381518110610f8957610f89612517565b60209081029190910101516001600160a01b03909116905250600101610e01565b50505b9250929050565b5f6001600160a01b038916610fdc5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0385166110035760405163e6c4247b60e01b815260040160405180910390fd5b5f6110146040860160208701611f60565b6001600160a01b03160361103b5760405163e6c4247b60e01b815260040160405180910390fd5b6040516323b4354160e11b815230906347686a8290611062908d908d908d90600401612075565b6020604051808303815f875af115801561107e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110a291906121c8565b6040516384715b1160e01b815260048101899052602481018890526001600160a01b038781166044830152336064830152919250908216906384715b1190349060840160606040518083038185885af1158015611101573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061112691906123a0565b505050806001600160a01b03166307f46d3f6040518060400160405280858152602001876111539061252b565b9052604080515f8082526020820190925290611185565b611172611803565b81526020019060019003908161116a5790505b50866040518463ffffffff1660e01b81526004016111a5939291906125bb565b5f604051808303815f87803b1580156111bc575f80fd5b505af11580156111ce573d5f803e3d5ffd5b505050509998505050505050505050565b6001600160a01b0381165f90815260036020908152604080832080548251818502810185019093528083526060949383018282801561124557602002820191905f5260205f20905b81546001600160a01b03168152600190910190602001808311611227575b505050505090505f815167ffffffffffffffff8111156112675761126761189d565b6040519080825280602002602001820160405280156112e657816020015b6112d360408051608080820183525f8083526020808401829052845160a081018652828152908101829052808501829052606081018290529182015290918201908152602001606081525090565b8152602001906001900390816112855790505b5090505f5b8251811015611489575f83828151811061130757611307612517565b6020908102919091018101516001600160a01b038082165f90815260028085526040918290208251608080820185528254861682526001830154861682890152845160a081018652838501548716815260038401548088169982019990995262ffffff600160a01b8a041681870152600160b81b90980490930b606080890191909152600483015490951692870192909252918101949094526005810180549395509092918401916113b89061220b565b80601f01602080910402602001604051908101604052809291908181526020018280546113e49061220b565b801561142f5780601f106114065761010080835404028352916020019161142f565b820191905f5260205f20905b81548152906001019060200180831161141257829003601f168201915b50505050508152505083838151811061144a5761144a612517565b60200260200101819052508083838151811061146857611468612517565b60209081029190910101516001600160a01b039091169052506001016112eb565b509392505050565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff165b92915050565b6114c5611788565b5f8281526001602090815260408083206001600160a01b038516845290915290205460ff16156105f7575f8281526001602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b61154e611788565b8061ffff165f03611572576040516358d620b360e01b815260040160405180910390fd5b6006805461ffff909216600160a01b027fffffffffffffffffffff0000ffffffffffffffffffffffffffffffffffffffff909216919091179055565b6115b6611788565b6001600160a01b0381166115dd5760405163e6c4247b60e01b815260040160405180910390fd5b600680546001600160a01b0319166001600160a01b0392909216919091179055565b5f80546001600160a01b038381169116148061163c57505f8381526001602090815260408083206001600160a01b038616845290915290205460ff165b9392505050565b61164b611788565b6001600160a01b03811661167457604051631e4fbdf760e01b81525f600482015260240161078c565b61167d816117b4565b50565b600260208181525f92835260409283902080546001820154855160a081018752838601546001600160a01b039081168252600385015480821696830196909652600160a01b860462ffffff1697820197909752600160b81b90940490940b60608401526004820154851660808401526005820180549186169590941693906117079061220b565b80601f01602080910402602001604051908101604052809291908181526020018280546117339061220b565b801561177e5780601f106117555761010080835404028352916020019161177e565b820191905f5260205f20905b81548152906001019060200180831161176157829003601f168201915b5050505050905084565b5f546001600160a01b03163314610ca85760405163118cdaa760e01b815233600482015260240161078c565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60405180604001604052806002906020820280368337509192915050565b6001600160a01b038116811461167d575f80fd5b803561184081611821565b919050565b5f8060408385031215611856575f80fd5b823561186181611821565b946020939093013593505050565b5f8060408385031215611880575f80fd5b82359150602083013561189281611821565b809150509250929050565b634e487b7160e01b5f52604160045260245ffd5b6040805190810167ffffffffffffffff811182821017156118d4576118d461189d565b60405290565b604051610100810167ffffffffffffffff811182821017156118d4576118d461189d565b60405160c0810167ffffffffffffffff811182821017156118d4576118d461189d565b604051601f8201601f1916810167ffffffffffffffff8111828210171561194a5761194a61189d565b604052919050565b803562ffffff81168114611840575f80fd5b8035600281900b8114611840575f80fd5b5f60a08284031215611985575f80fd5b60405160a0810167ffffffffffffffff811182821017156119a8576119a861189d565b60405290508082356119b981611821565b815260208301356119c981611821565b60208201526119da60408401611952565b60408201526119eb60608401611964565b606082015260808301356119fe81611821565b6080919091015292915050565b5f82601f830112611a1a575f80fd5b8135602083015f8067ffffffffffffffff841115611a3a57611a3a61189d565b50601f8301601f1916602001611a4f81611921565b915050828152858383011115611a63575f80fd5b828260208301375f92810160200192909252509392505050565b5f805f60e08486031215611a8f575f80fd5b611a998585611975565b925060a0840135611aa981611821565b915060c084013567ffffffffffffffff811115611ac4575f80fd5b611ad086828701611a0b565b9150509250925092565b5f82601f830112611ae9575f80fd5b813567ffffffffffffffff811115611b0357611b0361189d565b611b1260208260051b01611921565b8082825260208201915060208360061b860101925085831115611b33575f80fd5b602085015b83811015611b945786601f820112611b4e575f80fd5b611b566118b1565b806040830189811115611b67575f80fd5b835b81811015611b81578035845260209384019301611b69565b5050845250602090920191604001611b38565b5095945050505050565b80358015158114611840575f80fd5b5f6101008284031215611bbe575f80fd5b611bc66118da565b90508135611bd381611821565b8152611be160208301611964565b6020820152611bf260408301611952565b6040820152611c0360608301611952565b6060820152611c1460808301611964565b608082015260a0828101359082015260c08083013590820152611c3960e08301611b9e565b60e082015292915050565b5f805f805f805f80610260898b031215611c5c575f80fd5b611c668a8a611975565b975060a0890135611c7681611821565b965060c089013567ffffffffffffffff811115611c91575f80fd5b611c9d8b828c01611a0b565b96505060e089013594506101008901359350610120890135611cbe81611821565b925061014089013567ffffffffffffffff811115611cda575f80fd5b611ce68b828c01611ada565b925050611cf78a6101608b01611bad565b90509295985092959890939650565b5f8060408385031215611d17575f80fd5b50508035926020909101359150565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b5f82825180855260208501945060208160051b830101602085015f5b83811015611e3557601f1985840301885281516001600160a01b0381511684526001600160a01b0360208201511660208501526040810151611e0360408601826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b506060015161010060e08501819052611e1e90850182611d26565b6020998a0199909450929092019150600101611d70565b50909695505050505050565b604081525f611e536040830185611d54565b90508260208301529392505050565b5f60c08284031215611e72575f80fd5b50919050565b5f805f805f805f805f6102808a8c031215611e91575f80fd5b611e9b8b8b611975565b9850611ea960a08b01611835565b975060c08a013567ffffffffffffffff811115611ec4575f80fd5b611ed08c828d01611a0b565b97505060e08a013595506101008a01359450611eef6101208b01611835565b93506101408a013567ffffffffffffffff811115611f0b575f80fd5b611f178c828d01611e62565b9350506101608a013567ffffffffffffffff811115611f34575f80fd5b611f408c828d01611ada565b925050611f518b6101808c01611bad565b90509295985092959850929598565b5f60208284031215611f70575f80fd5b813561163c81611821565b602081525f61163c6020830184611d54565b5f60208284031215611f9d575f80fd5b813567ffffffffffffffff811115611fb3575f80fd5b611fbf84828501611a0b565b949350505050565b5f60208284031215611fd7575f80fd5b813561ffff8116811461163c575f80fd5b6001600160a01b03851681526001600160a01b038416602082015261205e60408201846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b61010060e08201525f610717610100830184611d26565b6120cd81856001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b6001600160a01b03831660a082015260e060c08201525f6120f160e0830184611d26565b95945050505050565b6001600160a01b038916815261216160208201896001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b6001600160a01b03871660c08201526001600160a01b03861660e08201526101806101008201525f612197610180830187611d26565b8281036101208401526121aa8187611d26565b61ffff95909516610140840152505061016001529695505050505050565b5f602082840312156121d8575f80fd5b815161163c81611821565b5f82518060208501845e5f920191825250919050565b602081525f61163c6020830184611d26565b600181811c9082168061221f57607f821691505b602082108103611e7257634e487b7160e01b5f52602260045260245ffd5b601f82111561228457805f5260205f20601f840160051c810160208510156122625750805b601f840160051c820191505b81811015612281575f815560010161226e565b50505b505050565b815167ffffffffffffffff8111156122a3576122a361189d565b6122b7816122b1845461220b565b8461223d565b6020601f8211600181146122e9575f83156122d25750848201515b5f19600385901b1c1916600184901b178455612281565b5f84815260208120601f198516915b8281101561231857878501518255602094850194600190920191016122f8565b508482101561233557868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b60a081016114b782846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b5f805f606084860312156123b2575f80fd5b5050815160208301516040909301519094929350919050565b6001600160a01b038151168252602081015160020b602083015262ffffff6040820151166040830152606081015161240a606084018262ffffff169052565b50608081015161241f608084018260020b9052565b5060a081015160a083015260c081015160c083015260e081015161228460e084018215159052565b5f8151808452602084019350602083015f5b8281101561249e578151865f5b6002811015612485578251825260209283019290910190600101612466565b5050506040959095019460209190910190600101612459565b5093949350505050565b6124b281856123cb565b6101406101008201525f6124ca610140830185612447565b8281036101208401526107178185612447565b634e487b7160e01b5f52601160045260245ffd5b808201808211156114b7576114b76124dd565b818103818111156114b7576114b76124dd565b634e487b7160e01b5f52603260045260245ffd5b5f60c0823603121561253b575f80fd5b6125436118fe565b823560048110612551575f80fd5b815261255f60208401611835565b6020820152604083013567ffffffffffffffff81111561257d575f80fd5b61258936828601611a0b565b60408301525061259b60608401611b9e565b60608201526080838101359082015260a092830135928101929092525090565b606081526125cd6060820185516123cb565b5f60208501516101206101608401528051600481106125fa57634e487b7160e01b5f52602160045260245ffd5b61018084015260208101516001600160a01b03166101a0840152604081015160c06101c085015261262f610240850182611d26565b905060608201516126456101e086018215159052565b50608082015161020085015260a0820151610220850152838103602085015261266e8187612447565b9150508281036040840152610717818561244756fea26469706673582212203fc0b258f905c20d1217deffe7285fea16b1f80ebcf572c47c741193027e3f0464736f6c634300081a0033

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

000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec10000000000000000000000001f98400000000000000000000000000000000004

-----Decoded View---------------
Arg [0] : _owner (address): 0xe911f518449ba0011D84b047B4cde50dAA081eC1
Arg [1] : _poolManager (address): 0x1F98400000000000000000000000000000000004

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


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

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.