ETH Price: $2,888.57 (-1.75%)

Contract

0x8a79bE4DBde8D6496578721B48eE0fEB71De29ee
Transaction Hash
Block
From
To
Cancel Order339717542025-12-03 0:01:5354 days ago1764720113IN
0x8a79bE4D...B71De29ee
0 ETH0.000000280.00150038
Cancel Order339717492025-12-03 0:01:4854 days ago1764720108IN
0x8a79bE4D...B71De29ee
0 ETH0.000000290.00150038
Create Scale Ord...339717252025-12-03 0:01:2454 days ago1764720084IN
0x8a79bE4D...B71De29ee
0.001 ETH0.000001160.00150038
Cancel Order291000172025-10-07 14:46:16110 days ago1759848376IN
0x8a79bE4D...B71De29ee
0 ETH0.000000190.00100035
Create Limit Ord...290999312025-10-07 14:44:50110 days ago1759848290IN
0x8a79bE4D...B71De29ee
0.0075 ETH0.000000410.00100036
Claim Order284781212025-09-30 10:01:20117 days ago1759226480IN
0x8a79bE4D...B71De29ee
0 ETH0.000000010.00010035
Cancel Order284781092025-09-30 10:01:08117 days ago1759226468IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010035
Create Limit Ord...284779552025-09-30 9:58:34117 days ago1759226314IN
0x8a79bE4D...B71De29ee
0.00302458 ETH0.000000040.00010034
Cancel Order284779342025-09-30 9:58:13117 days ago1759226293IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010034
Create Limit Ord...284777782025-09-30 9:55:37117 days ago1759226137IN
0x8a79bE4D...B71De29ee
0 ETH0.000000050.00010033
Create Limit Ord...284776712025-09-30 9:53:50117 days ago1759226030IN
0x8a79bE4D...B71De29ee
0.00302467 ETH0.000000040.00010032
Claim Order283831162025-09-29 7:37:55118 days ago1759131475IN
0x8a79bE4D...B71De29ee
0 ETH0.000000010.00010033
Create Limit Ord...283828552025-09-29 7:33:34118 days ago1759131214IN
0x8a79bE4D...B71De29ee
0.00194214 ETH0.000000040.00010032
Claim Order274148762025-09-18 2:40:35130 days ago1758163235IN
0x8a79bE4D...B71De29ee
0 ETH00.00000044
Create Limit Ord...273848262025-09-17 18:19:45130 days ago1758133185IN
0x8a79bE4D...B71De29ee
0.001 ETH00.00000436
Claim Order273018102025-09-16 19:16:09131 days ago1758050169IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010032
Cancel Order273017972025-09-16 19:15:56131 days ago1758050156IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010032
Create Limit Ord...273008402025-09-16 18:59:59131 days ago1758049199IN
0x8a79bE4D...B71De29ee
0 ETH0.000000050.00010029
Cancel Order273007612025-09-16 18:58:40131 days ago1758049120IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010029
Create Limit Ord...273001722025-09-16 18:48:51131 days ago1758048531IN
0x8a79bE4D...B71De29ee
0 ETH0.000000050.00010032
Create Limit Ord...273001272025-09-16 18:48:06131 days ago1758048486IN
0x8a79bE4D...B71De29ee
0.00301373 ETH0.000000040.00010032
Cancel Order273001052025-09-16 18:47:44131 days ago1758048464IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010032
Create Limit Ord...272991752025-09-16 18:32:14131 days ago1758047534IN
0x8a79bE4D...B71De29ee
0.00316046 ETH0.000000040.00010031
Claim Order269164972025-09-12 8:14:16135 days ago1757664856IN
0x8a79bE4D...B71De29ee
0 ETH0.000000020.00010031
Cancel Order269164322025-09-12 8:13:11135 days ago1757664791IN
0x8a79bE4D...B71De29ee
0 ETH0.000000030.00010031
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
339717252025-12-03 0:01:2454 days ago1764720084
0x8a79bE4D...B71De29ee
0.0005 ETH
339717252025-12-03 0:01:2454 days ago1764720084
0x8a79bE4D...B71De29ee
0.0005 ETH
290999312025-10-07 14:44:50110 days ago1759848290
0x8a79bE4D...B71De29ee
0.0075 ETH
284779552025-09-30 9:58:34117 days ago1759226314
0x8a79bE4D...B71De29ee
0.00302458 ETH
284776712025-09-30 9:53:50117 days ago1759226030
0x8a79bE4D...B71De29ee
0.00302467 ETH
283828552025-09-29 7:33:34118 days ago1759131214
0x8a79bE4D...B71De29ee
0.00194214 ETH
273848262025-09-17 18:19:45130 days ago1758133185
0x8a79bE4D...B71De29ee
0.001 ETH
273001272025-09-16 18:48:06131 days ago1758048486
0x8a79bE4D...B71De29ee
0.00301373 ETH
272991752025-09-16 18:32:14131 days ago1758047534
0x8a79bE4D...B71De29ee
0.00316046 ETH
269156762025-09-12 8:00:35135 days ago1757664035
0x8a79bE4D...B71De29ee
0.0028341 ETH
269153892025-09-12 7:55:48135 days ago1757663748
0x8a79bE4D...B71De29ee
0.00254887 ETH
263084502025-09-05 7:20:09142 days ago1757056809
0x8a79bE4D...B71De29ee
0.00344571 ETH
259591762025-09-01 6:18:55147 days ago1756707535
0x8a79bE4D...B71De29ee
0.00224984 ETH
256260442025-08-28 9:46:43150 days ago1756374403
0x8a79bE4D...B71De29ee
0.00314735 ETH
256240022025-08-28 9:12:41150 days ago1756372361
0x8a79bE4D...B71De29ee
0.00315435 ETH
253871332025-08-25 15:24:52153 days ago1756135492
0x8a79bE4D...B71De29ee
0.00389926 ETH
251891312025-08-23 8:24:50155 days ago1755937490
0x8a79bE4D...B71De29ee
0.0066864 ETH
251889922025-08-23 8:22:31155 days ago1755937351
0x8a79bE4D...B71De29ee
0.00949607 ETH
251885652025-08-23 8:15:24155 days ago1755936924
0x8a79bE4D...B71De29ee
0.00850728 ETH
251877192025-08-23 8:01:18155 days ago1755936078
0x8a79bE4D...B71De29ee
0.00806202 ETH
251870722025-08-23 7:50:31155 days ago1755935431
0x8a79bE4D...B71De29ee
0.00942258 ETH
249664592025-08-20 18:33:38158 days ago1755714818
0x8a79bE4D...B71De29ee
0.00345243 ETH
249660442025-08-20 18:26:43158 days ago1755714403
0x8a79bE4D...B71De29ee
0.0034087 ETH
249654402025-08-20 18:16:39158 days ago1755713799
0x8a79bE4D...B71De29ee
0.00338589 ETH
241637542025-08-11 11:35:13167 days ago1754912113
0x8a79bE4D...B71De29ee
0.00347975 ETH
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
LimitOrderManager

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 800 runs

Other Settings:
cancun EvmVersion
File 1 of 46 : LimitOrderManager.sol
// SPDX-License-Identifier: BSL
pragma solidity ^0.8.24;

import {ILimitOrderManager} from "./ILimitOrderManager.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SafeCast} from "v4-core/libraries/SafeCast.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import "./PositionManagement.sol";
import "./TickLibrary.sol";
import "./CallbackHandler.sol";
import "forge-std/console.sol";
import {TickBitmap} from "v4-core/libraries/TickBitmap.sol";
import {BitMath} from "v4-core/libraries/BitMath.sol";

/// @title LimitOrderManager
/// @notice Manages limit orders for Uniswap v4 pools
/// @dev Handles creation, execution, and cancellation of limit orders with fee collection and position tracking
contract LimitOrderManager is ILimitOrderManager, IUnlockCallback, Ownable, ReentrancyGuard, Pausable {
    using CurrencySettler for Currency;
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using BalanceDeltaLibrary for BalanceDelta;
    using PoolIdLibrary for PoolKey;
    using SafeCast for *;
    using TickLibrary for int24;
    using CallbackHandler for CallbackHandler.CallbackState;
    using SafeERC20 for IERC20;

    // Pool manager reference
    IPoolManager public immutable poolManager;
    
    // Hook address
    address public hook;

    // Constants
    uint256 public constant FEE_DENOMINATOR = 100000;
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);


    CallbackHandler.CallbackState private callbackState;
    address public override treasury;
    uint256 public override executablePositionsLimit = 75;
    uint256 public hook_fee_percentage = 50000;
    uint24 public maxOrderLimit = 100; 
    mapping(Currency => uint256) public override minAmount;
    mapping(address => bool) public override isKeeper;
    

    // Original state mappings
    mapping(PoolId => bool) public whitelistedPool;
    mapping(PoolId => mapping(bytes32 => EnumerableSet.AddressSet)) private positionContributors;
    mapping(PoolId => mapping(bytes32 => mapping(address => UserPosition))) public userPositions;
    mapping(PoolId => mapping(bytes32 => uint256)) public override currentNonce;

    mapping(PoolId => mapping(int16 => uint256)) public token0TickBitmap;
    mapping(PoolId => mapping(int16 => uint256)) public token1TickBitmap;
    mapping(PoolId => mapping(int24 => bytes32)) public token0PositionAtTick;
    mapping(PoolId => mapping(int24 => bytes32)) public token1PositionAtTick;

    mapping(PoolId => mapping(bytes32 => PositionState)) public positionState;
    mapping(address => mapping(PoolId => EnumerableSet.Bytes32Set)) private userPositionKeys;


    constructor(address _poolManagerAddr, address _treasury, address _owner) Ownable(_owner) {
        require(_treasury != address(0) && _poolManagerAddr != address(0));
            treasury = _treasury;
            poolManager = IPoolManager(_poolManagerAddr);

            // Initialize callback state
            callbackState.poolManager = poolManager;
            callbackState.treasury = _treasury;
            callbackState.feeDenominator = FEE_DENOMINATOR;
            callbackState.hookFeePercentage = hook_fee_percentage;
        }

// =========== Create Order Functions ===========
    /// @notice Creates a single limit order in a specified pool
    /// @param isToken0 True if order is for token0, false for token1
    /// @param targetTick The target tick price for the order
    /// @param amount The amount of tokens to use for the order
    /// @param key The pool key identifying the specific pool
    /// @return result Order creation result
    /// @dev Validates parameters and transfers tokens from user before creating order
    function createLimitOrder(
        bool isToken0,
        int24 targetTick,
        uint256 amount,
        PoolKey calldata key
    ) external payable override returns (CreateOrderResult memory) {

        
        PoolId poolId = key.toId();
        (, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);


        (int24 bottomTick, int24 topTick) = TickLibrary.getValidTickRange(
            currentTick,
            targetTick,
            key.tickSpacing,
            isToken0
        );

        ILimitOrderManager.OrderInfo[] memory orders = new ILimitOrderManager.OrderInfo[](1);
        orders[0] = ILimitOrderManager.OrderInfo({
            bottomTick: bottomTick,
            topTick: topTick,
            amount: 0,
            liquidity: 0
        });
        
        CreateOrderResult[] memory results = _createOrder(orders, isToken0, amount, 1, 0, key);
        return results[0]; 
    }


    /// @notice Creates multiple scaled limit orders across a price range
    /// @param isToken0 True if orders are for token0, false for token1
    /// @param bottomTick The lower tick bound of the order range
    /// @param topTick The upper tick bound of the order range
    /// @param totalAmount Total amount of tokens to distribute across orders
    /// @param totalOrders Number of orders to create
    /// @param sizeSkew Skew factor for order size distribution (1 for equal distribution)
    /// @param key The pool key identifying the specific pool
    /// @return results containing details of all created orders
    /// @dev Orders are distributed according to the sizeSkew parameter
    function createScaleOrders(
        bool isToken0,
        int24 bottomTick,
        int24 topTick,
        uint256 totalAmount,
        uint256 totalOrders,
        uint256 sizeSkew,
        PoolKey calldata key
    ) external payable returns (CreateOrderResult[] memory results) {
        // Get current tick for validation
        PoolId poolId = key.toId();

        (, int24 currentTick, , ) = StateLibrary.getSlot0(poolManager, poolId);

        require(totalOrders <= maxOrderLimit);
        ILimitOrderManager.OrderInfo[] memory orders = 
            TickLibrary.validateAndPrepareScaleOrders(bottomTick, topTick, currentTick, isToken0, totalOrders, sizeSkew, key.tickSpacing);
        
        results = _createOrder(orders, isToken0, totalAmount, totalOrders, sizeSkew, key);
    }

    /**
     * @notice Internal function to create one or more limit orders with specified parameters
     * @dev Handles the core logic of order creation
     * @param orders Array of OrderInfo structs containing initial order parameters
     * @param isToken0 True if orders are for token0, false for token1
     * @param totalAmount Total amount of tokens to be used across all orders
     * @param totalOrders Number of orders to create (used for scale calculations)
     * @param sizeSkew Distribution factor for order sizes (0 for equal distribution)
     * @param key Pool key identifying the specific Uniswap V4 pool
     * @return results Array of CreateOrderResult structs containing created order details
     */
    function _createOrder(
        ILimitOrderManager.OrderInfo[] memory orders,
        bool isToken0,
        uint256 totalAmount,
        uint256 totalOrders,
        uint256 sizeSkew,
        PoolKey calldata key
    ) internal whenNotPaused returns (CreateOrderResult[] memory results) {
        require(address(key.hooks) == hook);
        require(totalAmount != 0);
        PoolId poolId = key.toId();
        if (!whitelistedPool[poolId]) revert NotWhitelistedPool();
        orders = PositionManagement.calculateOrderSizes(orders, isToken0, totalAmount, totalOrders, sizeSkew);
        require(
            PositionManagement.validateScaleOrderSizes(orders, totalAmount, minAmount[isToken0 ? key.currency0 : key.currency1])
        );
        _handleTokenTransfer(isToken0, totalAmount, key);
        results = new CreateOrderResult[](orders.length);

        BalanceDelta[] memory feeDeltas = abi.decode(
            poolManager.unlock(abi.encode(
                UnlockCallbackData({
                    callbackType: CallbackType.CREATE_ORDERS,
                    data: abi.encode(CreateOrdersCallbackData({key: key, orders: orders, isToken0: isToken0, orderCreator: msg.sender}))
                })
            )),
            (BalanceDelta[])
        );

        bytes32 positionKey;
        OrderInfo memory order;
        for (uint256 i; i < orders.length; i++) {
            order = orders[i];
            (, positionKey) = PositionManagement.getPositionKeys(currentNonce, poolId, order.bottomTick, order.topTick, isToken0);
            require(!positionState[poolId][positionKey].isWaitingKeeper);
            _retrackPositionFee(poolId, positionKey, feeDeltas[i]);
            
            if(!positionState[poolId][positionKey].isActive) {
                positionState[poolId][positionKey].isActive = true;
                bytes32 baseKey = bytes32(
                    uint256(uint24(order.bottomTick)) << 232 |
                    uint256(uint24(order.topTick)) << 208 |
                    uint256(isToken0 ? 1 : 0)
                );
                positionState[poolId][positionKey].currentNonce = currentNonce[poolId][baseKey];
                
                int24 executableTick = isToken0 ? order.topTick : order.bottomTick;
                
                PositionManagement.addPositionToTick(
                    isToken0 ? token0PositionAtTick : token1PositionAtTick,
                    isToken0 ? token0TickBitmap : token1TickBitmap,
                    key,
                    executableTick,
                    positionKey
                );
            }   

            _updateUserPosition(poolId, positionKey, order.liquidity, msg.sender);

            results[i].usedAmount = order.amount;
            results[i].isToken0 = isToken0;
            results[i].bottomTick = order.bottomTick;
            results[i].topTick = order.topTick;
            emit OrderCreated(msg.sender, poolId, positionKey);
        }

        return results;
    }

// =========== Cancel Order Functions ===========
    /// @notice Cancels a single limit order position
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKey The unique identifier of the position to cancel
    function cancelOrder(PoolKey calldata key, bytes32 positionKey) external override nonReentrant{
        _cancelOrder(key, positionKey, msg.sender);
    }

    /// @notice Cancels multiple limit order positions in a batch
    /// @dev Uses pagination to handle large numbers of orders
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param offset Starting position in the user's position array
    /// @param limit Maximum number of positions to process in this call
    function cancelBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external override nonReentrant {
        PoolId poolId = key.toId();
        EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[msg.sender][poolId];
        

        if (offset >= userKeys.length()) {
            return;
        }
        

        uint256 endIndex = (offset + limit > userKeys.length()) ? 
            userKeys.length() : 
            offset + limit;
        
        
        uint256 i = endIndex;
        while (i > offset) {
            i--; 
            
            if (i < userKeys.length()) { 
                bytes32 positionKey = userKeys.at(i);
                _cancelOrder(key, positionKey, msg.sender);
            }
        }
    }

    /// @notice Cancels multiple limit order positions using direct position keys
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to cancel
    function cancelPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external nonReentrant {
        for (uint256 i = 0; i < positionKeys.length; i++) {
            _cancelOrder(key, positionKeys[i], msg.sender);
        }
    }

    /// @notice Emergency function to cancel orders on behalf of a user
    /// @dev Can only be called by the keeper in emergency situations
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param user The address of the user whose orders will be canceled
    /// @param positionKeys Array of position keys to cancel
    function emergencyCancelOrders(
        PoolKey calldata key,
        bytes32[] calldata positionKeys,
        address user
    ) external nonReentrant {
        require(isKeeper[msg.sender]);
        
        for (uint256 i = 0; i < positionKeys.length; i++) {
            _cancelOrder(key, positionKeys[i], user);
        }

    }

    /// @notice Internal function to handle the cancellation of a limit order
    /// @dev Handles both cancellation and claiming in a single transaction
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKey The unique identifier of the position to cancel
    /// @param user The address of the position owner
    function _cancelOrder(
        PoolKey calldata key,
        bytes32 positionKey,
        address user
    ) internal {
        PoolId poolId = key.toId();
        
        // Check if user has liquidity in this position
        uint128 userLiquidity = userPositions[poolId][positionKey][user].liquidity;
        require(userLiquidity > 0);

        // Early return for claimable balance
        if(userPositions[poolId][positionKey][user].claimablePrincipal != ZERO_DELTA || !positionState[poolId][positionKey].isActive) {
            _claimOrder(key, positionKey, user);
            return;
        }

        // Get position info 
        (int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(positionKey);
        
        // Cancel order through pool manager
        (BalanceDelta callerDelta, BalanceDelta feeDelta) = abi.decode(
            poolManager.unlock(
                abi.encode(
                    UnlockCallbackData({
                        callbackType: CallbackType.CANCEL_ORDER,
                        data: abi.encode(
                            CancelOrderCallbackData({
                                key: key,
                                bottomTick: bottomTick,
                                topTick: topTick,
                                liquidity: userLiquidity,
                                user: user,
                                isToken0: isToken0
                            })
                        )
                    })
                )
            ),
            (BalanceDelta, BalanceDelta)
        );

        _retrackPositionFee(poolId, positionKey, feeDelta);
        userPositions[poolId][positionKey][user].claimablePrincipal = callerDelta - feeDelta;
        positionState[poolId][positionKey].totalLiquidity -= userLiquidity;

        int24 executableTick = isToken0 ? topTick : bottomTick;
        
        _handlePositionRemoval(poolId, positionKey, user, key, isToken0, executableTick);

        emit OrderCanceled(user, poolId, positionKey);
    }

    /// @notice Updated helper function
    function _handlePositionRemoval(
        PoolId poolId,
        bytes32 positionKey,
        address user,
        PoolKey calldata key,
        bool isToken0,
        int24 executableTick
    ) internal {
        _claimOrder(key, positionKey, user);
        
        positionContributors[poolId][positionKey].remove(user);
        
        if(positionContributors[poolId][positionKey].length() == 0) {
            positionState[poolId][positionKey].isActive = false;
            positionState[poolId][positionKey].isWaitingKeeper = false;
            
            PositionManagement.removePositionFromTick(
                isToken0 ? token0PositionAtTick : token1PositionAtTick,
                isToken0 ? token0TickBitmap : token1TickBitmap,
                key,
                executableTick
            );
        }
    }

    // Decode position key to get all components including nonce
    function _decodePositionKey(bytes32 key) internal pure returns (
        int24 bottomTick,
        int24 topTick,
        bool isToken0,
        uint256 nonce
    ) {
        uint256 value = uint256(key);
        return (
            int24(uint24(value >> 232)),          
            int24(uint24(value >> 208)),          
            (value & 1) == 1,                     
            (value >> 8) & ((1 << 200) - 1)       
        );
    }

    /// @notice Allows claiming tokens from a canceled or executed limit order
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKey The unique identifier of the position to claim
    function claimOrder(PoolKey calldata key, bytes32 positionKey) nonReentrant external {
        _claimOrder(key, positionKey, msg.sender);
    }

    /// @notice Batch claims multiple orders that were executed or canceled
    /// @dev Uses pagination to handle large numbers of orders
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param offset Starting position in the user's position array
    /// @param limit Maximum number of positions to process in this call
    function claimBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external nonReentrant {
        PoolId poolId = key.toId();
        EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[msg.sender][poolId];
        
        if (offset >= userKeys.length()) {
            return;
        }
        
        uint256 endIndex = (offset + limit > userKeys.length()) ? 
            userKeys.length() : 
            offset + limit;
         
        uint256 i = endIndex;
        while (i > offset) {
            i--; 
            
            if (i < userKeys.length()) { 
                bytes32 positionKey = userKeys.at(i);
                UserPosition storage position = userPositions[poolId][positionKey][msg.sender];
                
                if (position.liquidity > 0 && 
                   (position.claimablePrincipal != ZERO_DELTA || !positionState[poolId][positionKey].isActive)) {
                    _claimOrder(key, positionKey, msg.sender);
                }
            }
        }
    }

    /// @notice Claims multiple limit order positions using direct position keys
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to claim
    function claimPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external nonReentrant {
        for (uint256 i = 0; i < positionKeys.length; i++) {
            _claimOrder(key, positionKeys[i], msg.sender);
        }
    }

    /// @notice Keeper function to claim positions on behalf of users
    /// @dev Only callable by keepers to help users claim their executed positions
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to claim
    /// @param user The address of the user whose positions to claim
    function keeperClaimPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys,
        address user
    ) external nonReentrant {
        require(isKeeper[msg.sender]);
        
        for (uint256 i = 0; i < positionKeys.length; i++) {
            _claimOrder(key, positionKeys[i], user);
        }
    }

    /// @notice Internal function to process claiming of tokens from a position
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKey The unique identifier of the position to claim
    /// @param user The address that will receive the claimed tokens
    function _claimOrder(PoolKey calldata key, bytes32 positionKey, address user) internal {
        PoolId poolId = key.toId();
        
        require(userPositions[poolId][positionKey][user].liquidity > 0);
        require(userPositions[poolId][positionKey][user].claimablePrincipal != ZERO_DELTA ||!positionState[poolId][positionKey].isActive);
        
        UserPosition storage position = userPositions[poolId][positionKey][user];

        if (!positionState[poolId][positionKey].isActive) {
            position.claimablePrincipal = PositionManagement.getBalanceDelta(positionKey, position.liquidity);
        }

        if (position.liquidity != 0) {
            BalanceDelta feeDiff = positionState[poolId][positionKey].feePerLiquidity - position.lastFeePerLiquidity;
            int128 liq = int128(position.liquidity);
            BalanceDelta pendingFees = position.fees + PositionManagement.calculateScaledUserFee(feeDiff, uint128(liq));
            
            if (!(pendingFees == position.fees)) {
                position.fees = pendingFees;
            }
        }
        
        position.lastFeePerLiquidity = positionState[poolId][positionKey].feePerLiquidity;

        BalanceDelta principal = position.claimablePrincipal;
        BalanceDelta fees = position.fees;
        

        delete userPositions[poolId][positionKey][user];
        

        userPositionKeys[user][poolId].remove(positionKey);
        
 
        poolManager.unlock(
            abi.encode(
                UnlockCallbackData({
                    callbackType: CallbackType.CLAIM_ORDER,
                    data: abi.encode(
                        ClaimOrderCallbackData({
                            principal: principal,
                            fees: fees,
                            key: key, 
                            user: user
                        })
                    )
                })
            )
        );

        emit OrderClaimed(
            user,
            poolId,
            positionKey,
            uint256(uint128(principal.amount0())),
            uint256(uint128(principal.amount1())),
            uint256(uint128(fees.amount0())),
            uint256(uint128(fees.amount1())),
            hook_fee_percentage
        );
    }

    /**
     * @notice Executes limit orders that have been triggered by price movements
     * @param key The pool key identifying the specific pool 
     * @param tickBeforeSwap The tick price before the swap started
     * @param tickAfterSwap The tick price after the swap completed
     * @param zeroForOne The direction of the swap (true for token0 to token1)
     */
    function executeOrder(
        PoolKey calldata key,
        int24 tickBeforeSwap,
        int24 tickAfterSwap,
        bool zeroForOne
    ) external override {
        require(msg.sender == hook);
        require(executablePositionsLimit != 0);
        
        PoolId poolId = key.toId();
        
        int24[] memory executableTicks = _findOverlappingPositions(
            poolId, 
            tickBeforeSwap, 
            tickAfterSwap, 
            zeroForOne,
            key.tickSpacing
        );
        
        if(executableTicks.length == 0) return;
        
        uint256 executableCount = executableTicks.length;
        
        if(executableCount > executablePositionsLimit) {
            executableCount = executablePositionsLimit;
            _handleLeftoverPositions(poolId, executableTicks, executableCount, zeroForOne);
        }
        
        for(uint256 i = 0; i < executableCount; i++) {
            int24 tick = executableTicks[i];
            
            bytes32 posKey = zeroForOne ? 
                token1PositionAtTick[poolId][tick] : 
                token0PositionAtTick[poolId][tick];
            
            if(posKey == bytes32(0)) continue;
            
            _executePosition(key, poolId, posKey, tick);
        }
    }

    /**
     * @notice Execute a single limit order position
     * @dev Processes a single position identified by its position key
     * @param key The pool key
     * @param poolId The pool identifier
     * @param posKey The position key to execute
     * @param tick The tick with the executable position
     */
    function _executePosition(
        PoolKey memory key,
        PoolId poolId,
        bytes32 posKey,
        int24 tick
    ) internal returns (BalanceDelta callerDelta, BalanceDelta feeDelta) {
        // Decode position data
        (int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(posKey);
        
        // Burn position liquidity and collect fees
        (callerDelta, feeDelta) = callbackState._burnLimitOrder(
            key,
            bottomTick,
            topTick,
            positionState[poolId][posKey].totalLiquidity,
            isToken0
        );
        
        // Update position state
        _retrackPositionFee(poolId, posKey, feeDelta);
        positionState[poolId][posKey].isActive = false;
        
        // Clear keeper flag if set
        if(positionState[poolId][posKey].isWaitingKeeper) {
            positionState[poolId][posKey].isWaitingKeeper = false;
        }
            
        // Remove position from tick tracking
        PositionManagement.removePositionFromTick(
            isToken0 ? token0PositionAtTick : token1PositionAtTick,
            isToken0 ? token0TickBitmap : token1TickBitmap,
            key,
            tick
        );
        
        // Update nonce for this position type to prevent key reuse
        bytes32 baseKey = bytes32(
            uint256(uint24(bottomTick)) << 232 |
            uint256(uint24(topTick)) << 208 |
            uint256(isToken0 ? 1 : 0)
        );
        currentNonce[poolId][baseKey]++;
        
        // Emit event for executed order
        emit OrderExecuted(poolId, posKey);
    }

    /**
     * @notice Handle positions that exceed the execution limit
     * @dev Marks positions for keeper execution and emits event with position details
     * @param poolId The pool identifier
     * @param executableTicks Array of ticks with positions
     * @param executableCount Number of positions being executed in this transaction
     * @param zeroForOne Direction of the swap
     */
    function _handleLeftoverPositions(
        PoolId poolId,
        int24[] memory executableTicks,
        uint256 executableCount,
        bool zeroForOne
    ) internal {
        uint256 leftoverCount = executableTicks.length - executableCount;
        bytes32[] memory leftOvers = new bytes32[](leftoverCount);
        
        for(uint256 i = executableCount; i < executableTicks.length; i++) {
            int24 tick = executableTicks[i];
            bytes32 posKey = zeroForOne ? 
                token1PositionAtTick[poolId][tick] : 
                token0PositionAtTick[poolId][tick];
                
            positionState[poolId][posKey].isWaitingKeeper = true;
            
            // Store the position key directly
            leftOvers[i - executableCount] = posKey;
        }
        
        // Emit event with position keys that need keeper execution
        emit PositionsLeftOver(poolId, leftOvers);
    }

    /// @notice Finds ticks with executable limit orders based on price movement
    /// @param poolId The pool identifier
    /// @param tickBeforeSwap The tick before the swap started
    /// @param tickAfterSwap The tick after the swap completed
    /// @param zeroForOne Direction of the swap (true for 0→1, false for 1→0)
    /// @param tickSpacing The pool's tick spacing
    /// @return executableTicks Array of ticks with executable orders
    function _findOverlappingPositions(
        PoolId poolId,
        int24 tickBeforeSwap,
        int24 tickAfterSwap,
        bool zeroForOne,
        int24 tickSpacing
    ) internal view returns (int24[] memory) {

        uint256 absDiff = uint256(int256(abs(tickBeforeSwap - tickAfterSwap)));
        int24[] memory executableTicks = new int24[]((absDiff / uint256(int256(tickSpacing))) + 1);
        uint256 resultCount = 0;
        
        mapping(int16 => uint256) storage bitmap = zeroForOne ? 
            token1TickBitmap[poolId] : token0TickBitmap[poolId];
        
        mapping(int24 => bytes32) storage positionMap = zeroForOne ?
            token1PositionAtTick[poolId] : token0PositionAtTick[poolId];
        
        int24 tick = tickBeforeSwap;
        
        while (true) {
            if (zeroForOne ? tick <= tickAfterSwap : tick >= tickAfterSwap) {
                break;
            }
            
            (int24 nextInitializedTick, bool initialized) = TickBitmap.nextInitializedTickWithinOneWord(
                bitmap,
                tick,
                tickSpacing,
                zeroForOne
            );
            
            bool beyondBoundary = zeroForOne ? 
                nextInitializedTick <= tickAfterSwap : 
                nextInitializedTick > tickAfterSwap;
                
            if (beyondBoundary) {
                nextInitializedTick = tickAfterSwap;
                initialized = false; 
            }
            
            if (initialized) {
                if (positionMap[nextInitializedTick] != bytes32(0)) {
                    executableTicks[resultCount++] = nextInitializedTick;
                }

            }
            
            if (nextInitializedTick == tickAfterSwap) {
                break;
            }
            
            tick = zeroForOne ? 
                nextInitializedTick - 1 : 
                nextInitializedTick;
        }
        
        assembly {
            mstore(executableTicks, resultCount)
        }
        
        return executableTicks;
    }

    // Helper function to get absolute value
    function abs(int24 x) private pure returns (int24) {
        return x < 0 ? -x : x;
    }

// Position Management Functions

    /// @notice Updates or creates a user's position with new liquidity
    /// @param poolId The unique identifier for the Uniswap V4 pool
    /// @param positionKey The unique identifier for the position
    /// @param liquidity The amount of liquidity to add
    /// @param user The address of the position owner
    function _updateUserPosition(PoolId poolId, bytes32 positionKey, uint128 liquidity, address user) internal {
        PositionState storage posState = positionState[poolId][positionKey];
        UserPosition storage position = userPositions[poolId][positionKey][user];

        if(!positionContributors[poolId][positionKey].contains(user)) {
            position.claimablePrincipal = ZERO_DELTA;
            position.fees = ZERO_DELTA;
            positionContributors[poolId][positionKey].add(user);
            userPositionKeys[user][poolId].add(positionKey);
        } else {
            if (position.liquidity != 0) {
                BalanceDelta feeDelta = posState.feePerLiquidity - position.lastFeePerLiquidity;
                int128 liq = int128(position.liquidity);
                BalanceDelta pendingFees = PositionManagement.calculateScaledUserFee(feeDelta, uint128(liq));
                if (pendingFees != ZERO_DELTA)
                    position.fees = position.fees + pendingFees;
            }
            
        }
        position.lastFeePerLiquidity = posState.feePerLiquidity;
        position.liquidity += liquidity;
        posState.totalLiquidity += liquidity;
    }


    /// @notice Callback function for handling pool manager unlock operations
    /// @dev Called by the pool manager during operations that modify pool state
    /// @param data Encoded callback data containing operation type and parameters
    /// @return bytes Encoded response data based on the callback type
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        require(msg.sender == address(poolManager));
        UnlockCallbackData memory cbd = abi.decode(data, (UnlockCallbackData));
        CallbackType ct = cbd.callbackType;
        
        if(ct == CallbackType.CREATE_ORDERS) return callbackState.handleCreateOrdersCallback(abi.decode(cbd.data, (CreateOrdersCallbackData)));
        if(ct == CallbackType.CLAIM_ORDER) return callbackState.handleClaimOrderCallback(abi.decode(cbd.data, (ClaimOrderCallbackData)));
        if(ct == CallbackType.CANCEL_ORDER) return callbackState.handleCancelOrderCallback(abi.decode(cbd.data, (CancelOrderCallbackData)));
        return _handleKeeperExecuteCallback(cbd.data);
    }

    /// @notice Handles the execution of keeper-managed limit orders
    /// @param data Encoded KeeperExecuteCallbackData containing positions to execute
    /// @return bytes Encoded arrays of caller deltas and fee deltas from executions
    function _handleKeeperExecuteCallback(bytes memory data) internal returns (bytes memory) {
        KeeperExecuteCallbackData memory keeperData = abi.decode(data, (KeeperExecuteCallbackData));
        PoolId poolId = keeperData.key.toId();
        
        for(uint256 i = 0; i < keeperData.positions.length; i++) {
            bytes32 positionKey = keeperData.positions[i];
            
            if (!positionState[poolId][positionKey].isWaitingKeeper) continue;
            
            (int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(positionKey);
            int24 executableTick = isToken0 ? topTick : bottomTick;
            
            _executePosition(keeperData.key, poolId, positionKey, executableTick);
        }
        
        return new bytes(0);
    }


    /// @notice Updates the accumulated fees per liquidity for a position
    /// @param poolId The unique identifier of the pool containing the position
    /// @param positionKey The unique identifier of the position being updated
    /// @param feeDelta The change in fees to be distributed, containing both token0 and token1 amounts
    function _retrackPositionFee(
        PoolId poolId,
        bytes32 positionKey,
        BalanceDelta feeDelta
    ) internal {
        PositionState storage posState = positionState[poolId][positionKey];
        if (posState.totalLiquidity == 0) return;

        if(feeDelta == ZERO_DELTA) return;
        
        posState.feePerLiquidity = posState.feePerLiquidity + 
            PositionManagement.calculateScaledFeePerLiquidity(feeDelta, posState.totalLiquidity);
    }

    function _handleTokenTransfer(
        bool isToken0,
        uint256 amount,
        PoolKey memory key
    ) internal nonReentrant {
        if (isToken0) {
            if (key.currency0.isAddressZero()) {
                require(msg.value >= amount);
                
                if (msg.value > amount) {
                    (bool success, ) = msg.sender.call{value: msg.value - amount}("");
                    require(success);
                }
            } else {
                require(msg.value == 0);
                IERC20(Currency.unwrap(key.currency0)).safeTransferFrom(msg.sender, address(this), amount);
            }
        } else {
            require(msg.value == 0);
            IERC20(Currency.unwrap(key.currency1)).safeTransferFrom(msg.sender, address(this), amount);
        }
    }

// =========== Getter Functions ===========


    /// @notice Get positions for a user in a specific pool with pagination
    /// @param user The address of the user
    /// @param poolId The pool identifier
    /// @param offset Starting position index (optional, default 0)
    /// @param limit Maximum number of positions to return (optional, use 0 for all positions)
    /// @return positions Array of position information
    function getUserPositions(
        address user,
        PoolId poolId,
        uint256 offset,
        uint256 limit
    ) external view returns (PositionInfo[] memory positions) {
        EnumerableSet.Bytes32Set storage userKeys = userPositionKeys[user][poolId];
        uint256 totalLength = userKeys.length();
        
        if (limit == 0) {
            limit = totalLength;
        }
        
        if (offset >= totalLength) {
            return new PositionInfo[](0);
        }
        
        uint256 resultCount = (offset + limit > totalLength) ? 
            (totalLength - offset) : limit;
        
        positions = new PositionInfo[](resultCount);
        
        for(uint256 i = 0; i < resultCount; i++) {
            uint256 keyIndex = offset + i;
            bytes32 key = userKeys.at(keyIndex);
            UserPosition memory userPosition = userPositions[poolId][key][user];
            
            positions[i] = PositionInfo({
                liquidity: userPosition.liquidity,
                fees: userPosition.fees,
                positionKey: key
            });
        }
    }

    function getUserPositionCount(
        address user,
        PoolId poolId
    ) external view returns (uint256) {
        return userPositionKeys[user][poolId].length();
    }


// =========== Admin Functions ===========

    function setHook(address _hook) external onlyOwner {
        hook = _hook;
    }

    function setWhitelistedPool(PoolId poolId, bool isWhitelisted) external onlyOwner {
        whitelistedPool[poolId] = isWhitelisted;
    }
    
    function setKeeper(address _keeper, bool _isKeeper) external onlyOwner {
        isKeeper[_keeper] = _isKeeper;
    }
    
    /// @notice Sets the maximum number of positions that can be executed in a single transaction
    /// @param _limit The new maximum number of positions that can be executed at once
    function setExecutablePositionsLimit(uint256 _limit) external override onlyOwner {
        require(_limit > 0);
        executablePositionsLimit = _limit;
    }


    /// @notice Sets the minimum order amount for a specific currency
    /// @param currency The token address for which to set the minimum amount
    /// @param _minAmount The minimum amount of tokens required to create an order for this currency
    function setMinAmount(Currency currency, uint256 _minAmount) external override onlyOwner {
        minAmount[currency] = _minAmount;
    }

    /// @notice Sets the hook fee percentage
    /// @param _percentage New fee percentage (scaled by FEE_DENOMINATOR)
    function setHookFeePercentage(uint256 _percentage) external onlyOwner {
        require(_percentage < FEE_DENOMINATOR);
        hook_fee_percentage = _percentage;
        callbackState.hookFeePercentage = _percentage;  
    }

    /// @notice Sets the maximum number of orders that can be created at once
    /// @param _limit The new maximum number of orders allowed per pool
    function setMaxOrderLimit(uint24 _limit) external onlyOwner {
        require(_limit > 1);
        maxOrderLimit = _limit;
    }


    /// @notice Pauses contract functionality
    /// @dev Only callable by the contract owner
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Unpauses contract functionality
    /// @dev Only callable by the contract owner
    function unpause() external onlyOwner {
        _unpause();
    }


    /// @notice Executes positions that were previously marked for keeper execution due to position limit overflow
    /// @param key The Uniswap V4 pool identifier containing the positions
    /// @param waitingPositions Array of position keys previously marked for keeper execution
    function executeOrderByKeeper(
        PoolKey calldata key,
        bytes32[] memory waitingPositions
    ) external {
        require(isKeeper[msg.sender]);
        if (waitingPositions.length == 0) return;
        PoolId poolId = key.toId();
        (, int24 currentTick, ,) = StateLibrary.getSlot0(poolManager, poolId);
        
        // Identify executable positions
        uint256 executableCount = 0;

        for (uint256 i = 0; i < waitingPositions.length; i++) {
            bytes32 positionKey = waitingPositions[i];
            
            // Decode position key to get details
            (int24 bottomTick, int24 topTick, bool isToken0, ) = _decodePositionKey(positionKey);
            // int24 executableTick = isToken0 ? topTick : bottomTick;
            
            // Validate position
            bool isExecutable = isToken0 ? 
                currentTick >= topTick :
                currentTick < bottomTick;
            
            if (positionState[poolId][positionKey].isWaitingKeeper && isExecutable && positionState[poolId][positionKey].totalLiquidity > 0) {
                // Keep this position for execution
                waitingPositions[executableCount++] = positionKey;
            } else {
                // No longer needs keeper execution
                positionState[poolId][positionKey].isWaitingKeeper = false;
            }
        }
        
        // Resize array
        assembly {
            mstore(waitingPositions, executableCount)
        }
        
        // Execute the positions
        if (executableCount > 0) {
            poolManager.unlock(
                abi.encode(
                    UnlockCallbackData({
                        callbackType: CallbackType.KEEPER_EXECUTE_ORDERS,
                        data: abi.encode(
                            KeeperExecuteCallbackData({
                                key: key,
                                positions: waitingPositions
                            })
                        )
                    })
                )
            );
        }
    }
}

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

import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";

interface ILimitOrderManager {
    // =========== Structs ===========
    struct PositionTickRange {
        int24 bottomTick;
        int24 topTick;
        bool isToken0;
    }

    struct ClaimableTokens {
        Currency token;  
        uint256 principal;
        uint256 fees;
    }

    struct UserPosition {
        uint128 liquidity;                
        BalanceDelta lastFeePerLiquidity; 
        BalanceDelta claimablePrincipal;  
        BalanceDelta fees;                
    }

    struct PositionState {
        BalanceDelta feePerLiquidity;  
        uint128 totalLiquidity;        
        bool isActive;
        bool isWaitingKeeper;
        uint256 currentNonce;
    }

    struct PositionInfo {
        uint128 liquidity;
        BalanceDelta fees;
        bytes32 positionKey;
    }

    struct PositionBalances {
        uint256 principal0;
        uint256 principal1;
        uint256 fees0;
        uint256 fees1;
    }

    struct CreateOrderResult {
        uint256 usedAmount;
        bool isToken0;
        int24 bottomTick;
        int24 topTick;
    }

    struct ScaleOrderParams {
        bool isToken0;
        int24 bottomTick;
        int24 topTick;
        uint256 totalAmount;
        uint256 totalOrders;
        uint256 sizeSkew;
    }
    struct OrderInfo {
        int24 bottomTick;
        int24 topTick;
        uint256 amount;
        uint128 liquidity;
    }

    struct CreateOrdersCallbackData {
        PoolKey key;
        OrderInfo[] orders;
        bool isToken0;
        address orderCreator;
    }

    struct CancelOrderCallbackData {
        PoolKey key;
        int24 bottomTick;
        int24 topTick;
        uint128 liquidity;
        address user;
        bool isToken0;
    }

    struct ClaimOrderCallbackData {
        BalanceDelta principal;
        BalanceDelta fees;
        PoolKey key;
        address user;
    }

    struct KeeperExecuteCallbackData {
        PoolKey key;
        bytes32[] positions;
    }

    struct UnlockCallbackData {
        CallbackType callbackType;
        bytes data;
    }

    enum CallbackType {
        CREATE_ORDERS,
        // CREATE_ORDER,
        CLAIM_ORDER,
        CANCEL_ORDER,
        // CREATE_SCALE_ORDERS,
        KEEPER_EXECUTE_ORDERS
    }

    // =========== Errors ===========

    error FeePercentageTooHigh();
    error AmountTooLow();
    error AddressZero();
    error NotAuthorized();
    error PositionIsWaitingForKeeper();
    error ZeroLimit();
    error NotWhitelistedPool();
    error MinimumAmountNotMet(uint256 provided, uint256 minimum);
    error MaxOrdersExceeded();
    error UnknownCallbackType();

    // =========== Events ===========
    event OrderClaimed(address owner, PoolId indexed poolId, bytes32 positionKey, uint256 principal0, uint256 principal1, uint256 fees0, uint256 fees1, uint256 hookFeePercentage);
    event OrderCreated(address user, PoolId indexed poolId, bytes32 positionKey);
    event OrderCanceled(address orderOwner, PoolId indexed poolId, bytes32 positionKey);
    event OrderExecuted(PoolId indexed poolId, bytes32 positionKey);
    event PositionsLeftOver(PoolId indexed poolId, bytes32[] leftoverPositions);
    event KeeperWaitingStatusReset(bytes32 positionKey, int24 bottomTick, int24 topTick, int24 currentTick);
    event HookFeePercentageUpdated (uint256 percentage);

    // =========== Functions ===========
    function createLimitOrder(
        bool isToken0,
        int24 targetTick,
        uint256 amount,
        PoolKey calldata key
    ) external payable returns (CreateOrderResult memory);

    function createScaleOrders(
        bool isToken0,
        int24 bottomTick,
        int24 topTick,
        uint256 totalAmount,
        uint256 totalOrders,
        uint256 sizeSkew,
        PoolKey calldata key
    ) external payable returns (CreateOrderResult[] memory results);

    function setHook(address _hook) external;

    function setHookFeePercentage(uint256 _percentage) external;
    
    function executeOrder(
        PoolKey calldata key,
        int24 tickBeforeSwap,
        int24 tickAfterSwap,
        bool zeroForOne
    ) external;

    function cancelOrder(PoolKey calldata key, bytes32 positionKey) external;

    function positionState(PoolId poolId, bytes32 positionKey) 
        external 
        view 
        returns (
            BalanceDelta feePerLiquidity,
            uint128 totalLiquidity,
            bool isActive,
            bool isWaitingKeeper,
            uint256 currentNonce
        );

    function cancelBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external;

    /// @notice Emergency function for keepers to cancel orders on behalf of users
    /// @dev Only callable by keepers to handle emergency situations
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to cancel
    /// @param user The address of the user whose orders to cancel
    function emergencyCancelOrders(
        PoolKey calldata key,
        bytes32[] calldata positionKeys,
        address user
    ) external;

    /// @notice Keeper function to claim positions on behalf of users
    /// @dev Only callable by keepers to help users claim their executed positions
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to claim
    /// @param user The address of the user whose positions to claim
    function keeperClaimPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys,
        address user
    ) external;

    function claimOrder(PoolKey calldata key, bytes32 positionKey) external;

    /// @notice Claims multiple positions using direct position keys
    /// @dev This is more robust than using indices as position keys don't shift when other positions are removed
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to claim
    function claimPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external;

    /// @notice Cancels multiple positions using direct position keys
    /// @dev This is more robust than using indices as position keys don't shift when other positions are removed
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param positionKeys Array of position keys to cancel
    function cancelPositionKeys(
        PoolKey calldata key,
        bytes32[] calldata positionKeys
    ) external;

    /// @notice Batch claims multiple orders that were executed or canceled
    /// @dev Uses pagination to handle large numbers of orders
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param offset Starting position in the user's position array
    /// @param limit Maximum number of positions to process in this call
    function claimBatchOrders(
        PoolKey calldata key,
        uint256 offset,             
        uint256 limit
    ) external;

    function executeOrderByKeeper(PoolKey calldata key, bytes32[] memory waitingPositions) external;
    function setKeeper(address _keeper, bool _isKeeper) external;
    function setExecutablePositionsLimit(uint256 _limit) external;
    function setMinAmount(Currency currency, uint256 _minAmount) external;

    // View functions
    function getUserPositions(address user, PoolId poolId, uint256 offset, uint256 limit) external view returns (PositionInfo[] memory positions);



    // Additional view functions for state variables
    function currentNonce(PoolId poolId, bytes32 baseKey) external view returns (uint256);
    function treasury() external view returns (address);
    function executablePositionsLimit() external view returns (uint256);
    function isKeeper(address) external view returns (bool);
    function minAmount(Currency currency) external view returns (uint256);

    function getUserPositionCount(address user, PoolId poolId) external view returns (uint256);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

using PoolIdLibrary for PoolKey global;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type PoolId is bytes32;

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

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

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 {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

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

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

    // feeGrowthGlobal1X128 offset in Pool.State = 2

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

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

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

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

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

        bytes32 data = manager.extsload(stateSlot);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 price = uint256(sqrtPriceX96) << 32;

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

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

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

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

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

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

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

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

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

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: 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
// 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) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {BalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {ILimitOrderManager} from "./ILimitOrderManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {LiquidityAmounts} from "@uniswap/v4-core/test/utils/LiquidityAmounts.sol";
import {BalanceDelta, toBalanceDelta} from "v4-core/types/BalanceDelta.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {TickBitmap} from "v4-core/libraries/TickBitmap.sol";
import {BitMath} from "v4-core/libraries/BitMath.sol";
import "forge-std/console.sol";


library PositionManagement {
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using BalanceDeltaLibrary for BalanceDelta;

    uint256 internal constant Q128 = 1 << 128;

    // ==== Errors ====
    error InvalidSizeSkew();
    error MinimumAmountNotMet(uint256 provided, uint256 minimum);
    error MaxOrdersExceeded();
    error InvalidTickRange();
    error MinimumTwoOrders();
    error InvalidScaleParameters();
    
    /// @notice Calculates distribution of amounts and corresponding liquidity across scale orders
    /// @param orders Array of OrderInfo structs with tick ranges defined
    /// @param isToken0 True if orders are for token0, false for token1
    /// @param totalAmount Total amount of tokens to distribute across orders
    /// @param totalOrders Number of orders to create
    /// @param sizeSkew Factor determining the distribution of amounts (scaled by 1e18)
    /// @return ILimitOrderManager.OrderInfo[] Updated orders array with amounts and liquidity calculated
    function calculateOrderSizes(
        ILimitOrderManager.OrderInfo[] memory orders,
        bool isToken0,
        uint256 totalAmount,
        uint256 totalOrders,
        uint256 sizeSkew
    ) public pure returns (ILimitOrderManager.OrderInfo[] memory) {
        uint256 totalAmountUsed;
        
        for (uint256 i = 0; i < totalOrders; i++) {
            uint256 orderAmount;
            if (i == totalOrders - 1) {
                orderAmount = totalAmount - totalAmountUsed;
            } else {
                orderAmount = _calculateOrderSize(
                    totalAmount,
                    totalOrders,
                    sizeSkew,
                    i + 1
                );
                totalAmountUsed += orderAmount;
            }
            orders[i].amount = orderAmount;

            // Calculate liquidity
            uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(orders[i].bottomTick);
            uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(orders[i].topTick);
            
            orders[i].liquidity = isToken0 
                ? LiquidityAmounts.getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, orderAmount)
                : LiquidityAmounts.getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, orderAmount);
        }

        return orders;
    }


    /// @notice Validates the sizes of scale orders against minimum and maximum constraints
    /// @param orders Array of scale orders to validate
    /// @param totalAmount Total amount allocated for all orders
    /// @param minRequired Minimum amount required for each order
    function validateScaleOrderSizes(
        ILimitOrderManager.OrderInfo[] memory orders,
        uint256 totalAmount,
        uint256 minRequired
    ) public pure returns (bool) {
        // if (orders.length == 0) return false;
        
        // Check first and last order sizes
        if (orders[0].amount < minRequired) {
            revert MinimumAmountNotMet(orders[0].amount, minRequired);
        }
        if (orders[orders.length - 1].amount < minRequired) {
            revert MinimumAmountNotMet(orders[orders.length - 1].amount, minRequired);
        }
        
        // Verify total amount bounds
        return orders[0].amount <= totalAmount && 
               orders[orders.length - 1].amount <= totalAmount;
    }

    /// @notice Internal function to calculate the size of a specific order in a scale order series
    /// @param totalSize Total amount of tokens to distribute
    /// @param numOrders Number of orders in the series
    /// @param sizeSkew Skew factor (scaled by 1e18, where 1e18 = no skew)
    /// @param orderIndex Position of order in series (1-based index)
    /// @return uint256 Calculated size for the specified order
    function _calculateOrderSize(
        uint256 totalSize,
        uint256 numOrders,
        uint256 sizeSkew,  // scaled by 1e18
        uint256 orderIndex // 1-based index
    ) public pure returns (uint256) {
        if (orderIndex == 0 || orderIndex > numOrders) revert InvalidScaleParameters();
        

        uint256 numerator1 = 2 * totalSize;
        uint256 denominator1 = numOrders * (1e18 + sizeSkew);
        uint256 basePart = FullMath.mulDiv(numerator1, 1e18, denominator1);
        
        

        uint256 kMinusOne = sizeSkew >= 1e18 ? sizeSkew - 1e18 : 1e18 - sizeSkew;
        uint256 indexRatio = FullMath.mulDiv(orderIndex - 1, 1e18, numOrders - 1);
        uint256 skewComponent = FullMath.mulDiv(kMinusOne, indexRatio, 1e18);
        uint256 multiplier = sizeSkew >= 1e18 ? 
            1e18 + skewComponent : 
            1e18 - skewComponent;
        return FullMath.mulDiv(basePart, multiplier, 1e18);
    }


    struct PositionParams {
        ILimitOrderManager.UserPosition position;
        ILimitOrderManager.PositionState posState;
        IPoolManager poolManager;
        PoolId poolId;
        int24 bottomTick;
        int24 topTick;
        bool isToken0;
        uint256 feeDenom;
        uint256 hookFeePercentage;
    }

    /// @notice Calculates the token balances and fees for a limit order position
    /// @param params See PositionParams above
    /// @return balances 
    function getPositionBalances(
        PositionParams memory params
    ) public view returns (ILimitOrderManager.PositionBalances memory balances) {
        uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(params.bottomTick);
        uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(params.topTick);

        // Calculate principals
        if (!params.posState.isActive) {
            if (params.isToken0) {
                balances.principal1 = LiquidityAmounts.getAmount1ForLiquidity(sqrtPriceAX96, sqrtPriceBX96, params.position.liquidity );
            } else {
                balances.principal0 = LiquidityAmounts.getAmount0ForLiquidity( sqrtPriceAX96,sqrtPriceBX96, params.position.liquidity );
            }
        } else {
            (uint160 sqrtPriceX96, , , ) = StateLibrary.getSlot0(params.poolManager, params.poolId);
            (balances.principal0, balances.principal1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtPriceAX96, sqrtPriceBX96, params.position.liquidity );
        }

        BalanceDelta fees;        
        if(params.posState.isActive) {
            (uint256 fee0Global, uint256 fee1Global) = calculatePositionFee(params.poolId, params.bottomTick, params.topTick, params.poolManager);
            fees = getUserProportionateFees(params.position, params.posState, fee0Global, fee1Global);
        } else {

            fees = params.position.fees;
            if (params.position.liquidity != 0) {
                BalanceDelta feeDiff = params.posState.feePerLiquidity - params.position.lastFeePerLiquidity;
                int128 liq = int128(params.position.liquidity);
                fees = params.position.fees + toBalanceDelta(
                    feeDiff.amount0() >= 0 
                        ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(uint128(liq)), 1e18)))
                        : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(uint128(liq)), 1e18))),
                    feeDiff.amount1() >= 0 
                        ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(uint128(liq)), 1e18)))
                        : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(uint128(liq)), 1e18)))
                );
            }
        }

        int128 fees0 = fees.amount0();
        int128 fees1 = fees.amount1();
        
        if(fees0 > 0) {
            balances.fees0 = (uint256(uint128(fees0)) * (params.feeDenom - params.hookFeePercentage)) / params.feeDenom;
        }
        if(fees1 > 0) {
            balances.fees1 = (uint256(uint128(fees1)) * (params.feeDenom - params.hookFeePercentage)) / params.feeDenom;
        }
    }

    /// @notice Calculates a user's proportionate share of accumulated fees
    /// @param position User's position data
    /// @param posState Position state
    /// @param globalFees0 Global fees for token0
    /// @param globalFees1 Global fees for token1
    /// @return BalanceDelta User's proportionate share of accumulated fees
    function getUserProportionateFees(
        ILimitOrderManager.UserPosition memory position,
        ILimitOrderManager.PositionState memory posState,
        uint256 globalFees0,
        uint256 globalFees1
    ) public pure returns (BalanceDelta) {
        if (position.liquidity == 0) return position.fees;
        if (posState.totalLiquidity == 0) return position.fees;

        int128 feePerLiq0 = int128(int256(FullMath.mulDiv(uint256(globalFees0), uint256(1e18), uint256(posState.totalLiquidity))));
        int128 feePerLiq1 = int128(int256(FullMath.mulDiv(uint256(globalFees1), uint256(1e18), uint256(posState.totalLiquidity))));
        
        BalanceDelta newTotalFeePerLiquidity = posState.feePerLiquidity + toBalanceDelta(feePerLiq0, feePerLiq1);
        BalanceDelta feeDiff = newTotalFeePerLiquidity - position.lastFeePerLiquidity;
        
        int128 userFee0 = feeDiff.amount0() >= 0
            ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(position.liquidity), uint256(1e18))))
            : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(position.liquidity), uint256(1e18))));
        int128 userFee1 = feeDiff.amount1() >= 0
            ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(position.liquidity), uint256(1e18))))
            : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(position.liquidity), uint256(1e18))));
        
        return position.fees + toBalanceDelta(userFee0, userFee1);
    }


    // Add position to tick-based storage using TickBitmap library
    function addPositionToTick(
        mapping(PoolId => mapping(int24 => bytes32)) storage positionAtTick,
        mapping(PoolId => mapping(int16 => uint256)) storage tickBitmap,
        PoolKey memory key,
        int24 executableTick,
        bytes32 positionKey
    ) internal {
        PoolId poolId = key.toId();
        
        int24 compressedTick = TickBitmap.compress(executableTick, key.tickSpacing);
        
        positionAtTick[poolId][executableTick] = positionKey;
        
        (int16 wordPos, uint8 bitPos) = TickBitmap.position(compressedTick);
        
        uint256 mask = 1 << bitPos;
        tickBitmap[poolId][wordPos] |= mask;
    }


    function removePositionFromTick(
        mapping(PoolId => mapping(int24 => bytes32)) storage positionAtTick,
        mapping(PoolId => mapping(int16 => uint256)) storage tickBitmap,
        PoolKey memory key,
        int24 executableTick
    ) internal {
        PoolId poolId = key.toId();
        
        int24 compressedTick = TickBitmap.compress(executableTick, key.tickSpacing);
        (int16 wordPos, uint8 bitPos) = TickBitmap.position(compressedTick);
        
        uint256 mask = ~(1 << bitPos);
        tickBitmap[poolId][wordPos] &= mask;
        
        positionAtTick[poolId][executableTick] = bytes32(0);
    }



    function calculatePositionFee(
        PoolId poolId,
        int24 bottomTick,
        int24 topTick,
        IPoolManager poolManager
    ) public view returns (uint256 fee0, uint256 fee1) {
        (uint128 liquidityBefore, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) = 
            StateLibrary.getPositionInfo(
                poolManager,
                poolId,
                address(this),
                bottomTick,
                topTick,
                bytes32(0) // salt
            );

        (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = StateLibrary.getFeeGrowthInside(
            poolManager,
            poolId,
            bottomTick,
            topTick
        );

        uint256 feeGrowthDelta0 = 0;
        uint256 feeGrowthDelta1 = 0;

        unchecked {
            if (feeGrowthInside0X128 != feeGrowthInside0LastX128) {
                feeGrowthDelta0 = feeGrowthInside0X128 - feeGrowthInside0LastX128;
            }
            if (feeGrowthInside1X128 != feeGrowthInside1LastX128) {
                feeGrowthDelta1 = feeGrowthInside1X128 - feeGrowthInside1LastX128;
            }
            fee0 = FullMath.mulDiv(feeGrowthDelta0, liquidityBefore, Q128);
            fee1 = FullMath.mulDiv(feeGrowthDelta1, liquidityBefore, Q128); 
        }

        return (fee0, fee1);
    }

    /// @notice Decodes a position key into its component parts
    /// @param positionKey The bytes32 key to decode
    /// @return bottomTick The lower tick boundary
    /// @return topTick The upper tick boundary
    /// @return isToken0 Whether the position is for token0
    /// @return nonce The nonce value used in the key
    function decodePositionKey(
        bytes32 positionKey
    ) public pure returns (
        int24 bottomTick,
        int24 topTick,
        bool isToken0,
        uint256 nonce
    ) {
        bottomTick = int24(uint24(uint256(positionKey) >> 232));
        topTick = int24(uint24(uint256(positionKey) >> 208));
        nonce = uint256(positionKey >> 8) & ((1 << 200) - 1);
        isToken0 = uint256(positionKey) & 1 == 1;
    }

    /// @notice Calculates the balance delta for a position based on its key
    /// @param positionKey The unique identifier of the position
    /// @param liquidity The position's liquidity amount
    /// @return BalanceDelta The calculated balance delta
    function getBalanceDelta(
        bytes32 positionKey,
        uint128 liquidity
    ) public pure returns (BalanceDelta) {
        (int24 bottomTick, int24 topTick, bool isToken0,) = decodePositionKey(positionKey);
        
        uint160 sqrtPriceAX96 = TickMath.getSqrtPriceAtTick(bottomTick);
        uint160 sqrtPriceBX96 = TickMath.getSqrtPriceAtTick(topTick);
        
        if (isToken0) {
            // Position was in token0, executed at topTick, got token1
            uint256 amount = LiquidityAmounts.getAmount1ForLiquidity(
                sqrtPriceAX96,
                sqrtPriceBX96,
                liquidity
            );
            return toBalanceDelta(0, int128(int256(amount)));
        } else {
            // Position was in token1, executed at bottomTick, got token0
            uint256 amount = LiquidityAmounts.getAmount0ForLiquidity(
                sqrtPriceAX96,
                sqrtPriceBX96,
                liquidity
            );
            return toBalanceDelta(int128(int256(amount)), 0);
        }
    }
    


    /// @notice Generates unique keys for position identification
    /// @return baseKey Key without nonce for tracking position versions
    /// @return positionKey Unique key including nonce for this specific position
    function getPositionKeys(
        mapping(PoolId => mapping(bytes32 => uint256)) storage currentNonce,
        PoolId poolId,
        int24 bottomTick, 
        int24 topTick,
        bool isToken0
    ) internal view returns (bytes32 baseKey, bytes32 positionKey) {
        // Generate base key combining bottomTick, topTick, and isToken0
        baseKey = bytes32(
            uint256(uint24(bottomTick)) << 232 |
            uint256(uint24(topTick)) << 208 |
            uint256(isToken0 ? 1 : 0)
        );
        
        // Generate full position key with nonce
        positionKey = bytes32(
            uint256(uint24(bottomTick)) << 232 |
            uint256(uint24(topTick)) << 208 |
            uint256(currentNonce[poolId][baseKey]) << 8 |
            uint256(isToken0 ? 1 : 0)
        );
    }    

    function calculateScaledFeePerLiquidity(
        BalanceDelta feeDelta, 
        uint128 liquidity
    ) public pure returns (BalanceDelta) {
        if(feeDelta == BalanceDelta.wrap(0) || liquidity == 0) return BalanceDelta.wrap(0);
        
        return toBalanceDelta(
            feeDelta.amount0() >= 0 
                ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDelta.amount0())), 1e18, liquidity)))
                : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDelta.amount0())), 1e18, liquidity))),
            feeDelta.amount1() >= 0 
                ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDelta.amount1())), 1e18, liquidity)))
                : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDelta.amount1())), 1e18, liquidity)))
        );
    }

    function calculateScaledUserFee(
        BalanceDelta feeDiff, 
        uint128 liquidity
    ) public pure returns (BalanceDelta) {
        if(feeDiff == BalanceDelta.wrap(0) || liquidity == 0) return BalanceDelta.wrap(0);
        
        return toBalanceDelta(
            feeDiff.amount0() >= 0 
                ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount0())), uint256(liquidity), 1e18)))
                : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount0())), uint256(liquidity), 1e18))),
            feeDiff.amount1() >= 0 
                ? int128(int256(FullMath.mulDiv(uint256(uint128(feeDiff.amount1())), uint256(liquidity), 1e18)))
                : -int128(int256(FullMath.mulDiv(uint256(uint128(-feeDiff.amount1())), uint256(liquidity), 1e18)))
        );
    }
}

// SPDX-License-Identifier: BSL
pragma solidity ^0.8.24;
import {PoolKey} from "v4-core/types/PoolKey.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 {ILimitOrderManager} from "./ILimitOrderManager.sol";

library TickLibrary {
    error WrongTargetTick(int24 currentTick, int24 targetTick, bool isToken0);
    error BottomTickMustBeGreaterThanCurrentTick(int24 currentTick, int24 bottomTick, bool isToken0);
    error TopTickMustBeLessThanOrEqualToCurrentTick(int24 currentTick, int24 topTick, bool isToken0);
    error RoundedTicksTooClose(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick, bool isToken0);
    error RoundedTargetTickLessThanRoundedCurrentTick(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick);
    error RoundedTargetTickGreaterThanRoundedCurrentTick(int24 currentTick, int24 roundedCurrentTick, int24 targetTick, int24 roundedTargetTick);
    error WrongTickRange(int24 bottomTick, int24 topTick, int24 currentTick, int24 targetTick, bool isToken0, bool isRange);
    error SingleTickWrongTickRange(int24 bottomTick, int24 topTick, int24 currentTick, int24 targetTick, bool isToken0);
    error TickOutOfBounds(int24 tick);
    error InvalidPrice(uint256 price);
    error PriceMustBeGreaterThanZero();
    error InvalidSizeSkew();
    error MaxOrdersExceeded();
    error InvalidTickRange();
    error MinimumTwoOrders();

    uint256 internal constant Q128 = 1 << 128;

    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (TickMath.MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (TickMath.MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    function getRoundedTargetTick(
        int24 targetTick,
        bool isToken0,
        int24 tickSpacing
    ) internal pure returns(int24 roundedTargetTick) {
        if (isToken0) {
            roundedTargetTick = targetTick >= 0 ? 
                (targetTick / tickSpacing) * tickSpacing :
                ((targetTick % tickSpacing == 0) ? targetTick : ((targetTick / tickSpacing) - 1) * tickSpacing);
        } else {
            roundedTargetTick = targetTick < 0 ?
                (targetTick / tickSpacing) * tickSpacing :
                ((targetTick % tickSpacing == 0) ? targetTick : ((targetTick / tickSpacing) + 1) * tickSpacing);
        }
    }

    function getRoundedCurrentTick(
        int24 currentTick,
        bool isToken0,
        int24 tickSpacing
    ) internal pure returns(int24 roundedCurrentTick) {
        if (isToken0) {
            roundedCurrentTick = currentTick >= 0 ? 
                (currentTick / tickSpacing) * tickSpacing + tickSpacing :
                ((currentTick % tickSpacing == 0) ? currentTick + tickSpacing : (currentTick / tickSpacing) * tickSpacing);
        } else {
            roundedCurrentTick = currentTick >= 0 ?
                (currentTick / tickSpacing) * tickSpacing :
                ((currentTick % tickSpacing == 0) ? currentTick : (currentTick / tickSpacing) * tickSpacing - tickSpacing);
        }
    }
    
    /// @notice Validates and calculates the appropriate tick range for a single-tick limit order
    /// @param currentTick The current market tick price
    /// @param targetTick The target tick price for the order
    /// @param tickSpacing The minimum tick spacing for the pool
    /// @param isToken0 True if order is for token0, false for token1
    /// @return bottomTick The calculated lower tick boundary
    /// @return topTick The calculated upper tick boundary
    function getValidTickRange(
        int24 currentTick,
        int24 targetTick,
        int24 tickSpacing,
        bool isToken0
    ) public pure returns (int24 bottomTick, int24 topTick) {
        if(isToken0 && currentTick >= targetTick)
            revert WrongTargetTick(currentTick, targetTick, true);
        if(!isToken0 && currentTick <= targetTick)
            revert WrongTargetTick(currentTick, targetTick, false);

        int24 roundedTargetTick = getRoundedTargetTick(targetTick, isToken0, tickSpacing);
        int24 roundedCurrentTick = getRoundedCurrentTick(currentTick, isToken0, tickSpacing);

        int24 tickDiff = roundedCurrentTick > roundedTargetTick ?
                        roundedCurrentTick - roundedTargetTick :
                        roundedTargetTick - roundedCurrentTick;
                        
        if(tickDiff < tickSpacing)
            revert RoundedTicksTooClose(currentTick, roundedCurrentTick, targetTick, roundedTargetTick, isToken0);

        if(isToken0) {
            if(roundedCurrentTick >= roundedTargetTick)
                revert RoundedTargetTickLessThanRoundedCurrentTick(currentTick, roundedCurrentTick, targetTick, roundedTargetTick);
            topTick = roundedTargetTick;
            bottomTick = topTick - tickSpacing;
        } else {
            if(roundedCurrentTick <= roundedTargetTick)
                revert RoundedTargetTickGreaterThanRoundedCurrentTick(currentTick, roundedCurrentTick, targetTick, roundedTargetTick);
            bottomTick = roundedTargetTick;
            topTick = bottomTick + tickSpacing;
        }

        if(bottomTick >= topTick)
            revert SingleTickWrongTickRange(bottomTick, topTick, currentTick, targetTick, isToken0);
        
        if (bottomTick < minUsableTick(tickSpacing) || topTick > maxUsableTick(tickSpacing)) 
            revert TickOutOfBounds(targetTick);
    }

    function validateAndPrepareScaleOrders(
        int24 bottomTick,
        int24 topTick,
        int24 currentTick,
        bool isToken0,
        uint256 totalOrders,
        uint256 sizeSkew,
        int24 tickSpacing
    ) public pure returns (ILimitOrderManager.OrderInfo[] memory orders) {
        if (totalOrders < 2) revert MinimumTwoOrders();
        if (bottomTick >= topTick) revert InvalidTickRange();
        if (sizeSkew == 0) revert InvalidSizeSkew();


        if(isToken0 && currentTick >= bottomTick)
            revert BottomTickMustBeGreaterThanCurrentTick(currentTick, bottomTick, true);
        if(!isToken0 && currentTick < topTick)
            revert TopTickMustBeLessThanOrEqualToCurrentTick(currentTick, topTick, false);
        
        // Validate and round ticks 
        if (isToken0) {
            // Rounded bottom tick is always greater or equal to original bottom tick
            bottomTick = bottomTick % tickSpacing == 0 ? bottomTick :
                        bottomTick > 0 ? (bottomTick / tickSpacing + 1) * tickSpacing :
                        (bottomTick / tickSpacing) * tickSpacing;
            topTick = getRoundedTargetTick(topTick, isToken0, tickSpacing);
            require(topTick > bottomTick, "Rounded top tick must be above rounded bottom tick for token0 orders");
        } else {
            // Rounded top tick is always less or equal to original top tick
            topTick = topTick % tickSpacing == 0 ? topTick :
                    topTick > 0 ? (topTick / tickSpacing) * tickSpacing :
                    (topTick / tickSpacing - 1) * tickSpacing;
            bottomTick = getRoundedTargetTick(bottomTick, isToken0, tickSpacing);
            require(bottomTick < topTick, "Rounded bottom tick must be below rounded top tick for token1 orders");
        }

        if (bottomTick < minUsableTick(tickSpacing) || topTick > maxUsableTick(tickSpacing)) 
            revert TickOutOfBounds(bottomTick < minUsableTick(tickSpacing) ? bottomTick : topTick);

        // Check if enough space for orders
        // Handle uint256 to uint24 conversion safely for totalOrders
        if (totalOrders > uint256(uint24((topTick - bottomTick) / tickSpacing)))
            revert MaxOrdersExceeded();

        // Initialize orders array
        orders = new ILimitOrderManager.OrderInfo[](totalOrders);

        // Calculate positions with improved distribution
        int24 effectiveRange = topTick - bottomTick - tickSpacing;
        
        if (isToken0) {
            for (uint256 i = 0; i < totalOrders; i++) {
                // Calculate position
                int24 orderBottomTick;
                if (i == totalOrders - 1) {
                    // Last order approaches max
                    orderBottomTick = topTick - tickSpacing;
                } else {
                    // Proportionally distribute
                    orderBottomTick = bottomTick + int24(uint24((i * uint256(uint24(effectiveRange))) / (totalOrders - 1)));
                    orderBottomTick = orderBottomTick % tickSpacing == 0 ?
                                    orderBottomTick :
                                    orderBottomTick >= 0 ?
                                        orderBottomTick / tickSpacing * tickSpacing + tickSpacing :
                                        orderBottomTick / tickSpacing * tickSpacing;
                }
                
                
                orders[i] = ILimitOrderManager.OrderInfo({
                    bottomTick: orderBottomTick,
                    topTick: orderBottomTick + tickSpacing,
                    amount: 0,
                    liquidity: 0
                });
            }
        } else {
            for (uint256 i = 0; i < totalOrders; i++) {
                // Calculate position
                int24 orderBottomTick;
                if (i == 0) {
                    // First order uses min
                    orderBottomTick = bottomTick;
                } else {
                    // Proportionally distribute
                    orderBottomTick = bottomTick + int24(uint24((i * uint256(uint24(effectiveRange))) / (totalOrders - 1)));
                    orderBottomTick = orderBottomTick % tickSpacing == 0 ?
                                    orderBottomTick :
                                    orderBottomTick >= 0 ?
                                        orderBottomTick / tickSpacing * tickSpacing + tickSpacing :
                                        orderBottomTick / tickSpacing * tickSpacing;
                }
                
                int24 orderTopTick = orderBottomTick + tickSpacing;

                
                orders[i] = ILimitOrderManager.OrderInfo({
                    bottomTick: orderBottomTick,
                    topTick: orderTopTick,
                    amount: 0,
                    liquidity: 0
                });
            }
        }
        
        return orders;
    }

    function getRoundedPrice(
        uint256 price,  //always expressed as token0/token1 price
        PoolKey calldata key,
        bool isToken0
    ) public pure returns (uint256 roundedPrice) {
        // Convert price to sqrtPriceX96
        uint160 targetSqrtPriceX96 = getSqrtPriceFromPrice(price);
        
        // Get raw tick from sqrt price
        int24 rawTargetTick = TickMath.getTickAtSqrtPrice(targetSqrtPriceX96);
        
        // Round the tick according to token direction and spacing
        int24 roundedTargetTick = getRoundedTargetTick(rawTargetTick, isToken0, key.tickSpacing);
        
        // Validate the rounded tick is within bounds
        if (roundedTargetTick < minUsableTick(key.tickSpacing) || 
            roundedTargetTick > maxUsableTick(key.tickSpacing)) {
            revert TickOutOfBounds(roundedTargetTick);
        }
        
        // Get the sqrtPriceX96 at the rounded tick
        uint160 roundedSqrtPriceX96 = TickMath.getSqrtPriceAtTick(roundedTargetTick);
        
        // Convert back to regular price
        roundedPrice = getPriceFromSqrtPrice(roundedSqrtPriceX96);
        
        return roundedPrice;
    }

    function getSqrtPriceFromPrice(uint256 price) public pure returns (uint160) {
        if (price == 0) revert PriceMustBeGreaterThanZero();
        
        // price = token1/token0
        // Convert price to Q96 format first
        uint256 priceQ96 = FullMath.mulDiv(price, FixedPoint96.Q96, 1 ether); // Since input price is in 1e18 format
    
        // Take square root using our sqrt function
        uint256 sqrtPriceX96 = sqrt(priceQ96) << 48;
        
        if (sqrtPriceX96 > type(uint160).max) revert InvalidPrice(price);
        
        return uint160(sqrtPriceX96);
    }

    function getPriceFromSqrtPrice(uint160 sqrtPriceX96) public pure returns (uint256) {
        // Square the sqrt price to get the price in Q96 format
        uint256 priceQ96 = FullMath.mulDiv(uint256(sqrtPriceX96), uint256(sqrtPriceX96), 1 << 96);
        
        // Convert from Q96 to regular price (1e18 format)
        return FullMath.mulDiv(priceQ96, 1 ether, FixedPoint96.Q96);
    }

    function sqrt(uint256 x) public pure returns (uint256 y) {
        uint256 z = (x + 1) / 2;
        y = x;
        while (z < y) {
            y = z;
            z = (x / z + z) / 2;
        }
    }
}

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {ILimitOrderManager} from "./ILimitOrderManager.sol";
import {Currency, CurrencyLibrary} from "v4-core/types/Currency.sol";
import {CurrencySettler} from "./CurrencySettler.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {ModifyLiquidityParams} from "v4-core/types/PoolOperation.sol";

library CallbackHandler {
    using CurrencySettler for Currency;
    using BalanceDeltaLibrary for BalanceDelta;
    using PoolIdLibrary for PoolKey;
    using SafeERC20 for IERC20;
    using TransientStateLibrary for IPoolManager;

    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    event FailedTransferSentToTreasury(Currency currency, address originalRecipient, uint256 amount);

    struct CallbackState {
        IPoolManager poolManager;
        address treasury;
        uint256 hookFeePercentage;
        uint256 feeDenominator;
    }

    /// @notice Handles the callback for claiming order proceeds and fees
    /// @param state The callback state containing pool manager and fee settings
    /// @param claimData Struct containing claim details including principal, fees, and user address
    /// @return bytes Encoded return value (always 0 for claim callbacks)
    function handleClaimOrderCallback(
        CallbackState storage state,
        ILimitOrderManager.ClaimOrderCallbackData memory claimData
    ) internal returns (bytes memory) {

        _handleTokenTransfersAndFees(
            state,
            uint256(uint128(claimData.principal.amount0())),
            uint256(uint128(claimData.fees.amount0())),
            claimData.key.currency0,
            claimData.user
        );

        _handleTokenTransfersAndFees(
            state,
            uint256(uint128(claimData.principal.amount1())),
            uint256(uint128(claimData.fees.amount1())),
            claimData.key.currency1,
            claimData.user
        );

        _clearExactDelta(state, claimData.key.currency0);
        _clearExactDelta(state, claimData.key.currency1);

        return abi.encode(0);
    }

    /// @notice Handles the callback for canceling a limit order
    /// @param state The callback state containing pool manager reference
    /// @param cancelData Struct containing order details needed for cancellation (ticks, liquidity)
    /// @return bytes ABI encoded balance deltas
    function handleCancelOrderCallback(
        CallbackState storage state,
        ILimitOrderManager.CancelOrderCallbackData memory cancelData
    ) internal returns (bytes memory) {
        (BalanceDelta callerDelta, BalanceDelta feeDelta) = _burnLimitOrder(
            state,
            cancelData.key,
            cancelData.bottomTick,
            cancelData.topTick,
            cancelData.liquidity,
            cancelData.isToken0
        );

        // Clear any remaining dust amounts
        _clearExactDelta(state, cancelData.key.currency0);
        _clearExactDelta(state, cancelData.key.currency1);

        return abi.encode(callerDelta, feeDelta);
    }

    /// @notice Burns liquidity for a limit order and mints corresponding tokens to the LimitOrderManager
    /// @param state The callback state containing pool manager reference
    /// @param key The pool key identifying the specific Uniswap V4 pool
    /// @param bottomTick The lower tick boundary of the position
    /// @param topTick The upper tick boundary of the position
    /// @param liquidity The amount of liquidity to burn
    /// @param isToken0 Whether the position is for token0 or token1
    /// @return callerDelta The net balance changes for the position owner
    /// @return feeDelta The accumulated fees for the position
    function _burnLimitOrder(
        CallbackState storage state,
        PoolKey memory key,
        int24 bottomTick,
        int24 topTick,
        uint128 liquidity,
        bool isToken0
    ) internal returns (BalanceDelta callerDelta, BalanceDelta feeDelta) {
        (callerDelta, feeDelta) = state.poolManager.modifyLiquidity(
            key,
            ModifyLiquidityParams({
                tickLower: bottomTick,
                tickUpper: topTick,
                liquidityDelta: -int128(liquidity),
                salt: bytes32(uint256(isToken0 ? 0 : 1))
            }),
            ""
        );

        int128 delta0 = callerDelta.amount0();
        int128 delta1 = callerDelta.amount1();
        
        if (delta0 > 0) {
            state.poolManager.mint(
                address(this), 
                uint256(uint160(Currency.unwrap(key.currency0))), 
                uint256(int256(delta0))
            );
        }
        
        if (delta1 > 0) {
            state.poolManager.mint(
                address(this), 
                uint256(uint160(Currency.unwrap(key.currency1))), 
                uint256(int256(delta1))
            );
        }
    }

    /// @notice Handles the callback for creating one or more limit orders
    /// @param state The callback state containing pool manager and fee settings
    /// @param callbackData Struct containing order details
    /// @return bytes ABI encoded arrays of balance deltas
    function handleCreateOrdersCallback(
        CallbackState storage state,
        ILimitOrderManager.CreateOrdersCallbackData memory callbackData
    ) internal returns(bytes memory) {
        // BalanceDelta[] memory deltas = new BalanceDelta[](callbackData.orders.length);
        BalanceDelta[] memory feeDeltas = new BalanceDelta[](callbackData.orders.length);
        BalanceDelta accumulatedMintFees;
        for (uint256 i = 0; i < callbackData.orders.length; i++) {
            ILimitOrderManager.OrderInfo memory order = callbackData.orders[i];
            callbackData.isToken0 ? 
                callbackData.key.currency0.settle(state.poolManager, address(this), order.amount, false) :
                callbackData.key.currency1.settle(state.poolManager, address(this), order.amount, false);
            (, BalanceDelta feeDelta) = state.poolManager.modifyLiquidity(
                callbackData.key,
                ModifyLiquidityParams({
                    tickLower: order.bottomTick,
                    tickUpper: order.topTick,
                    liquidityDelta: int256(uint256(order.liquidity)),
                    salt: bytes32(uint256(callbackData.isToken0 ? 0 : 1))
                }),
                ""
            );
            feeDeltas[i] = feeDelta;
            if (feeDelta != ZERO_DELTA) {
                accumulatedMintFees = accumulatedMintFees + feeDelta;
            }
        }
        _mintFeesToHook(state, callbackData.key, accumulatedMintFees);

        // Clear any remaining dust amounts
        _clearExactDelta(state, callbackData.key.currency0);
        _clearExactDelta(state, callbackData.key.currency1);
        
        return abi.encode(feeDeltas);
    }

    // Private helper functions
    function _mintFeesToHook(
        CallbackState storage state,
        PoolKey memory key,
        BalanceDelta feeDelta
    ) private {
        int128 fee0 = feeDelta.amount0();
        int128 fee1 = feeDelta.amount1();
        
        if (fee0 > 0) {
            state.poolManager.mint(
                address(this), 
                uint256(uint160(Currency.unwrap(key.currency0))), 
                uint256(int256(fee0))
            );
        }
        
        if (fee1 > 0) {
            state.poolManager.mint(
                address(this), 
                uint256(uint160(Currency.unwrap(key.currency1))), 
                uint256(int256(fee1))
            );
        }
    }

    function _handleTokenTransfersAndFees(
        CallbackState storage state,
        uint256 principalAmount,
        uint256 feeAmount,
        Currency currency,
        address user
    ) private {
        if (principalAmount == 0 && feeAmount == 0) return;
        
        uint256 currencyId = uint256(uint160(Currency.unwrap(currency)));
        uint256 treasuryFee = FullMath.mulDiv(feeAmount, state.hookFeePercentage, state.feeDenominator);
        uint256 userAmount = principalAmount + (feeAmount - treasuryFee);
        
        if (userAmount > 0) {
            state.poolManager.burn(address(this), currencyId, userAmount);
            
            try state.poolManager.take(currency, user, userAmount) {
            } catch {
                state.poolManager.take(currency, state.treasury, userAmount);
                emit FailedTransferSentToTreasury(currency, user, userAmount);
            }
        }
        
        if (treasuryFee > 0) {
            state.poolManager.burn(address(this), currencyId, treasuryFee);
            state.poolManager.take(currency, state.treasury, treasuryFee);
        }
    }


    function _clearExactDelta(CallbackState storage state, Currency currency) private {
        int256 delta = state.poolManager.currencyDelta(address(this), currency);
        if (delta > 0) {
            state.poolManager.clear(currency, uint256(delta));
        }
    }
}

File 23 of 46 : console.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

library console {
    address constant CONSOLE_ADDRESS =
        0x000000000000000000636F6e736F6c652e6c6f67;

    function _sendLogPayloadImplementation(bytes memory payload) internal view {
        address consoleAddress = CONSOLE_ADDRESS;
        /// @solidity memory-safe-assembly
        assembly {
            pop(
                staticcall(
                    gas(),
                    consoleAddress,
                    add(payload, 32),
                    mload(payload),
                    0,
                    0
                )
            )
        }
    }

    function _castToPure(
      function(bytes memory) internal view fnIn
    ) internal pure returns (function(bytes memory) pure fnOut) {
        assembly {
            fnOut := fnIn
        }
    }

    function _sendLogPayload(bytes memory payload) internal pure {
        _castToPure(_sendLogPayloadImplementation)(payload);
    }

    function log() internal pure {
        _sendLogPayload(abi.encodeWithSignature("log()"));
    }

    function logInt(int256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
    }

    function logUint(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }

    function logString(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }

    function logBool(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }

    function logAddress(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }

    function logBytes(bytes memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
    }

    function logBytes1(bytes1 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
    }

    function logBytes2(bytes2 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
    }

    function logBytes3(bytes3 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
    }

    function logBytes4(bytes4 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
    }

    function logBytes5(bytes5 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
    }

    function logBytes6(bytes6 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
    }

    function logBytes7(bytes7 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
    }

    function logBytes8(bytes8 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
    }

    function logBytes9(bytes9 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
    }

    function logBytes10(bytes10 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
    }

    function logBytes11(bytes11 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
    }

    function logBytes12(bytes12 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
    }

    function logBytes13(bytes13 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
    }

    function logBytes14(bytes14 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
    }

    function logBytes15(bytes15 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
    }

    function logBytes16(bytes16 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
    }

    function logBytes17(bytes17 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
    }

    function logBytes18(bytes18 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
    }

    function logBytes19(bytes19 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
    }

    function logBytes20(bytes20 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
    }

    function logBytes21(bytes21 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
    }

    function logBytes22(bytes22 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
    }

    function logBytes23(bytes23 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
    }

    function logBytes24(bytes24 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
    }

    function logBytes25(bytes25 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
    }

    function logBytes26(bytes26 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
    }

    function logBytes27(bytes27 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
    }

    function logBytes28(bytes28 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
    }

    function logBytes29(bytes29 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
    }

    function logBytes30(bytes30 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
    }

    function logBytes31(bytes31 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
    }

    function logBytes32(bytes32 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
    }

    function log(uint256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256)", p0));
    }

    function log(int256 p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(int256)", p0));
    }

    function log(string memory p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string)", p0));
    }

    function log(bool p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
    }

    function log(address p0) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address)", p0));
    }

    function log(uint256 p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256)", p0, p1));
    }

    function log(uint256 p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string)", p0, p1));
    }

    function log(uint256 p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool)", p0, p1));
    }

    function log(uint256 p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address)", p0, p1));
    }

    function log(string memory p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256)", p0, p1));
    }

    function log(string memory p0, int256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,int256)", p0, p1));
    }

    function log(string memory p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
    }

    function log(string memory p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
    }

    function log(string memory p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
    }

    function log(bool p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256)", p0, p1));
    }

    function log(bool p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
    }

    function log(bool p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
    }

    function log(bool p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
    }

    function log(address p0, uint256 p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256)", p0, p1));
    }

    function log(address p0, string memory p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
    }

    function log(address p0, bool p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
    }

    function log(address p0, address p1) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
    }

    function log(uint256 p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool)", p0, p1, p2));
    }

    function log(uint256 p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool)", p0, p1, p2));
    }

    function log(uint256 p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool)", p0, p1, p2));
    }

    function log(uint256 p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool)", p0, p1, p2));
    }

    function log(string memory p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
    }

    function log(string memory p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
    }

    function log(string memory p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
    }

    function log(string memory p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256)", p0, p1, p2));
    }

    function log(string memory p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
    }

    function log(string memory p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
    }

    function log(string memory p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool)", p0, p1, p2));
    }

    function log(bool p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
    }

    function log(bool p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
    }

    function log(bool p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256)", p0, p1, p2));
    }

    function log(bool p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
    }

    function log(bool p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
    }

    function log(bool p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
    }

    function log(bool p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256)", p0, p1, p2));
    }

    function log(bool p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
    }

    function log(bool p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
    }

    function log(bool p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool)", p0, p1, p2));
    }

    function log(address p0, uint256 p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address)", p0, p1, p2));
    }

    function log(address p0, string memory p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256)", p0, p1, p2));
    }

    function log(address p0, string memory p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
    }

    function log(address p0, string memory p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
    }

    function log(address p0, string memory p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
    }

    function log(address p0, bool p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256)", p0, p1, p2));
    }

    function log(address p0, bool p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
    }

    function log(address p0, bool p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
    }

    function log(address p0, bool p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
    }

    function log(address p0, address p1, uint256 p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256)", p0, p1, p2));
    }

    function log(address p0, address p1, string memory p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
    }

    function log(address p0, address p1, bool p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
    }

    function log(address p0, address p1, address p2) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,string,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,bool,address,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,string,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,bool,address)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,string)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,bool)", p0, p1, p2, p3));
    }

    function log(uint256 p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(uint256,address,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
    }

    function log(string memory p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
    }

    function log(bool p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, uint256 p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,uint256,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, string memory p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, bool p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, uint256 p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,uint256,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, string memory p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, bool p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, uint256 p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint256)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, string memory p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, bool p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
    }

    function log(address p0, address p1, address p2, address p3) internal pure {
        _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
    }
}

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

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

/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state
/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickBitmap {
    /// @notice Thrown when the tick is not enumerated by the tick spacing
    /// @param tick the invalid tick
    /// @param tickSpacing The tick spacing of the pool
    error TickMisaligned(int24 tick, int24 tickSpacing);

    /// @dev round towards negative infinity
    function compress(int24 tick, int24 tickSpacing) internal pure returns (int24 compressed) {
        // compressed = tick / tickSpacing;
        // if (tick < 0 && tick % tickSpacing != 0) compressed--;
        assembly ("memory-safe") {
            tick := signextend(2, tick)
            tickSpacing := signextend(2, tickSpacing)
            compressed :=
                sub(
                    sdiv(tick, tickSpacing),
                    // if (tick < 0 && tick % tickSpacing != 0) then tick % tickSpacing < 0, vice versa
                    slt(smod(tick, tickSpacing), 0)
                )
        }
    }

    /// @notice Computes the position in the mapping where the initialized bit for a tick lives
    /// @param tick The tick for which to compute the position
    /// @return wordPos The key in the mapping containing the word in which the bit is stored
    /// @return bitPos The bit position in the word where the flag is stored
    function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {
        assembly ("memory-safe") {
            // signed arithmetic shift right
            wordPos := sar(8, signextend(2, tick))
            bitPos := and(tick, 0xff)
        }
    }

    /// @notice Flips the initialized state for a given tick from false to true, or vice versa
    /// @param self The mapping in which to flip the tick
    /// @param tick The tick to flip
    /// @param tickSpacing The spacing between usable ticks
    function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal {
        // Equivalent to the following Solidity:
        //     if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing);
        //     (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing);
        //     uint256 mask = 1 << bitPos;
        //     self[wordPos] ^= mask;
        assembly ("memory-safe") {
            tick := signextend(2, tick)
            tickSpacing := signextend(2, tickSpacing)
            // ensure that the tick is spaced
            if smod(tick, tickSpacing) {
                let fmp := mload(0x40)
                mstore(fmp, 0xd4d8f3e6) // selector for TickMisaligned(int24,int24)
                mstore(add(fmp, 0x20), tick)
                mstore(add(fmp, 0x40), tickSpacing)
                revert(add(fmp, 0x1c), 0x44)
            }
            tick := sdiv(tick, tickSpacing)
            // calculate the storage slot corresponding to the tick
            // wordPos = tick >> 8
            mstore(0, sar(8, tick))
            mstore(0x20, self.slot)
            // the slot of self[wordPos] is keccak256(abi.encode(wordPos, self.slot))
            let slot := keccak256(0, 0x40)
            // mask = 1 << bitPos = 1 << (tick % 256)
            // self[wordPos] ^= mask
            sstore(slot, xor(sload(slot), shl(and(tick, 0xff), 1)))
        }
    }

    /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either
    /// to the left (less than or equal to) or right (greater than) of the given tick
    /// @param self The mapping in which to compute the next initialized tick
    /// @param tick The starting tick
    /// @param tickSpacing The spacing between usable ticks
    /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)
    /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick
    /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks
    function nextInitializedTickWithinOneWord(
        mapping(int16 => uint256) storage self,
        int24 tick,
        int24 tickSpacing,
        bool lte
    ) internal view returns (int24 next, bool initialized) {
        unchecked {
            int24 compressed = compress(tick, tickSpacing);

            if (lte) {
                (int16 wordPos, uint8 bitPos) = position(compressed);
                // all the 1s at or to the right of the current bitPos
                uint256 mask = type(uint256).max >> (uint256(type(uint8).max) - bitPos);
                uint256 masked = self[wordPos] & mask;

                // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                next = initialized
                    ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing
                    : (compressed - int24(uint24(bitPos))) * tickSpacing;
            } else {
                // start from the word of the next tick, since the current tick state doesn't matter
                (int16 wordPos, uint8 bitPos) = position(++compressed);
                // all the 1s at or to the left of the bitPos
                uint256 mask = ~((1 << bitPos) - 1);
                uint256 masked = self[wordPos] & mask;

                // if there are no initialized ticks to the left of the current tick, return leftmost in the word
                initialized = masked != 0;
                // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick
                next = initialized
                    ? (compressed + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing
                    : (compressed + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;
            }
        }
    }
}

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

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

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

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

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

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 31 of 46 : PoolOperation.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

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

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

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

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

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

File 35 of 46 : 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: 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) (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: 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.20;

import {Currency} from "v4-core/types/Currency.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";

/// @notice Library used to interact with PoolManager.sol to settle any open deltas.
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
library CurrencySettler {
    using SafeERC20 for IERC20;
    /// @notice Settle (pay) a currency to the PoolManager
    /// @param currency Currency to settle
    /// @param manager IPoolManager to settle to
    /// @param payer Address of the payer, the token sender
    /// @param amount Amount to send
    /// @param burn If true, burn the ERC-6909 token, otherwise ERC20-transfer to the PoolManager
    function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {
        if (burn) {
            manager.burn(payer, currency.toId(), amount);
        } else if (currency.isAddressZero()) {
            manager.settle{value: amount}();
        } else {
            manager.sync(currency);
            if (payer != address(this)) {
                IERC20(Currency.unwrap(currency)).safeTransferFrom(payer, address(manager), amount);
            } else {
                IERC20(Currency.unwrap(currency)).safeTransfer(address(manager), amount);
            }
            manager.settle();
        }
    }

    /// @notice Take (receive) a currency from the PoolManager
    /// @param currency Currency to take
    /// @param manager IPoolManager to take from
    /// @param recipient Address of the recipient, the token receiver
    /// @param amount Amount to receive
    /// @param claims If true, mint the ERC-6909 token, otherwise ERC20-transfer from the PoolManager to recipient
    function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {
        claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);
    }
}

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

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

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

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

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

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

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

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

library CurrencyReserves {
    using CustomRevert for bytes4;

    /// bytes32(uint256(keccak256("ReservesOf")) - 1)
    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
    /// bytes32(uint256(keccak256("Currency")) - 1)
    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;

    function getSyncedCurrency() internal view returns (Currency currency) {
        assembly ("memory-safe") {
            currency := tload(CURRENCY_SLOT)
        }
    }

    function resetCurrency() internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, 0)
        }
    }

    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            tstore(RESERVES_OF_SLOT, value)
        }
    }

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}

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

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;

    function read() internal view returns (uint256 count) {
        assembly ("memory-safe") {
            count := tload(NONZERO_DELTA_COUNT_SLOT)
        }
    }

    function increment() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := add(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}

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

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;

    function unlock() internal {
        assembly ("memory-safe") {
            // unlock
            tstore(IS_UNLOCKED_SLOT, true)
        }
    }

    function lock() internal {
        assembly ("memory-safe") {
            tstore(IS_UNLOCKED_SLOT, false)
        }
    }

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}

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/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "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/v4-core/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/lib/halmos-cheatcodes/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": false,
  "libraries": {
    "src/PositionManagement.sol": {
      "PositionManagement": "0xB163B2C672D972C58F23c5373C29163D0913E882"
    },
    "src/TickLibrary.sol": {
      "TickLibrary": "0x56581C4A975acE55fd18f1bfc1C952D42F0BcC0E"
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_poolManagerAddr","type":"address"},{"internalType":"address","name":"_treasury","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"AddressZero","type":"error"},{"inputs":[],"name":"AmountTooLow","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"FeePercentageTooHigh","type":"error"},{"inputs":[],"name":"MaxOrdersExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"provided","type":"uint256"},{"internalType":"uint256","name":"minimum","type":"uint256"}],"name":"MinimumAmountNotMet","type":"error"},{"inputs":[],"name":"NotAuthorized","type":"error"},{"inputs":[],"name":"NotWhitelistedPool","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":"PositionIsWaitingForKeeper","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UnknownCallbackType","type":"error"},{"inputs":[],"name":"ZeroLimit","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"Currency","name":"currency","type":"address"},{"indexed":false,"internalType":"address","name":"originalRecipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"FailedTransferSentToTreasury","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"percentage","type":"uint256"}],"name":"HookFeePercentageUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"positionKey","type":"bytes32"},{"indexed":false,"internalType":"int24","name":"bottomTick","type":"int24"},{"indexed":false,"internalType":"int24","name":"topTick","type":"int24"},{"indexed":false,"internalType":"int24","name":"currentTick","type":"int24"}],"name":"KeeperWaitingStatusReset","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"orderOwner","type":"address"},{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"OrderCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"positionKey","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"principal0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"principal1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fees0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fees1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"hookFeePercentage","type":"uint256"}],"name":"OrderClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"OrderCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"OrderExecuted","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":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"PoolId","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"bytes32[]","name":"leftoverPositions","type":"bytes32[]"}],"name":"PositionsLeftOver","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"FEE_DENOMINATOR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ZERO_DELTA","outputs":[{"internalType":"BalanceDelta","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"cancelBatchOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"cancelOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"}],"name":"cancelPositionKeys","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"claimBatchOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"name":"claimOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"}],"name":"claimPositionKeys","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"targetTick","type":"int24"},{"internalType":"uint256","name":"amount","type":"uint256"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"createLimitOrder","outputs":[{"components":[{"internalType":"uint256","name":"usedAmount","type":"uint256"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"}],"internalType":"struct ILimitOrderManager.CreateOrderResult","name":"","type":"tuple"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"},{"internalType":"uint256","name":"totalAmount","type":"uint256"},{"internalType":"uint256","name":"totalOrders","type":"uint256"},{"internalType":"uint256","name":"sizeSkew","type":"uint256"},{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"}],"name":"createScaleOrders","outputs":[{"components":[{"internalType":"uint256","name":"usedAmount","type":"uint256"},{"internalType":"bool","name":"isToken0","type":"bool"},{"internalType":"int24","name":"bottomTick","type":"int24"},{"internalType":"int24","name":"topTick","type":"int24"}],"internalType":"struct ILimitOrderManager.CreateOrderResult[]","name":"results","type":"tuple[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"currentNonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"},{"internalType":"address","name":"user","type":"address"}],"name":"emergencyCancelOrders","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"executablePositionsLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"int24","name":"tickBeforeSwap","type":"int24"},{"internalType":"int24","name":"tickAfterSwap","type":"int24"},{"internalType":"bool","name":"zeroForOne","type":"bool"}],"name":"executeOrder","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32[]","name":"waitingPositions","type":"bytes32[]"}],"name":"executeOrderByKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"}],"name":"getUserPositionCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getUserPositions","outputs":[{"components":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"BalanceDelta","name":"fees","type":"int256"},{"internalType":"bytes32","name":"positionKey","type":"bytes32"}],"internalType":"struct ILimitOrderManager.PositionInfo[]","name":"positions","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hook","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hook_fee_percentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isKeeper","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"Currency","name":"currency0","type":"address"},{"internalType":"Currency","name":"currency1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"},{"internalType":"contract IHooks","name":"hooks","type":"address"}],"internalType":"struct PoolKey","name":"key","type":"tuple"},{"internalType":"bytes32[]","name":"positionKeys","type":"bytes32[]"},{"internalType":"address","name":"user","type":"address"}],"name":"keeperClaimPositionKeys","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maxOrderLimit","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"Currency","name":"","type":"address"}],"name":"minAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"contract IPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"positionState","outputs":[{"internalType":"BalanceDelta","name":"feePerLiquidity","type":"int256"},{"internalType":"uint128","name":"totalLiquidity","type":"uint128"},{"internalType":"bool","name":"isActive","type":"bool"},{"internalType":"bool","name":"isWaitingKeeper","type":"bool"},{"internalType":"uint256","name":"currentNonce","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_limit","type":"uint256"}],"name":"setExecutablePositionsLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_hook","type":"address"}],"name":"setHook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_percentage","type":"uint256"}],"name":"setHookFeePercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_keeper","type":"address"},{"internalType":"bool","name":"_isKeeper","type":"bool"}],"name":"setKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"_limit","type":"uint24"}],"name":"setMaxOrderLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"},{"internalType":"uint256","name":"_minAmount","type":"uint256"}],"name":"setMinAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"poolId","type":"bytes32"},{"internalType":"bool","name":"isWhitelisted","type":"bool"}],"name":"setWhitelistedPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"int24","name":"","type":"int24"}],"name":"token0PositionAtTick","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"int16","name":"","type":"int16"}],"name":"token0TickBitmap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"int24","name":"","type":"int24"}],"name":"token1PositionAtTick","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"int16","name":"","type":"int16"}],"name":"token1TickBitmap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"treasury","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"unlockCallback","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"},{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"address","name":"","type":"address"}],"name":"userPositions","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"BalanceDelta","name":"lastFeePerLiquidity","type":"int256"},{"internalType":"BalanceDelta","name":"claimablePrincipal","type":"int256"},{"internalType":"BalanceDelta","name":"fees","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"PoolId","name":"","type":"bytes32"}],"name":"whitelistedPool","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]

60a0604052604b60085561c350600955600a805462ffffff19166064179055348015610029575f80fd5b5060405161611838038061611883398101604081905261004891610171565b806001600160a01b03811661007657604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b61007f81610107565b50600180556002805460ff191690556001600160a01b038216158015906100ae57506001600160a01b03831615155b6100b6575f80fd5b50600780546001600160a01b039283166001600160a01b03199182168117909255929091166080819052600380548416909117905560048054909216179055620186a06006556009546005556101b1565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b038116811461016c575f80fd5b919050565b5f805f60608486031215610183575f80fd5b61018c84610156565b925061019a60208501610156565b91506101a860408501610156565b90509250925092565b608051615f176102015f395f818161096001528181610b3b01528181610e0201528181610f60015281816111c3015281816112ed01528181611afa0152818161216d015261291f0152615f175ff3fe6080604052600436106102ed575f3560e01c806371ab3be611610186578063b422fe3e116100dc578063dc4c90d311610087578063f2fde38b11610062578063f2fde38b146109cd578063f4f9e737146109ec578063fd827deb14610a0b575f80fd5b8063dc4c90d31461094f578063e17c405a14610982578063e8019a7e146109ae575f80fd5b8063d1b9e853116100b7578063d1b9e853146108fb578063d5708d5a1461091a578063d73792a914610939575f80fd5b8063b422fe3e14610878578063b5b57ef914610897578063be7e5297146108c5575f80fd5b80638da5cb5b1161013c578063920c1d7b11610117578063920c1d7b14610824578063a5f6dda014610839578063b248549414610859575f80fd5b80638da5cb5b146107c957806391cb4669146107e557806391dd7346146107f8575f80fd5b80638456cb591161016c5780638456cb591461077757806385500c291461078b5780638b2d527a146107aa575f80fd5b806371ab3be6146107345780637f5a7c7b14610753575f80fd5b80634b20ccbf1161024657806361d027b3116101f15780636b3fc6ba116101cc5780636b3fc6ba146106d35780636ba42aaa146106f2578063715018a614610720575f80fd5b806361d027b31461064757806361d0b6c81461067e5780636a90700b146106b4575f80fd5b806357787da51161022157806357787da5146105e65780635c975abb146106055780636137011b14610628575f80fd5b80634b20ccbf1461057c5780634bd95a6f1461059b5780634d0a32db146105bb575f80fd5b80630fb9ba97116102a65780633dfd3873116102815780633dfd38731461052a5780633f4ba83a1461054957806349b7f7c11461055d575f80fd5b80630fb9ba97146103d55780631f26e4fc1461040b57806337d4059814610490575f80fd5b80630680ecd3116102d65780630680ecd3146103705780630affb3d61461039f5780630d30d42c146103c0575f80fd5b80630351e61e146102f157806305b123411461033a575b5f80fd5b3480156102fc575f80fd5b5061032761030b366004614a92565b601060209081525f928352604080842090915290825290205481565b6040519081526020015b60405180910390f35b348015610345575f80fd5b50610327610354366004614ab2565b601160209081525f928352604080842090915290825290205481565b34801561037b575f80fd5b50600a5461038b9062ffffff1681565b60405162ffffff9091168152602001610331565b3480156103aa575f80fd5b506103be6103b9366004614afc565b610a2a565b005b3480156103cb575f80fd5b5061032760095481565b3480156103e0575f80fd5b506103276103ef366004614ab2565b601260209081525f928352604080842090915290825290205481565b348015610416575f80fd5b50610466610425366004614b39565b600f60209081525f938452604080852082529284528284209052825290208054600182015460028301546003909301546001600160801b0390921692909184565b604080516001600160801b0390951685526020850193909352918301526060820152608001610331565b34801561049b575f80fd5b506104f46104aa366004614a92565b601560209081525f928352604080842090915290825290208054600182015460029092015490916001600160801b0381169160ff600160801b8304811692600160881b9004169085565b604080519586526001600160801b039094166020860152911515928401929092529015156060830152608082015260a001610331565b348015610535575f80fd5b506103be610544366004614b6f565b610a4a565b348015610554575f80fd5b506103be610a91565b348015610568575f80fd5b506103be610577366004614b8a565b610aa3565b348015610587575f80fd5b50610327610596366004614ba1565b610ac3565b6105ae6105a9366004614be6565b610af7565b6040516103319190614c36565b3480156105c6575f80fd5b506103276105d5366004614b6f565b600b6020525f908152604090205481565b3480156105f1575f80fd5b506103be610600366004614c6d565b610ce8565b348015610610575f80fd5b5060025460ff165b6040519015158152602001610331565b348015610633575f80fd5b506103be610642366004614d75565b610dc1565b348015610652575f80fd5b50600754610666906001600160a01b031681565b6040516001600160a01b039091168152602001610331565b348015610689575f80fd5b50610327610698366004614e1f565b601460209081525f928352604080842090915290825290205481565b3480156106bf575f80fd5b506103be6106ce366004614e42565b61107a565b3480156106de575f80fd5b506103be6106ed366004614ead565b6110a1565b3480156106fd575f80fd5b5061061861070c366004614b6f565b600c6020525f908152604090205460ff1681565b34801561072b575f80fd5b506103be611108565b34801561073f575f80fd5b506103be61074e366004614f10565b611119565b34801561075e575f80fd5b506002546106669061010090046001600160a01b031681565b348015610782575f80fd5b506103be611160565b348015610796575f80fd5b506103be6107a5366004614afc565b611170565b3480156107b5575f80fd5b506103be6107c4366004614f70565b611183565b3480156107d4575f80fd5b505f546001600160a01b0316610666565b3480156107f0575f80fd5b506103275f81565b348015610803575f80fd5b50610817610812366004614f8b565b6111b6565b6040516103319190615027565b34801561082f575f80fd5b5061032760085481565b61084c610847366004615039565b6112d0565b60405161033191906150ad565b348015610864575f80fd5b506103be610873366004614b8a565b611408565b348015610883575f80fd5b506103be610892366004614f10565b611420565b3480156108a2575f80fd5b506106186108b1366004614b8a565b600d6020525f908152604090205460ff1681565b3480156108d0575f80fd5b506103276108df366004614e1f565b601360209081525f928352604080842090915290825290205481565b348015610906575f80fd5b506103be610915366004615123565b61145d565b348015610925575f80fd5b506103be610934366004614ba1565b61148f565b348015610944575f80fd5b50610327620186a081565b34801561095a575f80fd5b506106667f000000000000000000000000000000000000000000000000000000000000000081565b34801561098d575f80fd5b506109a161099c36600461514f565b6114b2565b6040516103319190615187565b3480156109b9575f80fd5b506103be6109c8366004614c6d565b6116e3565b3480156109d8575f80fd5b506103be6109e7366004614b6f565b61181a565b3480156109f7575f80fd5b506103be610a063660046151e3565b61185c565b348015610a16575f80fd5b506103be610a25366004614ead565b61198f565b610a326119e6565b610a3d828233611a10565b610a4660018055565b5050565b610a52611dd2565b600280546001600160a01b03909216610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff909216919091179055565b610a99611dd2565b610aa1611dfe565b565b610aab611dd2565b620186a08110610ab9575f80fd5b6009819055600555565b6001600160a01b0382165f9081526016602090815260408083208484529091528120610aee90611e50565b90505b92915050565b604080516080810182525f808252602082018190529181018290526060810182905290610b33610b2c36859003850185615231565b60a0902090565b90505f610b607f000000000000000000000000000000000000000000000000000000000000000083611e59565b50509150505f807356581c4a975ace55fd18f1bfc1c952d42f0bcc0e6302e88654848a896060016020810190610b9691906152ab565b6040516001600160e01b031960e086901b168152600293840b600482015291830b602483015290910b60448201528b151560648201526084016040805180830381865af4158015610be9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c0d91906152c6565b6040805160018082528183019092529294509092505f9190816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610c2a57905050905060405180608001604052808460020b81526020018360020b81526020015f81526020015f6001600160801b0316815250815f81518110610ca057610ca06152f3565b60200260200101819052505f610cbb828c8b60015f8d611f0b565b9050805f81518110610ccf57610ccf6152f3565b602002602001015196505050505050505b949350505050565b610cf06119e6565b5f610d03610b2c36869003860186615231565b335f9081526016602090815260408083208484529091529020909150610d2881611e50565b8410610d35575050610db3565b5f610d3f82611e50565b610d49858761531b565b11610d5d57610d58848661531b565b610d66565b610d6682611e50565b9050805b85811115610dae5780610d7c8161532e565b915050610d8883611e50565b811015610da9575f610d9a84836125fd565b9050610da7888233611a10565b505b610d6a565b505050505b610dbc60018055565b505050565b335f908152600c602052604090205460ff16610ddb575f80fd5b80515f03610de7575050565b5f610dfa610b2c36859003850185615231565b90505f610e277f000000000000000000000000000000000000000000000000000000000000000083611e59565b50509150505f805b8451811015610f54575f858281518110610e4b57610e4b6152f3565b6020908102919091010151905060e881901c60d082901c6001808416145f81610e7c578360020b8860020b12610e87565b8260020b8860020b12155b5f8a8152601560209081526040808320898452909152902060010154909150600160881b900460ff168015610eb95750805b8015610ee857505f8981526015602090815260408083208884529091529020600101546001600160801b031615155b15610f1c57848a88610ef981615343565b995081518110610f0b57610f0b6152f3565b602002602001018181525050610f43565b5f8981526015602090815260408083208884529091529020600101805460ff60881b191690555b505060019093019250610e2f915050565b508084528015611073577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c894916040518060400160405280600380811115610faa57610faa61535b565b815260200160405180604001604052808a803603810190610fcb9190615231565b815260200189815250604051602001610fe491906153a9565b60408051601f198184030181529181529152516110049190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b815260040161102f9190615027565b5f604051808303815f875af115801561104a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611071919081019061548b565b505b5050505050565b611082611dd2565b5f918252600d6020526040909120805460ff1916911515919091179055565b6110a96119e6565b335f908152600c602052604090205460ff166110c3575f80fd5b5f5b828110156110f8576110f0858585848181106110e3576110e36152f3565b9050602002013584612608565b6001016110c5565b5061110260018055565b50505050565b611110611dd2565b610aa15f612b03565b6111216119e6565b5f5b818110156111565761114e84848484818110611141576111416152f3565b9050602002013533612608565b600101611123565b50610dbc60018055565b611168611dd2565b610aa1612b6a565b6111786119e6565b610a3d828233612608565b61118b611dd2565b60018162ffffff161161119c575f80fd5b600a805462ffffff191662ffffff92909216919091179055565b6060336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146111ec575f80fd5b5f6111f983850185615500565b80519091505f8160038111156112115761121161535b565b036112425761123982602001518060200190518101906112319190615703565b600390612ba7565b92505050610af1565b60018160038111156112565761125661535b565b0361127e57611239826020015180602001905181019061127691906157ad565b600390612ddd565b60028160038111156112925761129261535b565b036112ba5761123982602001518060200190518101906112b29190615802565b600390612ea5565b6112c78260200151612f07565b95945050505050565b60605f6112e5610b2c36859003850185615231565b90505f6113127f000000000000000000000000000000000000000000000000000000000000000083611e59565b5050600a5490925062ffffff16871115905061132c575f80fd5b5f7356581c4a975ace55fd18f1bfc1c952d42f0bcc0e63b62d6c378b8b858f8c8c61135d60808e0160608f016152ab565b6040516001600160e01b031960e08a901b168152600297880b600482015295870b602487015293860b60448601529115156064850152608484015260a483015290910b60c482015260e4015f60405180830381865af41580156113c2573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113e991908101906158ad565b90506113f9818c8a8a8a8a611f0b565b9b9a5050505050505050505050565b611410611dd2565b5f811161141b575f80fd5b600855565b6114286119e6565b5f5b818110156111565761145584848484818110611448576114486152f3565b9050602002013533611a10565b60010161142a565b611465611dd2565b6001600160a01b03919091165f908152600c60205260409020805460ff1916911515919091179055565b611497611dd2565b6001600160a01b039091165f908152600b6020526040902055565b6001600160a01b0384165f90815260166020908152604080832086845290915281206060916114e082611e50565b9050835f036114ed578093505b80851061153e57604080515f8082526020820190925290611534565b604080516060810182525f80825260208083018290529282015282525f199092019101816115095790505b5092505050610ce0565b5f8161154a868861531b565b11611555578461155f565b61155f86836158df565b90508067ffffffffffffffff81111561157a5761157a614c9e565b6040519080825280602002602001820160405280156115c357816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816115985790505b5093505f5b818110156116d7575f6115db828961531b565b90505f6115e886836125fd565b90505f600f5f8c81526020019081526020015f205f8381526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f206040518060800160405290815f82015f9054906101000a90046001600160801b03166001600160801b03166001600160801b03168152602001600182015481526020016002820154815260200160038201548152505090506040518060600160405280825f01516001600160801b0316815260200182606001518152602001838152508885815181106116c1576116c16152f3565b60209081029190910101525050506001016115c8565b50505050949350505050565b6116eb6119e6565b5f6116fe610b2c36869003860186615231565b335f908152601660209081526040808320848452909152902090915061172381611e50565b8410611730575050610db3565b5f61173a82611e50565b611744858761531b565b1161175857611753848661531b565b611761565b61176182611e50565b9050805b85811115610dae57806117778161532e565b91505061178383611e50565b811015611815575f61179584836125fd565b5f868152600f60209081526040808320848452825280832033845290915290208054919250906001600160801b0316158015906118025750600281015415158061180257505f868152601560209081526040808320858452909152902060010154600160801b900460ff16155b1561181257611812898333612608565b50505b611765565b611822611dd2565b6001600160a01b03811661185057604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b61185981612b03565b50565b60025461010090046001600160a01b03163314611877575f80fd5b6008545f03611884575f80fd5b5f611897610b2c36879003870187615231565b90505f6118b6828686866118b160808c0160608d016152ab565b612fe1565b905080515f036118c7575050611102565b80516008548111156118e357506008546118e3838383876131a6565b5f5b81811015611985575f838281518110611900576119006152f3565b602002602001015190505f86611932575f868152601360209081526040808320600286900b8452909152902054611950565b5f868152601460209081526040808320600286900b84529091529020545b90508061195e57505061197d565b611978611970368c90038c018c615231565b87838561330a565b505050505b6001016118e5565b5050505050505050565b6119976119e6565b335f908152600c602052604090205460ff166119b1575f80fd5b5f5b828110156110f8576119de858585848181106119d1576119d16152f3565b9050602002013584611a10565b6001016119b3565b600260015403611a0957604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b5f611a23610b2c36869003860186615231565b5f818152600f6020908152604080832087845282528083206001600160a01b03871684529091529020549091506001600160801b031680611a62575f80fd5b5f828152600f6020908152604080832087845282528083206001600160a01b0387168452909152902060020154151580611abf57505f828152601560209081526040808320878452909152902060010154600160801b900460ff16155b15611acf57611073858585612608565b6040805180820190915260e885901c9060d086901c90600180881614905f9081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906348c894919080600281526020016040518060c001604052808f803603810190611b459190615231565b81526020018a60020b81526020018960020b81526020018b6001600160801b031681526020018d6001600160a01b03168152602001881515815250604051602001611c289190815180516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116908201526101408101602083015160020b60a0830152604083015160020b60c08301526001600160801b0360608401511660e08301526001600160a01b0360808401511661010083015260a0830151151561012083015292915050565b60408051601f19818403018152918152915251611c489190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611c739190615027565b5f604051808303815f875af1158015611c8e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cb5919081019061548b565b806020019051810190611cc891906158f2565b91509150611cd7878a83613509565b611ce182826135a5565b5f888152600f602090815260408083208d845282528083206001600160a01b038d168452825280832060020193909355898252601581528282208c835290529081206001018054889290611d3f9084906001600160801b0316615914565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f83611d6f5785611d71565b845b9050611d81888b8b8e88866135e2565b604080516001600160a01b038b168152602081018c905289917f7716e682d2ec0d8c89df8d50e799be3ae2a2c13858f0968f97ae1856fa879eda910160405180910390a25050505050505050505050565b5f546001600160a01b03163314610aa15760405163118cdaa760e01b8152336004820152602401611847565b611e06613700565b6002805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f610af1825490565b5f805f805f611e6786613723565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa158015611eaf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ed39190615933565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b6060611f1561375f565b60025461010090046001600160a01b0316611f3660a0840160808501614b6f565b6001600160a01b031614611f48575f80fd5b845f03611f53575f80fd5b5f611f66610b2c36859003850185615231565b5f818152600d602052604090205490915060ff16611f9757604051636e2a3fc560e11b815260040160405180910390fd5b604051631813f41d60e31b815273b163b2c672d972c58f23c5373c29163d0913e8829063c09fa0e890611fd6908b908b908b908b908b906004016159b5565b5f60405180830381865af4158015611ff0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261201791908101906158ad565b975073b163b2c672d972c58f23c5373c29163d0913e88263a2e464ba8988600b5f8c6120525761204d60408a0160208b01614b6f565b61205f565b61205f60208a018a614b6f565b6001600160a01b03166001600160a01b031681526020019081526020015f20546040518463ffffffff1660e01b815260040161209d939291906159eb565b602060405180830381865af41580156120b8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120dc9190615a0f565b6120e4575f80fd5b6120fd87876120f836879003870187615231565b613783565b875167ffffffffffffffff81111561211757612117614c9e565b60405190808252806020026020018201604052801561216757816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f199092019101816121355790505b5091505f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c8949160405180604001604052805f60038111156121b7576121b761535b565b81526020016040518060800160405280898036038101906121d89190615231565b81526020018e81526020018d15158152602001336001600160a01b03168152506040516020016122089190615a2a565b60408051601f198184030181529181529152516122289190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016122539190615027565b5f604051808303815f875af115801561226e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612295919081019061548b565b8060200190518101906122a89190615b37565b604080516080810182525f8082526020820181905291810182905260608101829052919250905f5b8b518110156125ee578b81815181106122eb576122eb6152f3565b6020026020010151915061230a601086845f015185602001518f613857565b5f878152601560209081526040808320848452909152902060010154909450600160881b900460ff1615905061233e575f80fd5b6123628584868481518110612355576123556152f3565b6020026020010151613509565b5f858152601560209081526040808320868452909152902060010154600160801b900460ff166124f1575f8581526015602090815260408083208684529091528120600101805460ff60801b1916600160801b1790558b6123c3575f6123c6565b60015b60208481015185515f8a815260108452604080822060ff9690961660d09490941b62ffffff60d01b1660e89390931b7fffffff0000000000000000000000000000000000000000000000000000000000169290921792909217808352938352808220548a8352601584528183208984529093528120600201919091559091508c612451578351612457565b83602001515b90506124ee8d61246857601461246b565b60135b8e61247757601261247a565b60115b612489368d90038d018d615231565b848960a083206060909301515f84815260209687526040808220600295860b8084529089528183209490945594815294865283852090830b80830786139205919091039182900b60081d600190810b855294529120805460ff9092169290921b179055565b50505b61250185848460600151336138de565b8160400151868281518110612518576125186152f3565b60200260200101515f0181815250508a86828151811061253a5761253a6152f3565b60209081029190910181015191151591015281518651879083908110612562576125626152f3565b60200260200101516040019060020b908160020b815250508160200151868281518110612591576125916152f3565b60209081029190910181015160029290920b6060909201919091526040805133815291820185905286917f7aa6bb6d845d655f13d58b4bec40fc4b34f849e0915e2d039bdb533ba2b5bfd7910160405180910390a26001016122d0565b50505050509695505050505050565b5f610aee8383613b01565b5f61261b610b2c36869003860186615231565b5f818152600f6020908152604080832087845282528083206001600160a01b03871684529091529020549091506001600160801b0316612659575f80fd5b5f818152600f6020908152604080832086845282528083206001600160a01b03861684529091529020600201541515806126b657505f818152601560209081526040808320868452909152902060010154600160801b900460ff16155b6126be575f80fd5b5f818152600f6020908152604080832086845282528083206001600160a01b038616845282528083208484526015835281842087855290925290912060010154600160801b900460ff166127965780546040516390bd5b7f60e01b8152600481018690526001600160801b03909116602482015273b163b2c672d972c58f23c5373c29163d0913e882906390bd5b7f90604401602060405180830381865af415801561276c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127909190615933565b60028201555b80546001600160801b031615612888575f82815260156020908152604080832087845290915281205460018301546127ce91906135a5565b82546003840154604051630d496cc160e21b8152600481018490526001600160801b03909216602483018190529293505f91612869919073b163b2c672d972c58f23c5373c29163d0913e88290633525b304906044015b602060405180830381865af4158015612840573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128649190615933565b613b27565b90506128788185600301541490565b61288457600384018190555b5050505b5f828152601560209081526040808320878452825280832054600180860191909155600280860154600380880154898852600f87528588208c895287528588206001600160a01b038c168952875285882080546fffffffffffffffffffffffffffffffff191681559485018890559284018790559290920185905560168452828520878652909352922061291c9087613b48565b507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166348c8949160405180604001604052806001600381111561296a5761296a61535b565b815260200160405180608001604052808781526020018681526020018c8036038101906129979190615231565b81526001600160a01b038b166020918201526040516129b7929101615bbe565b60408051601f198184030181529181529152516129d79190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401612a029190615027565b5f604051808303815f875af1158015612a1d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612a44919081019061548b565b50837f837188de7bf9f082b892e9c947f0c47c6a8d0070da6e8879a61c1e1c3c23e7998688612a738660801d90565b6001600160801b0316612a8687600f0b90565b6001600160801b0316612a998760801d90565b6001600160801b0316612aac88600f0b90565b600954604080516001600160a01b039098168852602088019690965294860193909352606085019190915260808401526001600160801b031660a083015260c082015260e00160405180910390a250505050505050565b5f80546001600160a01b038381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b612b7261375f565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611e333390565b60605f82602001515167ffffffffffffffff811115612bc857612bc8614c9e565b604051908082528060200260200182016040528015612bf1578160200160208202803683370190505b5090505f805b846020015151811015612d85575f85602001518281518110612c1b57612c1b6152f3565b602002602001015190508560400151612c5b5786546040820151875160200151612c56926001600160a01b039182169291169030905f613b53565b612c80565b86546040820151875151612c80926001600160a01b039182169291169030905f613b53565b86548651604080516080810182528451600290810b825260208087015190910b908201526060808601516001600160801b031682840152918a01515f946001600160a01b031693635a6bcfda9390929190820190612cdf576001612ce1565b5f5b60ff1690526040516001600160e01b031960e085901b168152612d08929190600401615c4e565b60408051808303815f875af1158015612d23573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d4791906158f2565b91505080858481518110612d5d57612d5d6152f3565b60209081029190910101528015612d7b57612d788482613b27565b93505b5050600101612bf7565b50612d9485855f015183613d53565b835151612da2908690613e62565b612db385855f015160200151613e62565b81604051602001612dc49190615ced565b6040516020818303038152906040529250505092915050565b6060612e2283612df0845f015160801d90565b6001600160801b0316612e07856020015160801d90565b6001600160801b031685604001515f01518660600151613ee9565b8151612e60908490600f0b6001600160801b0316612e448560200151600f0b90565b6001600160801b03168560400151602001518660600151613ee9565b612e718383604001515f0151613e62565b612e8383836040015160200151613e62565b604080515f602082015201604051602081830303815290604052905092915050565b60605f80612eca85855f01518660200151876040015188606001518960a0015161419f565b8551519193509150612edd908690613e62565b612eee85855f015160200151613e62565b6040805160208101849052908101829052606001612dc4565b60605f82806020019051810190612f1e9190615d24565b805160a090209091505f5b826020015151811015612fca575f83602001518281518110612f4d57612f4d6152f3565b6020908102919091018101515f8581526015835260408082208383529093529190912060010154909150600160881b900460ff16612f8b5750612fc2565b60e881901c60d082901c6001808416145f81612fa75783612fa9565b825b9050612fba885f015188878461330a565b505050505050505b600101612f29565b5050604080515f8152602081019091529392505050565b60605f612ff6612ff18688615dfd565b614375565b60020b90505f8360020b8261300b9190615e22565b61301690600161531b565b67ffffffffffffffff81111561302e5761302e614c9e565b604051908082528060200260200182016040528015613057578160200160208202803683370190505b5090505f8086613073575f8a8152601160205260409020613081565b5f8a81526012602052604090205b90505f8761309b575f8b81526013602052604090206130a9565b5f8b81526014602052604090205b9050895b886130c1578960020b8160020b12156130cc565b8960020b8160020b13155b613196575f806130de85848c8e61438f565b915091505f8b6130f6578c60020b8360020b13613101565b8c60020b8360020b13155b90508015613110578c92505f91505b811561316157600283900b5f90815260208690526040902054156131615782888861313a81615343565b99508151811061314c5761314c6152f3565b602002602001019060020b908160020b815250505b8c60020b8360020b0361317657505050613196565b8b613181578261318c565b61318c600184615dfd565b93505050506130ad565b5050508152979650505050505050565b5f8284516131b491906158df565b90505f8167ffffffffffffffff8111156131d0576131d0614c9e565b6040519080825280602002602001820160405280156131f9578160200160208202803683370190505b509050835b85518110156132c9575f86828151811061321a5761321a6152f3565b602002602001015190505f8561324c575f898152601360209081526040808320600286900b845290915290205461326a565b5f898152601460209081526040808320600286900b84529091529020545b5f8a81526015602090815260408083208484529091529020600101805460ff60881b1916600160881b179055905080846132a489866158df565b815181106132b4576132b46152f3565b602090810291909101015250506001016131fe565b50857fe0b7c8733b12019f55165d26afd47f95c579a7c8cbea0775f30d30e05407439d826040516132fa9190615e41565b60405180910390a2505050505050565b5f8381526015602090815260408083208584529091528120600190810154829160e886901c9160d087901c918088161490613357906003908b90869086906001600160801b03168661419f565b9095509350613367888886613509565b5f8881526015602090815260408083208a84529091529020600101805460ff60801b191690819055600160881b900460ff16156133c5575f8881526015602090815260408083208a84529091529020600101805460ff60881b191690555b61344a816133d45760146133d7565b60135b826133e35760126133e6565b60115b60a08c2060608d01515f82815260209384526040808220600293840b8e850b8181078513918105919091039485900b60081d600190810b8552918752828420805460ff9096169290921b199094169055928152938352818420908452909152812055565b5f81613456575f613459565b60015b5f8a815260106020908152604080832060ff9490941660d088901b62ffffff60d01b1660e88a901b7fffffff00000000000000000000000000000000000000000000000000000000001617178084529390915281208054929350906134bd83615343565b9190505550887fe7ce370cc0425e330fd66bf98129d75f24695dba59b19d1df832da3c809327c3896040516134f491815260200190565b60405180910390a25050505094509492505050565b5f8381526015602090815260408083208584529091528120600181015490916001600160801b03909116900361353f5750505050565b8161354a5750505050565b8054600182015460405163df3f04d160e01b8152600481018590526001600160801b03909116602482015261359e919073b163b2c672d972c58f23c5373c29163d0913e8829063df3f04d190604401612825565b9055505050565b5f608082811d9084901d03600f83810b9085900b036112c76135c68361447c565b6135cf8361447c565b6001600160801b031660809190911b1790565b6135ed838686612608565b5f868152600e60209081526040808320888452909152902061360f908561449d565b505f868152600e60209081526040808320888452909152902061363190611e50565b5f03611071575f8681526015602090815260408083208884529091529020600101805471ffff00000000000000000000000000000000191690556110718261367a57601461367d565b60135b8361368957601261368c565b60115b61369b36879003870187615231565b60a081206060909101515f82815260209384526040808220600293840b89850b8181078513918105919091039485900b60081d600190810b8552918752828420805460ff9096169290921b199094169055928152938352818420908452909152812055565b60025460ff16610aa157604051638dfc202b60e01b815260040160405180910390fd5b6040515f90613742908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b60025460ff1615610aa15760405163d93c066560e01b815260040160405180910390fd5b61378b6119e6565b82156138335780516001600160a01b031661381257813410156137ac575f80fd5b8134111561380d575f336137c084346158df565b6040515f81818185875af1925050503d805f81146137f9576040519150601f19603f3d011682016040523d82523d5f602084013e6137fe565b606091505b505090508061380b575f80fd5b505b610db3565b341561381c575f80fd5b805161380d906001600160a01b03163330856144b1565b341561383d575f80fd5b6020810151610db3906001600160a01b03163330856144b1565b5f8082613864575f613867565b60015b60ff1660d08562ffffff16901b60e88762ffffff16901b17175f1b91508261388f575f613892565b60015b60ff166008885f8981526020019081526020015f205f8581526020019081526020015f2054901b60d08662ffffff16901b60e88862ffffff16901b1717175f1b90509550959350505050565b5f8481526015602090815260408083208684528252808320878452600f835281842087855283528184206001600160a01b03861685528352818420888552600e84528285208886529093529220613935908461452d565b61399c575f6002820181905560038201819055868152600e602090815260408083208884529091529020613969908461454e565b506001600160a01b0383165f90815260166020908152604080832089845290915290206139969086614562565b50613a69565b80546001600160801b031615613a69575f6139be835f015483600101546135a5565b8254604051630d496cc160e21b8152600481018390526001600160801b03909116602482018190529192505f9073b163b2c672d972c58f23c5373c29163d0913e88290633525b30490604401602060405180830381865af4158015613a25573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a499190615933565b90508015613a6557613a5f846003015482613b27565b60038501555b5050505b815460018201558054849082905f90613a8c9084906001600160801b0316615e53565b92506101000a8154816001600160801b0302191690836001600160801b0316021790555083826001015f8282829054906101000a90046001600160801b0316613ad59190615e53565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550505050505050565b5f825f018281548110613b1657613b166152f3565b905f5260205f200154905092915050565b5f608082811d9084901d01600f83810b9085900b016112c76135c68361447c565b5f610aee838361456d565b8015613be757836001600160a01b031663f5298aca84613b82886001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018590526064015f604051808303815f87803b158015613bcc575f80fd5b505af1158015613bde573d5f803e3d5ffd5b50505050611073565b6001600160a01b038516613c5e57836001600160a01b03166311da60b4836040518263ffffffff1660e01b815260040160206040518083038185885af1158015613c33573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190613c589190615933565b50611073565b604051632961046560e21b81526001600160a01b03868116600483015285169063a5841194906024015f604051808303815f87803b158015613c9e575f80fd5b505af1158015613cb0573d5f803e3d5ffd5b505050506001600160a01b0383163014613cde57613cd96001600160a01b0386168486856144b1565b613cf2565b613cf26001600160a01b0386168584614650565b836001600160a01b03166311da60b46040518163ffffffff1660e01b81526004016020604051808303815f875af1158015613d2f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110719190615933565b5f613d5e8260801d90565b90505f613d6b83600f0b90565b90505f82600f0b1315613de35784548451604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f85900b604482015291169063156e29f6906064015f604051808303815f87803b158015613dcc575f80fd5b505af1158015613dde573d5f803e3d5ffd5b505050505b5f81600f0b13156110735784546020850151604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f84900b604482015291169063156e29f6906064015f604051808303815f87803b158015613e45575f80fd5b505af1158015613e57573d5f803e3d5ffd5b505050505050505050565b81545f90613e7a906001600160a01b03163084614681565b90505f811315610dbc57825460405163203c2d1360e21b81526001600160a01b03848116600483015260248201849052909116906380f0b44c906044015f604051808303815f87803b158015613ece575f80fd5b505af1158015613ee0573d5f803e3d5ffd5b50505050505050565b83158015613ef5575082155b611073575f826001600160a01b031690505f613f1a858860020154896003015461471a565b90505f613f2782876158df565b613f31908861531b565b905080156140be578754604051637a94c56560e11b815230600482015260248101859052604481018390526001600160a01b039091169063f5298aca906064015f604051808303815f87803b158015613f88575f80fd5b505af1158015613f9a573d5f803e3d5ffd5b50508954604051630b0d9c0960e01b81526001600160a01b0389811660048301528881166024830152604482018690529091169250630b0d9c0991506064015f604051808303815f87803b158015613ff0575f80fd5b505af1925050508015614001575060015b6140be5787546001890154604051630b0d9c0960e01b81526001600160a01b038881166004830152918216602482015260448101849052911690630b0d9c09906064015f604051808303815f87803b15801561405b575f80fd5b505af115801561406d573d5f803e3d5ffd5b5050604080516001600160a01b03808a168252881660208201529081018490527f28012a1ba9530a2c13f4c905d8052e47e026a10b80e63d0c69730506cd9fa0829250606001905060405180910390a15b8115611985578754604051637a94c56560e11b815230600482015260248101859052604481018490526001600160a01b039091169063f5298aca906064015f604051808303815f87803b158015614113575f80fd5b505af1158015614125573d5f803e3d5ffd5b5050895460018b0154604051630b0d9c0960e01b81526001600160a01b038a8116600483015291821660248201526044810187905291169250630b0d9c0991506064015f604051808303815f87803b15801561417f575f80fd5b505af1158015614191573d5f803e3d5ffd5b505050505050505050505050565b855460408051608081018252600287810b825286900b60208201525f9283926001600160a01b0390911691635a6bcfda918a919081016141de89615e72565b600f0b8152602001876141f25760016141f4565b5f5b60ff1690526040516001600160e01b031960e085901b16815261421b929190600401615c4e565b60408051808303815f875af1158015614236573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061425a91906158f2565b90925090505f61426a8360801d90565b90505f61427784600f0b90565b90505f82600f0b13156142ef5789548951604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f85900b604482015291169063156e29f6906064015f604051808303815f87803b1580156142d8575f80fd5b505af11580156142ea573d5f803e3d5ffd5b505050505b5f81600f0b131561436857895460208a0151604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f84900b604482015291169063156e29f6906064015f604051808303815f87803b158015614351575f80fd5b505af1158015614363573d5f803e3d5ffd5b505050505b5050965096945050505050565b5f808260020b126143865781610af1565b610af182615e9f565b5f80600284810b9086900b818107831391900503831561440e57600281900b60081d600181900b5f908152602089905260409020545f1960ff808516908190039190911c9182168015159550909190856143f057888360ff16860302614403565b886143fa826147b6565b840360ff168603025b965050505050614472565b6001908101600281900b60081d80830b5f90815260208a905260409020545f1960ff841694851b01199081168015159550929391928561445857888360ff0360ff1686010261446b565b888361446383614841565b0360ff168601025b9650505050505b5094509492505050565b80600f81900b8114614498576144986393dafdf160e01b6148db565b919050565b5f610aee836001600160a01b03841661456d565b6040516001600160a01b0384811660248301528381166044830152606482018390526111029186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506148e3565b6001600160a01b0381165f9081526001830160205260408120541515610aee565b5f610aee836001600160a01b038416614944565b5f610aee8383614944565b5f8181526001830160205260408120548015614647575f61458f6001836158df565b85549091505f906145a2906001906158df565b9050808214614601575f865f0182815481106145c0576145c06152f3565b905f5260205f200154905080875f0184815481106145e0576145e06152f3565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061461257614612615eb7565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610af1565b5f915050610af1565b6040516001600160a01b03838116602483015260448201839052610dbc91859182169063a9059cbb906064016144e6565b5f806001600160a01b0384165f526001600160a01b03831660205260405f209050846001600160a01b031663f135baaa826040518263ffffffff1660e01b81526004016146d091815260200190565b602060405180830381865afa1580156146eb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061470f9190615933565b9150505b9392505050565b5f838302815f1985870982811083820303915050808411614739575f80fd5b805f0361474b57508290049050614713565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f8082116147c2575f80fd5b507f0706060506020500060203020504000106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be6001600160801b03841160071b84811c67ffffffffffffffff1060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b5f80821161484d575f80fd5b507e1f0d1e100c1d070f090b19131c1706010e11080a1a141802121b15031604055f8290039091166101e07f804040554300526644320000502061067405302602000010750620017611707760fc7fb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff840260f81c161b60f71c1690811c63d76453e004601f169190911a1790565b805f5260045ffd5b5f6148f76001600160a01b03841683614990565b905080515f1415801561491b5750808060200190518101906149199190615a0f565b155b15610dbc57604051635274afe760e01b81526001600160a01b0384166004820152602401611847565b5f81815260018301602052604081205461498957508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610af1565b505f610af1565b6060610aee83835f845f80856001600160a01b031684866040516149b49190615ecb565b5f6040518083038185875af1925050503d805f81146149ee576040519150601f19603f3d011682016040523d82523d5f602084013e6149f3565b606091505b5091509150614a03868383614a0d565b9695505050505050565b606082614a2257614a1d82614a69565b614713565b8151158015614a3957506001600160a01b0384163b155b15614a6257604051639996b31560e01b81526001600160a01b0385166004820152602401611847565b5080614713565b805115614a795780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f8060408385031215614aa3575f80fd5b50508035926020909101359150565b5f8060408385031215614ac3575f80fd5b823591506020830135600181900b8114614adb575f80fd5b809150509250929050565b5f60a08284031215614af6575f80fd5b50919050565b5f8060c08385031215614b0d575f80fd5b614b178484614ae6565b9460a0939093013593505050565b6001600160a01b0381168114611859575f80fd5b5f805f60608486031215614b4b575f80fd5b83359250602084013591506040840135614b6481614b25565b809150509250925092565b5f60208284031215614b7f575f80fd5b813561471381614b25565b5f60208284031215614b9a575f80fd5b5035919050565b5f8060408385031215614bb2575f80fd5b8235614bbd81614b25565b946020939093013593505050565b8015158114611859575f80fd5b8060020b8114611859575f80fd5b5f805f806101008587031215614bfa575f80fd5b8435614c0581614bcb565b93506020850135614c1581614bd8565b925060408501359150614c2b8660608701614ae6565b905092959194509250565b60808101610af1828480518252602081015115156020830152604081015160020b6040830152606081015160020b60608301525050565b5f805f60e08486031215614c7f575f80fd5b614c898585614ae6565b9560a0850135955060c0909401359392505050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b60405290565b6040805190810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b6040516080810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b604051601f8201601f1916810167ffffffffffffffff81118282101715614d4a57614d4a614c9e565b604052919050565b5f67ffffffffffffffff821115614d6b57614d6b614c9e565b5060051b60200190565b5f8060c08385031215614d86575f80fd5b614d908484614ae6565b915060a083013567ffffffffffffffff811115614dab575f80fd5b8301601f81018513614dbb575f80fd5b8035614dce614dc982614d52565b614d21565b8082825260208201915060208360051b850101925087831115614def575f80fd5b6020840193505b82841015614e11578335825260209384019390910190614df6565b809450505050509250929050565b5f8060408385031215614e30575f80fd5b823591506020830135614adb81614bd8565b5f8060408385031215614e53575f80fd5b823591506020830135614adb81614bcb565b5f8083601f840112614e75575f80fd5b50813567ffffffffffffffff811115614e8c575f80fd5b6020830191508360208260051b8501011115614ea6575f80fd5b9250929050565b5f805f8060e08587031215614ec0575f80fd5b614eca8686614ae6565b935060a085013567ffffffffffffffff811115614ee5575f80fd5b614ef187828801614e65565b90945092505060c0850135614f0581614b25565b939692955090935050565b5f805f60c08486031215614f22575f80fd5b614f2c8585614ae6565b925060a084013567ffffffffffffffff811115614f47575f80fd5b614f5386828701614e65565b9497909650939450505050565b62ffffff81168114611859575f80fd5b5f60208284031215614f80575f80fd5b813561471381614f60565b5f8060208385031215614f9c575f80fd5b823567ffffffffffffffff811115614fb2575f80fd5b8301601f81018513614fc2575f80fd5b803567ffffffffffffffff811115614fd8575f80fd5b856020828401011115614fe9575f80fd5b6020919091019590945092505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610aee6020830184614ff9565b5f805f805f805f610160888a031215615050575f80fd5b873561505b81614bcb565b9650602088013561506b81614bd8565b9550604088013561507b81614bd8565b9450606088013593506080880135925060a0880135915061509f8960c08a01614ae6565b905092959891949750929550565b602080825282518282018190525f918401906040840190835b818110156151185761510283855180518252602081015115156020830152604081015160020b6040830152606081015160020b60608301525050565b60209390930192608092909201916001016150c6565b509095945050505050565b5f8060408385031215615134575f80fd5b823561513f81614b25565b91506020830135614adb81614bcb565b5f805f8060808587031215615162575f80fd5b843561516d81614b25565b966020860135965060408601359560600135945092505050565b602080825282518282018190525f918401906040840190835b818110156151185783516001600160801b0381511684526020810151602085015260408101516040850152506060830192506020840193506001810190506151a0565b5f805f8061010085870312156151f7575f80fd5b6152018686614ae6565b935060a085013561521181614bd8565b925060c085013561522181614bd8565b915060e0850135614f0581614bcb565b5f60a0828403128015615242575f80fd5b5061524b614cb2565b823561525681614b25565b8152602083013561526681614b25565b6020820152604083013561527981614f60565b6040820152606083013561528c81614bd8565b6060820152608083013561529f81614b25565b60808201529392505050565b5f602082840312156152bb575f80fd5b813561471381614bd8565b5f80604083850312156152d7575f80fd5b82516152e281614bd8565b6020840151909250614adb81614bd8565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610af157610af1615307565b5f8161533c5761533c615307565b505f190190565b5f6001820161535457615354615307565b5060010190565b634e487b7160e01b5f52602160045260245ffd5b5f8151808452602084019350602083015f5b8281101561539f578151865260209586019590910190600101615381565b5093949350505050565b602081526154096020820183516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b5f602083015160c080840152610ce060e084018261536f565b602081525f82516004811061544557634e487b7160e01b5f52602160045260245ffd5b806020840152506020830151604080840152610ce06060840182614ff9565b5f67ffffffffffffffff82111561547d5761547d614c9e565b50601f01601f191660200190565b5f6020828403121561549b575f80fd5b815167ffffffffffffffff8111156154b1575f80fd5b8201601f810184136154c1575f80fd5b80516154cf614dc982615464565b8181528560208385010111156154e3575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f60208284031215615510575f80fd5b813567ffffffffffffffff811115615526575f80fd5b820160408185031215615537575f80fd5b61553f614cdb565b81356004811061554d575f80fd5b8152602082013567ffffffffffffffff811115615568575f80fd5b80830192505084601f83011261557c575f80fd5b813561558a614dc982615464565b81815286602083860101111561559e575f80fd5b816020850160208301375f602092820183015290820152949350505050565b5f60a082840312156155cd575f80fd5b6155d5614cb2565b905081516155e281614b25565b815260208201516155f281614b25565b6020820152604082015161560581614f60565b6040820152606082015161561881614bd8565b6060820152608082015161562b81614b25565b608082015292915050565b80516001600160801b0381168114614498575f80fd5b5f82601f83011261565b575f80fd5b8151615669614dc982614d52565b8082825260208201915060208360071b86010192508583111561568a575f80fd5b602085015b838110156156f957608081880312156156a6575f80fd5b6156ae614cfe565b81516156b981614bd8565b815260208201516156c981614bd8565b6020820152604082810151908201526156e460608301615636565b6060820152835260209092019160800161568f565b5095945050505050565b5f60208284031215615713575f80fd5b815167ffffffffffffffff811115615729575f80fd5b8201610100818503121561573b575f80fd5b615743614cfe565b61574d85836155bd565b815260a082015167ffffffffffffffff811115615768575f80fd5b6157748682850161564c565b60208301525060c082015161578881614bcb565b604082015260e091909101519061579e82614b25565b60608101919091529392505050565b5f6101008284031280156157bf575f80fd5b506157c8614cfe565b82518152602080840151908201526157e384604085016155bd565b604082015260e08301516157f681614b25565b60608201529392505050565b5f610140828403128015615814575f80fd5b5060405160c0810167ffffffffffffffff8111828210171561583857615838614c9e565b60405261584584846155bd565b815260a083015161585581614bd8565b602082015260c083015161586881614bd8565b604082015261587960e08401615636565b606082015261010083015161588d81614b25565b60808201526101208301516158a181614bcb565b60a08201529392505050565b5f602082840312156158bd575f80fd5b815167ffffffffffffffff8111156158d3575f80fd5b610ce08482850161564c565b81810381811115610af157610af1615307565b5f8060408385031215615903575f80fd5b505080516020909101519092909150565b6001600160801b038281168282160390811115610af157610af1615307565b5f60208284031215615943575f80fd5b5051919050565b5f8151808452602084019350602083015f5b8281101561539f5761599f868351805160020b8252602081015160020b6020830152604081015160408301526001600160801b0360608201511660608301525050565b608095909501946020919091019060010161595c565b60a081525f6159c760a083018861594a565b95151560208301525060408101939093526060830191909152608090910152919050565b606081525f6159fd606083018661594a565b60208301949094525060400152919050565b5f60208284031215615a1f575f80fd5b815161471381614bcb565b602081525f6101208201615a906020840185516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b60208481015161010060c086015280519283905201905f906101408501905b80831015615b0957615af2828551805160020b8252602081015160020b6020830152604081015160408301526001600160801b0360608201511660608301525050565b608082019150602084019350600183019250615aaf565b506040860151151560e08601526060909501516001600160a01b031661010090940193909352509192915050565b5f60208284031215615b47575f80fd5b815167ffffffffffffffff811115615b5d575f80fd5b8201601f81018413615b6d575f80fd5b8051615b7b614dc982614d52565b8082825260208201915060208360051b850101925086831115615b9c575f80fd5b6020840193505b82841015614a03578351825260209384019390910190615ba3565b5f6101008201905082518252602083015160208301526040830151615c3460408401826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b506001600160a01b0360608401511660e083015292915050565b615ca681846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8151600290810b60a08301526020830151900b60c0820152604082015160e082015260609091015161010082015261014061012082018190525f9082015261016001919050565b602080825282518282018190525f918401906040840190835b81811015615118578351835260209384019390920191600101615d06565b5f60208284031215615d34575f80fd5b815167ffffffffffffffff811115615d4a575f80fd5b820160c08185031215615d5b575f80fd5b615d63614cdb565b615d6d85836155bd565b815260a082015167ffffffffffffffff811115615d88575f80fd5b80830192505084601f830112615d9c575f80fd5b8151615daa614dc982614d52565b8082825260208201915060208360051b860101925087831115615dcb575f80fd5b6020850194505b82851015615ded578451825260209485019490910190615dd2565b6020840152509095945050505050565b600282810b9082900b03627fffff198112627fffff82131715610af157610af1615307565b5f82615e3c57634e487b7160e01b5f52601260045260245ffd5b500490565b602081525f610aee602083018461536f565b6001600160801b038181168382160190811115610af157610af1615307565b5f81600f0b6f7fffffffffffffffffffffffffffffff198103615e9757615e97615307565b5f0392915050565b5f8160020b627fffff198103615e9757615e97615307565b634e487b7160e01b5f52603160045260245ffd5b5f82518060208501845e5f92019182525091905056fea264697066735822122030ef006422669fb974ced209f82cdce41c4bc0ee3ec84fd5a687a9aa2d94861e64736f6c634300081a00330000000000000000000000001f98400000000000000000000000000000000004000000000000000000000000846e79175c78371dafe6598f57b503b66c03ef9c000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1

Deployed Bytecode

0x6080604052600436106102ed575f3560e01c806371ab3be611610186578063b422fe3e116100dc578063dc4c90d311610087578063f2fde38b11610062578063f2fde38b146109cd578063f4f9e737146109ec578063fd827deb14610a0b575f80fd5b8063dc4c90d31461094f578063e17c405a14610982578063e8019a7e146109ae575f80fd5b8063d1b9e853116100b7578063d1b9e853146108fb578063d5708d5a1461091a578063d73792a914610939575f80fd5b8063b422fe3e14610878578063b5b57ef914610897578063be7e5297146108c5575f80fd5b80638da5cb5b1161013c578063920c1d7b11610117578063920c1d7b14610824578063a5f6dda014610839578063b248549414610859575f80fd5b80638da5cb5b146107c957806391cb4669146107e557806391dd7346146107f8575f80fd5b80638456cb591161016c5780638456cb591461077757806385500c291461078b5780638b2d527a146107aa575f80fd5b806371ab3be6146107345780637f5a7c7b14610753575f80fd5b80634b20ccbf1161024657806361d027b3116101f15780636b3fc6ba116101cc5780636b3fc6ba146106d35780636ba42aaa146106f2578063715018a614610720575f80fd5b806361d027b31461064757806361d0b6c81461067e5780636a90700b146106b4575f80fd5b806357787da51161022157806357787da5146105e65780635c975abb146106055780636137011b14610628575f80fd5b80634b20ccbf1461057c5780634bd95a6f1461059b5780634d0a32db146105bb575f80fd5b80630fb9ba97116102a65780633dfd3873116102815780633dfd38731461052a5780633f4ba83a1461054957806349b7f7c11461055d575f80fd5b80630fb9ba97146103d55780631f26e4fc1461040b57806337d4059814610490575f80fd5b80630680ecd3116102d65780630680ecd3146103705780630affb3d61461039f5780630d30d42c146103c0575f80fd5b80630351e61e146102f157806305b123411461033a575b5f80fd5b3480156102fc575f80fd5b5061032761030b366004614a92565b601060209081525f928352604080842090915290825290205481565b6040519081526020015b60405180910390f35b348015610345575f80fd5b50610327610354366004614ab2565b601160209081525f928352604080842090915290825290205481565b34801561037b575f80fd5b50600a5461038b9062ffffff1681565b60405162ffffff9091168152602001610331565b3480156103aa575f80fd5b506103be6103b9366004614afc565b610a2a565b005b3480156103cb575f80fd5b5061032760095481565b3480156103e0575f80fd5b506103276103ef366004614ab2565b601260209081525f928352604080842090915290825290205481565b348015610416575f80fd5b50610466610425366004614b39565b600f60209081525f938452604080852082529284528284209052825290208054600182015460028301546003909301546001600160801b0390921692909184565b604080516001600160801b0390951685526020850193909352918301526060820152608001610331565b34801561049b575f80fd5b506104f46104aa366004614a92565b601560209081525f928352604080842090915290825290208054600182015460029092015490916001600160801b0381169160ff600160801b8304811692600160881b9004169085565b604080519586526001600160801b039094166020860152911515928401929092529015156060830152608082015260a001610331565b348015610535575f80fd5b506103be610544366004614b6f565b610a4a565b348015610554575f80fd5b506103be610a91565b348015610568575f80fd5b506103be610577366004614b8a565b610aa3565b348015610587575f80fd5b50610327610596366004614ba1565b610ac3565b6105ae6105a9366004614be6565b610af7565b6040516103319190614c36565b3480156105c6575f80fd5b506103276105d5366004614b6f565b600b6020525f908152604090205481565b3480156105f1575f80fd5b506103be610600366004614c6d565b610ce8565b348015610610575f80fd5b5060025460ff165b6040519015158152602001610331565b348015610633575f80fd5b506103be610642366004614d75565b610dc1565b348015610652575f80fd5b50600754610666906001600160a01b031681565b6040516001600160a01b039091168152602001610331565b348015610689575f80fd5b50610327610698366004614e1f565b601460209081525f928352604080842090915290825290205481565b3480156106bf575f80fd5b506103be6106ce366004614e42565b61107a565b3480156106de575f80fd5b506103be6106ed366004614ead565b6110a1565b3480156106fd575f80fd5b5061061861070c366004614b6f565b600c6020525f908152604090205460ff1681565b34801561072b575f80fd5b506103be611108565b34801561073f575f80fd5b506103be61074e366004614f10565b611119565b34801561075e575f80fd5b506002546106669061010090046001600160a01b031681565b348015610782575f80fd5b506103be611160565b348015610796575f80fd5b506103be6107a5366004614afc565b611170565b3480156107b5575f80fd5b506103be6107c4366004614f70565b611183565b3480156107d4575f80fd5b505f546001600160a01b0316610666565b3480156107f0575f80fd5b506103275f81565b348015610803575f80fd5b50610817610812366004614f8b565b6111b6565b6040516103319190615027565b34801561082f575f80fd5b5061032760085481565b61084c610847366004615039565b6112d0565b60405161033191906150ad565b348015610864575f80fd5b506103be610873366004614b8a565b611408565b348015610883575f80fd5b506103be610892366004614f10565b611420565b3480156108a2575f80fd5b506106186108b1366004614b8a565b600d6020525f908152604090205460ff1681565b3480156108d0575f80fd5b506103276108df366004614e1f565b601360209081525f928352604080842090915290825290205481565b348015610906575f80fd5b506103be610915366004615123565b61145d565b348015610925575f80fd5b506103be610934366004614ba1565b61148f565b348015610944575f80fd5b50610327620186a081565b34801561095a575f80fd5b506106667f0000000000000000000000001f9840000000000000000000000000000000000481565b34801561098d575f80fd5b506109a161099c36600461514f565b6114b2565b6040516103319190615187565b3480156109b9575f80fd5b506103be6109c8366004614c6d565b6116e3565b3480156109d8575f80fd5b506103be6109e7366004614b6f565b61181a565b3480156109f7575f80fd5b506103be610a063660046151e3565b61185c565b348015610a16575f80fd5b506103be610a25366004614ead565b61198f565b610a326119e6565b610a3d828233611a10565b610a4660018055565b5050565b610a52611dd2565b600280546001600160a01b03909216610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff909216919091179055565b610a99611dd2565b610aa1611dfe565b565b610aab611dd2565b620186a08110610ab9575f80fd5b6009819055600555565b6001600160a01b0382165f9081526016602090815260408083208484529091528120610aee90611e50565b90505b92915050565b604080516080810182525f808252602082018190529181018290526060810182905290610b33610b2c36859003850185615231565b60a0902090565b90505f610b607f0000000000000000000000001f9840000000000000000000000000000000000483611e59565b50509150505f807356581c4a975ace55fd18f1bfc1c952d42f0bcc0e6302e88654848a896060016020810190610b9691906152ab565b6040516001600160e01b031960e086901b168152600293840b600482015291830b602483015290910b60448201528b151560648201526084016040805180830381865af4158015610be9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c0d91906152c6565b6040805160018082528183019092529294509092505f9190816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610c2a57905050905060405180608001604052808460020b81526020018360020b81526020015f81526020015f6001600160801b0316815250815f81518110610ca057610ca06152f3565b60200260200101819052505f610cbb828c8b60015f8d611f0b565b9050805f81518110610ccf57610ccf6152f3565b602002602001015196505050505050505b949350505050565b610cf06119e6565b5f610d03610b2c36869003860186615231565b335f9081526016602090815260408083208484529091529020909150610d2881611e50565b8410610d35575050610db3565b5f610d3f82611e50565b610d49858761531b565b11610d5d57610d58848661531b565b610d66565b610d6682611e50565b9050805b85811115610dae5780610d7c8161532e565b915050610d8883611e50565b811015610da9575f610d9a84836125fd565b9050610da7888233611a10565b505b610d6a565b505050505b610dbc60018055565b505050565b335f908152600c602052604090205460ff16610ddb575f80fd5b80515f03610de7575050565b5f610dfa610b2c36859003850185615231565b90505f610e277f0000000000000000000000001f9840000000000000000000000000000000000483611e59565b50509150505f805b8451811015610f54575f858281518110610e4b57610e4b6152f3565b6020908102919091010151905060e881901c60d082901c6001808416145f81610e7c578360020b8860020b12610e87565b8260020b8860020b12155b5f8a8152601560209081526040808320898452909152902060010154909150600160881b900460ff168015610eb95750805b8015610ee857505f8981526015602090815260408083208884529091529020600101546001600160801b031615155b15610f1c57848a88610ef981615343565b995081518110610f0b57610f0b6152f3565b602002602001018181525050610f43565b5f8981526015602090815260408083208884529091529020600101805460ff60881b191690555b505060019093019250610e2f915050565b508084528015611073577f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c894916040518060400160405280600380811115610faa57610faa61535b565b815260200160405180604001604052808a803603810190610fcb9190615231565b815260200189815250604051602001610fe491906153a9565b60408051601f198184030181529181529152516110049190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b815260040161102f9190615027565b5f604051808303815f875af115801561104a573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611071919081019061548b565b505b5050505050565b611082611dd2565b5f918252600d6020526040909120805460ff1916911515919091179055565b6110a96119e6565b335f908152600c602052604090205460ff166110c3575f80fd5b5f5b828110156110f8576110f0858585848181106110e3576110e36152f3565b9050602002013584612608565b6001016110c5565b5061110260018055565b50505050565b611110611dd2565b610aa15f612b03565b6111216119e6565b5f5b818110156111565761114e84848484818110611141576111416152f3565b9050602002013533612608565b600101611123565b50610dbc60018055565b611168611dd2565b610aa1612b6a565b6111786119e6565b610a3d828233612608565b61118b611dd2565b60018162ffffff161161119c575f80fd5b600a805462ffffff191662ffffff92909216919091179055565b6060336001600160a01b037f0000000000000000000000001f9840000000000000000000000000000000000416146111ec575f80fd5b5f6111f983850185615500565b80519091505f8160038111156112115761121161535b565b036112425761123982602001518060200190518101906112319190615703565b600390612ba7565b92505050610af1565b60018160038111156112565761125661535b565b0361127e57611239826020015180602001905181019061127691906157ad565b600390612ddd565b60028160038111156112925761129261535b565b036112ba5761123982602001518060200190518101906112b29190615802565b600390612ea5565b6112c78260200151612f07565b95945050505050565b60605f6112e5610b2c36859003850185615231565b90505f6113127f0000000000000000000000001f9840000000000000000000000000000000000483611e59565b5050600a5490925062ffffff16871115905061132c575f80fd5b5f7356581c4a975ace55fd18f1bfc1c952d42f0bcc0e63b62d6c378b8b858f8c8c61135d60808e0160608f016152ab565b6040516001600160e01b031960e08a901b168152600297880b600482015295870b602487015293860b60448601529115156064850152608484015260a483015290910b60c482015260e4015f60405180830381865af41580156113c2573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113e991908101906158ad565b90506113f9818c8a8a8a8a611f0b565b9b9a5050505050505050505050565b611410611dd2565b5f811161141b575f80fd5b600855565b6114286119e6565b5f5b818110156111565761145584848484818110611448576114486152f3565b9050602002013533611a10565b60010161142a565b611465611dd2565b6001600160a01b03919091165f908152600c60205260409020805460ff1916911515919091179055565b611497611dd2565b6001600160a01b039091165f908152600b6020526040902055565b6001600160a01b0384165f90815260166020908152604080832086845290915281206060916114e082611e50565b9050835f036114ed578093505b80851061153e57604080515f8082526020820190925290611534565b604080516060810182525f80825260208083018290529282015282525f199092019101816115095790505b5092505050610ce0565b5f8161154a868861531b565b11611555578461155f565b61155f86836158df565b90508067ffffffffffffffff81111561157a5761157a614c9e565b6040519080825280602002602001820160405280156115c357816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816115985790505b5093505f5b818110156116d7575f6115db828961531b565b90505f6115e886836125fd565b90505f600f5f8c81526020019081526020015f205f8381526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f206040518060800160405290815f82015f9054906101000a90046001600160801b03166001600160801b03166001600160801b03168152602001600182015481526020016002820154815260200160038201548152505090506040518060600160405280825f01516001600160801b0316815260200182606001518152602001838152508885815181106116c1576116c16152f3565b60209081029190910101525050506001016115c8565b50505050949350505050565b6116eb6119e6565b5f6116fe610b2c36869003860186615231565b335f908152601660209081526040808320848452909152902090915061172381611e50565b8410611730575050610db3565b5f61173a82611e50565b611744858761531b565b1161175857611753848661531b565b611761565b61176182611e50565b9050805b85811115610dae57806117778161532e565b91505061178383611e50565b811015611815575f61179584836125fd565b5f868152600f60209081526040808320848452825280832033845290915290208054919250906001600160801b0316158015906118025750600281015415158061180257505f868152601560209081526040808320858452909152902060010154600160801b900460ff16155b1561181257611812898333612608565b50505b611765565b611822611dd2565b6001600160a01b03811661185057604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b61185981612b03565b50565b60025461010090046001600160a01b03163314611877575f80fd5b6008545f03611884575f80fd5b5f611897610b2c36879003870187615231565b90505f6118b6828686866118b160808c0160608d016152ab565b612fe1565b905080515f036118c7575050611102565b80516008548111156118e357506008546118e3838383876131a6565b5f5b81811015611985575f838281518110611900576119006152f3565b602002602001015190505f86611932575f868152601360209081526040808320600286900b8452909152902054611950565b5f868152601460209081526040808320600286900b84529091529020545b90508061195e57505061197d565b611978611970368c90038c018c615231565b87838561330a565b505050505b6001016118e5565b5050505050505050565b6119976119e6565b335f908152600c602052604090205460ff166119b1575f80fd5b5f5b828110156110f8576119de858585848181106119d1576119d16152f3565b9050602002013584611a10565b6001016119b3565b600260015403611a0957604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b5f611a23610b2c36869003860186615231565b5f818152600f6020908152604080832087845282528083206001600160a01b03871684529091529020549091506001600160801b031680611a62575f80fd5b5f828152600f6020908152604080832087845282528083206001600160a01b0387168452909152902060020154151580611abf57505f828152601560209081526040808320878452909152902060010154600160801b900460ff16155b15611acf57611073858585612608565b6040805180820190915260e885901c9060d086901c90600180881614905f9081906001600160a01b037f0000000000000000000000001f9840000000000000000000000000000000000416906348c894919080600281526020016040518060c001604052808f803603810190611b459190615231565b81526020018a60020b81526020018960020b81526020018b6001600160801b031681526020018d6001600160a01b03168152602001881515815250604051602001611c289190815180516001600160a01b03908116835260208083015182169084015260408083015162ffffff169084015260608083015160020b9084015260809182015116908201526101408101602083015160020b60a0830152604083015160020b60c08301526001600160801b0360608401511660e08301526001600160a01b0360808401511661010083015260a0830151151561012083015292915050565b60408051601f19818403018152918152915251611c489190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401611c739190615027565b5f604051808303815f875af1158015611c8e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611cb5919081019061548b565b806020019051810190611cc891906158f2565b91509150611cd7878a83613509565b611ce182826135a5565b5f888152600f602090815260408083208d845282528083206001600160a01b038d168452825280832060020193909355898252601581528282208c835290529081206001018054889290611d3f9084906001600160801b0316615914565b92506101000a8154816001600160801b0302191690836001600160801b031602179055505f83611d6f5785611d71565b845b9050611d81888b8b8e88866135e2565b604080516001600160a01b038b168152602081018c905289917f7716e682d2ec0d8c89df8d50e799be3ae2a2c13858f0968f97ae1856fa879eda910160405180910390a25050505050505050505050565b5f546001600160a01b03163314610aa15760405163118cdaa760e01b8152336004820152602401611847565b611e06613700565b6002805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b5f610af1825490565b5f805f805f611e6786613723565b604051631e2eaeaf60e01b8152600481018290529091505f906001600160a01b03891690631e2eaeaf90602401602060405180830381865afa158015611eaf573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ed39190615933565b90506001600160a01b03811695508060a01c60020b945062ffffff8160b81c16935062ffffff8160d01c169250505092959194509250565b6060611f1561375f565b60025461010090046001600160a01b0316611f3660a0840160808501614b6f565b6001600160a01b031614611f48575f80fd5b845f03611f53575f80fd5b5f611f66610b2c36859003850185615231565b5f818152600d602052604090205490915060ff16611f9757604051636e2a3fc560e11b815260040160405180910390fd5b604051631813f41d60e31b815273b163b2c672d972c58f23c5373c29163d0913e8829063c09fa0e890611fd6908b908b908b908b908b906004016159b5565b5f60405180830381865af4158015611ff0573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261201791908101906158ad565b975073b163b2c672d972c58f23c5373c29163d0913e88263a2e464ba8988600b5f8c6120525761204d60408a0160208b01614b6f565b61205f565b61205f60208a018a614b6f565b6001600160a01b03166001600160a01b031681526020019081526020015f20546040518463ffffffff1660e01b815260040161209d939291906159eb565b602060405180830381865af41580156120b8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906120dc9190615a0f565b6120e4575f80fd5b6120fd87876120f836879003870187615231565b613783565b875167ffffffffffffffff81111561211757612117614c9e565b60405190808252806020026020018201604052801561216757816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f199092019101816121355790505b5091505f7f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c8949160405180604001604052805f60038111156121b7576121b761535b565b81526020016040518060800160405280898036038101906121d89190615231565b81526020018e81526020018d15158152602001336001600160a01b03168152506040516020016122089190615a2a565b60408051601f198184030181529181529152516122289190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b81526004016122539190615027565b5f604051808303815f875af115801561226e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612295919081019061548b565b8060200190518101906122a89190615b37565b604080516080810182525f8082526020820181905291810182905260608101829052919250905f5b8b518110156125ee578b81815181106122eb576122eb6152f3565b6020026020010151915061230a601086845f015185602001518f613857565b5f878152601560209081526040808320848452909152902060010154909450600160881b900460ff1615905061233e575f80fd5b6123628584868481518110612355576123556152f3565b6020026020010151613509565b5f858152601560209081526040808320868452909152902060010154600160801b900460ff166124f1575f8581526015602090815260408083208684529091528120600101805460ff60801b1916600160801b1790558b6123c3575f6123c6565b60015b60208481015185515f8a815260108452604080822060ff9690961660d09490941b62ffffff60d01b1660e89390931b7fffffff0000000000000000000000000000000000000000000000000000000000169290921792909217808352938352808220548a8352601584528183208984529093528120600201919091559091508c612451578351612457565b83602001515b90506124ee8d61246857601461246b565b60135b8e61247757601261247a565b60115b612489368d90038d018d615231565b848960a083206060909301515f84815260209687526040808220600295860b8084529089528183209490945594815294865283852090830b80830786139205919091039182900b60081d600190810b855294529120805460ff9092169290921b179055565b50505b61250185848460600151336138de565b8160400151868281518110612518576125186152f3565b60200260200101515f0181815250508a86828151811061253a5761253a6152f3565b60209081029190910181015191151591015281518651879083908110612562576125626152f3565b60200260200101516040019060020b908160020b815250508160200151868281518110612591576125916152f3565b60209081029190910181015160029290920b6060909201919091526040805133815291820185905286917f7aa6bb6d845d655f13d58b4bec40fc4b34f849e0915e2d039bdb533ba2b5bfd7910160405180910390a26001016122d0565b50505050509695505050505050565b5f610aee8383613b01565b5f61261b610b2c36869003860186615231565b5f818152600f6020908152604080832087845282528083206001600160a01b03871684529091529020549091506001600160801b0316612659575f80fd5b5f818152600f6020908152604080832086845282528083206001600160a01b03861684529091529020600201541515806126b657505f818152601560209081526040808320868452909152902060010154600160801b900460ff16155b6126be575f80fd5b5f818152600f6020908152604080832086845282528083206001600160a01b038616845282528083208484526015835281842087855290925290912060010154600160801b900460ff166127965780546040516390bd5b7f60e01b8152600481018690526001600160801b03909116602482015273b163b2c672d972c58f23c5373c29163d0913e882906390bd5b7f90604401602060405180830381865af415801561276c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127909190615933565b60028201555b80546001600160801b031615612888575f82815260156020908152604080832087845290915281205460018301546127ce91906135a5565b82546003840154604051630d496cc160e21b8152600481018490526001600160801b03909216602483018190529293505f91612869919073b163b2c672d972c58f23c5373c29163d0913e88290633525b304906044015b602060405180830381865af4158015612840573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128649190615933565b613b27565b90506128788185600301541490565b61288457600384018190555b5050505b5f828152601560209081526040808320878452825280832054600180860191909155600280860154600380880154898852600f87528588208c895287528588206001600160a01b038c168952875285882080546fffffffffffffffffffffffffffffffff191681559485018890559284018790559290920185905560168452828520878652909352922061291c9087613b48565b507f0000000000000000000000001f984000000000000000000000000000000000046001600160a01b03166348c8949160405180604001604052806001600381111561296a5761296a61535b565b815260200160405180608001604052808781526020018681526020018c8036038101906129979190615231565b81526001600160a01b038b166020918201526040516129b7929101615bbe565b60408051601f198184030181529181529152516129d79190602001615422565b6040516020818303038152906040526040518263ffffffff1660e01b8152600401612a029190615027565b5f604051808303815f875af1158015612a1d573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052612a44919081019061548b565b50837f837188de7bf9f082b892e9c947f0c47c6a8d0070da6e8879a61c1e1c3c23e7998688612a738660801d90565b6001600160801b0316612a8687600f0b90565b6001600160801b0316612a998760801d90565b6001600160801b0316612aac88600f0b90565b600954604080516001600160a01b039098168852602088019690965294860193909352606085019190915260808401526001600160801b031660a083015260c082015260e00160405180910390a250505050505050565b5f80546001600160a01b038381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b612b7261375f565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611e333390565b60605f82602001515167ffffffffffffffff811115612bc857612bc8614c9e565b604051908082528060200260200182016040528015612bf1578160200160208202803683370190505b5090505f805b846020015151811015612d85575f85602001518281518110612c1b57612c1b6152f3565b602002602001015190508560400151612c5b5786546040820151875160200151612c56926001600160a01b039182169291169030905f613b53565b612c80565b86546040820151875151612c80926001600160a01b039182169291169030905f613b53565b86548651604080516080810182528451600290810b825260208087015190910b908201526060808601516001600160801b031682840152918a01515f946001600160a01b031693635a6bcfda9390929190820190612cdf576001612ce1565b5f5b60ff1690526040516001600160e01b031960e085901b168152612d08929190600401615c4e565b60408051808303815f875af1158015612d23573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612d4791906158f2565b91505080858481518110612d5d57612d5d6152f3565b60209081029190910101528015612d7b57612d788482613b27565b93505b5050600101612bf7565b50612d9485855f015183613d53565b835151612da2908690613e62565b612db385855f015160200151613e62565b81604051602001612dc49190615ced565b6040516020818303038152906040529250505092915050565b6060612e2283612df0845f015160801d90565b6001600160801b0316612e07856020015160801d90565b6001600160801b031685604001515f01518660600151613ee9565b8151612e60908490600f0b6001600160801b0316612e448560200151600f0b90565b6001600160801b03168560400151602001518660600151613ee9565b612e718383604001515f0151613e62565b612e8383836040015160200151613e62565b604080515f602082015201604051602081830303815290604052905092915050565b60605f80612eca85855f01518660200151876040015188606001518960a0015161419f565b8551519193509150612edd908690613e62565b612eee85855f015160200151613e62565b6040805160208101849052908101829052606001612dc4565b60605f82806020019051810190612f1e9190615d24565b805160a090209091505f5b826020015151811015612fca575f83602001518281518110612f4d57612f4d6152f3565b6020908102919091018101515f8581526015835260408082208383529093529190912060010154909150600160881b900460ff16612f8b5750612fc2565b60e881901c60d082901c6001808416145f81612fa75783612fa9565b825b9050612fba885f015188878461330a565b505050505050505b600101612f29565b5050604080515f8152602081019091529392505050565b60605f612ff6612ff18688615dfd565b614375565b60020b90505f8360020b8261300b9190615e22565b61301690600161531b565b67ffffffffffffffff81111561302e5761302e614c9e565b604051908082528060200260200182016040528015613057578160200160208202803683370190505b5090505f8086613073575f8a8152601160205260409020613081565b5f8a81526012602052604090205b90505f8761309b575f8b81526013602052604090206130a9565b5f8b81526014602052604090205b9050895b886130c1578960020b8160020b12156130cc565b8960020b8160020b13155b613196575f806130de85848c8e61438f565b915091505f8b6130f6578c60020b8360020b13613101565b8c60020b8360020b13155b90508015613110578c92505f91505b811561316157600283900b5f90815260208690526040902054156131615782888861313a81615343565b99508151811061314c5761314c6152f3565b602002602001019060020b908160020b815250505b8c60020b8360020b0361317657505050613196565b8b613181578261318c565b61318c600184615dfd565b93505050506130ad565b5050508152979650505050505050565b5f8284516131b491906158df565b90505f8167ffffffffffffffff8111156131d0576131d0614c9e565b6040519080825280602002602001820160405280156131f9578160200160208202803683370190505b509050835b85518110156132c9575f86828151811061321a5761321a6152f3565b602002602001015190505f8561324c575f898152601360209081526040808320600286900b845290915290205461326a565b5f898152601460209081526040808320600286900b84529091529020545b5f8a81526015602090815260408083208484529091529020600101805460ff60881b1916600160881b179055905080846132a489866158df565b815181106132b4576132b46152f3565b602090810291909101015250506001016131fe565b50857fe0b7c8733b12019f55165d26afd47f95c579a7c8cbea0775f30d30e05407439d826040516132fa9190615e41565b60405180910390a2505050505050565b5f8381526015602090815260408083208584529091528120600190810154829160e886901c9160d087901c918088161490613357906003908b90869086906001600160801b03168661419f565b9095509350613367888886613509565b5f8881526015602090815260408083208a84529091529020600101805460ff60801b191690819055600160881b900460ff16156133c5575f8881526015602090815260408083208a84529091529020600101805460ff60881b191690555b61344a816133d45760146133d7565b60135b826133e35760126133e6565b60115b60a08c2060608d01515f82815260209384526040808220600293840b8e850b8181078513918105919091039485900b60081d600190810b8552918752828420805460ff9096169290921b199094169055928152938352818420908452909152812055565b5f81613456575f613459565b60015b5f8a815260106020908152604080832060ff9490941660d088901b62ffffff60d01b1660e88a901b7fffffff00000000000000000000000000000000000000000000000000000000001617178084529390915281208054929350906134bd83615343565b9190505550887fe7ce370cc0425e330fd66bf98129d75f24695dba59b19d1df832da3c809327c3896040516134f491815260200190565b60405180910390a25050505094509492505050565b5f8381526015602090815260408083208584529091528120600181015490916001600160801b03909116900361353f5750505050565b8161354a5750505050565b8054600182015460405163df3f04d160e01b8152600481018590526001600160801b03909116602482015261359e919073b163b2c672d972c58f23c5373c29163d0913e8829063df3f04d190604401612825565b9055505050565b5f608082811d9084901d03600f83810b9085900b036112c76135c68361447c565b6135cf8361447c565b6001600160801b031660809190911b1790565b6135ed838686612608565b5f868152600e60209081526040808320888452909152902061360f908561449d565b505f868152600e60209081526040808320888452909152902061363190611e50565b5f03611071575f8681526015602090815260408083208884529091529020600101805471ffff00000000000000000000000000000000191690556110718261367a57601461367d565b60135b8361368957601261368c565b60115b61369b36879003870187615231565b60a081206060909101515f82815260209384526040808220600293840b89850b8181078513918105919091039485900b60081d600190810b8552918752828420805460ff9096169290921b199094169055928152938352818420908452909152812055565b60025460ff16610aa157604051638dfc202b60e01b815260040160405180910390fd5b6040515f90613742908390600690602001918252602082015260400190565b604051602081830303815290604052805190602001209050919050565b60025460ff1615610aa15760405163d93c066560e01b815260040160405180910390fd5b61378b6119e6565b82156138335780516001600160a01b031661381257813410156137ac575f80fd5b8134111561380d575f336137c084346158df565b6040515f81818185875af1925050503d805f81146137f9576040519150601f19603f3d011682016040523d82523d5f602084013e6137fe565b606091505b505090508061380b575f80fd5b505b610db3565b341561381c575f80fd5b805161380d906001600160a01b03163330856144b1565b341561383d575f80fd5b6020810151610db3906001600160a01b03163330856144b1565b5f8082613864575f613867565b60015b60ff1660d08562ffffff16901b60e88762ffffff16901b17175f1b91508261388f575f613892565b60015b60ff166008885f8981526020019081526020015f205f8581526020019081526020015f2054901b60d08662ffffff16901b60e88862ffffff16901b1717175f1b90509550959350505050565b5f8481526015602090815260408083208684528252808320878452600f835281842087855283528184206001600160a01b03861685528352818420888552600e84528285208886529093529220613935908461452d565b61399c575f6002820181905560038201819055868152600e602090815260408083208884529091529020613969908461454e565b506001600160a01b0383165f90815260166020908152604080832089845290915290206139969086614562565b50613a69565b80546001600160801b031615613a69575f6139be835f015483600101546135a5565b8254604051630d496cc160e21b8152600481018390526001600160801b03909116602482018190529192505f9073b163b2c672d972c58f23c5373c29163d0913e88290633525b30490604401602060405180830381865af4158015613a25573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613a499190615933565b90508015613a6557613a5f846003015482613b27565b60038501555b5050505b815460018201558054849082905f90613a8c9084906001600160801b0316615e53565b92506101000a8154816001600160801b0302191690836001600160801b0316021790555083826001015f8282829054906101000a90046001600160801b0316613ad59190615e53565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550505050505050565b5f825f018281548110613b1657613b166152f3565b905f5260205f200154905092915050565b5f608082811d9084901d01600f83810b9085900b016112c76135c68361447c565b5f610aee838361456d565b8015613be757836001600160a01b031663f5298aca84613b82886001600160a01b03166001600160a01b031690565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604481018590526064015f604051808303815f87803b158015613bcc575f80fd5b505af1158015613bde573d5f803e3d5ffd5b50505050611073565b6001600160a01b038516613c5e57836001600160a01b03166311da60b4836040518263ffffffff1660e01b815260040160206040518083038185885af1158015613c33573d5f803e3d5ffd5b50505050506040513d601f19601f82011682018060405250810190613c589190615933565b50611073565b604051632961046560e21b81526001600160a01b03868116600483015285169063a5841194906024015f604051808303815f87803b158015613c9e575f80fd5b505af1158015613cb0573d5f803e3d5ffd5b505050506001600160a01b0383163014613cde57613cd96001600160a01b0386168486856144b1565b613cf2565b613cf26001600160a01b0386168584614650565b836001600160a01b03166311da60b46040518163ffffffff1660e01b81526004016020604051808303815f875af1158015613d2f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110719190615933565b5f613d5e8260801d90565b90505f613d6b83600f0b90565b90505f82600f0b1315613de35784548451604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f85900b604482015291169063156e29f6906064015f604051808303815f87803b158015613dcc575f80fd5b505af1158015613dde573d5f803e3d5ffd5b505050505b5f81600f0b13156110735784546020850151604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f84900b604482015291169063156e29f6906064015f604051808303815f87803b158015613e45575f80fd5b505af1158015613e57573d5f803e3d5ffd5b505050505050505050565b81545f90613e7a906001600160a01b03163084614681565b90505f811315610dbc57825460405163203c2d1360e21b81526001600160a01b03848116600483015260248201849052909116906380f0b44c906044015f604051808303815f87803b158015613ece575f80fd5b505af1158015613ee0573d5f803e3d5ffd5b50505050505050565b83158015613ef5575082155b611073575f826001600160a01b031690505f613f1a858860020154896003015461471a565b90505f613f2782876158df565b613f31908861531b565b905080156140be578754604051637a94c56560e11b815230600482015260248101859052604481018390526001600160a01b039091169063f5298aca906064015f604051808303815f87803b158015613f88575f80fd5b505af1158015613f9a573d5f803e3d5ffd5b50508954604051630b0d9c0960e01b81526001600160a01b0389811660048301528881166024830152604482018690529091169250630b0d9c0991506064015f604051808303815f87803b158015613ff0575f80fd5b505af1925050508015614001575060015b6140be5787546001890154604051630b0d9c0960e01b81526001600160a01b038881166004830152918216602482015260448101849052911690630b0d9c09906064015f604051808303815f87803b15801561405b575f80fd5b505af115801561406d573d5f803e3d5ffd5b5050604080516001600160a01b03808a168252881660208201529081018490527f28012a1ba9530a2c13f4c905d8052e47e026a10b80e63d0c69730506cd9fa0829250606001905060405180910390a15b8115611985578754604051637a94c56560e11b815230600482015260248101859052604481018490526001600160a01b039091169063f5298aca906064015f604051808303815f87803b158015614113575f80fd5b505af1158015614125573d5f803e3d5ffd5b5050895460018b0154604051630b0d9c0960e01b81526001600160a01b038a8116600483015291821660248201526044810187905291169250630b0d9c0991506064015f604051808303815f87803b15801561417f575f80fd5b505af1158015614191573d5f803e3d5ffd5b505050505050505050505050565b855460408051608081018252600287810b825286900b60208201525f9283926001600160a01b0390911691635a6bcfda918a919081016141de89615e72565b600f0b8152602001876141f25760016141f4565b5f5b60ff1690526040516001600160e01b031960e085901b16815261421b929190600401615c4e565b60408051808303815f875af1158015614236573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061425a91906158f2565b90925090505f61426a8360801d90565b90505f61427784600f0b90565b90505f82600f0b13156142ef5789548951604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f85900b604482015291169063156e29f6906064015f604051808303815f87803b1580156142d8575f80fd5b505af11580156142ea573d5f803e3d5ffd5b505050505b5f81600f0b131561436857895460208a0151604051630ab714fb60e11b81523060048201526001600160a01b039182166024820152600f84900b604482015291169063156e29f6906064015f604051808303815f87803b158015614351575f80fd5b505af1158015614363573d5f803e3d5ffd5b505050505b5050965096945050505050565b5f808260020b126143865781610af1565b610af182615e9f565b5f80600284810b9086900b818107831391900503831561440e57600281900b60081d600181900b5f908152602089905260409020545f1960ff808516908190039190911c9182168015159550909190856143f057888360ff16860302614403565b886143fa826147b6565b840360ff168603025b965050505050614472565b6001908101600281900b60081d80830b5f90815260208a905260409020545f1960ff841694851b01199081168015159550929391928561445857888360ff0360ff1686010261446b565b888361446383614841565b0360ff168601025b9650505050505b5094509492505050565b80600f81900b8114614498576144986393dafdf160e01b6148db565b919050565b5f610aee836001600160a01b03841661456d565b6040516001600160a01b0384811660248301528381166044830152606482018390526111029186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506148e3565b6001600160a01b0381165f9081526001830160205260408120541515610aee565b5f610aee836001600160a01b038416614944565b5f610aee8383614944565b5f8181526001830160205260408120548015614647575f61458f6001836158df565b85549091505f906145a2906001906158df565b9050808214614601575f865f0182815481106145c0576145c06152f3565b905f5260205f200154905080875f0184815481106145e0576145e06152f3565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061461257614612615eb7565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050610af1565b5f915050610af1565b6040516001600160a01b03838116602483015260448201839052610dbc91859182169063a9059cbb906064016144e6565b5f806001600160a01b0384165f526001600160a01b03831660205260405f209050846001600160a01b031663f135baaa826040518263ffffffff1660e01b81526004016146d091815260200190565b602060405180830381865afa1580156146eb573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061470f9190615933565b9150505b9392505050565b5f838302815f1985870982811083820303915050808411614739575f80fd5b805f0361474b57508290049050614713565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f8082116147c2575f80fd5b507f0706060506020500060203020504000106050205030304010505030400000000601f6f8421084210842108cc6318c6db6d54be6001600160801b03841160071b84811c67ffffffffffffffff1060061b1784811c63ffffffff1060051b1784811c61ffff1060041b1784811c60ff1060031b1793841c1c161a1790565b5f80821161484d575f80fd5b507e1f0d1e100c1d070f090b19131c1706010e11080a1a141802121b15031604055f8290039091166101e07f804040554300526644320000502061067405302602000010750620017611707760fc7fb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff840260f81c161b60f71c1690811c63d76453e004601f169190911a1790565b805f5260045ffd5b5f6148f76001600160a01b03841683614990565b905080515f1415801561491b5750808060200190518101906149199190615a0f565b155b15610dbc57604051635274afe760e01b81526001600160a01b0384166004820152602401611847565b5f81815260018301602052604081205461498957508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155610af1565b505f610af1565b6060610aee83835f845f80856001600160a01b031684866040516149b49190615ecb565b5f6040518083038185875af1925050503d805f81146149ee576040519150601f19603f3d011682016040523d82523d5f602084013e6149f3565b606091505b5091509150614a03868383614a0d565b9695505050505050565b606082614a2257614a1d82614a69565b614713565b8151158015614a3957506001600160a01b0384163b155b15614a6257604051639996b31560e01b81526001600160a01b0385166004820152602401611847565b5080614713565b805115614a795780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f8060408385031215614aa3575f80fd5b50508035926020909101359150565b5f8060408385031215614ac3575f80fd5b823591506020830135600181900b8114614adb575f80fd5b809150509250929050565b5f60a08284031215614af6575f80fd5b50919050565b5f8060c08385031215614b0d575f80fd5b614b178484614ae6565b9460a0939093013593505050565b6001600160a01b0381168114611859575f80fd5b5f805f60608486031215614b4b575f80fd5b83359250602084013591506040840135614b6481614b25565b809150509250925092565b5f60208284031215614b7f575f80fd5b813561471381614b25565b5f60208284031215614b9a575f80fd5b5035919050565b5f8060408385031215614bb2575f80fd5b8235614bbd81614b25565b946020939093013593505050565b8015158114611859575f80fd5b8060020b8114611859575f80fd5b5f805f806101008587031215614bfa575f80fd5b8435614c0581614bcb565b93506020850135614c1581614bd8565b925060408501359150614c2b8660608701614ae6565b905092959194509250565b60808101610af1828480518252602081015115156020830152604081015160020b6040830152606081015160020b60608301525050565b5f805f60e08486031215614c7f575f80fd5b614c898585614ae6565b9560a0850135955060c0909401359392505050565b634e487b7160e01b5f52604160045260245ffd5b60405160a0810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b60405290565b6040805190810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b6040516080810167ffffffffffffffff81118282101715614cd557614cd5614c9e565b604051601f8201601f1916810167ffffffffffffffff81118282101715614d4a57614d4a614c9e565b604052919050565b5f67ffffffffffffffff821115614d6b57614d6b614c9e565b5060051b60200190565b5f8060c08385031215614d86575f80fd5b614d908484614ae6565b915060a083013567ffffffffffffffff811115614dab575f80fd5b8301601f81018513614dbb575f80fd5b8035614dce614dc982614d52565b614d21565b8082825260208201915060208360051b850101925087831115614def575f80fd5b6020840193505b82841015614e11578335825260209384019390910190614df6565b809450505050509250929050565b5f8060408385031215614e30575f80fd5b823591506020830135614adb81614bd8565b5f8060408385031215614e53575f80fd5b823591506020830135614adb81614bcb565b5f8083601f840112614e75575f80fd5b50813567ffffffffffffffff811115614e8c575f80fd5b6020830191508360208260051b8501011115614ea6575f80fd5b9250929050565b5f805f8060e08587031215614ec0575f80fd5b614eca8686614ae6565b935060a085013567ffffffffffffffff811115614ee5575f80fd5b614ef187828801614e65565b90945092505060c0850135614f0581614b25565b939692955090935050565b5f805f60c08486031215614f22575f80fd5b614f2c8585614ae6565b925060a084013567ffffffffffffffff811115614f47575f80fd5b614f5386828701614e65565b9497909650939450505050565b62ffffff81168114611859575f80fd5b5f60208284031215614f80575f80fd5b813561471381614f60565b5f8060208385031215614f9c575f80fd5b823567ffffffffffffffff811115614fb2575f80fd5b8301601f81018513614fc2575f80fd5b803567ffffffffffffffff811115614fd8575f80fd5b856020828401011115614fe9575f80fd5b6020919091019590945092505050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f610aee6020830184614ff9565b5f805f805f805f610160888a031215615050575f80fd5b873561505b81614bcb565b9650602088013561506b81614bd8565b9550604088013561507b81614bd8565b9450606088013593506080880135925060a0880135915061509f8960c08a01614ae6565b905092959891949750929550565b602080825282518282018190525f918401906040840190835b818110156151185761510283855180518252602081015115156020830152604081015160020b6040830152606081015160020b60608301525050565b60209390930192608092909201916001016150c6565b509095945050505050565b5f8060408385031215615134575f80fd5b823561513f81614b25565b91506020830135614adb81614bcb565b5f805f8060808587031215615162575f80fd5b843561516d81614b25565b966020860135965060408601359560600135945092505050565b602080825282518282018190525f918401906040840190835b818110156151185783516001600160801b0381511684526020810151602085015260408101516040850152506060830192506020840193506001810190506151a0565b5f805f8061010085870312156151f7575f80fd5b6152018686614ae6565b935060a085013561521181614bd8565b925060c085013561522181614bd8565b915060e0850135614f0581614bcb565b5f60a0828403128015615242575f80fd5b5061524b614cb2565b823561525681614b25565b8152602083013561526681614b25565b6020820152604083013561527981614f60565b6040820152606083013561528c81614bd8565b6060820152608083013561529f81614b25565b60808201529392505050565b5f602082840312156152bb575f80fd5b813561471381614bd8565b5f80604083850312156152d7575f80fd5b82516152e281614bd8565b6020840151909250614adb81614bd8565b634e487b7160e01b5f52603260045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610af157610af1615307565b5f8161533c5761533c615307565b505f190190565b5f6001820161535457615354615307565b5060010190565b634e487b7160e01b5f52602160045260245ffd5b5f8151808452602084019350602083015f5b8281101561539f578151865260209586019590910190600101615381565b5093949350505050565b602081526154096020820183516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b5f602083015160c080840152610ce060e084018261536f565b602081525f82516004811061544557634e487b7160e01b5f52602160045260245ffd5b806020840152506020830151604080840152610ce06060840182614ff9565b5f67ffffffffffffffff82111561547d5761547d614c9e565b50601f01601f191660200190565b5f6020828403121561549b575f80fd5b815167ffffffffffffffff8111156154b1575f80fd5b8201601f810184136154c1575f80fd5b80516154cf614dc982615464565b8181528560208385010111156154e3575f80fd5b8160208401602083015e5f91810160200191909152949350505050565b5f60208284031215615510575f80fd5b813567ffffffffffffffff811115615526575f80fd5b820160408185031215615537575f80fd5b61553f614cdb565b81356004811061554d575f80fd5b8152602082013567ffffffffffffffff811115615568575f80fd5b80830192505084601f83011261557c575f80fd5b813561558a614dc982615464565b81815286602083860101111561559e575f80fd5b816020850160208301375f602092820183015290820152949350505050565b5f60a082840312156155cd575f80fd5b6155d5614cb2565b905081516155e281614b25565b815260208201516155f281614b25565b6020820152604082015161560581614f60565b6040820152606082015161561881614bd8565b6060820152608082015161562b81614b25565b608082015292915050565b80516001600160801b0381168114614498575f80fd5b5f82601f83011261565b575f80fd5b8151615669614dc982614d52565b8082825260208201915060208360071b86010192508583111561568a575f80fd5b602085015b838110156156f957608081880312156156a6575f80fd5b6156ae614cfe565b81516156b981614bd8565b815260208201516156c981614bd8565b6020820152604082810151908201526156e460608301615636565b6060820152835260209092019160800161568f565b5095945050505050565b5f60208284031215615713575f80fd5b815167ffffffffffffffff811115615729575f80fd5b8201610100818503121561573b575f80fd5b615743614cfe565b61574d85836155bd565b815260a082015167ffffffffffffffff811115615768575f80fd5b6157748682850161564c565b60208301525060c082015161578881614bcb565b604082015260e091909101519061579e82614b25565b60608101919091529392505050565b5f6101008284031280156157bf575f80fd5b506157c8614cfe565b82518152602080840151908201526157e384604085016155bd565b604082015260e08301516157f681614b25565b60608201529392505050565b5f610140828403128015615814575f80fd5b5060405160c0810167ffffffffffffffff8111828210171561583857615838614c9e565b60405261584584846155bd565b815260a083015161585581614bd8565b602082015260c083015161586881614bd8565b604082015261587960e08401615636565b606082015261010083015161588d81614b25565b60808201526101208301516158a181614bcb565b60a08201529392505050565b5f602082840312156158bd575f80fd5b815167ffffffffffffffff8111156158d3575f80fd5b610ce08482850161564c565b81810381811115610af157610af1615307565b5f8060408385031215615903575f80fd5b505080516020909101519092909150565b6001600160801b038281168282160390811115610af157610af1615307565b5f60208284031215615943575f80fd5b5051919050565b5f8151808452602084019350602083015f5b8281101561539f5761599f868351805160020b8252602081015160020b6020830152604081015160408301526001600160801b0360608201511660608301525050565b608095909501946020919091019060010161595c565b60a081525f6159c760a083018861594a565b95151560208301525060408101939093526060830191909152608090910152919050565b606081525f6159fd606083018661594a565b60208301949094525060400152919050565b5f60208284031215615a1f575f80fd5b815161471381614bcb565b602081525f6101208201615a906020840185516001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b60208481015161010060c086015280519283905201905f906101408501905b80831015615b0957615af2828551805160020b8252602081015160020b6020830152604081015160408301526001600160801b0360608201511660608301525050565b608082019150602084019350600183019250615aaf565b506040860151151560e08601526060909501516001600160a01b031661010090940193909352509192915050565b5f60208284031215615b47575f80fd5b815167ffffffffffffffff811115615b5d575f80fd5b8201601f81018413615b6d575f80fd5b8051615b7b614dc982614d52565b8082825260208201915060208360051b850101925086831115615b9c575f80fd5b6020840193505b82841015614a03578351825260209384019390910190615ba3565b5f6101008201905082518252602083015160208301526040830151615c3460408401826001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b506001600160a01b0360608401511660e083015292915050565b615ca681846001600160a01b0381511682526001600160a01b03602082015116602083015262ffffff6040820151166040830152606081015160020b60608301526001600160a01b0360808201511660808301525050565b8151600290810b60a08301526020830151900b60c0820152604082015160e082015260609091015161010082015261014061012082018190525f9082015261016001919050565b602080825282518282018190525f918401906040840190835b81811015615118578351835260209384019390920191600101615d06565b5f60208284031215615d34575f80fd5b815167ffffffffffffffff811115615d4a575f80fd5b820160c08185031215615d5b575f80fd5b615d63614cdb565b615d6d85836155bd565b815260a082015167ffffffffffffffff811115615d88575f80fd5b80830192505084601f830112615d9c575f80fd5b8151615daa614dc982614d52565b8082825260208201915060208360051b860101925087831115615dcb575f80fd5b6020850194505b82851015615ded578451825260209485019490910190615dd2565b6020840152509095945050505050565b600282810b9082900b03627fffff198112627fffff82131715610af157610af1615307565b5f82615e3c57634e487b7160e01b5f52601260045260245ffd5b500490565b602081525f610aee602083018461536f565b6001600160801b038181168382160190811115610af157610af1615307565b5f81600f0b6f7fffffffffffffffffffffffffffffff198103615e9757615e97615307565b5f0392915050565b5f8160020b627fffff198103615e9757615e97615307565b634e487b7160e01b5f52603160045260245ffd5b5f82518060208501845e5f92019182525091905056fea264697066735822122030ef006422669fb974ced209f82cdce41c4bc0ee3ec84fd5a687a9aa2d94861e64736f6c634300081a0033

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

0000000000000000000000001f98400000000000000000000000000000000004000000000000000000000000846e79175c78371dafe6598f57b503b66c03ef9c000000000000000000000000e911f518449ba0011d84b047b4cde50daa081ec1

-----Decoded View---------------
Arg [0] : _poolManagerAddr (address): 0x1F98400000000000000000000000000000000004
Arg [1] : _treasury (address): 0x846E79175c78371DafE6598F57b503B66C03Ef9C
Arg [2] : _owner (address): 0xe911f518449ba0011D84b047B4cde50dAA081eC1

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


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]
[ 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.