ETH Price: $2,844.19 (-3.22%)
 

Overview

ETH Balance

0 ETH

ETH Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

Transaction Hash
Block
From
To
Execute413046202026-01-26 3:36:279 mins ago1769398587IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002520.00971468
Execute413046152026-01-26 3:36:179 mins ago1769398577IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002570.00969981
Execute413046062026-01-26 3:35:5910 mins ago1769398559IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002540.00960116
Execute413046002026-01-26 3:35:4710 mins ago1769398547IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002530.00957899
Execute413045592026-01-26 3:34:2511 mins ago1769398465IN
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH0.00000220.00935697
Execute413045482026-01-26 3:34:0312 mins ago1769398443IN
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH0.000002140.00911419
Execute413045412026-01-26 3:33:4912 mins ago1769398429IN
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH0.000002120.00907137
Execute413045352026-01-26 3:33:3712 mins ago1769398417IN
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH0.000002250.00893775
Execute413044672026-01-26 3:31:2114 mins ago1769398281IN
Pancakeswap Infinity: UniversalRouter
0.00000004 ETH0.000004990.01842345
Execute413044242026-01-26 3:29:5516 mins ago1769398195IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.00000160.00838901
Execute413043982026-01-26 3:29:0317 mins ago1769398143IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.00000590.00881528
Execute413043762026-01-26 3:28:1917 mins ago1769398099IN
Pancakeswap Infinity: UniversalRouter
0.042599 ETH0.000001310.00882511
Execute413043662026-01-26 3:27:5918 mins ago1769398079IN
Pancakeswap Infinity: UniversalRouter
1.60709355 ETH0.000002130.00891735
Execute413043512026-01-26 3:27:2918 mins ago1769398049IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002520.01881689
Execute413043312026-01-26 3:26:4919 mins ago1769398009IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000002480.01849394
Execute413043142026-01-26 3:26:1519 mins ago1769397975IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000001160.00863811
Execute413043052026-01-26 3:25:5720 mins ago1769397957IN
Pancakeswap Infinity: UniversalRouter
0.00129599 ETH0.000004310.008694
Execute413042992026-01-26 3:25:4520 mins ago1769397945IN
Pancakeswap Infinity: UniversalRouter
0.00129599 ETH0.000004580.0087191
Execute413042912026-01-26 3:25:2920 mins ago1769397929IN
Pancakeswap Infinity: UniversalRouter
0.00129599 ETH0.000004370.0086872
Execute413042852026-01-26 3:25:1720 mins ago1769397917IN
Pancakeswap Infinity: UniversalRouter
0.00129599 ETH0.000004290.0086255
Execute413042812026-01-26 3:25:0921 mins ago1769397909IN
Pancakeswap Infinity: UniversalRouter
0.01202314 ETH0.000001520.00865416
Execute413042642026-01-26 3:24:3521 mins ago1769397875IN
Pancakeswap Infinity: UniversalRouter
0.0047575 ETH0.000001450.00890496
Execute413042412026-01-26 3:23:4922 mins ago1769397829IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000001780.0088867
Execute413042352026-01-26 3:23:3722 mins ago1769397817IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000001890.00892306
Execute413042272026-01-26 3:23:2122 mins ago1769397801IN
Pancakeswap Infinity: UniversalRouter
0 ETH0.000003710.00895508
View all transactions

Latest 25 internal transactions (View All)

Parent Transaction Hash Block From To
413047152026-01-26 3:39:376 mins ago1769398777
Pancakeswap Infinity: UniversalRouter
0.0343 ETH
413047152026-01-26 3:39:376 mins ago1769398777
Pancakeswap Infinity: UniversalRouter
0.0343 ETH
413045592026-01-26 3:34:2511 mins ago1769398465
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH
413045482026-01-26 3:34:0312 mins ago1769398443
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH
413045412026-01-26 3:33:4912 mins ago1769398429
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH
413045352026-01-26 3:33:3712 mins ago1769398417
Pancakeswap Infinity: UniversalRouter
0.00129069 ETH
413045342026-01-26 3:33:3512 mins ago1769398415
Pancakeswap Infinity: UniversalRouter
0.00684668 ETH
413045342026-01-26 3:33:3512 mins ago1769398415
Pancakeswap Infinity: UniversalRouter
0.00684668 ETH
413044672026-01-26 3:31:2114 mins ago1769398281
Pancakeswap Infinity: UniversalRouter
0 ETH
413044672026-01-26 3:31:2114 mins ago1769398281
Pancakeswap Infinity: UniversalRouter
0 ETH
413044672026-01-26 3:31:2114 mins ago1769398281
Pancakeswap Infinity: UniversalRouter
0.00000004 ETH
413044562026-01-26 3:30:5915 mins ago1769398259
Pancakeswap Infinity: UniversalRouter
0.00862387 ETH
413044562026-01-26 3:30:5915 mins ago1769398259
Pancakeswap Infinity: UniversalRouter
0.00862387 ETH
413044302026-01-26 3:30:0716 mins ago1769398207
Pancakeswap Infinity: UniversalRouter
0.00008 ETH
413044302026-01-26 3:30:0716 mins ago1769398207
Pancakeswap Infinity: UniversalRouter
0.00008 ETH
413044242026-01-26 3:29:5516 mins ago1769398195
Pancakeswap Infinity: UniversalRouter
0.04258498 ETH
413044242026-01-26 3:29:5516 mins ago1769398195
Pancakeswap Infinity: UniversalRouter
0.04258498 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.01277747 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.01277747 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.00425916 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.00425916 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.00851833 ETH
413043982026-01-26 3:29:0317 mins ago1769398143
Pancakeswap Infinity: UniversalRouter
0.00851833 ETH
413043762026-01-26 3:28:1917 mins ago1769398099
Pancakeswap Infinity: UniversalRouter
0.042599 ETH
413043662026-01-26 3:27:5918 mins ago1769398079
Pancakeswap Infinity: UniversalRouter
1.60709355 ETH
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
UniversalRouter

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 20000 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity 0.8.26;

// Command implementations
import {Dispatcher} from "./base/Dispatcher.sol";
import {RouterParameters, RouterImmutables} from "./base/RouterImmutables.sol";
import {InfinitySwapRouter} from "./modules/pancakeswap/infinity/InfinitySwapRouter.sol";
import {Commands} from "./libraries/Commands.sol";
import {Constants} from "./libraries/Constants.sol";
import {IUniversalRouter} from "./interfaces/IUniversalRouter.sol";
import {StableSwapRouter} from "./modules/pancakeswap/StableSwapRouter.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";

contract UniversalRouter is RouterImmutables, IUniversalRouter, Dispatcher, Pausable {
    constructor(RouterParameters memory params)
        RouterImmutables(params)
        StableSwapRouter(params.stableFactory, params.stableInfo)
        InfinitySwapRouter(params.infiVault, params.infiClPoolManager, params.infiBinPoolManager)
    {}

    modifier checkDeadline(uint256 deadline) {
        if (block.timestamp > deadline) revert TransactionDeadlinePassed();
        _;
    }

    /// @notice To receive ETH from WETH
    receive() external payable {
        if (msg.sender != address(WETH9) && msg.sender != address(vault)) revert InvalidEthSender();
    }

    /// @inheritdoc IUniversalRouter
    function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline)
        external
        payable
        checkDeadline(deadline)
    {
        execute(commands, inputs);
    }

    /// @inheritdoc Dispatcher
    function execute(bytes calldata commands, bytes[] calldata inputs)
        public
        payable
        override
        isNotLocked
        whenNotPaused
    {
        bool success;
        bytes memory output;
        uint256 numCommands = commands.length;
        if (inputs.length != numCommands) revert LengthMismatch();

        // loop through all given commands, execute them and pass along outputs as defined
        for (uint256 commandIndex = 0; commandIndex < numCommands; commandIndex++) {
            bytes1 command = commands[commandIndex];

            bytes calldata input = inputs[commandIndex];

            (success, output) = dispatch(command, input);

            if (!success && successRequired(command)) {
                revert ExecutionFailed({commandIndex: commandIndex, message: output});
            }
        }
    }

    function successRequired(bytes1 command) internal pure returns (bool) {
        return command & Commands.FLAG_ALLOW_REVERT == 0;
    }

    /**
     * @dev called by the owner to pause, triggers stopped state
     */
    function pause() external onlyOwner whenNotPaused {
        _pause();
    }

    /**
     * @dev called by the owner to unpause, returns to normal state
     */
    function unpause() external onlyOwner whenPaused {
        _unpause();
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;

import {V2SwapRouter} from "../modules/pancakeswap/v2/V2SwapRouter.sol";
import {V3SwapRouter} from "../modules/pancakeswap/v3/V3SwapRouter.sol";
import {InfinitySwapRouter} from "../modules/pancakeswap/infinity/InfinitySwapRouter.sol";
import {StableSwapRouter} from "../modules/pancakeswap/StableSwapRouter.sol";
import {Payments} from "../modules/Payments.sol";
import {RouterImmutables} from "../base/RouterImmutables.sol";
import {V3ToInfinityMigrator} from "../modules/V3ToInfinityMigrator.sol";
import {BytesLib} from "../libraries/BytesLib.sol";
import {Commands} from "../libraries/Commands.sol";
import {Lock} from "./Lock.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";
import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {ActionConstants} from "infinity-periphery/src/libraries/ActionConstants.sol";
import {BaseActionsRouter} from "infinity-periphery/src/base/BaseActionsRouter.sol";
import {CalldataDecoder} from "infinity-periphery/src/libraries/CalldataDecoder.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {ICLPoolManager} from "infinity-core/src/pool-cl/interfaces/ICLPoolManager.sol";
import {IBinPoolManager} from "infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol";

/// @title Decodes and Executes Commands
/// @notice Called by the UniversalRouter contract to efficiently decode and execute a singular command
abstract contract Dispatcher is
    Payments,
    V2SwapRouter,
    V3SwapRouter,
    StableSwapRouter,
    InfinitySwapRouter,
    V3ToInfinityMigrator,
    Lock
{
    using BytesLib for bytes;
    using CalldataDecoder for bytes;

    error InvalidCommandType(uint256 commandType);
    error BalanceTooLow();

    /// @notice Executes encoded commands along with provided inputs.
    /// @param commands A set of concatenated commands, each 1 byte in length
    /// @param inputs An array of byte strings containing abi encoded inputs for each command
    function execute(bytes calldata commands, bytes[] calldata inputs) external payable virtual;

    /// @notice Public view function to be used instead of msg.sender, as the contract performs self-reentrancy and at
    /// times msg.sender == address(this). Instead msgSender() returns the initiator of the lock
    function msgSender() public view override(BaseActionsRouter) returns (address) {
        return _getLocker();
    }

    /// @notice Decodes and executes the given command with the given inputs
    /// @param commandType The command type to execute
    /// @param inputs The inputs to execute the command with
    /// @dev inputs must be ABI encoded using abi.encode() to ensure proper padding. WARNING: Direct calldata
    //       manipulation or abi.encodePacked() can result in incorrect data reads.
    /// @dev 2 masks are used to enable use of a nested-if statement in execution for efficiency reasons
    /// @return success True on success of the command, false on failure
    /// @return output The outputs or error messages, if any, from the command
    function dispatch(bytes1 commandType, bytes calldata inputs) internal returns (bool success, bytes memory output) {
        uint256 command = uint8(commandType & Commands.COMMAND_TYPE_MASK);

        success = true;

        // 0x00 <= command < 0x21
        if (command < Commands.EXECUTE_SUB_PLAN) {
            // 0x00 <= command < 0x10
            if (command < Commands.INFI_SWAP) {
                // 0x00 <= command < 0x08
                if (command < Commands.V2_SWAP_EXACT_IN) {
                    if (command == Commands.V3_SWAP_EXACT_IN) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountIn;
                        uint256 amountOutMin;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountIn := calldataload(add(inputs.offset, 0x20))
                            amountOutMin := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        bytes calldata path = inputs.toBytes(3);
                        address payer = payerIsUser ? msgSender() : address(this);
                        v3SwapExactInput(map(recipient), amountIn, amountOutMin, path, payer);
                        return (success, output);
                    } else if (command == Commands.V3_SWAP_EXACT_OUT) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountOut;
                        uint256 amountInMax;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountOut := calldataload(add(inputs.offset, 0x20))
                            amountInMax := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        bytes calldata path = inputs.toBytes(3);
                        address payer = payerIsUser ? msgSender() : address(this);
                        v3SwapExactOutput(map(recipient), amountOut, amountInMax, path, payer);
                        return (success, output);
                    } else if (command == Commands.PERMIT2_TRANSFER_FROM) {
                        // equivalent: abi.decode(inputs, (address, address, uint160))
                        address token;
                        address recipient;
                        uint160 amount;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            amount := calldataload(add(inputs.offset, 0x40))
                        }
                        permit2TransferFrom(token, msgSender(), map(recipient), amount);
                        return (success, output);
                    } else if (command == Commands.PERMIT2_PERMIT_BATCH) {
                        IAllowanceTransfer.PermitBatch calldata permitBatch;
                        assembly {
                            // this is a variable length struct, so calldataload(inputs.offset) contains the
                            // offset from inputs.offset at which the struct begins
                            permitBatch := add(inputs.offset, calldataload(inputs.offset))
                        }
                        bytes calldata data = inputs.toBytes(1);
                        (success, output) = address(PERMIT2).call(
                            abi.encodeWithSignature(
                                "permit(address,((address,uint160,uint48,uint48)[],address,uint256),bytes)",
                                msgSender(),
                                permitBatch,
                                data
                            )
                        );
                        return (success, output);
                    } else if (command == Commands.SWEEP) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint160 amountMin;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            amountMin := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.sweep(token, map(recipient), amountMin);
                        return (success, output);
                    } else if (command == Commands.TRANSFER) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint256 value;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            value := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.pay(token, map(recipient), value);
                        return (success, output);
                    } else if (command == Commands.PAY_PORTION) {
                        // equivalent:  abi.decode(inputs, (address, address, uint256))
                        address token;
                        address recipient;
                        uint256 bips;
                        assembly {
                            token := calldataload(inputs.offset)
                            recipient := calldataload(add(inputs.offset, 0x20))
                            bips := calldataload(add(inputs.offset, 0x40))
                        }
                        Payments.payPortion(token, map(recipient), bips);
                        return (success, output);
                    } else {
                        // placeholder area for command 0x07
                        revert InvalidCommandType(command);
                    }
                } else {
                    // 0x08 <= command < 0x10
                    if (command == Commands.V2_SWAP_EXACT_IN) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountIn;
                        uint256 amountOutMin;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountIn := calldataload(add(inputs.offset, 0x20))
                            amountOutMin := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        address[] calldata path = inputs.toAddressArray(3);
                        address payer = payerIsUser ? msgSender() : address(this);
                        v2SwapExactInput(map(recipient), amountIn, amountOutMin, path, payer);
                        return (success, output);
                    } else if (command == Commands.V2_SWAP_EXACT_OUT) {
                        // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bool))
                        address recipient;
                        uint256 amountOut;
                        uint256 amountInMax;
                        bool payerIsUser;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountOut := calldataload(add(inputs.offset, 0x20))
                            amountInMax := calldataload(add(inputs.offset, 0x40))
                            // 0x60 offset is the path, decoded below
                            payerIsUser := calldataload(add(inputs.offset, 0x80))
                        }
                        address[] calldata path = inputs.toAddressArray(3);
                        address payer = payerIsUser ? msgSender() : address(this);
                        v2SwapExactOutput(map(recipient), amountOut, amountInMax, path, payer);
                        return (success, output);
                    } else if (command == Commands.PERMIT2_PERMIT) {
                        // equivalent: abi.decode(inputs, (IAllowanceTransfer.PermitSingle, bytes))
                        IAllowanceTransfer.PermitSingle calldata permitSingle;
                        assembly {
                            permitSingle := inputs.offset
                        }
                        bytes calldata data = inputs.toBytes(6); // PermitSingle takes first 6 slots (0..5)
                        (success, output) = address(PERMIT2).call(
                            abi.encodeWithSignature(
                                "permit(address,((address,uint160,uint48,uint48),address,uint256),bytes)",
                                msgSender(),
                                permitSingle,
                                data
                            )
                        );
                        return (success, output);
                    } else if (command == Commands.WRAP_ETH) {
                        // equivalent: abi.decode(inputs, (address, uint256))
                        address recipient;
                        uint256 amount;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amount := calldataload(add(inputs.offset, 0x20))
                        }
                        Payments.wrapETH(map(recipient), amount);
                        return (success, output);
                    } else if (command == Commands.UNWRAP_WETH) {
                        // equivalent: abi.decode(inputs, (address, uint256))
                        address recipient;
                        uint256 amountMin;
                        assembly {
                            recipient := calldataload(inputs.offset)
                            amountMin := calldataload(add(inputs.offset, 0x20))
                        }
                        Payments.unwrapWETH9(map(recipient), amountMin);
                        return (success, output);
                    } else if (command == Commands.PERMIT2_TRANSFER_FROM_BATCH) {
                        IAllowanceTransfer.AllowanceTransferDetails[] calldata batchDetails;
                        (uint256 length, uint256 offset) = inputs.toLengthOffset(0);
                        assembly {
                            batchDetails.length := length
                            batchDetails.offset := offset
                        }
                        permit2TransferFrom(batchDetails, msgSender());
                        return (success, output);
                    } else if (command == Commands.BALANCE_CHECK_ERC20) {
                        // equivalent: abi.decode(inputs, (address, address, uint256))
                        address owner;
                        address token;
                        uint256 minBalance;
                        assembly {
                            owner := calldataload(inputs.offset)
                            token := calldataload(add(inputs.offset, 0x20))
                            minBalance := calldataload(add(inputs.offset, 0x40))
                        }
                        success = (ERC20(token).balanceOf(owner) >= minBalance);
                        if (!success) output = abi.encodePacked(BalanceTooLow.selector);
                        return (success, output);
                    } else {
                        // placeholder area for command 0x0f
                        revert InvalidCommandType(command);
                    }
                }
            } else {
                // 0x10 <= command < 0x21
                if (command == Commands.INFI_SWAP) {
                    // pass the calldata provided to InfinitySwapRouter._executeActions (defined in BaseActionsRouter)
                    _executeActions(inputs);
                    return (success, output);
                    // This contract MUST be approved to spend the token since its going to be doing the call on the position manager
                } else if (command == Commands.V3_POSITION_MANAGER_PERMIT) {
                    _checkV3PermitCall(inputs);
                    (success, output) = address(V3_POSITION_MANAGER).call(inputs);
                    return (success, output);
                } else if (command == Commands.V3_POSITION_MANAGER_CALL) {
                    _checkV3PositionManagerCall(inputs, msgSender());
                    /// @dev ensure there's follow-up action if v3 position's removed token are sent to router contract
                    (success, output) = address(V3_POSITION_MANAGER).call(inputs);
                    return (success, output);
                } else if (command == Commands.INFI_CL_INITIALIZE_POOL) {
                    // equivalent: abi.decode(inputs, (PoolKey, uint160)) where PoolKey is
                    // (Currency currency0, Currency currency1, IHooks hooks, IPoolManager poolManager, uint24 fee, bytes32 parameters)
                    PoolKey calldata poolKey;
                    uint160 sqrtPriceX96;
                    assembly {
                        poolKey := inputs.offset
                        sqrtPriceX96 := calldataload(add(inputs.offset, 0xc0)) // poolKey has 6 variable, so it takes 192 space = 0xc0
                    }
                    (success, output) =
                        address(clPoolManager).call(abi.encodeCall(ICLPoolManager.initialize, (poolKey, sqrtPriceX96)));
                } else if (command == Commands.INFI_BIN_INITIALIZE_POOL) {
                    // equivalent: abi.decode(inputs, (PoolKey, uint24)) where PoolKey is
                    // (Currency currency0, Currency currency1, IHooks hooks, IPoolManager poolManager, uint24 fee, bytes32 parameters)
                    PoolKey calldata poolKey;
                    uint24 activeId;
                    assembly {
                        poolKey := inputs.offset
                        activeId := calldataload(add(inputs.offset, 0xc0)) // poolKey has 6 variable, so it takes 192 space = 0xc0
                    }
                    (success, output) =
                        address(binPoolManager).call(abi.encodeCall(IBinPoolManager.initialize, (poolKey, activeId)));
                } else if (command == Commands.INFI_CL_POSITION_CALL) {
                    _checkInfiClPositionManagerCall(inputs);
                    (success, output) = address(INFI_CL_POSITION_MANAGER).call{value: address(this).balance}(inputs);
                    return (success, output);
                } else if (command == Commands.INFI_BIN_POSITION_CALL) {
                    _checkInfiBinPositionManagerCall(inputs);
                    (success, output) = address(INFI_BIN_POSITION_MANAGER).call{value: address(this).balance}(inputs);
                    return (success, output);
                } else {
                    // placeholder area for commands 0x15-0x20
                    revert InvalidCommandType(command);
                }
            }
        } else {
            // 0x21 <= command
            if (command == Commands.EXECUTE_SUB_PLAN) {
                (bytes calldata _commands, bytes[] calldata _inputs) = inputs.decodeCommandsAndInputs();
                (success, output) = (address(this)).call(abi.encodeCall(Dispatcher.execute, (_commands, _inputs)));
                return (success, output);
            } else if (command == Commands.STABLE_SWAP_EXACT_IN) {
                // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bytes, bool))
                address recipient;
                uint256 amountIn;
                uint256 amountOutMin;
                bool payerIsUser;
                assembly {
                    recipient := calldataload(inputs.offset)
                    amountIn := calldataload(add(inputs.offset, 0x20))
                    amountOutMin := calldataload(add(inputs.offset, 0x40))
                    // 0x60 offset is the path and 0x80 is the flag, decoded below
                    payerIsUser := calldataload(add(inputs.offset, 0xa0))
                }
                address[] calldata path = inputs.toAddressArray(3);
                uint256[] calldata flag = inputs.toUintArray(4);
                address payer = payerIsUser ? msgSender() : address(this);
                stableSwapExactInput(map(recipient), amountIn, amountOutMin, path, flag, payer);
                return (success, output);
            } else if (command == Commands.STABLE_SWAP_EXACT_OUT) {
                // equivalent: abi.decode(inputs, (address, uint256, uint256, bytes, bytes, bool))
                address recipient;
                uint256 amountOut;
                uint256 amountInMax;
                bool payerIsUser;
                assembly {
                    recipient := calldataload(inputs.offset)
                    amountOut := calldataload(add(inputs.offset, 0x20))
                    amountInMax := calldataload(add(inputs.offset, 0x40))
                    // 0x60 offset is the path and 0x80 is the flag, decoded below
                    payerIsUser := calldataload(add(inputs.offset, 0xa0))
                }
                address[] calldata path = inputs.toAddressArray(3);
                uint256[] calldata flag = inputs.toUintArray(4);
                address payer = payerIsUser ? msgSender() : address(this);

                /// @dev structured this way as stack too deep by Yul
                uint256 amountIn = stableSwapExactOutputAmountIn(amountOut, amountInMax, path, flag);
                stableSwapExactOutput(map(recipient), amountIn, amountOut, path, flag, payer);
                return (success, output);
            } else {
                // placeholder area for commands 0x24-0x3f
                revert InvalidCommandType(command);
            }
        }
    }

    /// @notice Calculates the recipient address for a command
    /// @param recipient The recipient or recipient-flag for the command
    /// @return output The resultant recipient for the command
    function map(address recipient) internal view returns (address) {
        if (recipient == ActionConstants.MSG_SENDER) {
            return msgSender();
        } else if (recipient == ActionConstants.ADDRESS_THIS) {
            return address(this);
        } else {
            return recipient;
        }
    }
}

File 3 of 120 : RouterImmutables.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IPermit2} from "permit2/src/interfaces/IPermit2.sol";
import {IV3NonfungiblePositionManager} from
    "infinity-periphery/src/interfaces/external/IV3NonfungiblePositionManager.sol";
import {IPositionManager} from "infinity-periphery/src/interfaces/IPositionManager.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";
import {IWETH9} from "infinity-periphery/src/interfaces/external/IWETH9.sol";

struct RouterParameters {
    // Payment parameters
    address permit2;
    address weth9;
    // PCS swapping parameters
    address v2Factory;
    address v3Factory;
    address v3Deployer;
    bytes32 v2InitCodeHash;
    bytes32 v3InitCodeHash;
    address stableFactory;
    address stableInfo;
    // PCS infinity swapping parameters, param not in this contract as stored in infiSwapRouter
    address infiVault;
    address infiClPoolManager;
    address infiBinPoolManager;
    // PCS v3->infinity migration parameters
    address v3NFTPositionManager;
    address infiClPositionManager;
    address infiBinPositionManager;
}

/// @title Router Immutable Storage contract
/// @notice Used along with the `RouterParameters` struct for ease of cross-chain deployment
contract RouterImmutables {
    /// @dev WETH9 address
    IWETH9 internal immutable WETH9;

    /// @dev Permit2 address
    IPermit2 internal immutable PERMIT2;

    /// @dev The address of PancakeSwapV2Factory
    address internal immutable PANCAKESWAP_V2_FACTORY;

    /// @dev The PancakeSwapV2Pair initcodehash
    bytes32 internal immutable PANCAKESWAP_V2_PAIR_INIT_CODE_HASH;

    /// @dev The address of PancakeSwapV3Factory
    address internal immutable PANCAKESWAP_V3_FACTORY;

    /// @dev The PancakeSwapV3Pool initcodehash
    bytes32 internal immutable PANCAKESWAP_V3_POOL_INIT_CODE_HASH;

    /// @dev The address of PancakeSwap V3 Deployer
    address internal immutable PANCAKESWAP_V3_DEPLOYER;

    /// @dev v3PositionManager address
    IV3NonfungiblePositionManager public immutable V3_POSITION_MANAGER;

    /// @dev infinity CLPositionManager address
    IPositionManager public immutable INFI_CL_POSITION_MANAGER;

    /// @dev infinity BinPositionManager address
    IPositionManager public immutable INFI_BIN_POSITION_MANAGER;

    constructor(RouterParameters memory params) {
        PERMIT2 = IPermit2(params.permit2);
        WETH9 = IWETH9(params.weth9);
        PANCAKESWAP_V2_FACTORY = params.v2Factory;
        PANCAKESWAP_V2_PAIR_INIT_CODE_HASH = params.v2InitCodeHash;
        PANCAKESWAP_V3_FACTORY = params.v3Factory;
        PANCAKESWAP_V3_POOL_INIT_CODE_HASH = params.v3InitCodeHash;
        PANCAKESWAP_V3_DEPLOYER = params.v3Deployer;
        V3_POSITION_MANAGER = IV3NonfungiblePositionManager(params.v3NFTPositionManager);
        INFI_CL_POSITION_MANAGER = IPositionManager(params.infiClPositionManager);
        INFI_BIN_POSITION_MANAGER = IPositionManager(params.infiBinPositionManager);
    }
}

File 4 of 120 : InfinitySwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {Permit2Payments} from "../../Permit2Payments.sol";
import {InfinityRouter} from "infinity-periphery/src/InfinityRouter.sol";
import {IVault} from "infinity-core/src/interfaces/IVault.sol";
import {ICLPoolManager} from "infinity-core/src/pool-cl/interfaces/ICLPoolManager.sol";
import {IBinPoolManager} from "infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {Currency} from "infinity-core/src/types/Currency.sol";

/// @title Router for PCS Infinity Trades
abstract contract InfinitySwapRouter is InfinityRouter, Permit2Payments {
    constructor(address _vault, address _clPoolManager, address _binPoolManager)
        InfinityRouter(IVault(_vault), ICLPoolManager(_clPoolManager), IBinPoolManager(_binPoolManager))
    {}

    function _pay(Currency token, address payer, uint256 amount) internal override {
        payOrPermit2Transfer(Currency.unwrap(token), payer, address(vault), amount);
    }
}

File 5 of 120 : Commands.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/// @title Commands
/// @notice Command Flags used to decode commands
library Commands {
    // Masks to extract certain bits of commands
    bytes1 internal constant FLAG_ALLOW_REVERT = 0x80;
    bytes1 internal constant COMMAND_TYPE_MASK = 0x3f;

    // Command Types. Maximum supported command at this moment is 0x3f.
    // The commands are executed in nested if blocks to minimise gas consumption

    // Command Types where value<=0x07, executed in the first nested-if block
    uint256 constant V3_SWAP_EXACT_IN = 0x00;
    uint256 constant V3_SWAP_EXACT_OUT = 0x01;
    uint256 constant PERMIT2_TRANSFER_FROM = 0x02;
    uint256 constant PERMIT2_PERMIT_BATCH = 0x03;
    uint256 constant SWEEP = 0x04;
    uint256 constant TRANSFER = 0x05;
    uint256 constant PAY_PORTION = 0x06;
    // COMMAND_PLACEHOLDER = 0x07;

    // Command Types where 0x08<=value<=0x0f, executed in the second nested-if block
    uint256 constant V2_SWAP_EXACT_IN = 0x08;
    uint256 constant V2_SWAP_EXACT_OUT = 0x09;
    uint256 constant PERMIT2_PERMIT = 0x0a;
    uint256 constant WRAP_ETH = 0x0b;
    uint256 constant UNWRAP_WETH = 0x0c;
    uint256 constant PERMIT2_TRANSFER_FROM_BATCH = 0x0d;
    uint256 constant BALANCE_CHECK_ERC20 = 0x0e;
    // COMMAND_PLACEHOLDER = 0x0f;

    // Command Types where 0x10<=value<=0x20, executed in the third nested-if block
    uint256 constant INFI_SWAP = 0x10;
    uint256 constant V3_POSITION_MANAGER_PERMIT = 0x11;
    uint256 constant V3_POSITION_MANAGER_CALL = 0x12;
    uint256 constant INFI_CL_INITIALIZE_POOL = 0x13;
    uint256 constant INFI_BIN_INITIALIZE_POOL = 0x14;
    uint256 constant INFI_CL_POSITION_CALL = 0x15;
    uint256 constant INFI_BIN_POSITION_CALL = 0x16;
    // COMMAND_PLACEHOLDER = 0x17 -> 0x20

    // Command Types where 0x21<=value<=0x3f
    uint256 constant EXECUTE_SUB_PLAN = 0x21;
    uint256 constant STABLE_SWAP_EXACT_IN = 0x22;
    uint256 constant STABLE_SWAP_EXACT_OUT = 0x23;
    // COMMAND_PLACEHOLDER = 0x24 -> 0x3f
}

File 6 of 120 : Constants.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/// @title Constant state
/// @notice Constant state used by the Universal Router
library Constants {
    /// @dev Used for identifying cases when a v2 pair has already received input tokens
    uint256 internal constant ALREADY_PAID = 0;

    /// @dev Used as a flag for identifying the transfer of ETH instead of a token
    address internal constant ETH = address(0);

    /// @dev The length of the bytes encoded address
    uint256 internal constant ADDR_SIZE = 20;

    /// @dev The length of the bytes encoded fee
    uint256 internal constant V3_FEE_SIZE = 3;

    /// @dev The offset of a single token address (20) and pool fee (3)
    uint256 internal constant NEXT_V3_POOL_OFFSET = ADDR_SIZE + V3_FEE_SIZE;

    /// @dev The offset of an encoded pool key
    /// Token (20) + Fee (3) + Token (20) = 43
    uint256 internal constant V3_POP_OFFSET = NEXT_V3_POOL_OFFSET + ADDR_SIZE;

    /// @dev The minimum length of an encoding that contains 2 or more pools
    uint256 internal constant MULTIPLE_V3_POOLS_MIN_LENGTH = V3_POP_OFFSET + NEXT_V3_POOL_OFFSET;
}

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

interface IUniversalRouter {
    /// @notice Thrown when a required command has failed
    error ExecutionFailed(uint256 commandIndex, bytes message);

    /// @notice Thrown when attempting to send ETH directly to the contract
    error ETHNotAccepted();

    /// @notice Thrown when executing commands with an expired deadline
    error TransactionDeadlinePassed();

    /// @notice Thrown when attempting to execute commands and an incorrect number of inputs are provided
    error LengthMismatch();

    // @notice Thrown when an address that isnt WETH tries to send ETH to the router without calldata
    error InvalidEthSender();

    /// @notice Executes encoded commands along with provided inputs. Reverts if deadline has expired.
    /// @dev Caller is advised to add a sweep command at the end to take any remaining ETH in contract
    /// @param commands A set of concatenated commands, each 1 byte in length
    /// @param inputs An array of byte strings containing abi encoded inputs for each command
    /// @param deadline The deadline by which the transaction must be executed
    function execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline) external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {ActionConstants} from "infinity-periphery/src/libraries/ActionConstants.sol";
import {RouterImmutables} from "../../base/RouterImmutables.sol";
import {Payments} from "../Payments.sol";
import {Permit2Payments} from "../Permit2Payments.sol";
import {Constants} from "../../libraries/Constants.sol";
import {UniversalRouterHelper} from "../../libraries/UniversalRouterHelper.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol";
import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IStableSwap} from "../../interfaces/IStableSwap.sol";

/// @title Router for PancakeSwap Stable Trades
abstract contract StableSwapRouter is RouterImmutables, Permit2Payments, Ownable2Step {
    using SafeTransferLib for ERC20;
    using UniversalRouterHelper for address;

    error StableTooLittleReceived();
    error StableTooMuchRequested();
    error StableInvalidPath();

    address public stableSwapFactory;
    address public stableSwapInfo;

    event SetStableSwap(address indexed factory, address indexed info);

    constructor(address _stableSwapFactory, address _stableSwapInfo) Ownable(msg.sender) {
        stableSwapFactory = _stableSwapFactory;
        stableSwapInfo = _stableSwapInfo;
    }

    /**
     * @notice Set Pancake Stable Swap Factory and Info
     * @dev Only callable by contract owner
     */
    function setStableSwap(address _factory, address _info) external onlyOwner {
        require(_factory != address(0) && _info != address(0));

        stableSwapFactory = _factory;
        stableSwapInfo = _info;

        emit SetStableSwap(stableSwapFactory, stableSwapInfo);
    }

    function _stableSwap(address[] calldata path, uint256[] calldata flag) private {
        unchecked {
            if (path.length - 1 != flag.length) revert StableInvalidPath();

            for (uint256 i; i < flag.length; i++) {
                (address input, address output) = (path[i], path[i + 1]);
                (uint256 k, uint256 j, address swapContract) = stableSwapFactory.getStableInfo(input, output, flag[i]);
                uint256 amountIn = ERC20(input).balanceOf(address(this));
                ERC20(input).safeApprove(swapContract, amountIn);
                IStableSwap(swapContract).exchange(k, j, amountIn, 0);
            }
        }
    }

    /// @notice Performs a PancakeSwap stable exact input swap
    /// @param recipient The recipient of the output tokens
    /// @param amountIn The amount of input tokens for the trade
    /// @param amountOutMinimum The minimum desired amount of output tokens
    /// @param path The path of the trade as an array of token addresses
    /// @param flag token amount in a stable swap pool. 2 for 2pool, 3 for 3pool
    /// @param payer The address that will be paying the input
    function stableSwapExactInput(
        address recipient,
        uint256 amountIn,
        uint256 amountOutMinimum,
        address[] calldata path,
        uint256[] calldata flag,
        address payer
    ) internal {
        if (amountIn != Constants.ALREADY_PAID && amountIn != ActionConstants.CONTRACT_BALANCE) {
            payOrPermit2Transfer(path[0], payer, address(this), amountIn);
        }

        ERC20 tokenOut = ERC20(path[path.length - 1]);
        uint256 balanceBefore = tokenOut.balanceOf(address(this));

        _stableSwap(path, flag);

        uint256 amountOut = tokenOut.balanceOf(address(this)) - balanceBefore;
        if (amountOut < amountOutMinimum) revert StableTooLittleReceived();

        if (recipient != address(this)) pay(address(tokenOut), recipient, amountOut);
    }

    /// @notice Performs a PancakeSwap stable exact output swap
    /// @param recipient The recipient of the output tokens
    /// @param amountIn The amount of input token
    /// @param amountOut The amount of output tokens to receive for the trade
    /// @param path The path of the trade as an array of token addresses
    /// @param flag token amount in a stable swap pool. 2 for 2pool, 3 for 3pool
    /// @param payer The address that will be paying the input
    function stableSwapExactOutput(
        address recipient,
        uint256 amountIn,
        uint256 amountOut,
        address[] calldata path,
        uint256[] calldata flag,
        address payer
    ) internal {
        payOrPermit2Transfer(path[0], payer, address(this), amountIn);

        _stableSwap(path, flag);

        if (recipient != address(this)) pay(path[path.length - 1], recipient, amountOut);
    }

    function stableSwapExactOutputAmountIn(
        uint256 amountOut,
        uint256 amountInMaximum,
        address[] calldata path,
        uint256[] calldata flag
    ) internal returns (uint256 amountIn) {
        amountIn = stableSwapFactory.getStableAmountsIn(stableSwapInfo, path, flag, amountOut)[0];

        if (amountIn > amountInMaximum) revert StableTooMuchRequested();
    }
}

// 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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {IPancakeV2Pair} from "./interfaces/IPancakeV2Pair.sol";
import {RouterImmutables} from "../../../base/RouterImmutables.sol";
import {Permit2Payments} from "../../Permit2Payments.sol";
import {Constants} from "../../../libraries/Constants.sol";
import {UniversalRouterHelper} from "../../../libraries/UniversalRouterHelper.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";

/// @title Router for PancakeSwap v2 Trades
abstract contract V2SwapRouter is RouterImmutables, Permit2Payments {
    error V2TooLittleReceived();
    error V2TooMuchRequested();
    error V2InvalidPath();

    function _v2Swap(address[] calldata path, address recipient, address pair) private {
        unchecked {
            if (path.length < 2) revert V2InvalidPath();

            // cached to save on duplicate operations
            (address token0,) = UniversalRouterHelper.sortTokens(path[0], path[1]);
            uint256 finalPairIndex = path.length - 1;
            uint256 penultimatePairIndex = finalPairIndex - 1;
            for (uint256 i; i < finalPairIndex; i++) {
                (address input, address output) = (path[i], path[i + 1]);
                (uint256 reserve0, uint256 reserve1,) = IPancakeV2Pair(pair).getReserves();
                (uint256 reserveInput, uint256 reserveOutput) =
                    input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                uint256 amountInput = ERC20(input).balanceOf(pair) - reserveInput;
                uint256 amountOutput = UniversalRouterHelper.getAmountOut(amountInput, reserveInput, reserveOutput);
                (uint256 amount0Out, uint256 amount1Out) =
                    input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0));
                address nextPair;
                (nextPair, token0) = i < penultimatePairIndex
                    ? UniversalRouterHelper.pairAndToken0For(
                        PANCAKESWAP_V2_FACTORY, PANCAKESWAP_V2_PAIR_INIT_CODE_HASH, output, path[i + 2]
                    )
                    : (recipient, address(0));
                IPancakeV2Pair(pair).swap(amount0Out, amount1Out, nextPair, new bytes(0));
                pair = nextPair;
            }
        }
    }

    /// @notice Performs a PancakeSwap v2 exact input swap
    /// @param recipient The recipient of the output tokens
    /// @param amountIn The amount of input tokens for the trade
    /// @param amountOutMinimum The minimum desired amount of output tokens
    /// @param path The path of the trade as an array of token addresses
    /// @param payer The address that will be paying the input
    function v2SwapExactInput(
        address recipient,
        uint256 amountIn,
        uint256 amountOutMinimum,
        address[] calldata path,
        address payer
    ) internal {
        address firstPair =
            UniversalRouterHelper.pairFor(PANCAKESWAP_V2_FACTORY, PANCAKESWAP_V2_PAIR_INIT_CODE_HASH, path[0], path[1]);
        if (
            amountIn != Constants.ALREADY_PAID // amountIn of 0 to signal that the pair already has the tokens
        ) {
            payOrPermit2Transfer(path[0], payer, firstPair, amountIn);
        }

        ERC20 tokenOut = ERC20(path[path.length - 1]);
        uint256 balanceBefore = tokenOut.balanceOf(recipient);

        _v2Swap(path, recipient, firstPair);

        uint256 amountOut = tokenOut.balanceOf(recipient) - balanceBefore;
        if (amountOut < amountOutMinimum) revert V2TooLittleReceived();
    }

    /// @notice Performs a PancakeSwap v2 exact output swap
    /// @param recipient The recipient of the output tokens
    /// @param amountOut The amount of output tokens to receive for the trade
    /// @param amountInMaximum The maximum desired amount of input tokens
    /// @param path The path of the trade as an array of token addresses
    /// @param payer The address that will be paying the input
    function v2SwapExactOutput(
        address recipient,
        uint256 amountOut,
        uint256 amountInMaximum,
        address[] calldata path,
        address payer
    ) internal {
        (uint256 amountIn, address firstPair) = UniversalRouterHelper.getAmountInMultihop(
            PANCAKESWAP_V2_FACTORY, PANCAKESWAP_V2_PAIR_INIT_CODE_HASH, amountOut, path
        );
        if (amountIn > amountInMaximum) revert V2TooMuchRequested();

        payOrPermit2Transfer(path[0], payer, firstPair, amountIn);
        _v2Swap(path, recipient, firstPair);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {ActionConstants} from "infinity-periphery/src/libraries/ActionConstants.sol";
import {SafeCast} from "./SafeCast.sol";
import {IPancakeV3Pool} from "./interfaces/IPancakeV3Pool.sol";
import {IPancakeV3SwapCallback} from "./interfaces/IPancakeV3SwapCallback.sol";
import {BytesLib} from "../../../libraries/BytesLib.sol";
import {Constants} from "../../../libraries/Constants.sol";
import {UniversalRouterHelper} from "../../../libraries/UniversalRouterHelper.sol";
import {RouterImmutables} from "../../../base/RouterImmutables.sol";
import {Permit2Payments} from "../../Permit2Payments.sol";
import {MaxInputAmount} from "../../../libraries/MaxInputAmount.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";
import {CalldataDecoder} from "infinity-periphery/src/libraries/CalldataDecoder.sol";

/// @title Router for PancakeSwap v3 Trades
abstract contract V3SwapRouter is RouterImmutables, Permit2Payments, IPancakeV3SwapCallback {
    using UniversalRouterHelper for bytes;
    using BytesLib for bytes;
    using CalldataDecoder for bytes;
    using SafeCast for uint256;

    error V3InvalidSwap();
    error V3TooLittleReceived();
    error V3TooMuchRequested();
    error V3InvalidAmountOut();
    error V3InvalidCaller();

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;

    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external {
        if (amount0Delta <= 0 && amount1Delta <= 0) revert V3InvalidSwap(); // swaps entirely within 0-liquidity regions are not supported
        (, address payer) = abi.decode(data, (bytes, address));
        bytes calldata path = data.toBytes(0);

        // because exact output swaps are executed in reverse order, in this case tokenOut is actually tokenIn
        (address tokenIn, uint24 fee, address tokenOut) = path.decodeFirstPool();

        if (
            UniversalRouterHelper.computePoolAddress(
                PANCAKESWAP_V3_DEPLOYER, PANCAKESWAP_V3_POOL_INIT_CODE_HASH, tokenIn, tokenOut, fee
            ) != msg.sender
        ) revert V3InvalidCaller();

        (bool isExactInput, uint256 amountToPay) =
            amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta)) : (tokenOut < tokenIn, uint256(amount1Delta));

        if (isExactInput) {
            // Pay the pool (msg.sender)
            payOrPermit2Transfer(tokenIn, payer, msg.sender, amountToPay);
        } else {
            // either initiate the next swap or pay
            if (path.hasMultiplePools()) {
                // this is an intermediate step so the payer is actually this contract
                path = path.skipToken();
                _swap(-amountToPay.toInt256(), msg.sender, path, payer, false);
            } else {
                if (amountToPay > MaxInputAmount.get()) revert V3TooMuchRequested();
                // note that because exact output swaps are executed in reverse order, tokenOut is actually tokenIn
                payOrPermit2Transfer(tokenOut, payer, msg.sender, amountToPay);
            }
        }
    }

    /// @notice Performs a PancakeSwap v3 exact input swap
    /// @param recipient The recipient of the output tokens
    /// @param amountIn The amount of input tokens for the trade
    /// @param amountOutMinimum The minimum desired amount of output tokens
    /// @param path The path of the trade as a bytes string
    /// @param payer The address that will be paying the input
    function v3SwapExactInput(
        address recipient,
        uint256 amountIn,
        uint256 amountOutMinimum,
        bytes calldata path,
        address payer
    ) internal {
        // use amountIn == ActionConstants.CONTRACT_BALANCE as a flag to swap the entire balance of the contract
        if (amountIn == ActionConstants.CONTRACT_BALANCE) {
            address tokenIn = path.decodeFirstToken();
            amountIn = ERC20(tokenIn).balanceOf(address(this));
        }

        uint256 amountOut;
        while (true) {
            bool hasMultiplePools = path.hasMultiplePools();

            // the outputs of prior swaps become the inputs to subsequent ones
            (int256 amount0Delta, int256 amount1Delta, bool zeroForOne) = _swap(
                amountIn.toInt256(),
                hasMultiplePools ? address(this) : recipient, // for intermediate swaps, this contract custodies
                path.getFirstPool(), // only the first pool is needed
                payer, // for intermediate swaps, this contract custodies
                true
            );

            amountIn = uint256(-(zeroForOne ? amount1Delta : amount0Delta));

            // decide whether to continue or terminate
            if (hasMultiplePools) {
                payer = address(this);
                path = path.skipToken();
            } else {
                amountOut = amountIn;
                break;
            }
        }

        if (amountOut < amountOutMinimum) revert V3TooLittleReceived();
    }

    /// @notice Performs a PancakeSwap v3 exact output swap
    /// @param recipient The recipient of the output tokens
    /// @param amountOut The amount of output tokens to receive for the trade
    /// @param amountInMaximum The maximum desired amount of input tokens
    /// @param path The path of the trade as a bytes string
    /// @param payer The address that will be paying the input
    function v3SwapExactOutput(
        address recipient,
        uint256 amountOut,
        uint256 amountInMaximum,
        bytes calldata path,
        address payer
    ) internal {
        MaxInputAmount.set(amountInMaximum);
        (int256 amount0Delta, int256 amount1Delta, bool zeroForOne) =
            _swap(-amountOut.toInt256(), recipient, path, payer, false);

        uint256 amountOutReceived = zeroForOne ? uint256(-amount1Delta) : uint256(-amount0Delta);

        if (amountOutReceived != amountOut) revert V3InvalidAmountOut();

        MaxInputAmount.set(0);
    }

    /// @dev Performs a single swap for both exactIn and exactOut
    /// For exactIn, `amount` is `amountIn`. For exactOut, `amount` is `-amountOut`
    function _swap(int256 amount, address recipient, bytes calldata path, address payer, bool isExactIn)
        private
        returns (int256 amount0Delta, int256 amount1Delta, bool zeroForOne)
    {
        (address tokenIn, uint24 fee, address tokenOut) = path.decodeFirstPool();

        zeroForOne = isExactIn ? tokenIn < tokenOut : tokenOut < tokenIn;

        (amount0Delta, amount1Delta) = IPancakeV3Pool(
            UniversalRouterHelper.computePoolAddress(
                PANCAKESWAP_V3_DEPLOYER, PANCAKESWAP_V3_POOL_INIT_CODE_HASH, tokenIn, tokenOut, fee
            )
        ).swap(
            recipient,
            zeroForOne,
            amount,
            (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1),
            abi.encode(path, payer)
        );
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {Constants} from "../libraries/Constants.sol";
import {ActionConstants} from "infinity-periphery/src/libraries/ActionConstants.sol";
import {BipsLibrary} from "infinity-periphery/src/libraries/BipsLibrary.sol";
import {RouterImmutables} from "../base/RouterImmutables.sol";
import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol";
import {ERC20} from "solmate/src/tokens/ERC20.sol";
import {ERC721} from "solmate/src/tokens/ERC721.sol";
import {ERC1155} from "solmate/src/tokens/ERC1155.sol";

/// @title Payments contract
/// @notice Performs various operations around the payment of ETH and tokens
abstract contract Payments is RouterImmutables {
    using SafeTransferLib for ERC20;
    using SafeTransferLib for address;
    using BipsLibrary for uint256;

    error InsufficientToken();
    error InsufficientETH();

    /// @notice Pays an amount of ETH or ERC20 to a recipient
    /// @param token The token to pay (can be ETH using Constants.ETH)
    /// @param recipient The address that will receive the payment
    /// @param value The amount to pay
    function pay(address token, address recipient, uint256 value) internal {
        if (token == Constants.ETH) {
            recipient.safeTransferETH(value);
        } else {
            if (value == ActionConstants.CONTRACT_BALANCE) {
                value = ERC20(token).balanceOf(address(this));
            }

            ERC20(token).safeTransfer(recipient, value);
        }
    }

    /// @notice Pays a proportion of the contract's ETH or ERC20 to a recipient
    /// @param token The token to pay (can be ETH using Constants.ETH)
    /// @param recipient The address that will receive payment
    /// @param bips Portion in bips of whole balance of the contract
    function payPortion(address token, address recipient, uint256 bips) internal {
        if (token == Constants.ETH) {
            uint256 balance = address(this).balance;
            uint256 amount = balance.calculatePortion(bips);
            recipient.safeTransferETH(amount);
        } else {
            uint256 balance = ERC20(token).balanceOf(address(this));
            uint256 amount = balance.calculatePortion(bips);
            ERC20(token).safeTransfer(recipient, amount);
        }
    }

    /// @notice Sweeps all of the contract's ERC20 or ETH to an address
    /// @param token The token to sweep (can be ETH using Constants.ETH)
    /// @param recipient The address that will receive payment
    /// @param amountMinimum The minimum desired amount
    function sweep(address token, address recipient, uint256 amountMinimum) internal {
        uint256 balance;
        if (token == Constants.ETH) {
            balance = address(this).balance;
            if (balance < amountMinimum) revert InsufficientETH();
            if (balance > 0) recipient.safeTransferETH(balance);
        } else {
            balance = ERC20(token).balanceOf(address(this));
            if (balance < amountMinimum) revert InsufficientToken();
            if (balance > 0) ERC20(token).safeTransfer(recipient, balance);
        }
    }

    /// @notice Wraps an amount of ETH into WETH
    /// @param recipient The recipient of the WETH
    /// @param amount The amount to wrap (can be CONTRACT_BALANCE)
    function wrapETH(address recipient, uint256 amount) internal {
        if (amount == ActionConstants.CONTRACT_BALANCE) {
            amount = address(this).balance;
        } else if (amount > address(this).balance) {
            revert InsufficientETH();
        }
        if (amount > 0) {
            WETH9.deposit{value: amount}();
            if (recipient != address(this)) {
                WETH9.transfer(recipient, amount);
            }
        }
    }

    /// @notice Unwraps all of the contract's WETH into ETH
    /// @param recipient The recipient of the ETH
    /// @param amountMinimum The minimum amount of ETH desired
    function unwrapWETH9(address recipient, uint256 amountMinimum) internal {
        uint256 value = WETH9.balanceOf(address(this));
        if (value < amountMinimum) {
            revert InsufficientETH();
        }
        if (value > 0) {
            WETH9.withdraw(value);
            if (recipient != address(this)) {
                recipient.safeTransferETH(value);
            }
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {RouterImmutables} from "../base/RouterImmutables.sol";
import {IV3NonfungiblePositionManager} from
    "infinity-periphery/src/interfaces/external/IV3NonfungiblePositionManager.sol";
import {Actions} from "infinity-periphery/src/libraries/Actions.sol";
import {CalldataDecoder} from "infinity-periphery/src/libraries/CalldataDecoder.sol";
import {IPositionManager} from "infinity-periphery/src/interfaces/IPositionManager.sol";
import {IERC721Permit} from "infinity-periphery/src/interfaces/IERC721Permit.sol";

/// @title V3 to Infinity Migrator
/// @notice A contract that migrates liquidity from PancakeSwap V3 to Infinity
abstract contract V3ToInfinityMigrator is RouterImmutables {
    using CalldataDecoder for bytes;

    error NotAuthorizedForToken(uint256 tokenId);
    error InvalidAction(bytes4 action);
    error OnlyMintAllowed();
    error OnlyAddLiqudityAllowed();

    /// @dev validate if an action is decreaseLiquidity, collect, or burn
    function _isValidAction(bytes4 selector) private pure returns (bool) {
        return selector == IV3NonfungiblePositionManager.decreaseLiquidity.selector
            || selector == IV3NonfungiblePositionManager.collect.selector
            || selector == IV3NonfungiblePositionManager.burn.selector;
    }

    /// @dev the caller is authorized for the token if its the owner, spender, or operator
    function _isAuthorizedForToken(address caller, uint256 tokenId) private view returns (bool) {
        address owner = V3_POSITION_MANAGER.ownerOf(tokenId);
        return caller == owner || V3_POSITION_MANAGER.getApproved(tokenId) == caller
            || V3_POSITION_MANAGER.isApprovedForAll(owner, caller);
    }

    /// @dev check that a call is to the ERC721 permit function
    function _checkV3PermitCall(bytes calldata inputs) internal pure {
        bytes4 selector;
        assembly {
            selector := calldataload(inputs.offset)
        }

        if (selector != IERC721Permit.permit.selector) {
            revert InvalidAction(selector);
        }
    }

    /// @dev check that the v3 position manager call is a safe call
    function _checkV3PositionManagerCall(bytes calldata inputs, address caller) internal view {
        bytes4 selector;
        assembly {
            selector := calldataload(inputs.offset)
        }

        if (!_isValidAction(selector)) {
            revert InvalidAction(selector);
        }

        uint256 tokenId;
        assembly {
            // tokenId is always the first parameter in the valid actions
            tokenId := calldataload(add(inputs.offset, 0x04))
        }
        // If any other address that is not the owner wants to call this function, it also needs to be approved (in addition to this contract)
        // This can be done in 2 ways:
        //    1. This contract is permitted for the specific token and the caller is approved for ALL of the owner's tokens
        //    2. This contract is permitted for ALL of the owner's tokens and the caller is permitted for the specific token
        if (!_isAuthorizedForToken(caller, tokenId)) {
            revert NotAuthorizedForToken(tokenId);
        }
    }

    /// @dev check that the infinity cl position manager call is a safe call
    /// of the position-altering Actions, we only allow Actions.MINT
    /// this is because, if a user could be tricked into approving the UniversalRouter for
    /// their position, an attacker could take their fees, or drain their entire position
    function _checkInfiClPositionManagerCall(bytes calldata inputs) internal view {
        bytes4 selector;
        assembly {
            selector := calldataload(inputs.offset)
        }
        if (selector != INFI_CL_POSITION_MANAGER.modifyLiquidities.selector) {
            revert InvalidAction(selector);
        }

        // slice is `abi.encode(bytes unlockData, uint256 deadline)`
        bytes calldata slice = inputs[4:];
        // the first bytes(0) extracts the unlockData parameter from modifyLiquidities
        // unlockData = `abi.encode(bytes actions, bytes[] params)`
        // the second bytes(0) extracts the actions parameter from unlockData
        bytes calldata actions = slice.toBytes(0).toBytes(0);

        uint256 numActions = actions.length;

        for (uint256 actionIndex = 0; actionIndex < numActions; actionIndex++) {
            uint256 action = uint8(actions[actionIndex]);

            if (
                action == Actions.CL_INCREASE_LIQUIDITY || action == Actions.CL_DECREASE_LIQUIDITY
                    || action == Actions.CL_BURN_POSITION
            ) {
                revert OnlyMintAllowed();
            }
        }
    }

    /// @dev check that the infinity bin position manager call is a safe call
    /// of the position-altering Actions, we only allow Actions.BIN_ADD_LIQUIDITY
    /// this is because, if a user could be tricked into approving the UniversalRouter for
    /// their position, an attacker could drain their entire position
    function _checkInfiBinPositionManagerCall(bytes calldata inputs) internal view {
        bytes4 selector;
        assembly {
            selector := calldataload(inputs.offset)
        }
        if (selector != INFI_BIN_POSITION_MANAGER.modifyLiquidities.selector) {
            revert InvalidAction(selector);
        }

        // slice is `abi.encode(bytes unlockData, uint256 deadline)`
        bytes calldata slice = inputs[4:];
        // the first bytes(0) extracts the unlockData parameter from modifyLiquidities
        // unlockData = `abi.encode(bytes actions, bytes[] params)`
        // the second bytes(0) extracts the actions parameter from unlockData
        bytes calldata actions = slice.toBytes(0).toBytes(0);

        uint256 numActions = actions.length;

        for (uint256 actionIndex = 0; actionIndex < numActions; actionIndex++) {
            uint256 action = uint8(actions[actionIndex]);
            if (action == Actions.BIN_REMOVE_LIQUIDITY) {
                revert OnlyAddLiqudityAllowed();
            }
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later

/// @title Library for Bytes Manipulation
pragma solidity ^0.8.0;

import {Constants} from "./Constants.sol";
import {CalldataDecoder} from "infinity-periphery/src/libraries/CalldataDecoder.sol";

library BytesLib {
    using CalldataDecoder for bytes;

    error SliceOutOfBounds();

    /// @notice Returns the address starting at byte 0
    /// @dev length and overflow checks must be carried out before calling
    /// @param _bytes The input bytes string to slice
    /// @return _address The address starting at byte 0
    function toAddress(bytes calldata _bytes) internal pure returns (address _address) {
        if (_bytes.length < Constants.ADDR_SIZE) revert SliceOutOfBounds();
        assembly {
            _address := shr(96, calldataload(_bytes.offset))
        }
    }

    /// @notice Decode the `_arg`-th element in `_bytes` as a dynamic array
    /// @dev The decoding of `length` and `offset` is universal,
    /// whereas the type declaration of `res` instructs the compiler how to read it.
    /// @param _bytes The input bytes string to slice
    /// @param _arg The index of the argument to extract
    /// @return length Length of the array
    /// @return offset Pointer to the data part of the array
    function toLengthOffset(bytes calldata _bytes, uint256 _arg)
        internal
        pure
        returns (uint256 length, uint256 offset)
    {
        uint256 relativeOffset;
        assembly {
            // The offset of the `_arg`-th element is `32 * arg`, which stores the offset of the length pointer.
            // shl(5, x) is equivalent to mul(32, x)
            let lengthPtr := add(_bytes.offset, calldataload(add(_bytes.offset, shl(5, _arg))))
            length := calldataload(lengthPtr)
            offset := add(lengthPtr, 0x20)
            relativeOffset := sub(offset, _bytes.offset)
        }
        if (_bytes.length < length + relativeOffset) revert SliceOutOfBounds();
    }

    /// @notice Returns the pool details starting at byte 0
    /// @dev length and overflow checks must be carried out before calling
    /// @param _bytes The input bytes string to slice
    /// @return token0 The address at byte 0
    /// @return fee The uint24 starting at byte 20
    /// @return token1 The address at byte 23
    function toPool(bytes calldata _bytes) internal pure returns (address token0, uint24 fee, address token1) {
        if (_bytes.length < Constants.V3_POP_OFFSET) revert SliceOutOfBounds();
        assembly {
            let firstWord := calldataload(_bytes.offset)
            token0 := shr(96, firstWord)
            fee := and(shr(72, firstWord), 0xffffff)
            token1 := shr(96, calldataload(add(_bytes.offset, 23)))
        }
    }

    /// @notice Decode the `_arg`-th element in `_bytes` as `address[]`
    /// @param _bytes The input bytes string to extract an address array from
    /// @param _arg The index of the argument to extract
    function toAddressArray(bytes calldata _bytes, uint256 _arg) internal pure returns (address[] calldata res) {
        (uint256 length, uint256 offset) = toLengthOffset(_bytes, _arg);
        assembly {
            res.length := length
            res.offset := offset
        }
    }

    /// @notice Decode the `_arg`-th element in `_bytes` as `uint[]`
    /// @param _bytes The input bytes string to extract an uint array from
    /// @param _arg The index of the argument to extract
    function toUintArray(bytes calldata _bytes, uint256 _arg) internal pure returns (uint256[] calldata res) {
        (uint256 length, uint256 offset) = toLengthOffset(_bytes, _arg);
        assembly {
            res.length := length
            res.offset := offset
        }
    }

    /// @notice Equivalent to abi.decode(bytes, bytes[])
    /// @param _bytes The input bytes string to extract an parameters from
    function decodeCommandsAndInputs(bytes calldata _bytes) internal pure returns (bytes calldata, bytes[] calldata) {
        return _bytes.decodeActionsRouterParams();
    }
}

File 15 of 120 : Lock.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;

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

/// @title Lock
/// @notice A contract that provides a reentrancy lock for external calls
contract Lock {
    /// @notice Thrown when attempting to reenter a locked function from an external caller
    error ContractLocked();

    /// @notice Modifier enforcing a reentrancy lock that allows self-reentrancy
    /// @dev If the contract is not locked, use msg.sender as the locker
    modifier isNotLocked() {
        // Apply a reentrancy lock for all external callers
        if (msg.sender != address(this)) {
            if (Locker.isLocked()) revert ContractLocked();
            Locker.set(msg.sender);
            _;
            Locker.set(address(0));
        } else {
            // The contract is allowed to reenter itself, so the lock is not checked
            _;
        }
    }

    /// @notice return the current locker of the contract
    function _getLocker() internal view returns (address) {
        return Locker.get();
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

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

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

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

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

/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
    /// @notice Thrown when an allowance on a token has expired.
    /// @param deadline The timestamp at which the allowed amount is no longer valid
    error AllowanceExpired(uint256 deadline);

    /// @notice Thrown when an allowance on a token has been depleted.
    /// @param amount The maximum amount allowed
    error InsufficientAllowance(uint256 amount);

    /// @notice Thrown when too many nonces are invalidated.
    error ExcessiveInvalidation();

    /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
    event NonceInvalidation(
        address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce
    );

    /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
    event Approval(
        address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration
    );

    /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
    event Permit(
        address indexed owner,
        address indexed token,
        address indexed spender,
        uint160 amount,
        uint48 expiration,
        uint48 nonce
    );

    /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
    event Lockdown(address indexed owner, address token, address spender);

    /// @notice The permit data for a token
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice The permit message signed for a single token allownce
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The permit message signed for multiple token allowances
    struct PermitBatch {
        // the permit data for multiple token allowances
        PermitDetails[] details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The saved permissions
    /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice A token spender pair.
    struct TokenSpenderPair {
        // the token the spender is approved
        address token;
        // the spender address
        address spender;
    }

    /// @notice Details for a token transfer.
    struct AllowanceTransferDetails {
        // the owner of the token
        address from;
        // the recipient of the token
        address to;
        // the amount of the token
        uint160 amount;
        // the token to be transferred
        address token;
    }

    /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
    /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
    /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
    function allowance(address user, address token, address spender)
        external
        view
        returns (uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Approves the spender to use up to amount of the specified token up until the expiration
    /// @param token The token to approve
    /// @param spender The spender address to approve
    /// @param amount The approved amount of the token
    /// @param expiration The timestamp at which the approval is no longer valid
    /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitSingle Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitBatch Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;

    /// @notice Transfer approved tokens from one address to another
    /// @param from The address to transfer from
    /// @param to The address of the recipient
    /// @param amount The amount of the token to transfer
    /// @param token The token address to transfer
    /// @dev Requires the from address to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(address from, address to, uint160 amount, address token) external;

    /// @notice Transfer approved tokens in a batch
    /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
    /// @dev Requires the from addresses to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;

    /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
    /// by batch revoking approvals
    /// @param approvals Array of approvals to revoke.
    function lockdown(TokenSpenderPair[] calldata approvals) external;

    /// @notice Invalidate nonces for a given (token, spender) pair
    /// @param token The token to invalidate nonces for
    /// @param spender The spender to invalidate nonces for
    /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
    /// @dev Can't invalidate more than 2**16 nonces per transaction.
    function invalidateNonces(address token, address spender, uint48 newNonce) external;
}

File 18 of 120 : ActionConstants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title Action Constants
/// @notice Common constants used in actions
/// @dev Constants are gas efficient alternatives to their literal values
library ActionConstants {
    /// @notice used to signal that an action should use the input value of the open delta on the vault
    /// or of the balance that the contract holds
    uint128 internal constant OPEN_DELTA = 0;
    /// @notice used to signal that an action should use the contract's entire balance of a currency
    /// This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit.
    uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;

    /// @notice used to signal that the recipient of an action should be the msgSender
    address internal constant MSG_SENDER = address(1);

    /// @notice used to signal that the recipient of an action should be the address(this)
    address internal constant ADDRESS_THIS = address(2);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {IVault} from "infinity-core/src/interfaces/IVault.sol";
import {SafeCallback} from "./SafeCallback.sol";
import {CalldataDecoder} from "../libraries/CalldataDecoder.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";

/// @notice Abstract contract for performing a combination of actions on Pancakeswap infinity.
/// @dev Suggested uint256 action values are defined in Actions.sol, however any definition can be used
abstract contract BaseActionsRouter is SafeCallback {
    using CalldataDecoder for bytes;

    /// @notice emitted when different numbers of parameters and actions are provided
    error InputLengthMismatch();

    /// @notice emitted when an inheriting contract does not support an action
    error UnsupportedAction(uint256 action);

    constructor(IVault _vault) SafeCallback(_vault) {}

    /// @notice internal function that triggers the execution of a set of actions on infinity
    /// @dev inheriting contracts should call this function to trigger execution
    function _executeActions(bytes calldata data) internal {
        vault.lock(data);
    }

    /// @notice function that is called by the Vault through the SafeCallback.lockAcquired
    /// @param data Abi encoding of (bytes actions, bytes[] params)
    /// where params[i] is the encoded parameters for actions[i]
    function _lockAcquired(bytes calldata data) internal override returns (bytes memory) {
        // abi.decode(data, (bytes, bytes[]));
        (bytes calldata actions, bytes[] calldata params) = data.decodeActionsRouterParams();
        _executeActionsWithoutLock(actions, params);
        return "";
    }

    function _executeActionsWithoutLock(bytes calldata actions, bytes[] calldata params) internal {
        uint256 numActions = actions.length;
        if (numActions != params.length) revert InputLengthMismatch();

        for (uint256 actionIndex = 0; actionIndex < numActions; actionIndex++) {
            uint256 action = uint8(actions[actionIndex]);

            _handleAction(action, params[actionIndex]);
        }
    }

    /// @notice function to handle the parsing and execution of an action and its parameters
    function _handleAction(uint256 action, bytes calldata params) internal virtual;

    /// @notice function that returns address considered executor of the actions
    /// @dev The other context functions, _msgData and _msgValue, are not supported by this contract
    /// In many contracts this will be the address that calls the initial entry point that calls `_executeActions`
    /// `msg.sender` shouldnt be used, as this will be the vault contract that calls `lockAcquired`
    /// If using ReentrancyLock.sol, this function can return _getLocker()
    function msgSender() public view virtual returns (address);

    /// @notice Calculates the address for a action
    function _mapRecipient(address recipient) internal view returns (address) {
        if (recipient == ActionConstants.MSG_SENDER) {
            return msgSender();
        } else if (recipient == ActionConstants.ADDRESS_THIS) {
            return address(this);
        } else {
            return recipient;
        }
    }

    /// @notice Calculates the payer for an action
    function _mapPayer(bool payerIsUser) internal view returns (address) {
        return payerIsUser ? msgSender() : address(this);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {Currency} from "infinity-core/src/types/Currency.sol";

/// @title Library for abi decoding in calldata
library CalldataDecoder {
    using CalldataDecoder for bytes;

    error SliceOutOfBounds();

    /// @notice mask used for offsets and lengths to ensure no overflow
    /// @dev no sane abi encoding will pass in an offset or length greater than type(uint32).max
    ///      (note that this does deviate from standard solidity behavior and offsets/lengths will
    ///      be interpreted as mod type(uint32).max which will only impact malicious/buggy callers)
    uint256 constant OFFSET_OR_LENGTH_MASK = 0xffffffff;
    uint256 constant OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN = 0xffffffe0;

    /// @notice equivalent to SliceOutOfBounds.selector, stored in least-significant bits
    uint256 constant SLICE_ERROR_SELECTOR = 0x3b99b53d;

    /// @dev equivalent to: abi.decode(params, (bytes, bytes[])) in calldata (requires strict abi encoding)
    function decodeActionsRouterParams(bytes calldata _bytes)
        internal
        pure
        returns (bytes calldata actions, bytes[] calldata params)
    {
        assembly ("memory-safe") {
            // Strict encoding requires that the data begin with:
            // 0x00: 0x40 (offset to `actions.length`)
            // 0x20: 0x60 + actions.length (offset to `params.length`)
            // 0x40: `actions.length`
            // 0x60: beginning of actions

            // Verify actions offset matches strict encoding
            let invalidData := xor(calldataload(_bytes.offset), 0x40)
            actions.offset := add(_bytes.offset, 0x60)
            actions.length := and(calldataload(add(_bytes.offset, 0x40)), OFFSET_OR_LENGTH_MASK)

            // Round actions length up to be word-aligned, and add 0x60 (for the first 3 words of encoding)
            let paramsLengthOffset := add(and(add(actions.length, 0x1f), OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN), 0x60)
            // Verify params offset matches strict encoding
            invalidData := or(invalidData, xor(calldataload(add(_bytes.offset, 0x20)), paramsLengthOffset))
            let paramsLengthPointer := add(_bytes.offset, paramsLengthOffset)
            params.length := and(calldataload(paramsLengthPointer), OFFSET_OR_LENGTH_MASK)
            params.offset := add(paramsLengthPointer, 0x20)

            // Expected offset for `params[0]` is params.length * 32
            // As the first `params.length` slots are pointers to each of the array element lengths
            let tailOffset := shl(5, params.length)
            let expectedOffset := tailOffset

            for { let offset := 0 } lt(offset, tailOffset) { offset := add(offset, 32) } {
                let itemLengthOffset := calldataload(add(params.offset, offset))
                // Verify that the offset matches the expected offset from strict encoding
                invalidData := or(invalidData, xor(itemLengthOffset, expectedOffset))
                let itemLengthPointer := add(params.offset, itemLengthOffset)
                let length :=
                    add(and(add(calldataload(itemLengthPointer), 0x1f), OFFSET_OR_LENGTH_MASK_AND_WORD_ALIGN), 0x20)
                expectedOffset := add(expectedOffset, length)
            }

            // if the data encoding was invalid, or the provided bytes string isnt as long as the encoding says, revert
            if or(invalidData, lt(add(_bytes.length, _bytes.offset), add(params.offset, expectedOffset))) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency)) in calldata
    function decodeCurrency(bytes calldata params) internal pure returns (Currency currency) {
        assembly ("memory-safe") {
            if lt(params.length, 0x20) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency := calldataload(params.offset)
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, Currency)) in calldata
    function decodeCurrencyPair(bytes calldata params) internal pure returns (Currency currency0, Currency currency1) {
        assembly ("memory-safe") {
            if lt(params.length, 0x40) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency0 := calldataload(params.offset)
            currency1 := calldataload(add(params.offset, 0x20))
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, Currency, address)) in calldata
    function decodeCurrencyPairAndAddress(bytes calldata params)
        internal
        pure
        returns (Currency currency0, Currency currency1, address _address)
    {
        assembly ("memory-safe") {
            if lt(params.length, 0x60) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency0 := calldataload(params.offset)
            currency1 := calldataload(add(params.offset, 0x20))
            _address := calldataload(add(params.offset, 0x40))
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, address)) in calldata
    function decodeCurrencyAndAddress(bytes calldata params)
        internal
        pure
        returns (Currency currency, address _address)
    {
        assembly ("memory-safe") {
            if lt(params.length, 0x40) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency := calldataload(params.offset)
            _address := calldataload(add(params.offset, 0x20))
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, address, uint256)) in calldata
    function decodeCurrencyAddressAndUint256(bytes calldata params)
        internal
        pure
        returns (Currency currency, address _address, uint256 amount)
    {
        assembly ("memory-safe") {
            if lt(params.length, 0x60) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency := calldataload(params.offset)
            _address := calldataload(add(params.offset, 0x20))
            amount := calldataload(add(params.offset, 0x40))
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, uint256)) in calldata
    function decodeCurrencyAndUint256(bytes calldata params)
        internal
        pure
        returns (Currency currency, uint256 amount)
    {
        assembly ("memory-safe") {
            if lt(params.length, 0x40) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency := calldataload(params.offset)
            amount := calldataload(add(params.offset, 0x20))
        }
    }

    /// @dev equivalent to: abi.decode(params, (uint256)) in calldata
    function decodeUint256(bytes calldata params) internal pure returns (uint256 amount) {
        assembly ("memory-safe") {
            if lt(params.length, 0x20) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            amount := calldataload(params.offset)
        }
    }

    /// @dev equivalent to: abi.decode(params, (Currency, uint256, bool)) in calldata
    function decodeCurrencyUint256AndBool(bytes calldata params)
        internal
        pure
        returns (Currency currency, uint256 amount, bool boolean)
    {
        assembly ("memory-safe") {
            if lt(params.length, 0x60) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            currency := calldataload(params.offset)
            amount := calldataload(add(params.offset, 0x20))
            boolean := calldataload(add(params.offset, 0x40))
        }
    }

    /// @notice Decode the `_arg`-th element in `_bytes` as `bytes`
    /// @param _bytes The input bytes string to extract a bytes string from
    /// @param _arg The index of the argument to extract
    function toBytes(bytes calldata _bytes, uint256 _arg) internal pure returns (bytes calldata res) {
        uint256 length;
        assembly ("memory-safe") {
            // The offset of the `_arg`-th element is `32 * arg`, which stores the offset of the length pointer.
            // shl(5, x) is equivalent to mul(32, x)
            let lengthPtr :=
                add(_bytes.offset, and(calldataload(add(_bytes.offset, shl(5, _arg))), OFFSET_OR_LENGTH_MASK))
            // the number of bytes in the bytes string
            length := and(calldataload(lengthPtr), OFFSET_OR_LENGTH_MASK)
            // the offset where the bytes string begins
            let offset := add(lengthPtr, 0x20)
            // assign the return parameters
            res.length := length
            res.offset := offset

            // if the provided bytes string isnt as long as the encoding says, revert
            if lt(add(_bytes.length, _bytes.offset), add(length, offset)) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
        }
    }
}

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

import {Currency} from "./Currency.sol";
import {IPoolManager} from "../interfaces/IPoolManager.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 hooks of the pool, won't have a general interface because hooks interface vary on pool type
    IHooks hooks;
    /// @notice The pool manager of the pool
    IPoolManager poolManager;
    /// @notice The pool lp fee, capped at 1_000_000. If the pool has a dynamic fee then it must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Hooks callback and pool specific parameters, i.e. tickSpacing for CL, binStep for bin
    bytes32 parameters;
}

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

import {Currency} from "../../types/Currency.sol";
import {PoolKey} from "../../types/PoolKey.sol";
import {CLPool} from "../libraries/CLPool.sol";
import {IHooks} from "../../interfaces/IHooks.sol";
import {IProtocolFees} from "../../interfaces/IProtocolFees.sol";
import {BalanceDelta} from "../../types/BalanceDelta.sol";
import {PoolId} from "../../types/PoolId.sol";
import {CLPosition} from "../libraries/CLPosition.sol";
import {IPoolManager} from "../../interfaces/IPoolManager.sol";
import {IExtsload} from "../../interfaces/IExtsload.sol";
import {Tick} from "../libraries/Tick.sol";

interface ICLPoolManager is IProtocolFees, IPoolManager, IExtsload {
    /// @notice PoolManagerMismatch is thrown when pool manager specified in the pool key does not match current contract
    error PoolManagerMismatch();
    /// @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 Error thrown when add liquidity is called when paused()
    error PoolPaused();
    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    /// @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 hooks The hooks contract address for the pool, or address(0) if none
    /// @param fee The lp fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param parameters Includes hooks callback bitmap and tickSpacing
    /// @param sqrtPriceX96 The sqrt(price) of the pool on initialization, as a Q64.96
    /// @param tick The tick corresponding to the price of the pool on initialization
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        IHooks hooks,
        uint24 fee,
        bytes32 parameters,
        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 value used to create a unique liquidity position
    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 fee collected upon every swap in the pool (including protocol fee and LP fee), denominated in hundredths of a bip
    /// @param protocolFee Single direction protocol fee from the swap, also denominated 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,
        uint16 protocolFee
    );

    /// @notice Emitted when donate happen
    /// @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 amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param tick The donated tick
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1, int24 tick);

    /// @notice Get the current value in slot0 of the given pool
    function getSlot0(PoolId id)
        external
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);

    /// @notice Get the current value of liquidity of the given pool
    function getLiquidity(PoolId id) external view returns (uint128 liquidity);

    /// @notice Get the current value of liquidity for the specified pool and position
    function getLiquidity(PoolId id, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        external
        view
        returns (uint128 liquidity);

    /// @notice Get the tick info about a specific tick in the pool
    function getPoolTickInfo(PoolId id, int24 tick) external view returns (Tick.Info memory);

    /// @notice Get the tick bitmap info about a specific range (a word range) in the pool
    function getPoolBitmapInfo(PoolId id, int16 word) external view returns (uint256 tickBitmap);

    /// @notice Get the fee growth global for the given pool
    /// @return feeGrowthGlobal0x128 The global fee growth for token0
    /// @return feeGrowthGlobal1x128 The global fee growth for token1
    /// @dev feeGrowthGlobal 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 freely inflate feeGrowthGlobal
    /// atomically donating and collecting fees in the same lockAcquired callback may make the inflated value more extreme
    function getFeeGrowthGlobals(PoolId id)
        external
        view
        returns (uint256 feeGrowthGlobal0x128, uint256 feeGrowthGlobal1x128);

    /// @notice Get the position struct for a specified pool and position
    function getPosition(PoolId id, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        external
        view
        returns (CLPosition.Info memory position);

    /// @notice Initialize the state for a given pool ID
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

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

    /// @notice Modify the position for the given pool
    /// @return delta The total balance delta of the caller of modifyLiquidity.
    /// @return feeDelta The balance delta of the fees generated in the liquidity range.
    /// @dev feeDelta 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 feeDelta)
    /// atomically donating and collecting fees in the same lockAcquired callback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta delta, BalanceDelta feeDelta);

    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData Any data to pass to the callback
    /// @return delta 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 delta);

    /// @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 pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData Any data to pass to the callback
    /// @return delta The balance delta of the address donating
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta delta);
}

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

import {Currency} from "../../types/Currency.sol";
import {IProtocolFees} from "../../interfaces/IProtocolFees.sol";
import {PoolId} from "../../types/PoolId.sol";
import {PoolKey} from "../../types/PoolKey.sol";
import {BalanceDelta} from "../../types/BalanceDelta.sol";
import {IPoolManager} from "../../interfaces/IPoolManager.sol";
import {IExtsload} from "../../interfaces/IExtsload.sol";
import {IHooks} from "../../interfaces/IHooks.sol";
import {BinPosition, BinPool} from "../libraries/BinPool.sol";

interface IBinPoolManager is IProtocolFees, IPoolManager, IExtsload {
    /// @notice PoolManagerMismatch is thrown when pool manager specified in the pool key does not match current contract
    error PoolManagerMismatch();

    /// @notice Pool binStep cannot be lesser than 1. Otherwise there will be no price jump between bin
    error BinStepTooSmall(uint16 binStep);

    /// @notice Pool binstep cannot be greater than the limit set at maxBinStep
    error BinStepTooLarge(uint16 binStep);

    /// @notice Error thrown when owner set max bin step too small
    error MaxBinStepTooSmall(uint16 maxBinStep);

    /// @notice Error thrown when bin has insufficient shares to accept donation
    error InsufficientBinShareForDonate(uint256 shares);

    /// @notice Error thrown when amount specified is 0 in swap
    error AmountSpecifiedIsZero();

    /// @notice Returns the constant representing the max bin step
    /// @return maxBinStep a value of 100 would represent a 1% price jump between bin (limit can be raised by owner)
    function maxBinStep() external view returns (uint16);

    /// @notice Returns the constant representing the min bin step
    /// @dev 1 would represent a 0.01% price jump between bin
    function MIN_BIN_STEP() external view returns (uint16);

    /// @notice min share in bin before donate is allowed in current bin
    function minBinShareForDonate() external view returns (uint256);

    /// @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 hooks The hooks contract address for the pool, or address(0) if none
    /// @param fee The lp fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param parameters Includes hooks callback bitmap and binStep
    /// @param activeId The id of active bin on initialization
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        IHooks hooks,
        uint24 fee,
        bytes32 parameters,
        uint24 activeId
    );

    /// @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 activeId The activeId of the pool after the swap
    /// @param fee The fee collected upon every swap in the pool (including protocol fee and LP fee), denominated in hundredths of a bip
    /// @param protocolFee Single direction protocol fee from the swap, also denominated in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint24 activeId,
        uint24 fee,
        uint16 protocolFee
    );

    /// @notice Emitted when liquidity is added
    /// @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 ids List of binId with liquidity added
    /// @param salt The salt to distinguish different mint from the same owner
    /// @param amounts List of amount added to each bin
    /// @param compositionFeeAmount fee occurred
    /// @param feeAmountToProtocol Protocol fee from the swap: token0 and token1 amount
    event Mint(
        PoolId indexed id,
        address indexed sender,
        uint256[] ids,
        bytes32 salt,
        bytes32[] amounts,
        bytes32 compositionFeeAmount,
        bytes32 feeAmountToProtocol
    );

    /// @notice Emitted when liquidity is removed
    /// @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 ids List of binId with liquidity removed
    /// @param salt The salt to specify the position to burn if multiple positions are available
    /// @param amounts List of amount removed from each bin
    event Burn(PoolId indexed id, address indexed sender, uint256[] ids, bytes32 salt, bytes32[] amounts);

    /// @notice Emitted when donate happen
    /// @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 amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param binId The donated bin id
    event Donate(PoolId indexed id, address indexed sender, int128 amount0, int128 amount1, uint24 binId);

    /// @notice Emitted when min share for donate is updated
    event SetMinBinSharesForDonate(uint256 minLiquidity);

    /// @notice Emitted when bin step is updated
    event SetMaxBinStep(uint16 maxBinStep);

    struct MintParams {
        bytes32[] liquidityConfigs;
        /// @dev amountIn intended
        bytes32 amountIn;
        /// the salt to distinguish different mint from the same owner
        bytes32 salt;
    }

    struct BurnParams {
        /// @notice id of the bin from which to withdraw
        uint256[] ids;
        /// @notice amount of share to burn for each bin
        uint256[] amountsToBurn;
        /// the salt to specify the position to burn if multiple positions are available
        bytes32 salt;
    }

    /// @notice Get the current value in slot0 of the given pool
    function getSlot0(PoolId id) external view returns (uint24 activeId, uint24 protocolFee, uint24 lpFee);

    /// @notice Returns the reserves of a bin
    /// @param id The id of the bin
    /// @return binReserveX The reserve of token X in the bin
    /// @return binReserveY The reserve of token Y in the bin
    /// @return binLiquidity The total liquidity in the bin
    /// @return totalShares The total shares minted in the bin
    function getBin(PoolId id, uint24 binId)
        external
        view
        returns (uint128 binReserveX, uint128 binReserveY, uint256 binLiquidity, uint256 totalShares);

    /// @notice Returns the positon of owner at a binId
    /// @param id The id of PoolKey
    /// @param owner Address of the owner
    /// @param binId The id of the bin
    /// @param salt The salt to distinguish different positions for the same owner
    function getPosition(PoolId id, address owner, uint24 binId, bytes32 salt)
        external
        view
        returns (BinPosition.Info memory position);

    /// @notice Returns the next non-empty bin
    /// @dev The next non-empty bin is the bin with a higher (if swapForY is true) or lower (if swapForY is false)
    ///     id that has a non-zero reserve of token X or Y.
    /// @param swapForY Whether the swap is for token Y (true) or token X (false)
    /// @param id The id of the bin
    /// @return nextId The id of the next non-empty bin
    function getNextNonEmptyBin(PoolId id, bool swapForY, uint24 binId) external view returns (uint24 nextId);

    /// @notice Initialize a new pool
    function initialize(PoolKey memory key, uint24 activeId) external;

    /// @notice Add liquidity to a pool
    /// @dev For the first liquidity added to a bin, the share minted would be slightly lessser (1e3 lesser) to prevent
    /// share inflation attack.
    /// @return delta BalanceDelta, will be negative indicating how much total amt0 and amt1 liquidity added
    /// @return mintArray Liquidity added in which ids, how much amt0, amt1 and how much liquidity added
    function mint(PoolKey memory key, IBinPoolManager.MintParams calldata params, bytes calldata hookData)
        external
        returns (BalanceDelta delta, BinPool.MintArrays memory mintArray);

    /// @notice Remove liquidity from a pool
    /// @return delta BalanceDelta, will be positive indicating how much total amt0 and amt1 liquidity removed
    function burn(PoolKey memory key, IBinPoolManager.BurnParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta delta);

    /// @notice Peform a swap to a pool
    /// @param key The pool key
    /// @param swapForY If true, swap token X for Y, if false, swap token Y for X
    /// @param amountSpecified If negative, imply exactInput, if positive, imply exactOutput.
    function swap(PoolKey memory key, bool swapForY, int128 amountSpecified, bytes calldata hookData)
        external
        returns (BalanceDelta delta);

    /// @notice Donate the given currency amounts to the active bin 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.
    /// @param key The pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData Any data to pass to the callback
    /// @return delta Negative amt means the caller owes the vault, while positive amt means the vault owes the caller
    /// @return binId The donated bin id, which is the current active bin id. if no-op happen, binId will be 0
    function donate(PoolKey memory key, uint128 amount0, uint128 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta delta, uint24 binId);

    /// @notice Set max bin step for BinPool
    /// @dev To be realistic, its highly unlikely a pool type with > 100 bin step is required. (>1% price jump per bin)
    function setMaxBinStep(uint16 maxBinStep) external;

    /// @notice Set min shares in bin before donate is allowed in current bin
    /// @dev Bin share is 1:1 liquidity when liquidity is first added. And liquidity: price * x + y << 128, where price is a 128.128 number. A
    ///         min share amount required in the bin for donate prevents share inflation attack.
    /// Min share should always be greater than 0, there should be a validation on BinPoolManagerOwner to prevent setting min share to 0
    function setMinBinSharesForDonate(uint256 minShare) external;
}

File 24 of 120 : IPermit2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {ISignatureTransfer} from "./ISignatureTransfer.sol";
import {IAllowanceTransfer} from "./IAllowanceTransfer.sol";

/// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer.
/// @dev Users must approve Permit2 before calling any of the transfer functions.
interface IPermit2 is ISignatureTransfer, IAllowanceTransfer {
// IPermit2 unifies the two interfaces so users have maximal flexibility with their approval.
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

/// @title IV3NonfungiblePositionManager
/// @notice Wraps PancakeSwap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized. Copying from PancakeSwap-V3
/// https://github.com/pancakeswap/pancake-v3-contracts/blob/main/projects/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol
interface IV3NonfungiblePositionManager is IERC721Permit {
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return fee The fee associated with the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(uint256 tokenId)
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(MintParams calldata params)
        external
        payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;

    function createAndInitializePoolIfNecessary(address token0, address token1, uint24 fee, uint160 sqrtPriceX96)
        external
        payable
        returns (address pool);
}

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

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

/// @title IPositionManager
/// @notice Interface for the PositionManager contract
interface IPositionManager is IImmutableState {
    /// @notice Thrown when the block.timestamp exceeds the user-provided deadline
    error DeadlinePassed(uint256 deadline);

    /// @notice Thrown when calling transfer, subscribe, or unsubscribe on CLPositionManager
    /// or batchTransferFrom on BinPositionManager when the vault is locked.
    /// @dev This is to prevent hooks from being able to trigger actions or notifications at the same time the position is being modified.
    error VaultMustBeUnlocked();

    /// @notice Thrown when the token ID is bind to an unexisting pool
    error InvalidTokenID();

    /// @notice Unlocks Vault and batches actions for modifying liquidity
    /// @dev This is the standard entrypoint for the PositionManager
    /// @param payload is an encoding of actions, and parameters for those actions
    /// @param deadline is the deadline for the batched actions to be executed
    function modifyLiquidities(bytes calldata payload, uint256 deadline) external payable;

    /// @notice Batches actions for modifying liquidity without getting a lock from vault
    /// @dev This must be called by a contract that has already locked the vault
    /// @param actions the actions to perform
    /// @param params the parameters to provide for the actions
    function modifyLiquiditiesWithoutLock(bytes calldata actions, bytes[] calldata params) external payable;
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

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

/// @title IWETH9
/// @notice Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {IAllowanceTransfer} from "permit2/src/interfaces/IAllowanceTransfer.sol";
import {SafeCast160} from "permit2/src/libraries/SafeCast160.sol";
import {Payments} from "./Payments.sol";

/// @title Payments through Permit2
/// @notice Performs interactions with Permit2 to transfer tokens
abstract contract Permit2Payments is Payments {
    using SafeCast160 for uint256;

    error FromAddressIsNotOwner();

    /// @notice Performs a transferFrom on Permit2
    /// @param token The token to transfer
    /// @param from The address to transfer from
    /// @param to The recipient of the transfer
    /// @param amount The amount to transfer
    function permit2TransferFrom(address token, address from, address to, uint160 amount) internal {
        PERMIT2.transferFrom(from, to, amount, token);
    }

    /// @notice Performs a batch transferFrom on Permit2
    /// @param batchDetails An array detailing each of the transfers that should occur
    /// @param owner The address that should be the owner of all transfers
    function permit2TransferFrom(IAllowanceTransfer.AllowanceTransferDetails[] calldata batchDetails, address owner)
        internal
    {
        uint256 batchLength = batchDetails.length;
        for (uint256 i = 0; i < batchLength; ++i) {
            if (batchDetails[i].from != owner) revert FromAddressIsNotOwner();
        }
        PERMIT2.transferFrom(batchDetails);
    }

    /// @notice Either performs a regular payment or transferFrom on Permit2, depending on the payer address
    /// @param token The token to transfer
    /// @param payer The address to pay for the transfer
    /// @param recipient The recipient of the transfer
    /// @param amount The amount to transfer
    function payOrPermit2Transfer(address token, address payer, address recipient, uint256 amount) internal {
        if (payer == address(this)) pay(token, recipient, amount);
        else permit2TransferFrom(token, payer, recipient, amount.toUint160());
    }
}

File 29 of 120 : InfinityRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {IVault} from "infinity-core/src/interfaces/IVault.sol";
import {ICLPoolManager} from "infinity-core/src/pool-cl/interfaces/ICLPoolManager.sol";
import {IBinPoolManager} from "infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {Currency} from "infinity-core/src/types/Currency.sol";
import {BipsLibrary} from "./libraries/BipsLibrary.sol";
import {CalldataDecoder} from "./libraries/CalldataDecoder.sol";
import {IInfinityRouter} from "./interfaces/IInfinityRouter.sol";
import {BaseActionsRouter} from "./base/BaseActionsRouter.sol";
import {DeltaResolver} from "./base/DeltaResolver.sol";
import {Actions} from "./libraries/Actions.sol";
import {CLCalldataDecoder} from "./pool-cl/libraries/CLCalldataDecoder.sol";
import {BinCalldataDecoder} from "./pool-bin/libraries/BinCalldataDecoder.sol";
import {CLRouterBase} from "./pool-cl/CLRouterBase.sol";
import {BinRouterBase} from "./pool-bin/BinRouterBase.sol";

/// @title InfinityRouter
/// @notice Abstract contract that contains all internal logic needed for routing through Pancakeswap infinity pools
/// @dev the entry point to executing actions in this contract is calling `BaseActionsRouter._executeActions`
/// An inheriting contract should call _executeActions at the point that they wish actions to be executed
abstract contract InfinityRouter is IInfinityRouter, CLRouterBase, BinRouterBase, BaseActionsRouter {
    using BipsLibrary for uint256;
    using CalldataDecoder for bytes;
    using CLCalldataDecoder for bytes;
    using BinCalldataDecoder for bytes;

    constructor(IVault _vault, ICLPoolManager _clPoolManager, IBinPoolManager _binPoolManager)
        BaseActionsRouter(_vault)
        CLRouterBase(_clPoolManager)
        BinRouterBase(_binPoolManager)
    {}

    function _handleAction(uint256 action, bytes calldata params) internal override {
        // swap actions and payment actions in different blocks for gas efficiency
        if (action < Actions.SETTLE) {
            if (action == Actions.CL_SWAP_EXACT_IN) {
                IInfinityRouter.CLSwapExactInputParams calldata swapParams = params.decodeCLSwapExactInParams();
                _swapExactInput(swapParams);
                return;
            } else if (action == Actions.CL_SWAP_EXACT_IN_SINGLE) {
                IInfinityRouter.CLSwapExactInputSingleParams calldata swapParams =
                    params.decodeCLSwapExactInSingleParams();
                _swapExactInputSingle(swapParams);
                return;
            } else if (action == Actions.CL_SWAP_EXACT_OUT) {
                IInfinityRouter.CLSwapExactOutputParams calldata swapParams = params.decodeCLSwapExactOutParams();
                _swapExactOutput(swapParams);
                return;
            } else if (action == Actions.CL_SWAP_EXACT_OUT_SINGLE) {
                IInfinityRouter.CLSwapExactOutputSingleParams calldata swapParams =
                    params.decodeCLSwapExactOutSingleParams();
                _swapExactOutputSingle(swapParams);
                return;
            }
        } else if (action > Actions.BURN_6909) {
            if (action == Actions.BIN_SWAP_EXACT_IN) {
                IInfinityRouter.BinSwapExactInputParams calldata swapParams = params.decodeBinSwapExactInParams();
                _swapExactInput(swapParams);
                return;
            } else if (action == Actions.BIN_SWAP_EXACT_IN_SINGLE) {
                IInfinityRouter.BinSwapExactInputSingleParams calldata swapParams =
                    params.decodeBinSwapExactInSingleParams();
                _swapExactInputSingle(swapParams);
                return;
            } else if (action == Actions.BIN_SWAP_EXACT_OUT) {
                IInfinityRouter.BinSwapExactOutputParams calldata swapParams = params.decodeBinSwapExactOutParams();
                _swapExactOutput(swapParams);
                return;
            } else if (action == Actions.BIN_SWAP_EXACT_OUT_SINGLE) {
                IInfinityRouter.BinSwapExactOutputSingleParams calldata swapParams =
                    params.decodeBinSwapExactOutSingleParams();
                _swapExactOutputSingle(swapParams);
                return;
            }
        } else {
            if (action == Actions.SETTLE_ALL) {
                (Currency currency, uint256 maxAmount) = params.decodeCurrencyAndUint256();
                uint256 amount = _getFullDebt(currency);
                if (amount > maxAmount) revert TooMuchRequested(maxAmount, amount);
                _settle(currency, msgSender(), amount);
                return;
            } else if (action == Actions.TAKE_ALL) {
                (Currency currency, uint256 minAmount) = params.decodeCurrencyAndUint256();
                uint256 amount = _getFullCredit(currency);
                if (amount < minAmount) revert TooLittleReceived(minAmount, amount);
                _take(currency, msgSender(), amount);
                return;
            } else if (action == Actions.SETTLE) {
                (Currency currency, uint256 amount, bool payerIsUser) = params.decodeCurrencyUint256AndBool();
                _settle(currency, _mapPayer(payerIsUser), _mapSettleAmount(amount, currency));
                return;
            } else if (action == Actions.TAKE) {
                (Currency currency, address recipient, uint256 amount) = params.decodeCurrencyAddressAndUint256();
                _take(currency, _mapRecipient(recipient), _mapTakeAmount(amount, currency));
                return;
            } else if (action == Actions.TAKE_PORTION) {
                (Currency currency, address recipient, uint256 bips) = params.decodeCurrencyAddressAndUint256();
                _take(currency, _mapRecipient(recipient), _getFullCredit(currency).calculatePortion(bips));
                return;
            }
        }
        revert UnsupportedAction(action);
    }
}

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

import {Currency} from "../types/Currency.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {IVaultToken} from "./IVaultToken.sol";

interface IVault is IVaultToken {
    event AppRegistered(address indexed app);

    /// @notice Thrown when a app is not registered
    error AppUnregistered();

    /// @notice Thrown when a currency is not netted out after a lock
    error CurrencyNotSettled();

    /// @notice Thrown when there is already a locker
    /// @param locker The address of the current locker
    error LockerAlreadySet(address locker);

    /// @notice Thrown when passing in msg.value for non-native currency
    error SettleNonNativeCurrencyWithValue();

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

    /// @notice Thrown when there is no locker
    error NoLocker();

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

    function isAppRegistered(address app) external returns (bool);

    /// @notice Returns the reserves for a a given pool type and currency
    function reservesOfApp(address app, Currency currency) external view returns (uint256);

    /// @notice register an app so that it can perform accounting base on vault
    function registerApp(address app) external;

    /// @notice Returns the locker who is locking the vault
    function getLocker() external view returns (address locker);

    /// @notice Returns the reserve and its amount that is currently being stored in trnasient storage
    function getVaultReserve() external view returns (Currency, uint256);

    /// @notice Returns lock data
    function getUnsettledDeltasCount() external view returns (uint256 count);

    /// @notice Get the current delta for a locker in the given currency
    /// @param currency The currency for which to lookup the delta
    function currencyDelta(address settler, Currency currency) external view returns (int256);

    /// @notice All operations go through this function
    /// @param data Any data to pass to the callback, via `ILockCallback(msg.sender).lockCallback(data)`
    /// @return The data returned by the call to `ILockCallback(msg.sender).lockCallback(data)`
    function lock(bytes calldata data) external returns (bytes memory);

    /// @notice Called by registered app to account for a change in the pool balance,
    /// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate,
    /// include the case where hookDelta is involved
    /// @param currency0 The PoolKey currency0 to update
    /// @param currency1 The PoolKey currency1 to update
    /// @param delta The change in the pool's balance
    /// @param settler The address whose delta will be updated
    /// @param hookDelta The change in the pool's balance from hook
    /// @param hook The address whose hookDelta will be updated
    function accountAppBalanceDelta(
        Currency currency0,
        Currency currency1,
        BalanceDelta delta,
        address settler,
        BalanceDelta hookDelta,
        address hook
    ) external;

    /// @notice Called by registered app to account for a change in the pool balance,
    /// convenient for AMM pool manager, typically after modifyLiquidity, swap, donate
    /// @param currency0 The PoolKey currency0 to update
    /// @param currency1 The PoolKey currency1 to update
    /// @param delta The change in the pool's balance
    /// @param settler The address whose delta will be updated
    function accountAppBalanceDelta(Currency currency0, Currency currency1, BalanceDelta delta, address settler)
        external;

    /// @notice This works as a general accounting mechanism for non-dex app
    /// @param currency The currency to update
    /// @param delta The change in the balance
    /// @param settler The address whose delta will be updated
    function accountAppBalanceDelta(Currency currency, int128 delta, address settler) 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
    function take(Currency currency, address to, uint256 amount) external;

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

    /// @notice Called by the user to pay what is owed
    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-retreivable, 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 app to collect any fee related
    /// @dev no restriction on caller, underflow happen if caller collect more than the reserve
    function collectFee(Currency currency, uint256 amount, address recipient) external;

    /// @notice Called by the user to store surplus tokens in the vault
    function mint(address to, Currency currency, uint256 amount) external;

    /// @notice Called by the user to use surplus tokens for payment settlement
    function burn(address from, Currency currency, uint256 amount) external;
}

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

import {IERC20Minimal} from "../interfaces/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 {
    using CurrencyLibrary for Currency;

    /// @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 NATIVE = 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.isNative()) {
            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.isNative()) {
            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.isNative()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

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

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

    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IPancakeV2Pair} from "../modules/pancakeswap/v2/interfaces/IPancakeV2Pair.sol";
import {IPancakeV3Pool} from "../modules/pancakeswap/v3/interfaces/IPancakeV3Pool.sol";
import {IStableSwapFactory} from "../interfaces/IStableSwapFactory.sol";
import {IStableSwapInfo} from "../interfaces/IStableSwapInfo.sol";
import {BytesLib} from "./BytesLib.sol";
import {Constants} from "./Constants.sol";

library UniversalRouterHelper {
    using BytesLib for bytes;

    error InvalidPoolAddress();
    error InvalidPoolLength();
    error InvalidReserves();
    error InvalidPath();

    /**
     * Stable *************************************************
     */

    // get the pool info in stable swap
    function getStableInfo(address stableSwapFactory, address input, address output, uint256 flag)
        internal
        view
        returns (uint256 i, uint256 j, address swapContract)
    {
        if (flag == 2) {
            IStableSwapFactory.StableSwapPairInfo memory info =
                IStableSwapFactory(stableSwapFactory).getPairInfo(input, output);
            i = input == info.token0 ? 0 : 1;
            j = (i == 0) ? 1 : 0;
            swapContract = info.swapContract;
        } else if (flag == 3) {
            IStableSwapFactory.StableSwapThreePoolPairInfo memory info =
                IStableSwapFactory(stableSwapFactory).getThreePoolPairInfo(input, output);

            if (input == info.token0) i = 0;
            else if (input == info.token1) i = 1;
            else if (input == info.token2) i = 2;

            if (output == info.token0) j = 0;
            else if (output == info.token1) j = 1;
            else if (output == info.token2) j = 2;

            swapContract = info.swapContract;
        }

        if (swapContract == address(0)) revert InvalidPoolAddress();
    }

    function getStableAmountsIn(
        address stableSwapFactory,
        address stableSwapInfo,
        address[] calldata path,
        uint256[] calldata flag,
        uint256 amountOut
    ) internal view returns (uint256[] memory amounts) {
        uint256 length = path.length;
        if (length < 2) revert InvalidPoolLength();

        amounts = new uint256[](length);
        amounts[length - 1] = amountOut;

        for (uint256 i = length - 1; i > 0; i--) {
            uint256 last = i - 1;
            (uint256 k, uint256 j, address swapContract) =
                getStableInfo(stableSwapFactory, path[last], path[i], flag[last]);
            amounts[last] = IStableSwapInfo(stableSwapInfo).get_dx(swapContract, k, j, amounts[i], type(uint256).max);
        }
    }

    /**
     * V2 *************************************************
     */
    /// @notice Sorts two tokens to return token0 and token1
    /// @param tokenA The first token to sort
    /// @param tokenB The other token to sort
    /// @return token0 The smaller token by address value
    /// @return token1 The larger token by address value
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
    }

    /// @notice Calculates the v2 address for a pair assuming the input tokens are pre-sorted
    /// @param factory The address of the v2 factory
    /// @param initCodeHash The hash of the pair initcode
    /// @param token0 The pair's token0
    /// @param token1 The pair's token1
    /// @return pair The resultant v2 pair address
    function pairForPreSorted(address factory, bytes32 initCodeHash, address token0, address token1)
        private
        pure
        returns (address pair)
    {
        pair = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash)
                    )
                )
            )
        );
    }

    /// @notice Calculates the v2 address for a pair without making any external calls
    /// @param factory The address of the v2 factory
    /// @param initCodeHash The hash of the pair initcode
    /// @param tokenA One of the tokens in the pair
    /// @param tokenB The other token in the pair
    /// @return pair The resultant v2 pair address
    function pairFor(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
        internal
        pure
        returns (address pair)
    {
        (address token0, address token1) = sortTokens(tokenA, tokenB);
        pair = pairForPreSorted(factory, initCodeHash, token0, token1);
    }

    /// @notice Calculates the v2 address for a pair and the pair's token0
    /// @param factory The address of the v2 factory
    /// @param initCodeHash The hash of the pair initcode
    /// @param tokenA One of the tokens in the pair
    /// @param tokenB The other token in the pair
    /// @return pair The resultant v2 pair address
    /// @return token0 The token considered token0 in this pair
    function pairAndToken0For(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
        internal
        pure
        returns (address pair, address token0)
    {
        address token1;
        (token0, token1) = sortTokens(tokenA, tokenB);
        pair = pairForPreSorted(factory, initCodeHash, token0, token1);
    }

    /// @notice Calculates the v2 address for a pair and fetches the reserves for each token
    /// @param factory The address of the v2 factory
    /// @param initCodeHash The hash of the pair initcode
    /// @param tokenA One of the tokens in the pair
    /// @param tokenB The other token in the pair
    /// @return pair The resultant v2 pair address
    /// @return reserveA The reserves for tokenA
    /// @return reserveB The reserves for tokenB
    function pairAndReservesFor(address factory, bytes32 initCodeHash, address tokenA, address tokenB)
        private
        view
        returns (address pair, uint256 reserveA, uint256 reserveB)
    {
        address token0;
        (pair, token0) = pairAndToken0For(factory, initCodeHash, tokenA, tokenB);
        (uint256 reserve0, uint256 reserve1,) = IPancakeV2Pair(pair).getReserves();
        (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
    }

    /// @notice Given an input asset amount returns the maximum output amount of the other asset
    /// @param amountIn The token input amount
    /// @param reserveIn The reserves available of the input token
    /// @param reserveOut The reserves available of the output token
    /// @return amountOut The output amount of the output token
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountOut)
    {
        if (reserveIn == 0 || reserveOut == 0) revert InvalidReserves();
        uint256 amountInWithFee = amountIn * 9975;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = reserveIn * 10000 + amountInWithFee;
        amountOut = numerator / denominator;
    }

    /// @notice Returns the input amount needed for a desired output amount in a single-hop trade
    /// @param amountOut The desired output amount
    /// @param reserveIn The reserves available of the input token
    /// @param reserveOut The reserves available of the output token
    /// @return amountIn The input amount of the input token
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountIn)
    {
        if (reserveIn == 0 || reserveOut == 0) revert InvalidReserves();
        uint256 numerator = reserveIn * amountOut * 10000;
        uint256 denominator = (reserveOut - amountOut) * 9975;
        amountIn = (numerator / denominator) + 1;
    }

    /// @notice Returns the input amount needed for a desired output amount in a multi-hop trade
    /// @param factory The address of the v2 factory
    /// @param initCodeHash The hash of the pair initcode
    /// @param amountOut The desired output amount
    /// @param path The path of the multi-hop trade
    /// @return amount The input amount of the input token
    /// @return pair The first pair in the trade
    function getAmountInMultihop(address factory, bytes32 initCodeHash, uint256 amountOut, address[] calldata path)
        internal
        view
        returns (uint256 amount, address pair)
    {
        if (path.length < 2) revert InvalidPath();
        amount = amountOut;
        for (uint256 i = path.length - 1; i > 0; i--) {
            uint256 reserveIn;
            uint256 reserveOut;

            (pair, reserveIn, reserveOut) = pairAndReservesFor(factory, initCodeHash, path[i - 1], path[i]);
            amount = getAmountIn(amount, reserveIn, reserveOut);
        }
    }

    /**
     * V3 *************************************************
     */
    /// @notice Returns true iff the path contains two or more pools
    /// @param path The encoded swap path
    /// @return True if path contains two or more pools, otherwise false
    function hasMultiplePools(bytes calldata path) internal pure returns (bool) {
        return path.length >= Constants.MULTIPLE_V3_POOLS_MIN_LENGTH;
    }

    /// @notice Decodes the first pool in path
    /// @param path The bytes encoded swap path
    /// @return tokenA The first token of the given pool
    /// @return fee The fee level of the pool
    /// @return tokenB The second token of the given pool
    function decodeFirstPool(bytes calldata path) internal pure returns (address, uint24, address) {
        return path.toPool();
    }

    /// @notice Gets the segment corresponding to the first pool in the path
    /// @param path The bytes encoded swap path
    /// @return The segment containing all data necessary to target the first pool in the path
    function getFirstPool(bytes calldata path) internal pure returns (bytes calldata) {
        return path[:Constants.V3_POP_OFFSET];
    }

    function decodeFirstToken(bytes calldata path) internal pure returns (address tokenA) {
        tokenA = path.toAddress();
    }

    /// @notice Skips a token + fee element
    /// @param path The swap path
    function skipToken(bytes calldata path) internal pure returns (bytes calldata) {
        return path[Constants.NEXT_V3_POOL_OFFSET:];
    }

    function computePoolAddress(address deployer, bytes32 initCodeHash, address tokenA, address tokenB, uint24 fee)
        internal
        pure
        returns (address pool)
    {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        pool = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(hex"ff", deployer, keccak256(abi.encode(tokenA, tokenB, fee)), initCodeHash)
                    )
                )
            )
        );
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 68), 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 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // 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(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 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(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 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(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

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

interface IStableSwap {
    // solium-disable-next-line mixedcase
    function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256 dy);

    // solium-disable-next-line mixedcase
    function exchange(uint256 i, uint256 j, uint256 dx, uint256 minDy) external payable;

    // solium-disable-next-line mixedcase
    function coins(uint256 i) external view returns (address);

    // solium-disable-next-line mixedcase
    function balances(uint256 i) external view returns (uint256);

    // solium-disable-next-line mixedcase
    function A() external view returns (uint256);

    // solium-disable-next-line mixedcase
    function fee() external view returns (uint256);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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

interface IPancakeV2Pair {
    event Approval(address indexed owner, address indexed spender, uint256 value);
    event Transfer(address indexed from, address indexed to, uint256 value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint256);
    function balanceOf(address owner) external view returns (uint256);
    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 value) external returns (bool);
    function transfer(address to, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint256);

    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    event Mint(address indexed sender, uint256 amount0, uint256 amount1);
    event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint256 amount0In,
        uint256 amount1In,
        uint256 amount0Out,
        uint256 amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint256);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint256);
    function price1CumulativeLast() external view returns (uint256);
    function kLast() external view returns (uint256);

    function mint(address to) external returns (uint256 liquidity);
    function burn(address to) external returns (uint256 amount0, uint256 amount1);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param y The uint256 to be downcasted
    /// @return z The downcasted integer, now type uint160
    function toUint160(uint256 y) internal pure returns (uint160 z) {
        require((z = uint160(y)) == y);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param y The int256 to be downcasted
    /// @return z The downcasted integer, now type int128
    function toInt128(int256 y) internal pure returns (int128 z) {
        require((z = int128(y)) == y);
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param y The uint256 to be casted
    /// @return z The casted integer, now type int256
    function toInt256(uint256 y) internal pure returns (int256 z) {
        require(y < 2 ** 255);
        z = int256(y);
    }
}

File 39 of 120 : IPancakeV3Pool.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./pool/IPancakeV3PoolImmutables.sol";
import "./pool/IPancakeV3PoolState.sol";
import "./pool/IPancakeV3PoolDerivedState.sol";
import "./pool/IPancakeV3PoolActions.sol";
import "./pool/IPancakeV3PoolOwnerActions.sol";
import "./pool/IPancakeV3PoolEvents.sol";

/// @title The interface for a PancakeSwap V3 Pool
/// @notice A PancakeSwap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IPancakeV3Pool is
    IPancakeV3PoolImmutables,
    IPancakeV3PoolState,
    IPancakeV3PoolDerivedState,
    IPancakeV3PoolActions,
    IPancakeV3PoolOwnerActions,
    IPancakeV3PoolEvents
{}

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

/// @title Callback for IPancakeV3PoolActions#swap
/// @notice Any contract that calls IPancakeV3PoolActions#swap must implement this interface
interface IPancakeV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IPancakeV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a PancakeV3Pool deployed by the canonical PancakeV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IPancakeV3PoolActions#swap call
    function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;

/// @notice A library used to store the maximum desired amount of input tokens for exact output swaps; used for checking slippage
library MaxInputAmount {
    // The slot holding the the maximum desired amount of input tokens, transiently. bytes32(uint256(keccak256("MaxAmountIn")) - 1)
    bytes32 constant MAX_AMOUNT_IN_SLOT = 0xaf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f692;

    function set(uint256 maxAmountIn) internal {
        assembly ("memory-safe") {
            tstore(MAX_AMOUNT_IN_SLOT, maxAmountIn)
        }
    }

    function get() internal view returns (uint256 maxAmountIn) {
        assembly ("memory-safe") {
            maxAmountIn := tload(MAX_AMOUNT_IN_SLOT)
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title For calculating a percentage of an amount, using bips
// TODO: Post-audit move to core, as core will use something similar.
library BipsLibrary {
    uint256 internal constant BPS_DENOMINATOR = 10_000;

    /// @notice emitted when an invalid percentage is provided
    error InvalidBips();

    /// @param amount The total amount to calculate a percentage of
    /// @param bips The percentage to calculate, in bips
    function calculatePortion(uint256 amount, uint256 bips) internal pure returns (uint256) {
        if (bips > BPS_DENOMINATOR) revert InvalidBips();
        return (amount * bips) / BPS_DENOMINATOR;
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern, minimalist, and gas efficient ERC-721 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

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

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

    /*//////////////////////////////////////////////////////////////
                         METADATA STORAGE/LOGIC
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    function tokenURI(uint256 id) public view virtual returns (string memory);

    /*//////////////////////////////////////////////////////////////
                      ERC721 BALANCE/OWNER STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) internal _ownerOf;

    mapping(address => uint256) internal _balanceOf;

    function ownerOf(uint256 id) public view virtual returns (address owner) {
        require((owner = _ownerOf[id]) != address(0), "NOT_MINTED");
    }

    function balanceOf(address owner) public view virtual returns (uint256) {
        require(owner != address(0), "ZERO_ADDRESS");

        return _balanceOf[owner];
    }

    /*//////////////////////////////////////////////////////////////
                         ERC721 APPROVAL STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 => address) public getApproved;

    mapping(address => mapping(address => bool)) public isApprovedForAll;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(string memory _name, string memory _symbol) {
        name = _name;
        symbol = _symbol;
    }

    /*//////////////////////////////////////////////////////////////
                              ERC721 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 id) public virtual {
        address owner = _ownerOf[id];

        require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED");

        getApproved[id] = spender;

        emit Approval(owner, spender, id);
    }

    function setApprovalForAll(address operator, bool approved) public virtual {
        isApprovedForAll[msg.sender][operator] = approved;

        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function transferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        require(from == _ownerOf[id], "WRONG_FROM");

        require(to != address(0), "INVALID_RECIPIENT");

        require(
            msg.sender == from || isApprovedForAll[from][msg.sender] || msg.sender == getApproved[id],
            "NOT_AUTHORIZED"
        );

        // Underflow of the sender's balance is impossible because we check for
        // ownership above and the recipient's balance can't realistically overflow.
        unchecked {
            _balanceOf[from]--;

            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        delete getApproved[id];

        emit Transfer(from, to, id);
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id
    ) public virtual {
        transferFrom(from, to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        bytes calldata data
    ) public virtual {
        transferFrom(from, to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    /*//////////////////////////////////////////////////////////////
                              ERC165 LOGIC
    //////////////////////////////////////////////////////////////*/

    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return
            interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
            interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721
            interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 id) internal virtual {
        require(to != address(0), "INVALID_RECIPIENT");

        require(_ownerOf[id] == address(0), "ALREADY_MINTED");

        // Counter overflow is incredibly unrealistic.
        unchecked {
            _balanceOf[to]++;
        }

        _ownerOf[id] = to;

        emit Transfer(address(0), to, id);
    }

    function _burn(uint256 id) internal virtual {
        address owner = _ownerOf[id];

        require(owner != address(0), "NOT_MINTED");

        // Ownership check above ensures no underflow.
        unchecked {
            _balanceOf[owner]--;
        }

        delete _ownerOf[id];

        delete getApproved[id];

        emit Transfer(owner, address(0), id);
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL SAFE MINT LOGIC
    //////////////////////////////////////////////////////////////*/

    function _safeMint(address to, uint256 id) internal virtual {
        _mint(to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, "") ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function _safeMint(
        address to,
        uint256 id,
        bytes memory data
    ) internal virtual {
        _mint(to, id);

        require(
            to.code.length == 0 ||
                ERC721TokenReceiver(to).onERC721Received(msg.sender, address(0), id, data) ==
                ERC721TokenReceiver.onERC721Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }
}

/// @notice A generic interface for a contract which properly accepts ERC721 tokens.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
abstract contract ERC721TokenReceiver {
    function onERC721Received(
        address,
        address,
        uint256,
        bytes calldata
    ) external virtual returns (bytes4) {
        return ERC721TokenReceiver.onERC721Received.selector;
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Minimalist and gas efficient standard ERC1155 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC1155.sol)
abstract contract ERC1155 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event TransferSingle(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256 id,
        uint256 amount
    );

    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] amounts
    );

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

    event URI(string value, uint256 indexed id);

    /*//////////////////////////////////////////////////////////////
                             ERC1155 STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(address => mapping(uint256 => uint256)) public balanceOf;

    mapping(address => mapping(address => bool)) public isApprovedForAll;

    /*//////////////////////////////////////////////////////////////
                             METADATA LOGIC
    //////////////////////////////////////////////////////////////*/

    function uri(uint256 id) public view virtual returns (string memory);

    /*//////////////////////////////////////////////////////////////
                              ERC1155 LOGIC
    //////////////////////////////////////////////////////////////*/

    function setApprovalForAll(address operator, bool approved) public virtual {
        isApprovedForAll[msg.sender][operator] = approved;

        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) public virtual {
        require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");

        balanceOf[from][id] -= amount;
        balanceOf[to][id] += amount;

        emit TransferSingle(msg.sender, from, to, id, amount);

        require(
            to.code.length == 0
                ? to != address(0)
                : ERC1155TokenReceiver(to).onERC1155Received(msg.sender, from, id, amount, data) ==
                    ERC1155TokenReceiver.onERC1155Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) public virtual {
        require(ids.length == amounts.length, "LENGTH_MISMATCH");

        require(msg.sender == from || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED");

        // Storing these outside the loop saves ~15 gas per iteration.
        uint256 id;
        uint256 amount;

        for (uint256 i = 0; i < ids.length; ) {
            id = ids[i];
            amount = amounts[i];

            balanceOf[from][id] -= amount;
            balanceOf[to][id] += amount;

            // An array can't have a total length
            // larger than the max uint256 value.
            unchecked {
                ++i;
            }
        }

        emit TransferBatch(msg.sender, from, to, ids, amounts);

        require(
            to.code.length == 0
                ? to != address(0)
                : ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, from, ids, amounts, data) ==
                    ERC1155TokenReceiver.onERC1155BatchReceived.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function balanceOfBatch(address[] calldata owners, uint256[] calldata ids)
        public
        view
        virtual
        returns (uint256[] memory balances)
    {
        require(owners.length == ids.length, "LENGTH_MISMATCH");

        balances = new uint256[](owners.length);

        // Unchecked because the only math done is incrementing
        // the array index counter which cannot possibly overflow.
        unchecked {
            for (uint256 i = 0; i < owners.length; ++i) {
                balances[i] = balanceOf[owners[i]][ids[i]];
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                              ERC165 LOGIC
    //////////////////////////////////////////////////////////////*/

    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return
            interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165
            interfaceId == 0xd9b67a26 || // ERC165 Interface ID for ERC1155
            interfaceId == 0x0e89341c; // ERC165 Interface ID for ERC1155MetadataURI
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(
        address to,
        uint256 id,
        uint256 amount,
        bytes memory data
    ) internal virtual {
        balanceOf[to][id] += amount;

        emit TransferSingle(msg.sender, address(0), to, id, amount);

        require(
            to.code.length == 0
                ? to != address(0)
                : ERC1155TokenReceiver(to).onERC1155Received(msg.sender, address(0), id, amount, data) ==
                    ERC1155TokenReceiver.onERC1155Received.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function _batchMint(
        address to,
        uint256[] memory ids,
        uint256[] memory amounts,
        bytes memory data
    ) internal virtual {
        uint256 idsLength = ids.length; // Saves MLOADs.

        require(idsLength == amounts.length, "LENGTH_MISMATCH");

        for (uint256 i = 0; i < idsLength; ) {
            balanceOf[to][ids[i]] += amounts[i];

            // An array can't have a total length
            // larger than the max uint256 value.
            unchecked {
                ++i;
            }
        }

        emit TransferBatch(msg.sender, address(0), to, ids, amounts);

        require(
            to.code.length == 0
                ? to != address(0)
                : ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, address(0), ids, amounts, data) ==
                    ERC1155TokenReceiver.onERC1155BatchReceived.selector,
            "UNSAFE_RECIPIENT"
        );
    }

    function _batchBurn(
        address from,
        uint256[] memory ids,
        uint256[] memory amounts
    ) internal virtual {
        uint256 idsLength = ids.length; // Saves MLOADs.

        require(idsLength == amounts.length, "LENGTH_MISMATCH");

        for (uint256 i = 0; i < idsLength; ) {
            balanceOf[from][ids[i]] -= amounts[i];

            // An array can't have a total length
            // larger than the max uint256 value.
            unchecked {
                ++i;
            }
        }

        emit TransferBatch(msg.sender, from, address(0), ids, amounts);
    }

    function _burn(
        address from,
        uint256 id,
        uint256 amount
    ) internal virtual {
        balanceOf[from][id] -= amount;

        emit TransferSingle(msg.sender, from, address(0), id, amount);
    }
}

/// @notice A generic interface for a contract which properly accepts ERC1155 tokens.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC1155.sol)
abstract contract ERC1155TokenReceiver {
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes calldata
    ) external virtual returns (bytes4) {
        return ERC1155TokenReceiver.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] calldata,
        uint256[] calldata,
        bytes calldata
    ) external virtual returns (bytes4) {
        return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
    }
}

File 45 of 120 : Actions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice Library to define different pool actions.
/// @dev These are suggested common commands, however additional commands should be defined as required
/// Some of these actions are not supported in the Router contracts or Position Manager contracts, but are left as they may be helpful commands for other peripheral contracts.
library Actions {
    // cl-pool actions
    // liquidity actions
    uint256 internal constant CL_INCREASE_LIQUIDITY = 0x00;
    uint256 internal constant CL_DECREASE_LIQUIDITY = 0x01;
    uint256 internal constant CL_MINT_POSITION = 0x02;
    uint256 internal constant CL_BURN_POSITION = 0x03;
    uint256 internal constant CL_INCREASE_LIQUIDITY_FROM_DELTAS = 0x04;
    uint256 internal constant CL_MINT_POSITION_FROM_DELTAS = 0x05;

    // swapping
    uint256 internal constant CL_SWAP_EXACT_IN_SINGLE = 0x06;
    uint256 internal constant CL_SWAP_EXACT_IN = 0x07;
    uint256 internal constant CL_SWAP_EXACT_OUT_SINGLE = 0x08;
    uint256 internal constant CL_SWAP_EXACT_OUT = 0x09;

    // donate
    /// @dev this is not supported in the position manager or router
    uint256 internal constant CL_DONATE = 0x0a;

    // closing deltas on the pool manager
    // settling
    uint256 internal constant SETTLE = 0x0b;
    uint256 internal constant SETTLE_ALL = 0x0c;
    uint256 internal constant SETTLE_PAIR = 0x0d;
    // taking
    uint256 internal constant TAKE = 0x0e;
    uint256 internal constant TAKE_ALL = 0x0f;
    uint256 internal constant TAKE_PORTION = 0x10;
    uint256 internal constant TAKE_PAIR = 0x11;

    uint256 internal constant CLOSE_CURRENCY = 0x12;
    uint256 internal constant CLEAR_OR_TAKE = 0x13;
    uint256 internal constant SWEEP = 0x14;
    uint256 internal constant WRAP = 0x15;
    uint256 internal constant UNWRAP = 0x16;

    // minting/burning 6909s to close deltas
    /// @dev this is not supported in the position manager or router
    uint256 internal constant MINT_6909 = 0x17;
    uint256 internal constant BURN_6909 = 0x18;

    // bin-pool actions
    // liquidity actions
    uint256 internal constant BIN_ADD_LIQUIDITY = 0x19;
    uint256 internal constant BIN_REMOVE_LIQUIDITY = 0x1a;
    uint256 internal constant BIN_ADD_LIQUIDITY_FROM_DELTAS = 0x1b;
    // swapping
    uint256 internal constant BIN_SWAP_EXACT_IN_SINGLE = 0x1c;
    uint256 internal constant BIN_SWAP_EXACT_IN = 0x1d;
    uint256 internal constant BIN_SWAP_EXACT_OUT_SINGLE = 0x1e;
    uint256 internal constant BIN_SWAP_EXACT_OUT = 0x1f;
    // donate
    uint256 internal constant BIN_DONATE = 0x20;
}

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

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain seperator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external
        payable;
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.24;

/// @notice A library to implement a reentrancy lock in transient storage.
/// @dev Instead of storing a boolean, the locker's address is stored to allow the contract to know who locked the contract
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Locker {
    // The slot holding the locker state, transiently. bytes32(uint256(keccak256("Locker")) - 1)
    bytes32 constant LOCKER_SLOT = 0x0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a708;

    function set(address locker) internal {
        // The locker is always msg.sender or address(0) so does not need to be cleaned
        assembly ("memory-safe") {
            tstore(LOCKER_SLOT, locker)
        }
    }

    function get() internal view returns (address locker) {
        assembly ("memory-safe") {
            locker := tload(LOCKER_SLOT)
        }
    }

    function isLocked() internal view returns (bool) {
        return Locker.get() != address(0);
    }
}

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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {ILockCallback} from "infinity-core/src/interfaces/ILockCallback.sol";
import {IVault} from "infinity-core/src/interfaces/IVault.sol";
import {ImmutableState} from "./ImmutableState.sol";

/// @title Safe Callback
/// @notice A contract that only allows the PCS Infinity Vault to call the lockAcquired function
abstract contract SafeCallback is ImmutableState, ILockCallback {
    /// @notice Thrown when calling lockAcquired where the caller is not the Vault
    error NotVault();

    constructor(IVault _vault) ImmutableState(_vault) {}

    /// @notice Only allow calls from the Vault contract
    modifier onlyByVault() {
        if (msg.sender != address(vault)) revert NotVault();
        _;
    }

    /// @inheritdoc ILockCallback
    /// @dev We force the onlyByVault modifier by exposing a virtual function after the onlyByVault check.
    function lockAcquired(bytes calldata data) external onlyByVault returns (bytes memory) {
        return _lockAcquired(data);
    }

    /// @dev to be implemented by the child contract, to safely guarantee the logic is only executed by the Vault
    function _lockAcquired(bytes calldata data) internal virtual returns (bytes memory);
}

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

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

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

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesInitializedOutOfOrder(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 is not a dynamic fee pool.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Emitted when lp fee is updated
    /// @dev The event is emitted even if the updated fee value is the same as previous one
    event DynamicLPFeeUpdated(PoolId indexed id, uint24 dynamicLPFee);

    /// @notice Updates lp fee for a dyanmic fee pool
    /// @dev Some of the use case could be:
    ///   1) when hook#beforeSwap() is called and hook call this function to update the lp fee
    ///   2) For BinPool only, when hook#beforeMint() is called and hook call this function to update the lp fee
    ///   3) other use case where the hook might want to on an ad-hoc basis increase/reduce lp fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;

    /// @notice Return PoolKey for a given PoolId
    function poolIdToPoolKey(PoolId id)
        external
        view
        returns (
            Currency currency0,
            Currency currency1,
            IHooks hooks,
            IPoolManager poolManager,
            uint24 fee,
            bytes32 parameters
        );
}

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

interface IHooks {
    function getHooksRegistrationBitmap() external view returns (uint16);
}

//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 {
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xc0 represents the total size of the poolKey struct (6 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xc0)
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {CLPosition} from "./CLPosition.sol";
import {TickMath} from "./TickMath.sol";
import {BalanceDelta, BalanceDeltaLibrary, toBalanceDelta} from "../../types/BalanceDelta.sol";
import {CLSlot0} from "../types/CLSlot0.sol";
import {Tick} from "./Tick.sol";
import {TickBitmap} from "./TickBitmap.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
import {SafeCast} from "../../libraries/SafeCast.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {UnsafeMath} from "../../libraries/math/UnsafeMath.sol";
import {SwapMath} from "./SwapMath.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {ProtocolFeeLibrary} from "../../libraries/ProtocolFeeLibrary.sol";
import {LPFeeLibrary} from "../../libraries/LPFeeLibrary.sol";

/// @notice a library with all actions that can be performed on cl pool
library CLPool {
    using SafeCast for int256;
    using SafeCast for uint256;
    using Tick for mapping(int24 => Tick.Info);
    using TickBitmap for mapping(int16 => uint256);
    using CLPosition for mapping(bytes32 => CLPosition.Info);
    using CLPosition for CLPosition.Info;
    using LiquidityMath for uint128;
    using CLPool for State;
    using ProtocolFeeLibrary for uint24;
    using ProtocolFeeLibrary for uint16;
    using LPFeeLibrary for uint24;

    /// @notice Thrown when trying to initalize an already initialized pool
    error PoolAlreadyInitialized();

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

    /// @notice Thrown when trying to swap with max lp fee and specifying an output amount
    error InvalidFeeForExactOut();

    /// @notice Thrown when sqrtPriceLimitX96 is out of range
    /// @param sqrtPriceCurrentX96 current price in the pool
    /// @param sqrtPriceLimitX96 The price limit specified by user
    error InvalidSqrtPriceLimit(uint160 sqrtPriceCurrentX96, uint160 sqrtPriceLimitX96);

    /// @notice Thrown by donate if there is currently 0 liquidity, since the fees will not go to any liquidity providers
    error NoLiquidityToReceiveFees();

    /// @notice The state of a pool
    /// @dev 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 lockAcquired callback may make the inflated value more extreme
    struct State {
        CLSlot0 slot0;
        /// @dev accumulated lp fees
        uint256 feeGrowthGlobal0X128;
        uint256 feeGrowthGlobal1X128;
        /// @dev current active liquidity
        uint128 liquidity;
        mapping(int24 tick => Tick.Info info) ticks;
        mapping(int16 pos => uint256 bitmap) tickBitmap;
        mapping(bytes32 positionHash => CLPosition.Info info) positions;
    }

    function initialize(State storage self, uint160 sqrtPriceX96, uint24 protocolFee, uint24 lpFee)
        internal
        returns (int24 tick)
    {
        if (self.slot0.sqrtPriceX96() != 0) revert PoolAlreadyInitialized();

        tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);

        self.slot0 = CLSlot0.wrap(bytes32(0)).setSqrtPriceX96(sqrtPriceX96).setTick(tick).setProtocolFee(protocolFee)
            .setLpFee(lpFee);
    }

    struct ModifyLiquidityParams {
        // the address that owns the position
        address owner;
        // the lower and upper tick of the position
        int24 tickLower;
        int24 tickUpper;
        // any change in liquidity
        int128 liquidityDelta;
        // the spacing between ticks
        int24 tickSpacing;
        // used to distinguish positions of the same owner, at the same tick range
        bytes32 salt;
    }

    /// @dev Effect changes to the liquidity of a position in a pool
    /// @param params the position details and the change to the position's liquidity to effect
    /// @return delta the deltas from liquidity changes
    /// @return feeDelta the delta of the fees generated in the liquidity range
    function modifyLiquidity(State storage self, ModifyLiquidityParams memory params)
        internal
        returns (BalanceDelta delta, BalanceDelta feeDelta)
    {
        int24 tickLower = params.tickLower;
        int24 tickUpper = params.tickUpper;
        Tick.checkTicks(tickLower, tickUpper);

        int24 tick = self.slot0.tick();
        (uint256 feesOwed0, uint256 feesOwed1) = _updatePosition(self, params, tick);

        ///@dev calculate the tokens delta needed
        int128 liquidityDelta = params.liquidityDelta;
        if (liquidityDelta != 0) {
            uint160 sqrtPriceX96 = self.slot0.sqrtPriceX96();
            int128 amount0;
            int128 amount1;
            if (tick < tickLower) {
                // current tick is below the passed range; liquidity can only become in range by crossing from left to
                // right, when we'll need _more_ currency0 (it's becoming more valuable) so user must provide it
                amount0 = SqrtPriceMath.getAmount0Delta(
                    TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta
                ).toInt128();
            } else if (tick < tickUpper) {
                amount0 = SqrtPriceMath.getAmount0Delta(
                    sqrtPriceX96, TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta
                ).toInt128();
                amount1 = SqrtPriceMath.getAmount1Delta(
                    TickMath.getSqrtRatioAtTick(tickLower), sqrtPriceX96, liquidityDelta
                ).toInt128();

                self.liquidity = LiquidityMath.addDelta(self.liquidity, liquidityDelta);
            } else {
                // current tick is above the passed range; liquidity can only become in range by crossing from right to
                // left, when we'll need _more_ currency1 (it's becoming more valuable) so user must provide it
                amount1 = SqrtPriceMath.getAmount1Delta(
                    TickMath.getSqrtRatioAtTick(tickLower), TickMath.getSqrtRatioAtTick(tickUpper), liquidityDelta
                ).toInt128();
            }

            // Amount required for updating liquidity
            delta = toBalanceDelta(amount0, amount1);
        }

        // Fees earned from LPing are removed from the pool balance and returned separately
        feeDelta = toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128());
    }

    // the top level state of the swap, the results of which are recorded in storage at the end
    struct SwapState {
        // the amount remaining to be swapped in/out of the input/output asset
        int256 amountSpecifiedRemaining;
        // the amount already swapped out/in of the output/input asset
        int256 amountCalculated;
        // current sqrt(price)
        uint160 sqrtPriceX96;
        // the tick associated with the current price
        int24 tick;
        // the swapFee (the total percentage charged within a swap, including the protocol fee and the LP fee)
        uint24 swapFee;
        // the single direction protocol fee for the swap
        uint16 protocolFee;
        // the global fee growth of the input token
        uint256 feeGrowthGlobalX128;
        // amount of input token paid as protocol fee
        uint256 feeAmountToProtocol;
        // the current liquidity in range
        uint128 liquidity;
    }

    struct StepComputations {
        // the price at the beginning of the step
        uint160 sqrtPriceStartX96;
        // the next tick to swap to from the current tick in the swap direction
        int24 tickNext;
        // whether tickNext is initialized or not
        bool initialized;
        // sqrt(price) for the next tick (1/0)
        uint160 sqrtPriceNextX96;
        // how much is being swapped in in this step
        uint256 amountIn;
        // how much is being swapped out
        uint256 amountOut;
        // how much fee is being paid in
        uint256 feeAmount;
    }

    struct SwapParams {
        int24 tickSpacing;
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
        uint24 lpFeeOverride;
    }

    function swap(State storage self, SwapParams memory params)
        internal
        returns (BalanceDelta balanceDelta, SwapState memory state)
    {
        // cache variables for gas optimization
        CLSlot0 slot0Start = self.slot0;
        bool zeroForOne = params.zeroForOne;
        uint160 sqrtPriceLimitX96 = params.sqrtPriceLimitX96;

        // check price limit
        // Swaps can never occur at MIN_TICK, only at MIN_TICK + 1, except at initialization of a pool
        // Under certain circumstances outlined below, the tick will preemptively reach MIN_TICK without swapping there
        if (
            zeroForOne
                ? (sqrtPriceLimitX96 >= slot0Start.sqrtPriceX96() || sqrtPriceLimitX96 <= TickMath.MIN_SQRT_RATIO)
                : (sqrtPriceLimitX96 <= slot0Start.sqrtPriceX96() || sqrtPriceLimitX96 >= TickMath.MAX_SQRT_RATIO)
        ) {
            revert InvalidSqrtPriceLimit(slot0Start.sqrtPriceX96(), sqrtPriceLimitX96);
        }

        // cache variables for gas optimization
        // liquidity at the beginning of the swap
        uint128 liquidityStart = self.liquidity;
        bool exactInput = params.amountSpecified < 0;

        // init swap state
        {
            uint16 protocolFee =
                zeroForOne ? slot0Start.protocolFee().getZeroForOneFee() : slot0Start.protocolFee().getOneForZeroFee();

            uint24 lpFee = params.lpFeeOverride.isOverride()
                ? params.lpFeeOverride.removeOverrideAndValidate(LPFeeLibrary.ONE_HUNDRED_PERCENT_FEE)
                : slot0Start.lpFee();

            state = SwapState({
                amountSpecifiedRemaining: params.amountSpecified,
                amountCalculated: 0,
                sqrtPriceX96: slot0Start.sqrtPriceX96(),
                tick: slot0Start.tick(),
                swapFee: protocolFee == 0 ? lpFee : protocolFee.calculateSwapFee(lpFee),
                protocolFee: protocolFee,
                feeGrowthGlobalX128: zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128,
                feeAmountToProtocol: 0,
                liquidity: liquidityStart
            });
        }

        /// @dev a swap fee totaling 100% makes exact output swaps impossible since the input is entirely consumed by the fee
        if (state.swapFee >= LPFeeLibrary.ONE_HUNDRED_PERCENT_FEE) {
            if (!exactInput) {
                revert InvalidFeeForExactOut();
            }
        }

        /// @notice early return if hook has updated amountSpecified to 0
        if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, state);

        StepComputations memory step;
        // continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
        while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {
            step.sqrtPriceStartX96 = state.sqrtPriceX96;

            (step.tickNext, step.initialized) =
                self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, zeroForOne);

            // ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
            if (step.tickNext < TickMath.MIN_TICK) {
                step.tickNext = TickMath.MIN_TICK;
            } else if (step.tickNext > TickMath.MAX_TICK) {
                step.tickNext = TickMath.MAX_TICK;
            }

            // get the price for the next tick
            step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);

            // compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
            (state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(
                state.sqrtPriceX96,
                SwapMath.getSqrtPriceTarget(zeroForOne, step.sqrtPriceNextX96, sqrtPriceLimitX96),
                state.liquidity,
                state.amountSpecifiedRemaining,
                state.swapFee
            );

            if (exactInput) {
                /// @dev SwapMath will always ensure that amountSpecified > amountIn + feeAmount
                unchecked {
                    state.amountSpecifiedRemaining += (step.amountIn + step.feeAmount).toInt256();
                }

                /// @dev amountCalculated is the amount of output token, hence neg in this case
                state.amountCalculated += step.amountOut.toInt256();
            } else {
                unchecked {
                    state.amountSpecifiedRemaining -= step.amountOut.toInt256();
                }
                state.amountCalculated -= (step.amountIn + step.feeAmount).toInt256();
            }

            /// @dev if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
            if (state.protocolFee > 0) {
                unchecked {
                    // cannot overflow due to limits on the size of protocolFee and params.amountSpecified
                    // this rounds down to favor LPs over the protocol
                    uint256 delta = (state.swapFee == state.protocolFee)
                        ? step.feeAmount // lp fee is 0, so the entire fee is owed to the protocol instead
                        : (step.amountIn + step.feeAmount) * state.protocolFee / ProtocolFeeLibrary.PIPS_DENOMINATOR;

                    // subtract it from the total fee then left over is the LP fee
                    step.feeAmount -= delta;
                    state.feeAmountToProtocol += delta;
                }
            }

            // update global fee tracker
            if (state.liquidity > 0) {
                unchecked {
                    state.feeGrowthGlobalX128 +=
                        UnsafeMath.simpleMulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
                }
            }

            // Shift tick if we reached the next price, and preemptively decrement for zeroForOne swaps to tickNext - 1.
            // If the swap doesnt continue (if amountRemaining == 0 or sqrtPriceLimit is met), slot0.tick will be 1 less
            // than getTickAtSqrtPrice(slot0.sqrtPrice). This doesn't affect swaps, but donation calls should verify both
            // price and tick to reward the correct LPs.
            if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
                // if the tick is initialized, run the tick transition
                if (step.initialized) {
                    int128 liquidityNet = self.ticks.cross(
                        step.tickNext,
                        (zeroForOne ? state.feeGrowthGlobalX128 : self.feeGrowthGlobal0X128),
                        (zeroForOne ? self.feeGrowthGlobal1X128 : state.feeGrowthGlobalX128)
                    );
                    // if we're moving leftward, we interpret liquidityNet as the opposite sign
                    // safe because liquidityNet cannot be type(int128).min
                    unchecked {
                        if (zeroForOne) liquidityNet = -liquidityNet;
                    }

                    state.liquidity = state.liquidity.addDelta(liquidityNet);
                }

                unchecked {
                    state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
                }
            } else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
                // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
                state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
            }
        }

        // update tick and price if changed
        if (state.tick != slot0Start.tick()) {
            self.slot0 = self.slot0.setSqrtPriceX96(state.sqrtPriceX96).setTick(state.tick);
        } else {
            // otherwise just update the price
            self.slot0 = self.slot0.setSqrtPriceX96(state.sqrtPriceX96);
        }

        // update liquidity if it changed
        if (liquidityStart != state.liquidity) self.liquidity = state.liquidity;

        // update fee growth global
        if (zeroForOne) {
            self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
        } else {
            self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
        }

        unchecked {
            (int128 amount0, int128 amount1) = zeroForOne == exactInput
                ? ((params.amountSpecified - state.amountSpecifiedRemaining).toInt128(), state.amountCalculated.toInt128())
                : (
                    (state.amountCalculated.toInt128()),
                    (params.amountSpecified - state.amountSpecifiedRemaining).toInt128()
                );

            balanceDelta = toBalanceDelta(amount0, amount1);
        }
    }

    struct UpdatePositionCache {
        bool flippedLower;
        bool flippedUpper;
        uint256 feeGrowthInside0X128;
        uint256 feeGrowthInside1X128;
        uint256 feesOwed0;
        uint256 feesOwed1;
        uint128 maxLiquidityPerTick;
    }

    function _updatePosition(State storage self, ModifyLiquidityParams memory params, int24 tick)
        internal
        returns (uint256, uint256)
    {
        //@dev avoid stack too deep
        UpdatePositionCache memory cache;
        {
            uint256 _feeGrowthGlobal0X128 = self.feeGrowthGlobal0X128; // SLOAD for gas optimization
            uint256 _feeGrowthGlobal1X128 = self.feeGrowthGlobal1X128; // SLOAD for gas optimization

            ///@dev  update ticks if nencessary
            if (params.liquidityDelta != 0) {
                cache.maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(params.tickSpacing);
                cache.flippedLower = self.ticks.update(
                    params.tickLower,
                    tick,
                    params.liquidityDelta,
                    _feeGrowthGlobal0X128,
                    _feeGrowthGlobal1X128,
                    false,
                    cache.maxLiquidityPerTick
                );
                cache.flippedUpper = self.ticks.update(
                    params.tickUpper,
                    tick,
                    params.liquidityDelta,
                    _feeGrowthGlobal0X128,
                    _feeGrowthGlobal1X128,
                    true,
                    cache.maxLiquidityPerTick
                );

                if (cache.flippedLower) {
                    self.tickBitmap.flipTick(params.tickLower, params.tickSpacing);
                }
                if (cache.flippedUpper) {
                    self.tickBitmap.flipTick(params.tickUpper, params.tickSpacing);
                }
            }

            (cache.feeGrowthInside0X128, cache.feeGrowthInside1X128) = self.ticks.getFeeGrowthInside(
                params.tickLower, params.tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128
            );
        }

        ///@dev update user position and collect fees
        /// must be done after ticks are updated in case of a 0 -> 1 flip
        (cache.feesOwed0, cache.feesOwed1) = self.positions.get(
            params.owner, params.tickLower, params.tickUpper, params.salt
        ).update(params.liquidityDelta, cache.feeGrowthInside0X128, cache.feeGrowthInside1X128);

        ///@dev clear any tick data that is no longer needed
        /// must be done after fee collection in case of a 1 -> 0 flip
        if (params.liquidityDelta < 0) {
            if (cache.flippedLower) {
                self.ticks.clear(params.tickLower);
            }
            if (cache.flippedUpper) {
                self.ticks.clear(params.tickUpper);
            }
        }

        return (cache.feesOwed0, cache.feesOwed1);
    }

    /// @notice Donates are in fact giving token to in-ranged liquidity providers only
    function donate(State storage state, uint256 amount0, uint256 amount1)
        internal
        returns (BalanceDelta delta, int24 tick)
    {
        if (state.liquidity == 0) revert NoLiquidityToReceiveFees();
        delta = toBalanceDelta(-(amount0.toInt128()), -(amount1.toInt128()));
        unchecked {
            if (amount0 > 0) {
                state.feeGrowthGlobal0X128 += UnsafeMath.simpleMulDiv(amount0, FixedPoint128.Q128, state.liquidity);
            }
            if (amount1 > 0) {
                state.feeGrowthGlobal1X128 += UnsafeMath.simpleMulDiv(amount1, FixedPoint128.Q128, state.liquidity);
            }
            tick = state.slot0.tick();
        }
    }

    function setProtocolFee(State storage self, uint24 protocolFee) internal {
        self.checkPoolInitialized();

        self.slot0 = self.slot0.setProtocolFee(protocolFee);
    }

    /// @notice Only dynamic fee pools may update the lp fee.
    function setLPFee(State storage self, uint24 lpFee) internal {
        self.checkPoolInitialized();

        self.slot0 = self.slot0.setLpFee(lpFee);
    }

    function checkPoolInitialized(State storage self) internal view {
        if (self.slot0.sqrtPriceX96() == 0) {
            // revert PoolNotInitialized();
            assembly ("memory-safe") {
                mstore(0x00, 0x486aa307)
                revert(0x1c, 0x04)
            }
        }
    }
}

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

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

interface IProtocolFees {
    /// @notice Thrown when the protocol fee exceeds the upper limit.
    error ProtocolFeeTooLarge(uint24 fee);
    /// @notice Thrown when calls to protocolFeeController fails or return size is not 32 bytes
    error ProtocolFeeCannotBeFetched();

    /// @notice Thrown when user not authorized to set or collect protocol fee
    error InvalidCaller();

    /// @notice Emitted when protocol fee is updated
    /// @dev The event is emitted even if the updated protocolFee is the same as previous protocolFee
    /// @param id The pool id for which the protocol fee is updated
    /// @param protocolFee  The new protocol fee value
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Emitted when protocol fee controller is updated
    /// @param protocolFeeController The new protocol fee controller
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @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 given currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

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

    /// @notice Sets the protocol's swap fee for the given pool
    /// @param key The pool key for which to set the protocol fee
    /// @param newProtocolFee The new protocol fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Update the protocol fee controller, called by the owner
    /// @param controller The new protocol fee controller to be set
    function setProtocolFeeController(IProtocolFeeController controller) external;

    /// @notice Collects the protocol fee accrued in the given currency, called by the owner or the protocol fee controller
    /// @dev This will revert if vault is locked
    /// @param recipient The address to which the protocol fees should be sent
    /// @param currency The currency in which to collect the protocol fees
    /// @param amount The amount of protocol fees to collect
    /// @return amountCollected The amount of protocol fees actually collected
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the vault where the protocol fees are safely stored
    /// @return IVault The address of the vault
    function vault() external view returns (IVault);
}

// 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 Constant for a BalanceDelta of zero value
    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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

/// @title CLPosition
/// @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 CLPosition {
    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct Info {
        // 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 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 key)
    {
        // same as `positionKey = keccak256(abi.encodePacked(tickLower, tickUpper, owner, salt))`
        // make salt, tickUpper, tickLower, owner to be tightly packed in memory
        assembly ("memory-safe") {
            mstore(
                0x0,
                or(
                    shl(160, and(0xFFFFFF, tickUpper)),
                    or(shl(184, tickLower), and(owner, 0xffffffffffffffffffffffffffffffffffffffff))
                )
            ) // tickLower at [0x06, 0x09), tickUpper at [0x09,0x0c), owner at [0x0c, 0x20)
            mstore(0x20, salt) // salt at [0x20, 0x40)
            key := keccak256(0x06, 0x3a) // len is 58 bytes
        }
    }

    /// @notice Returns the Info 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 => Info) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (Info storage position)
    {
        bytes32 key = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[key];
    }

    /// @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(
        Info storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        uint128 liquidityNext;
        if (liquidityDelta == 0) {
            if (liquidity == 0) revert CannotUpdateEmptyPosition(); // disallow pokes for 0 liquidity positions
            liquidityNext = liquidity;
        } else {
            liquidityNext = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        ///@dev Tho overflow is expected, it's technically possible users can lose their rewards if it hits type(uint128).max
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        if (liquidityDelta != 0) self.liquidity = liquidityNext;
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

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

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 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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import "../../libraries/SafeCast.sol";
import "./TickMath.sol";
import "./LiquidityMath.sol";

/// @title Tick
/// @notice Contains functions for managing tick processes and relevant calculations
library Tick {
    using SafeCast for int256;

    /// @notice Thrown when tickLower is not below tickUpper
    /// @param tickLower The invalid tickLower
    /// @param tickUpper The invalid tickUpper
    error TicksMisordered(int24 tickLower, int24 tickUpper);

    /// @notice Thrown when tickLower is less than min tick
    /// @param tickLower The invalid tickLower
    error TickLowerOutOfBounds(int24 tickLower);

    /// @notice Thrown when tickUpper exceeds max tick
    /// @param tickUpper The invalid tickUpper
    error TickUpperOutOfBounds(int24 tickUpper);

    /// @notice For the tick spacing, the tick has too much liquidity
    error TickLiquidityOverflow(int24 tick);

    // info stored for each initialized individual tick
    struct Info {
        // the total position liquidity that references this tick
        uint128 liquidityGross;
        // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),
        int128 liquidityNet;
        // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
        // only has relative meaning, not absolute — the value depends on when the tick is initialized
        uint256 feeGrowthOutside0X128;
        uint256 feeGrowthOutside1X128;
    }
    /// @dev Common checks for valid tick inputs.

    function checkTicks(int24 tickLower, int24 tickUpper) internal pure {
        if (tickLower >= tickUpper) revert TicksMisordered(tickLower, tickUpper);
        if (tickLower < TickMath.MIN_TICK) revert TickLowerOutOfBounds(tickLower);
        if (tickUpper > TickMath.MAX_TICK) revert TickUpperOutOfBounds(tickUpper);
    }

    /// @notice Derives max liquidity per tick from given tick spacing
    /// @dev Executed within the pool constructor
    /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`
    ///     e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...
    /// @return result The max liquidity per tick
    function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128 result) {
        // Equivalent to v3 but in assembly for gas efficiency:
        // int24 minTick = (TickMath.MIN_TICK / tickSpacing);
        // if (TickMath.MIN_TICK  % tickSpacing != 0) minTick--;
        // int24 maxTick = (TickMath.MAX_TICK / tickSpacing);
        // uint24 numTicks = maxTick - minTick + 1;
        // return type(uint128).max / numTicks;
        int24 MAX_TICK = TickMath.MAX_TICK;
        int24 MIN_TICK = TickMath.MIN_TICK;
        // tick spacing will never be 0 since TickMath.MIN_TICK_SPACING is 1
        assembly ("memory-safe") {
            tickSpacing := signextend(2, tickSpacing)
            let minTick := sub(sdiv(MIN_TICK, tickSpacing), slt(smod(MIN_TICK, tickSpacing), 0))
            let maxTick := sdiv(MAX_TICK, tickSpacing)
            let numTicks := add(sub(maxTick, minTick), 1)
            result := div(sub(shl(128, 1), 1), numTicks)
        }
    }

    /// @notice Retrieves fee growth data
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param tickCurrent The current tick
    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
    /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
    /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
    function getFeeGrowthInside(
        mapping(int24 => Tick.Info) storage self,
        int24 tickLower,
        int24 tickUpper,
        int24 tickCurrent,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128
    ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {
        Info storage lower = self[tickLower];
        Info storage upper = self[tickUpper];

        // calculate fee growth below
        uint256 feeGrowthBelow0X128;
        uint256 feeGrowthBelow1X128;
        unchecked {
            if (tickCurrent >= tickLower) {
                feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;
                feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;
            } else {
                feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;
                feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;
            }

            // calculate fee growth above
            uint256 feeGrowthAbove0X128;
            uint256 feeGrowthAbove1X128;
            if (tickCurrent < tickUpper) {
                feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;
                feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;
            } else {
                feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;
                feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;
            }

            feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;
            feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;
        }
    }

    /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tick The tick that will be updated
    /// @param tickCurrent The current tick
    /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
    /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick
    /// @param maxLiquidity The maximum liquidity allocation for a single tick
    /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
    function update(
        mapping(int24 => Tick.Info) storage self,
        int24 tick,
        int24 tickCurrent,
        int128 liquidityDelta,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128,
        bool upper,
        uint128 maxLiquidity
    ) internal returns (bool flipped) {
        Tick.Info storage info = self[tick];

        ///@dev accessing two members without touching the same slot twice
        uint128 liquidityGrossBefore;
        int128 liquidityNetBefore;
        assembly ("memory-safe") {
            let slot0 := sload(info.slot)
            liquidityGrossBefore := shr(128, shl(128, slot0))
            liquidityNetBefore := shr(128, slot0)
        }

        uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);

        if (liquidityGrossAfter > maxLiquidity) revert TickLiquidityOverflow(tick);

        flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);

        if (liquidityGrossBefore == 0) {
            // by convention, we assume that all growth before a tick was initialized happened _below_ the tick
            if (tick <= tickCurrent) {
                info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;
                info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;
            }
        }

        // when the lower (upper) tick is crossed left to right, liquidity must be added (removed)
        // when the lower (upper) tick is crossed right to left, liquidity must be removed (added)
        int128 liquidityNetAfter = upper ? (liquidityNetBefore - liquidityDelta) : (liquidityNetBefore + liquidityDelta);

        // update two members in one go
        assembly ("memory-safe") {
            sstore(
                info.slot, or(and(liquidityGrossAfter, 0xffffffffffffffffffffffffffffffff), shl(128, liquidityNetAfter))
            )
        }
    }

    /// @notice Clears tick data
    /// @param self The mapping containing all initialized tick information for initialized ticks
    /// @param tick The tick that will be cleared
    function clear(mapping(int24 => Tick.Info) storage self, int24 tick) internal {
        delete self[tick];
    }

    /// @notice Transitions to next tick as needed by price movement
    /// @param self The mapping containing all tick information for initialized ticks
    /// @param tick The destination tick of the transition
    /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0
    /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1
    /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
    function cross(
        mapping(int24 => Tick.Info) storage self,
        int24 tick,
        uint256 feeGrowthGlobal0X128,
        uint256 feeGrowthGlobal1X128
    ) internal returns (int128 liquidityNet) {
        unchecked {
            Tick.Info storage info = self[tick];
            info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;
            info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;
            liquidityNet = info.liquidityNet;
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {BalanceDelta, toBalanceDelta} from "../../types/BalanceDelta.sol";
import {BinSlot0} from "../types/BinSlot0.sol";
import {LiquidityConfigurations} from "./math/LiquidityConfigurations.sol";
import {PackedUint128Math} from "./math/PackedUint128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {TreeMath} from "./math/TreeMath.sol";
import {PriceHelper} from "./PriceHelper.sol";
import {BinHelper} from "./BinHelper.sol";
import {BinPosition} from "./BinPosition.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
import {FeeHelper} from "./FeeHelper.sol";
import {ProtocolFeeLibrary} from "../../libraries/ProtocolFeeLibrary.sol";
import {LPFeeLibrary} from "../../libraries/LPFeeLibrary.sol";

/// @notice a library with all actions that can be performed on bin pool
library BinPool {
    using BinHelper for bytes32;
    using LiquidityConfigurations for bytes32;
    using PackedUint128Math for bytes32;
    using PackedUint128Math for uint128;
    using PriceHelper for uint24;
    using Uint256x256Math for uint256;
    using BinPosition for mapping(bytes32 => BinPosition.Info);
    using BinPosition for BinPosition.Info;
    using TreeMath for bytes32;
    using SafeCast for uint256;
    using SafeCast for uint128;
    using FeeHelper for uint128;
    using BinPool for State;
    using ProtocolFeeLibrary for uint24;
    using ProtocolFeeLibrary for uint16;
    using LPFeeLibrary for uint24;

    error PoolNotInitialized();
    error PoolAlreadyInitialized();
    error PoolInvalidParameter();
    error BinPool__EmptyLiquidityConfigs();
    error BinPool__ZeroShares(uint24 id);
    error BinPool__InvalidBurnInput();
    error BinPool__BurnZeroAmount(uint24 id);
    error BinPool__ZeroAmountsOut(uint24 id);
    error BinPool__OutOfLiquidity();
    error BinPool__NoLiquidityToReceiveFees();
    /// @dev if swap exactIn, x for y, unspecifiedToken = token y. if swap x for exact out y, unspecified token is x
    error BinPool__InsufficientAmountUnSpecified();
    error BinPool__MaxLiquidityPerBinExceeded();

    /// @dev The state of a pool
    struct State {
        BinSlot0 slot0;
        /// @notice binId ==> (reserve of token x and y in the bin)
        mapping(uint256 binId => bytes32 reserve) reserveOfBin;
        /// @notice binId ==> (total share minted)
        mapping(uint256 binId => uint256 share) shareOfBin;
        /// @notice (user, binId, salt) => shares of user in a binId
        mapping(bytes32 positionHash => BinPosition.Info info) positions;
        /// @dev todo: cannot nest a struct with mapping, error: recursive type is not allowed for public state variables.
        /// TreeMath.TreeUint24 _tree;
        /// the 3 attributes below come from TreeMath
        bytes32 level0;
        mapping(bytes32 => bytes32) level1;
        mapping(bytes32 => bytes32) level2;
    }

    /// @dev when a bin has supply for the first time, 1e3 share will be locked up
    /// this is to prevent share inflation attack on BinPool type
    uint256 constant MINIMUM_SHARE = 1e3;

    function initialize(State storage self, uint24 activeId, uint24 protocolFee, uint24 lpFee) internal {
        /// An initialized pool will not have activeId: 0
        if (self.slot0.activeId() != 0) revert PoolAlreadyInitialized();

        self.slot0 = BinSlot0.wrap(bytes32(0)).setActiveId(activeId).setProtocolFee(protocolFee).setLpFee(lpFee);
    }

    function setProtocolFee(State storage self, uint24 protocolFee) internal {
        self.checkPoolInitialized();
        self.slot0 = self.slot0.setProtocolFee(protocolFee);
    }

    /// @notice Only dynamic fee pools may update the swap fee.
    function setLPFee(State storage self, uint24 lpFee) internal {
        self.checkPoolInitialized();

        self.slot0 = self.slot0.setLpFee(lpFee);
    }

    struct SwapParams {
        bool swapForY;
        uint16 binStep;
        uint24 lpFeeOverride;
        int128 amountSpecified; // negative for exactInput, positive for exactOutput
    }

    struct SwapState {
        // current activeId
        uint24 activeId;
        // the protocol fee for the swap (single direction)
        uint16 protocolFee;
        // the swapFee (the total percentage charged within a swap, including the protocol fee and the LP fee)
        uint24 swapFee;
        // how much protocol fee has been charged
        bytes32 feeAmountToProtocol;
    }

    function swap(State storage self, SwapParams memory params)
        internal
        returns (BalanceDelta result, SwapState memory swapState)
    {
        BinSlot0 slot0Cache = self.slot0;
        swapState.activeId = slot0Cache.activeId();
        bool swapForY = params.swapForY;
        swapState.protocolFee =
            swapForY ? slot0Cache.protocolFee().getZeroForOneFee() : slot0Cache.protocolFee().getOneForZeroFee();
        bool exactInput = params.amountSpecified < 0;

        {
            uint24 lpFee = params.lpFeeOverride.isOverride()
                ? params.lpFeeOverride.removeOverrideAndValidate(LPFeeLibrary.TEN_PERCENT_FEE)
                : slot0Cache.lpFee();

            /// @dev swap fee includes protocolFee (charged first) and lpFee
            swapState.swapFee = swapState.protocolFee == 0 ? lpFee : swapState.protocolFee.calculateSwapFee(lpFee);
        }

        /// @notice early return if hook has updated amountSpecified to 0
        if (params.amountSpecified == 0) return (result, swapState);

        uint128 amount;
        unchecked {
            amount = params.amountSpecified > 0 ? uint128(params.amountSpecified) : uint128(-params.amountSpecified);
        }

        /// @dev Amount of token left. In exactIn, refer to how much input left. In exactOut, refer to how much output left
        bytes32 amountsLeft = (swapForY == exactInput) ? amount.encodeFirst() : amount.encodeSecond();

        /// @dev Amount of token on the other side. In exactIn, refer to how much token out. In exactOut, refer to how much token in
        bytes32 amountsUnspecified;

        while (true) {
            bytes32 binReserves = self.reserveOfBin[swapState.activeId];
            if (!binReserves.isEmpty(!swapForY)) {
                bytes32 amountsInWithFees;
                bytes32 amountsOutOfBin;
                bytes32 totalFee;

                if (exactInput) {
                    (amountsInWithFees, amountsOutOfBin, totalFee) = binReserves.getAmountsOut(
                        swapState.swapFee, params.binStep, swapForY, swapState.activeId, amountsLeft
                    );

                    amountsLeft = amountsLeft.sub(amountsInWithFees);
                    amountsUnspecified = amountsUnspecified.add(amountsOutOfBin);
                } else {
                    (amountsInWithFees, amountsOutOfBin, totalFee) = binReserves.getAmountsIn(
                        swapState.swapFee, params.binStep, swapForY, swapState.activeId, amountsLeft
                    );

                    amountsLeft = amountsLeft.sub(amountsOutOfBin);
                    amountsUnspecified = amountsUnspecified.add(amountsInWithFees);
                }

                if (amountsInWithFees > 0) {
                    /// @dev calc protocol fee for current bin, totalFee * protocolFee / (protocolFee + lpFee)
                    bytes32 pFee = totalFee.getProtocolFeeAmt(slot0Cache.protocolFee(), swapState.swapFee);
                    if (pFee != 0) {
                        swapState.feeAmountToProtocol = swapState.feeAmountToProtocol.add(pFee);
                        amountsInWithFees = amountsInWithFees.sub(pFee);
                    }

                    self.reserveOfBin[swapState.activeId] = binReserves.add(amountsInWithFees).sub(amountsOutOfBin);

                    if (
                        self.reserveOfBin[swapState.activeId].getLiquidity(
                            swapState.activeId.getPriceFromId(params.binStep)
                        ) > Constants.MAX_LIQUIDITY_PER_BIN
                    ) {
                        revert BinPool__MaxLiquidityPerBinExceeded();
                    }
                }
            }

            if (amountsLeft == 0) {
                break;
            } else {
                uint24 nextId = getNextNonEmptyBin(self, swapForY, swapState.activeId);
                // Equivalent to: if (nextId == 0 || nextId == type(uint24).max) revert BinPool__OutOfLiquidity();
                assembly ("memory-safe") {
                    if or(iszero(nextId), eq(nextId, 0xffffff)) {
                        mstore(0x00, 0x96aa65ad) // Selector BinPool__OutOfLiquidity()
                        revert(0x1c, 0x04)
                    }
                }
                swapState.activeId = nextId;
            }
        }

        if (amountsUnspecified == 0) revert BinPool__InsufficientAmountUnSpecified();

        self.slot0 = self.slot0.setActiveId(swapState.activeId);
        unchecked {
            // uncheckeck as negating positive int128 is safe
            if (exactInput) {
                if (swapForY) {
                    result = toBalanceDelta(-amount.safeInt128(), amountsUnspecified.decodeY().safeInt128());
                } else {
                    result = toBalanceDelta(amountsUnspecified.decodeX().safeInt128(), -(amount.safeInt128()));
                }
            } else {
                if (swapForY) {
                    result = toBalanceDelta(-amountsUnspecified.decodeX().safeInt128(), amount.safeInt128());
                } else {
                    result = toBalanceDelta(amount.safeInt128(), -(amountsUnspecified.decodeY().safeInt128()));
                }
            }
        }
    }

    struct MintParams {
        address to; // nft minted to
        bytes32[] liquidityConfigs;
        bytes32 amountIn;
        uint16 binStep;
        uint24 lpFeeOverride;
        bytes32 salt;
    }

    struct MintArrays {
        uint256[] ids;
        bytes32[] amounts;
        uint256[] liquidityMinted;
    }

    /// @return result the delta of the token balance of the pool (inclusive of fees)
    /// @return feeAmountToProtocol total protocol fee amount
    /// @return arrays the ids, amounts and liquidity minted for each bin
    /// @return compositionFeeAmount composition fee for adding different ratio to active bin
    function mint(State storage self, MintParams memory params)
        internal
        returns (
            BalanceDelta result,
            bytes32 feeAmountToProtocol,
            MintArrays memory arrays,
            bytes32 compositionFeeAmount
        )
    {
        if (params.liquidityConfigs.length == 0) revert BinPool__EmptyLiquidityConfigs();

        arrays = MintArrays({
            ids: new uint256[](params.liquidityConfigs.length),
            amounts: new bytes32[](params.liquidityConfigs.length),
            liquidityMinted: new uint256[](params.liquidityConfigs.length)
        });

        (bytes32 amountsLeft, bytes32 feeAmt, bytes32 compoFeeAmt) = _mintBins(self, params, arrays);
        feeAmountToProtocol = feeAmt;
        compositionFeeAmount = compoFeeAmt;

        (uint128 x1, uint128 x2) = params.amountIn.sub(amountsLeft).decode();

        // set balanceDelta to negative (so user must settle()) from the vault
        result = toBalanceDelta(-(x1.safeInt128()), -(x2.safeInt128()));
    }

    /// @notice Returns the reserves of a bin
    /// @param binStep The binStep of the bin
    /// @param id The id of the bin
    /// @return binReserveX The reserve of token X in the bin
    /// @return binReserveY The reserve of token Y in the bin
    /// @return binLiquidity The liquidity in the bin
    /// @return binShare The shares in the bin
    function getBin(State storage self, uint16 binStep, uint24 id)
        internal
        view
        returns (uint128 binReserveX, uint128 binReserveY, uint256 binLiquidity, uint256 binShare)
    {
        bytes32 binReserves = self.reserveOfBin[id];

        (binReserveX, binReserveY) = binReserves.decode();
        binLiquidity = binReserves.getLiquidity(id.getPriceFromId(binStep));
        binShare = self.shareOfBin[id];
    }

    /// @dev Returns next non-empty bin
    /// @param swapForY Whether the swap is for Y
    /// @param id The id of the bin
    /// @return The id of the next non-empty bin
    function getNextNonEmptyBin(State storage self, bool swapForY, uint24 id) internal view returns (uint24) {
        return swapForY
            ? TreeMath.findFirstRight(self.level0, self.level1, self.level2, id)
            : TreeMath.findFirstLeft(self.level0, self.level1, self.level2, id);
    }

    struct BurnParams {
        address from;
        uint256[] ids;
        uint256[] amountsToBurn;
        bytes32 salt;
    }

    /// @notice Burn user's share and withdraw tokens form the pool.
    /// @return result the delta of the token balance of the pool
    function burn(State storage self, BurnParams memory params)
        internal
        returns (BalanceDelta result, uint256[] memory ids, bytes32[] memory amounts)
    {
        ids = params.ids;
        uint256 idsLength = ids.length;
        uint256[] memory amountsToBurn = params.amountsToBurn;

        if (idsLength == 0 || idsLength != amountsToBurn.length) revert BinPool__InvalidBurnInput();

        bytes32 amountsOut;
        amounts = new bytes32[](idsLength);
        for (uint256 i; i < idsLength;) {
            uint24 id = ids[i].safe24();
            uint256 amountToBurn = amountsToBurn[i];

            if (amountToBurn == 0) revert BinPool__BurnZeroAmount(id);

            bytes32 binReserves = self.reserveOfBin[id];
            uint256 supply = self.shareOfBin[id];

            _subShare(self, params.from, id, params.salt, amountToBurn);

            bytes32 amountsOutFromBin = binReserves.getAmountOutOfBin(amountToBurn, supply);

            if (amountsOutFromBin == 0) revert BinPool__ZeroAmountsOut(id);

            binReserves = binReserves.sub(amountsOutFromBin);

            /// @dev _removeBinIdToTree if supply is MINIMUM_SHARE after burning as min share is too low liquidity for trade anyway
            if (supply - amountToBurn == MINIMUM_SHARE) _removeBinIdToTree(self, id);

            self.reserveOfBin[id] = binReserves;
            amounts[i] = amountsOutFromBin;
            amountsOut = amountsOut.add(amountsOutFromBin);

            unchecked {
                ++i;
            }
        }

        result = toBalanceDelta(amountsOut.decodeX().safeInt128(), amountsOut.decodeY().safeInt128());
    }

    function donate(State storage self, uint16 binStep, uint128 amount0, uint128 amount1)
        internal
        returns (BalanceDelta result, uint24 activeId)
    {
        activeId = self.slot0.activeId();
        bytes32 amountIn = amount0.encode(amount1);

        bytes32 binReserves = self.reserveOfBin[activeId];
        if (binReserves == 0) revert BinPool__NoLiquidityToReceiveFees();

        /// @dev overflow check on total reserves and the resulting liquidity
        uint256 price = activeId.getPriceFromId(binStep);
        bytes32 newReserves = binReserves.add(amountIn);
        if (newReserves.getLiquidity(price) > Constants.MAX_LIQUIDITY_PER_BIN) {
            revert BinPool__MaxLiquidityPerBinExceeded();
        }

        self.reserveOfBin[activeId] = newReserves;
        result = toBalanceDelta(-(amount0.safeInt128()), -(amount1.safeInt128()));
    }

    /// @dev Helper function to mint liquidity in each bin in the liquidity configurations
    /// @param params MintParams (to, liquidityConfig, amountIn, binStep and fee)
    /// @param arrays MintArrays (ids[] , amounts[], liquidityMinted[])
    /// @return amountsLeft amountLeft after deducting all the input (inclusive of fee) from amountIn
    /// @return feeAmountToProtocol total protocol fee for minting
    /// @return compositionFeeAmount composition fee for adding different ratio to active bin
    function _mintBins(State storage self, MintParams memory params, MintArrays memory arrays)
        private
        returns (bytes32 amountsLeft, bytes32 feeAmountToProtocol, bytes32 compositionFeeAmount)
    {
        amountsLeft = params.amountIn;

        uint24 id;
        uint256 shares;
        bytes32 amountsIn;
        bytes32 amountsInToBin;
        bytes32 binFeeAmt;
        bytes32 binCompositionFee;
        uint256 liquidityConfigsLength = params.liquidityConfigs.length;
        for (uint256 i; i < liquidityConfigsLength;) {
            // fix stack too deep
            {
                bytes32 maxAmountsInToBin;
                (maxAmountsInToBin, id) = params.liquidityConfigs[i].getAmountsAndId(params.amountIn);

                (shares, amountsIn, amountsInToBin, binFeeAmt, binCompositionFee) =
                    _updateBin(self, params, id, maxAmountsInToBin);
            }

            amountsLeft = amountsLeft.sub(amountsIn);
            feeAmountToProtocol = feeAmountToProtocol.add(binFeeAmt);

            shares = _addShare(self, params.to, id, params.salt, shares);

            arrays.ids[i] = id;
            arrays.amounts[i] = amountsInToBin;
            arrays.liquidityMinted[i] = shares;

            compositionFeeAmount = compositionFeeAmount.add(binCompositionFee);

            unchecked {
                ++i;
            }
        }
    }

    /// @dev Helper function to update a bin during minting
    /// @param id The id of the bin
    /// @param maxAmountsInToBin The maximum amounts in to the bin
    /// @return shares The amount of shares minted
    /// @return amountsIn The amounts in
    /// @return amountsInToBin The amounts in to the bin
    /// @return feeAmountToProtocol The amounts of fee for protocol
    /// @return compositionFeeAmount The total amount of composition fee
    function _updateBin(State storage self, MintParams memory params, uint24 id, bytes32 maxAmountsInToBin)
        internal
        returns (
            uint256 shares,
            bytes32 amountsIn,
            bytes32 amountsInToBin,
            bytes32 feeAmountToProtocol,
            bytes32 compositionFeeAmount
        )
    {
        BinSlot0 slot0Cache = self.slot0;
        uint24 activeId = slot0Cache.activeId();
        bytes32 binReserves = self.reserveOfBin[id];

        uint256 price = id.getPriceFromId(params.binStep);
        uint256 supply = self.shareOfBin[id];

        (shares, amountsIn) = binReserves.getSharesAndEffectiveAmountsIn(maxAmountsInToBin, price, supply);
        amountsInToBin = amountsIn;

        if (id == activeId) {
            // Fees happens when user try to add liquidity in active bin but with different ratio of (x, y)
            /// eg. current bin is 40/60 (a,b) but user tries to add liquidity with 50/50 ratio
            uint24 lpFee = params.lpFeeOverride.isOverride()
                ? params.lpFeeOverride.removeOverrideAndValidate(LPFeeLibrary.TEN_PERCENT_FEE)
                : slot0Cache.lpFee();

            bytes32 feesAmount;
            (feesAmount, feeAmountToProtocol) =
                binReserves.getCompositionFeesAmount(slot0Cache.protocolFee(), lpFee, amountsIn, supply, shares);
            compositionFeeAmount = feesAmount;
            if (feesAmount != 0) {
                {
                    uint256 userLiquidity = amountsIn.sub(feesAmount).getLiquidity(price);
                    /// @dev Ensure fee accrued only to existing lp, before calculating new share for minter
                    uint256 binLiquidity = binReserves.add(feesAmount.sub(feeAmountToProtocol)).getLiquidity(price);
                    shares = userLiquidity.mulDivRoundDown(supply, binLiquidity);
                }

                if (feeAmountToProtocol != 0) {
                    amountsInToBin = amountsInToBin.sub(feeAmountToProtocol);
                }
            }
        } else {
            amountsIn.verifyAmounts(activeId, id);
        }

        if (shares == 0 || amountsInToBin == 0) revert BinPool__ZeroShares(id);
        /// @dev if supply was originally MINIMUM_SHARE (people added and remove liquidity before) or 0 (new bin), add binId to tree
        if (supply <= MINIMUM_SHARE) _addBinIdToTree(self, id);

        bytes32 newReserves = binReserves.add(amountsInToBin);
        if (newReserves.getLiquidity(price) > Constants.MAX_LIQUIDITY_PER_BIN) {
            revert BinPool__MaxLiquidityPerBinExceeded();
        }

        self.reserveOfBin[id] = newReserves;
    }

    /// @notice Subtract share from user's position and update total share supply of bin
    function _subShare(State storage self, address owner, uint24 binId, bytes32 salt, uint256 shares) internal {
        self.positions.get(owner, binId, salt).subShare(shares);
        self.shareOfBin[binId] -= shares;
    }

    /// @notice Add share to user's position and update total share supply of bin
    /// @dev if bin is empty, deduct MINIMUM_SHARE from shares
    /// @return userShareAdded The amount of share added to user's position
    function _addShare(State storage self, address owner, uint24 binId, bytes32 salt, uint256 shares)
        internal
        returns (uint256 userShareAdded)
    {
        userShareAdded = shares;
        if (self.shareOfBin[binId] == 0) {
            /// @dev Only for first liquidity provider for the bin, deduct MINIMUM_SHARE, expected to underflow
            /// if shares < MINIMUM_SHARE for first mint
            userShareAdded = shares - MINIMUM_SHARE;
        }

        self.positions.get(owner, binId, salt).addShare(userShareAdded);
        self.shareOfBin[binId] += shares;
    }

    /// @notice Enable bin id for a pool
    function _addBinIdToTree(State storage self, uint24 binId) internal {
        (, self.level0) = TreeMath.add(self.level0, self.level1, self.level2, binId);
    }

    /// @notice remove bin id for a pool
    function _removeBinIdToTree(State storage self, uint24 binId) internal {
        (, self.level0) = TreeMath.remove(self.level0, self.level1, self.level2, binId);
    }

    function checkPoolInitialized(State storage self) internal view {
        if (self.slot0.activeId() == 0) {
            // revert PoolNotInitialized();
            assembly ("memory-safe") {
                mstore(0x00, 0x486aa307)
                revert(0x1c, 0x04)
            }
        }
    }
}

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

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

/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
    /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
    /// @param maxAmount The maximum amount a spender can request to transfer
    error InvalidAmount(uint256 maxAmount);

    /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
    /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
    error LengthMismatch();

    /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
    event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);

    /// @notice The token and amount details for a transfer signed in the permit transfer signature
    struct TokenPermissions {
        // ERC20 token address
        address token;
        // the maximum amount that can be spent
        uint256 amount;
    }

    /// @notice The signed permit message for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice Specifies the recipient address and amount for batched transfers.
    /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
    /// @dev Reverts if the requested amount is greater than the permitted signed amount.
    struct SignatureTransferDetails {
        // recipient address
        address to;
        // spender requested amount
        uint256 requestedAmount;
    }

    /// @notice Used to reconstruct the signed permit message for multiple token transfers
    /// @dev Do not need to pass in spender address as it is required that it is msg.sender
    /// @dev Note that a user still signs over a spender address
    struct PermitBatchTransferFrom {
        // the tokens and corresponding amounts permitted for a transfer
        TokenPermissions[] permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
    /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
    /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
    /// @dev It returns a uint256 bitmap
    /// @dev The index, or wordPosition is capped at type(uint248).max
    function nonceBitmap(address, uint256) external view returns (uint256);

    /// @notice Transfers a token using a signed permit message
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers a token using a signed permit message
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Invalidates the bits specified in mask for the bitmap at the word position
    /// @dev The wordPos is maxed at type(uint248).max
    /// @param wordPos A number to index the nonceBitmap at
    /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}

File 61 of 120 : IImmutableState.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {IVault} from "infinity-core/src/interfaces/IVault.sol";

/// @title IImmutableState
/// @notice Interface for the ImmutableState contract
interface IImmutableState {
    /// @notice The Pancakeswap Infinity Vault contract
    function vault() external view returns (IVault);
}

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

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

library SafeCast160 {
    /// @notice Thrown when a valude greater than type(uint160).max is cast to uint160
    error UnsafeCast();

    /// @notice Safely casts uint256 to uint160
    /// @param value The uint256 to be cast
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) revert UnsafeCast();
        return uint160(value);
    }
}

File 64 of 120 : IInfinityRouter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {Currency} from "infinity-core/src/types/Currency.sol";
import {PathKey} from "../libraries/PathKey.sol";
import {ICLRouterBase} from "../pool-cl/interfaces/ICLRouterBase.sol";
import {IBinRouterBase} from "../pool-bin/interfaces/IBinRouterBase.sol";

/// @title IInfinityRouter
/// @notice Interface containing all the structs and errors for different infinity swap types
interface IInfinityRouter is ICLRouterBase, IBinRouterBase {
    /// @notice Emitted when an exactInput swap does not receive its minAmountOut
    error TooLittleReceived(uint256 minAmountOutReceived, uint256 amountReceived);
    /// @notice Emitted when an exactOutput is asked for more than its maxAmountIn
    error TooMuchRequested(uint256 maxAmountInRequested, uint256 amountRequested);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {Currency} from "infinity-core/src/types/Currency.sol";
import {ImmutableState} from "./ImmutableState.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";

/// @notice Abstract contract used to sync, send, and settle funds to the vault
/// @dev Note that sync() is called before any erc-20 transfer in `settle`.
abstract contract DeltaResolver is ImmutableState {
    /// @notice Emitted trying to settle a positive delta.
    error DeltaNotPositive(Currency currency);
    /// @notice Emitted trying to take a negative delta.
    error DeltaNotNegative(Currency currency);
    /// @notice Emitted when the contract does not have enough balance to wrap or unwrap.
    error InsufficientBalance();

    /// @notice Take an amount of currency out of the vault
    /// @param currency Currency to take
    /// @param recipient Address to receive the currency
    /// @param amount Amount to take
    /// @dev Returns early if the amount is 0
    function _take(Currency currency, address recipient, uint256 amount) internal {
        if (amount == 0) return;
        vault.take(currency, recipient, amount);
    }

    /// @notice Pay and settle a currency to the vault
    /// @dev The implementing contract must ensure that the `payer` is a secure address
    /// @param currency Currency to settle
    /// @param payer Address of the payer
    /// @param amount Amount to send
    /// @dev Returns early if the amount is 0
    function _settle(Currency currency, address payer, uint256 amount) internal {
        if (amount == 0) return;

        vault.sync(currency);
        if (currency.isNative()) {
            vault.settle{value: amount}();
        } else {
            _pay(currency, payer, amount);
            vault.settle();
        }
    }

    /// @notice Abstract function for contracts to implement paying tokens to the vault
    /// @dev The recipient of the payment should be the vault
    /// @param token The token to settle. This is known not to be the native currency
    /// @param payer The address who should pay tokens
    /// @param amount The number of tokens to send
    function _pay(Currency token, address payer, uint256 amount) internal virtual;

    /// @notice Obtain the full amount owed by this contract (negative delta)
    /// @param currency Currency to get the delta for
    /// @return amount The amount owed by this contract as a uint256
    function _getFullDebt(Currency currency) internal view returns (uint256 amount) {
        int256 _amount = vault.currencyDelta(address(this), currency);
        // If the amount is positive, it should be taken not settled.
        if (_amount > 0) revert DeltaNotNegative(currency);
        // Casting is safe due to limits on the total supply of a pool
        amount = uint256(-_amount);
    }

    /// @notice Obtain the full credit owed to this contract (positive delta)
    /// @param currency Currency to get the delta for
    /// @return amount The amount owed to this contract as a uint256
    function _getFullCredit(Currency currency) internal view returns (uint256 amount) {
        int256 _amount = vault.currencyDelta(address(this), currency);
        // If the amount is negative, it should be settled not taken.
        if (_amount < 0) revert DeltaNotPositive(currency);
        amount = uint256(_amount);
    }

    /// @notice Calculates the amount for a settle action
    function _mapSettleAmount(uint256 amount, Currency currency) internal view returns (uint256) {
        if (amount == ActionConstants.CONTRACT_BALANCE) {
            return currency.balanceOfSelf();
        } else if (amount == ActionConstants.OPEN_DELTA) {
            return _getFullDebt(currency);
        } else {
            return amount;
        }
    }

    /// @notice Calculates the amount for a take action
    function _mapTakeAmount(uint256 amount, Currency currency) internal view returns (uint256) {
        if (amount == ActionConstants.OPEN_DELTA) {
            return _getFullCredit(currency);
        } else {
            return amount;
        }
    }

    /// @notice Calculates the sanitized amount before wrapping/unwrapping.
    /// @param inputCurrency The currency, either native or wrapped native, that this contract holds
    /// @param amount The amount to wrap or unwrap. Can be CONTRACT_BALANCE, OPEN_DELTA or a specific amount
    /// @param outputCurrency The currency after the wrap/unwrap that the user may owe a balance in on the poolManager
    function _mapWrapUnwrapAmount(Currency inputCurrency, uint256 amount, Currency outputCurrency)
        internal
        view
        returns (uint256)
    {
        // if wrapping, the balance in this contract is in ETH
        // if unwrapping, the balance in this contract is in WETH
        uint256 balance = inputCurrency.balanceOf(address(this));
        if (amount == ActionConstants.CONTRACT_BALANCE) {
            // return early to avoid unnecessary balance check
            return balance;
        }
        if (amount == ActionConstants.OPEN_DELTA) {
            // if wrapping, the open currency on the PoolManager is WETH.
            // if unwrapping, the open currency on the PoolManager is ETH.
            // note that we use the DEBT amount. Positive deltas can be taken and then wrapped.
            amount = _getFullDebt(outputCurrency);
        }
        if (amount > balance) revert InsufficientBalance();
        return amount;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {IInfinityRouter} from "../../interfaces/IInfinityRouter.sol";
import {CalldataDecoder} from "../../libraries/CalldataDecoder.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";

/// @title Library for abi decoding in cl pool calldata
library CLCalldataDecoder {
    using CalldataDecoder for bytes;

    /// @notice equivalent to SliceOutOfBounds.selector, stored in least-significant bits
    uint256 constant SLICE_ERROR_SELECTOR = 0x3b99b53d;

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.CLExactInputParams))
    function decodeCLSwapExactInParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.CLSwapExactInputParams calldata swapParams)
    {
        // CLExactInputParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where path is empty
            // 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
            if lt(params.length, 0xa0) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.CLExactInputSingleParams))
    function decodeCLSwapExactInSingleParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.CLSwapExactInputSingleParams calldata swapParams)
    {
        // CLExactInputSingleParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where hookData is empty
            // 0x160 = 11 * 0x20 -> 9 elements, bytes offset, and bytes length 0
            if lt(params.length, 0x160) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.CLExactOutputParams))
    function decodeCLSwapExactOutParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.CLSwapExactOutputParams calldata swapParams)
    {
        // CLExactOutputParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where path is empty
            // 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
            if lt(params.length, 0xa0) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.CLExactOutputSingleParams))
    function decodeCLSwapExactOutSingleParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.CLSwapExactOutputSingleParams calldata swapParams)
    {
        // CLExactOutputSingleParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where hookData is empty
            // 0x160 = 9 * 0x20 -> 9 elements, bytes offset, and bytes length 0
            if lt(params.length, 0x160) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (uint256, uint256, uint128, uint128, bytes)) in calldata
    function decodeCLModifyLiquidityParams(bytes calldata params)
        internal
        pure
        returns (uint256 tokenId, uint256 liquidity, uint128 amount0, uint128 amount1, bytes calldata hookData)
    {
        // length validation is already handled in `params.toBytes`
        assembly ("memory-safe") {
            tokenId := calldataload(params.offset)
            liquidity := calldataload(add(params.offset, 0x20))
            amount0 := calldataload(add(params.offset, 0x40))
            amount1 := calldataload(add(params.offset, 0x60))
        }

        hookData = params.toBytes(4);
    }

    /// @dev equivalent to: abi.decode(params, (uint256, uint128, uint128, bytes)) in calldata
    function decodeCLIncreaseLiquidityFromDeltasParams(bytes calldata params)
        internal
        pure
        returns (uint256 tokenId, uint128 amount0Max, uint128 amount1Max, bytes calldata hookData)
    {
        // length validation is already handled in `params.toBytes`
        assembly ("memory-safe") {
            tokenId := calldataload(params.offset)
            amount0Max := calldataload(add(params.offset, 0x20))
            amount1Max := calldataload(add(params.offset, 0x40))
        }

        hookData = params.toBytes(3);
    }

    /// @dev equivalent to: abi.decode(params, (PoolKey, int24, int24, uint256, uint128, uint128, address, bytes)) in calldata
    function decodeCLMintParams(bytes calldata params)
        internal
        pure
        returns (
            PoolKey calldata poolKey,
            int24 tickLower,
            int24 tickUpper,
            uint256 liquidity,
            uint128 amount0Max,
            uint128 amount1Max,
            address owner,
            bytes calldata hookData
        )
    {
        // length validation is already handled in `params.toBytes`
        assembly ("memory-safe") {
            poolKey := params.offset
            tickLower := calldataload(add(params.offset, 0xc0))
            tickUpper := calldataload(add(params.offset, 0xe0))
            liquidity := calldataload(add(params.offset, 0x100))
            amount0Max := calldataload(add(params.offset, 0x120))
            amount1Max := calldataload(add(params.offset, 0x140))
            owner := calldataload(add(params.offset, 0x160))
        }
        hookData = params.toBytes(12);
    }

    /// @dev equivalent to: abi.decode(params, (PoolKey, int24, int24, uint128, uint128, address, bytes)) in calldata
    function decodeCLMintFromDeltasParams(bytes calldata params)
        internal
        pure
        returns (
            PoolKey calldata poolKey,
            int24 tickLower,
            int24 tickUpper,
            uint128 amount0Max,
            uint128 amount1Max,
            address owner,
            bytes calldata hookData
        )
    {
        // length validation is already handled in `params.toBytes`
        assembly ("memory-safe") {
            poolKey := params.offset
            tickLower := calldataload(add(params.offset, 0xc0))
            tickUpper := calldataload(add(params.offset, 0xe0))
            amount0Max := calldataload(add(params.offset, 0x100))
            amount1Max := calldataload(add(params.offset, 0x120))
            owner := calldataload(add(params.offset, 0x140))
        }

        hookData = params.toBytes(11);
    }

    /// @dev equivalent to: abi.decode(params, (uint256, uint128, uint128, bytes)) in calldata
    function decodeCLBurnParams(bytes calldata params)
        internal
        pure
        returns (uint256 tokenId, uint128 amount0Min, uint128 amount1Min, bytes calldata hookData)
    {
        // length validation is already handled in `params.toBytes`
        assembly ("memory-safe") {
            tokenId := calldataload(params.offset)
            amount0Min := calldataload(add(params.offset, 0x20))
            amount1Min := calldataload(add(params.offset, 0x40))
        }
        hookData = params.toBytes(3);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {IBinPositionManager} from "../interfaces/IBinPositionManager.sol";
import {IInfinityRouter} from "../../interfaces/IInfinityRouter.sol";

/// @title Library for abi decoding in bin pool calldata
library BinCalldataDecoder {
    /// @notice equivalent to SliceOutOfBounds.selector, stored in least-significant bits
    uint256 constant SLICE_ERROR_SELECTOR = 0x3b99b53d;

    /// todo: <wip> see if tweaking to calldataload saves gas
    /// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinAddLiquidityParams))
    function decodeBinAddLiquidityParams(bytes calldata params)
        internal
        pure
        returns (IBinPositionManager.BinAddLiquidityParams calldata addLiquidityParams)
    {
        assembly ("memory-safe") {
            addLiquidityParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// todo: <wip> see if tweaking to calldataload saves gas
    /// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinRemoveLiquidityParams))
    function decodeBinRemoveLiquidityParams(bytes calldata params)
        internal
        pure
        returns (IBinPositionManager.BinRemoveLiquidityParams calldata removeLiquidityParams)
    {
        assembly ("memory-safe") {
            removeLiquidityParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IBinPositionManager.BinAddLiquidityFromDeltasParams))
    function decodeBinAddLiquidityFromDeltasParams(bytes calldata params)
        internal
        pure
        returns (IBinPositionManager.BinAddLiquidityFromDeltasParams calldata addLiquidityParams)
    {
        assembly ("memory-safe") {
            addLiquidityParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.BinExactInputParams))
    function decodeBinSwapExactInParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.BinSwapExactInputParams calldata swapParams)
    {
        // BinExactInputParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where path is empty
            // 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
            if lt(params.length, 0xa0) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.BinExactInputSingleParams))
    function decodeBinSwapExactInSingleParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.BinSwapExactInputSingleParams calldata swapParams)
    {
        // BinExactInputSingleParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where hookData is empty
            // 0x160 = 11 * 0x20 -> 9 elements, bytes offset, and bytes length 0
            if lt(params.length, 0x160) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.BinExactOutputParams))
    function decodeBinSwapExactOutParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.BinSwapExactOutputParams calldata swapParams)
    {
        // BinExactOutputParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where path is empty
            // 0xa0 = 5 * 0x20 -> 3 elements, path offset, and path length 0
            if lt(params.length, 0xa0) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }

    /// @dev equivalent to: abi.decode(params, (IInfinityRouter.BinExactOutputSingleParams))
    function decodeBinSwapExactOutSingleParams(bytes calldata params)
        internal
        pure
        returns (IInfinityRouter.BinSwapExactOutputSingleParams calldata swapParams)
    {
        // BinExactOutputSingleParams is a variable length struct so we just have to look up its location
        assembly ("memory-safe") {
            // only safety checks for the minimum length, where hookData is empty
            // 0x160 = 9 * 0x20 -> 9 elements, bytes offset, and bytes length 0
            if lt(params.length, 0x160) {
                mstore(0, SLICE_ERROR_SELECTOR)
                revert(0x1c, 4)
            }
            swapParams := add(params.offset, calldataload(params.offset))
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {CurrencyLibrary, Currency} from "infinity-core/src/types/Currency.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {BalanceDelta} from "infinity-core/src/types/BalanceDelta.sol";
import {ICLPoolManager} from "infinity-core/src/pool-cl/interfaces/ICLPoolManager.sol";
import {TickMath} from "infinity-core/src/pool-cl/libraries/TickMath.sol";
import {ICLRouterBase} from "./interfaces/ICLRouterBase.sol";
import {IInfinityRouter} from "../interfaces/IInfinityRouter.sol";
import {PathKeyLibrary, PathKey} from "../libraries/PathKey.sol";
import {SafeCastTemp} from "../libraries/SafeCast.sol";
import {DeltaResolver} from "../base/DeltaResolver.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";

abstract contract CLRouterBase is ICLRouterBase, DeltaResolver {
    using SafeCastTemp for *;

    ICLPoolManager public immutable clPoolManager;

    constructor(ICLPoolManager _clPoolManager) {
        clPoolManager = _clPoolManager;
    }

    function _swapExactInputSingle(CLSwapExactInputSingleParams calldata params) internal {
        uint128 amountIn = params.amountIn;
        if (amountIn == ActionConstants.OPEN_DELTA) {
            amountIn =
                _getFullCredit(params.zeroForOne ? params.poolKey.currency0 : params.poolKey.currency1).toUint128();
        }
        uint128 amountOut = _swapExactPrivate(
            params.poolKey, params.zeroForOne, -int256(uint256(amountIn)), params.hookData
        ).toUint128();
        if (amountOut < params.amountOutMinimum) {
            revert IInfinityRouter.TooLittleReceived(params.amountOutMinimum, amountOut);
        }
    }

    function _swapExactInput(CLSwapExactInputParams calldata params) internal {
        unchecked {
            // Caching for gas savings
            uint256 pathLength = params.path.length;
            uint128 amountOut;
            Currency currencyIn = params.currencyIn;
            uint128 amountIn = params.amountIn;
            if (amountIn == ActionConstants.OPEN_DELTA) amountIn = _getFullCredit(currencyIn).toUint128();
            PathKey calldata pathKey;

            for (uint256 i = 0; i < pathLength; i++) {
                pathKey = params.path[i];
                (PoolKey memory poolKey, bool zeroForOne) = pathKey.getPoolAndSwapDirection(currencyIn);
                // The output delta will always be positive, except for when interacting with certain hook pools
                amountOut =
                    _swapExactPrivate(poolKey, zeroForOne, -int256(uint256(amountIn)), pathKey.hookData).toUint128();

                amountIn = amountOut;
                currencyIn = pathKey.intermediateCurrency;
            }

            if (amountOut < params.amountOutMinimum) {
                revert IInfinityRouter.TooLittleReceived(params.amountOutMinimum, amountOut);
            }
        }
    }

    function _swapExactOutputSingle(CLSwapExactOutputSingleParams calldata params) internal {
        uint128 amountOut = params.amountOut;
        if (amountOut == ActionConstants.OPEN_DELTA) {
            amountOut =
                _getFullDebt(params.zeroForOne ? params.poolKey.currency1 : params.poolKey.currency0).toUint128();
        }
        uint128 amountIn = (
            -_swapExactPrivate(params.poolKey, params.zeroForOne, int256(uint256(amountOut)), params.hookData)
        ).toUint128();
        if (amountIn > params.amountInMaximum) {
            revert IInfinityRouter.TooMuchRequested(params.amountInMaximum, amountIn);
        }
    }

    function _swapExactOutput(CLSwapExactOutputParams calldata params) internal {
        unchecked {
            // Caching for gas savings
            uint256 pathLength = params.path.length;
            uint128 amountIn;
            uint128 amountOut = params.amountOut;
            Currency currencyOut = params.currencyOut;
            PathKey calldata pathKey;

            if (amountOut == ActionConstants.OPEN_DELTA) {
                amountOut = _getFullDebt(currencyOut).toUint128();
            }

            for (uint256 i = pathLength; i > 0; i--) {
                pathKey = params.path[i - 1];
                (PoolKey memory poolKey, bool oneForZero) = pathKey.getPoolAndSwapDirection(currencyOut);
                // The output delta will always be negative, except for when interacting with certain hook pools
                amountIn = (
                    uint256(
                        -int256(_swapExactPrivate(poolKey, !oneForZero, int256(uint256(amountOut)), pathKey.hookData))
                    )
                ).toUint128();

                amountOut = amountIn;
                currencyOut = pathKey.intermediateCurrency;
            }
            if (amountIn > params.amountInMaximum) {
                revert IInfinityRouter.TooMuchRequested(params.amountInMaximum, amountIn);
            }
        }
    }

    /// @return reciprocalAmount The amount of the reciprocal token
    //      If exactInput token0 for token1, the reciprocalAmount is the amount of token1.
    //      If exactOutput token0 for token1, the reciprocalAmount is the amount of token0.
    function _swapExactPrivate(PoolKey memory poolKey, bool zeroForOne, int256 amountSpecified, bytes calldata hookData)
        private
        returns (int128 reciprocalAmount)
    {
        BalanceDelta delta = clPoolManager.swap(
            poolKey,
            ICLPoolManager.SwapParams(
                zeroForOne, amountSpecified, zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1
            ),
            hookData
        );

        reciprocalAmount = (zeroForOne == amountSpecified < 0) ? delta.amount1() : delta.amount0();
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.24;

import {CurrencyLibrary, Currency} from "infinity-core/src/types/Currency.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {BalanceDelta} from "infinity-core/src/types/BalanceDelta.sol";
import {IBinPoolManager} from "infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {IBinRouterBase} from "./interfaces/IBinRouterBase.sol";
import {IInfinityRouter} from "../interfaces/IInfinityRouter.sol";
import {PathKeyLibrary, PathKey} from "../libraries/PathKey.sol";
import {SafeCastTemp} from "../libraries/SafeCast.sol";
import {SafeCast} from "infinity-core/src/pool-bin/libraries/math/SafeCast.sol";
import {DeltaResolver} from "../base/DeltaResolver.sol";
import {ActionConstants} from "../libraries/ActionConstants.sol";

abstract contract BinRouterBase is IBinRouterBase, DeltaResolver {
    using SafeCastTemp for *;
    using SafeCast for *;

    IBinPoolManager public immutable binPoolManager;

    constructor(IBinPoolManager _binPoolManager) {
        binPoolManager = _binPoolManager;
    }

    /// @notice Perform a swap with `amountIn` in and ensure at least `amountOutMinimum` out
    function _swapExactInputSingle(BinSwapExactInputSingleParams calldata params) internal {
        uint128 amountIn = params.amountIn;
        if (amountIn == ActionConstants.OPEN_DELTA) {
            amountIn = _getFullCredit(params.swapForY ? params.poolKey.currency0 : params.poolKey.currency1).safe128();
        }
        uint128 amountOut =
            _swapExactPrivate(params.poolKey, params.swapForY, -(amountIn.safeInt128()), params.hookData).toUint128();

        if (amountOut < params.amountOutMinimum) {
            revert IInfinityRouter.TooLittleReceived(params.amountOutMinimum, amountOut);
        }
    }

    /// @notice Perform a swap with `amountIn` in and ensure at least `amountOutMinimum` out
    function _swapExactInput(BinSwapExactInputParams calldata params) internal {
        unchecked {
            // Caching for gas savings
            uint256 pathLength = params.path.length;
            uint128 amountOut;
            Currency currencyIn = params.currencyIn;
            uint128 amountIn = params.amountIn;
            if (amountIn == ActionConstants.OPEN_DELTA) amountIn = _getFullCredit(currencyIn).safe128();
            PathKey calldata pathKey;

            for (uint256 i = 0; i < pathLength; i++) {
                pathKey = params.path[i];
                (PoolKey memory poolKey, bool swapForY) = pathKey.getPoolAndSwapDirection(currencyIn);

                amountOut = _swapExactPrivate(poolKey, swapForY, -(amountIn.safeInt128()), pathKey.hookData).toUint128();

                amountIn = amountOut;
                currencyIn = pathKey.intermediateCurrency;
            }

            if (amountOut < params.amountOutMinimum) {
                revert IInfinityRouter.TooLittleReceived(params.amountOutMinimum, amountOut);
            }
        }
    }

    /// @notice Perform a swap that ensure at least `amountOut` tokens with `amountInMaximum` tokens
    function _swapExactOutputSingle(BinSwapExactOutputSingleParams calldata params) internal {
        uint128 amountOut = params.amountOut;
        if (amountOut == ActionConstants.OPEN_DELTA) {
            amountOut = _getFullDebt(params.swapForY ? params.poolKey.currency1 : params.poolKey.currency0).toUint128();
        }
        uint128 amountIn =
            (-_swapExactPrivate(params.poolKey, params.swapForY, amountOut.safeInt128(), params.hookData)).toUint128();

        if (amountIn > params.amountInMaximum) {
            revert IInfinityRouter.TooMuchRequested(params.amountInMaximum, amountIn);
        }
    }

    /// @notice Perform a swap that ensure at least `amountOut` tokens with `amountInMaximum` tokens
    function _swapExactOutput(BinSwapExactOutputParams calldata params) internal {
        unchecked {
            // Caching for gas savings
            uint256 pathLength = params.path.length;
            uint128 amountIn;
            uint128 amountOut = params.amountOut;
            Currency currencyOut = params.currencyOut;
            PathKey calldata pathKey;

            if (amountOut == ActionConstants.OPEN_DELTA) {
                amountOut = _getFullDebt(currencyOut).toUint128();
            }

            /// @dev Iterate backward from last path to first path
            for (uint256 i = pathLength; i > 0; i--) {
                pathKey = params.path[i - 1];
                // find out poolKey and how much amountIn required to get amountOut
                (PoolKey memory poolKey, bool swapForY) = pathKey.getPoolAndSwapDirection(currencyOut);

                amountIn =
                    (-_swapExactPrivate(poolKey, !swapForY, amountOut.safeInt128(), pathKey.hookData)).toUint128();

                amountOut = amountIn;
                currencyOut = pathKey.intermediateCurrency;
            }

            if (amountIn > params.amountInMaximum) {
                revert IInfinityRouter.TooMuchRequested(params.amountInMaximum, amountIn);
            }
        }
    }

    /// @return reciprocalAmount The amount of the reciprocal token
    //      If exactInput token0 for token1, the reciprocalAmount is the amount of token1.
    //      If exactOutput token0 for token1, the reciprocalAmount is the amount of token0.
    function _swapExactPrivate(PoolKey memory poolKey, bool swapForY, int128 amountSpecified, bytes calldata hookData)
        private
        returns (int128 reciprocalAmount)
    {
        BalanceDelta delta = binPoolManager.swap(poolKey, swapForY, amountSpecified, hookData);
        reciprocalAmount = (swapForY == amountSpecified < 0) ? delta.amount1() : delta.amount0();
    }
}

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

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

interface IVaultToken {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

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

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

    /// @notice get the amount of owner's surplus token in vault
    /// @param owner The address you want to query the balance of
    /// @param currency The currency you want to query the balance of
    /// @return balance The balance of the specified address
    function balanceOf(address owner, Currency currency) external view returns (uint256 balance);

    /// @notice get the amount that owner has authorized for spender to use
    /// @param owner The address of the owner
    /// @param spender The address who is allowed to spend the owner's token
    /// @param currency The currency the spender is allowed to spend
    /// @return amount The amount of token the spender is allowed to spend
    function allowance(address owner, address spender, Currency currency) external view returns (uint256 amount);

    /// @notice approve spender for using user's token
    /// @param spender The address msg.sender is approving to spend the his token
    /// @param currency The currency the spender is allowed to spend
    /// @param amount The amount of token the spender is allowed to spend
    /// @return bool Whether the approval was successful or not
    function approve(address spender, Currency currency, uint256 amount) external returns (bool);

    /// @notice transfer msg.sender's token to someone else
    /// @param to The address to transfer the token to
    /// @param currency The currency to transfer
    /// @param amount The amount of token to transfer
    /// @return bool Whether the transfer was successful or not
    function transfer(address to, Currency currency, uint256 amount) external returns (bool);

    /// @notice transfer from address's token on behalf of him
    /// @param from The address to transfer the token from
    /// @param to The address to transfer the token to
    /// @param currency The currency to transfer
    /// @param amount The amount of token to transfer
    /// @return bool Whether the transfer was successful or not
    function transferFrom(address from, address to, Currency currency, uint256 amount) external returns (bool);
}

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

/// @title Minimal ERC20 interface for PancakeSwap
/// @notice Contains a subset of the full ERC20 interface that is used in PancakeSwap V3
interface IERC20Minimal {
    /// @notice Returns the balance of a 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 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);

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

            let fmp := mload(0x40)

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

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

interface IStableSwapFactory {
    struct StableSwapPairInfo {
        address swapContract;
        address token0;
        address token1;
        address LPContract;
    }

    struct StableSwapThreePoolPairInfo {
        address swapContract;
        address token0;
        address token1;
        address token2;
        address LPContract;
    }

    // solium-disable-next-line mixedcase
    function pairLength() external view returns (uint256);

    function getPairInfo(address _tokenA, address _tokenB) external view returns (StableSwapPairInfo memory info);

    function getThreePoolPairInfo(address _tokenA, address _tokenB)
        external
        view
        returns (StableSwapThreePoolPairInfo memory info);
}

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

interface IStableSwapInfo {
    function get_dx(address _swap, uint256 i, uint256 j, uint256 dy, uint256 max_dx) external view returns (uint256);
}

// 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 Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IPancakeV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IPancakeV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

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

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IPancakeV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint32 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

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

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IPancakeV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside);
}

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

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IPancakeV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IPancakeV3MintCallback#pancakeV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data)
        external
        returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(int24 tickLower, int24 tickUpper, uint128 amount)
        external
        returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IPancakeV3SwapCallback#pancakeV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IPancakeV3FlashCallback#pancakeV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

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

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IPancakeV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint32 feeProtocol0, uint32 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(address recipient, uint128 amount0Requested, uint128 amount1Requested)
        external
        returns (uint128 amount0, uint128 amount1);

    /// @notice Set the LM pool to enable liquidity mining
    function setLmPool(address lmPool) external;
}

File 81 of 120 : IPancakeV3PoolEvents.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IPancakeV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 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 price of the pool after the swap
    /// @param protocolFeesToken0 The protocol fee of token0 in the swap
    /// @param protocolFeesToken1 The protocol fee of token1 in the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint128 protocolFeesToken0,
        uint128 protocolFeesToken1
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(
        uint32 feeProtocol0Old, uint32 feeProtocol1Old, uint32 feeProtocol0New, uint32 feeProtocol1New
    );

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

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

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

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

/// @notice Interface for the callback executed when an address locks the vault
interface ILockCallback {
    /// @notice Called by the pool manager on `msg.sender` when a lock is acquired
    /// @param data The data that was passed to the call to lock
    /// @return Any data that you want to be returned from the lock call
    function lockAcquired(bytes calldata data) external returns (bytes memory);
}

File 84 of 120 : ImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {IVault} from "infinity-core/src/interfaces/IVault.sol";
import {IImmutableState} from "../interfaces/IImmutableState.sol";

/// @title Immutable State
/// @notice A collection of immutable state variables, commonly used across multiple contracts
contract ImmutableState is IImmutableState {
    /// @inheritdoc IImmutableState
    IVault public immutable vault;

    constructor(IVault _vault) {
        vault = _vault;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @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 {
    /// @notice Thrown when the tick passed to #getSqrtRatioAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the ratio passed to #getTickAtSqrtRatio does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtRatio(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick 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 getSqrtRatioAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick 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 getSqrtRatioAtTick 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 #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_RATIO - MIN_SQRT_RATIO - 1`
    uint160 internal constant MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_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 ratio of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            // Equivalent: uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) revert InvalidTick(tick);

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

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

                // 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`
                // `ratio + type(uint32).max` will not overflow because `ratio` fits in 192 bits
                sqrtPriceX96 := shr(32, add(ratio, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // 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_RATIO) > MAX_SQRT_RATIO_MINUS_MIN_SQRT_RATIO_MINUS_ONE) {
                revert InvalidSqrtRatio(sqrtPriceX96);
            }

            uint256 ratio = uint256(sqrtPriceX96) << 32;

            uint256 r = ratio;
            uint256 msb = 0;

            assembly ("memory-safe") {
                let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(5, gt(r, 0xFFFFFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(4, gt(r, 0xFFFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(3, gt(r, 0xFF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(2, gt(r, 0xF))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := shl(1, gt(r, 0x3))
                msb := or(msb, f)
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                let f := gt(r, 0x1)
                msb := or(msb, f)
            }

            if (msb >= 128) r = ratio >> (msb - 127);
            else r = ratio << (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; // 128.128 number

            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

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

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

/**
 * @dev CLSlot0 is a packed version of solidity structure.
 * Using the packaged version saves gas by not storing the structure fields in memory slots.
 *
 * Layout:
 * 24 bits empty | 24 bits lpFee | 12 bits protocolFee 1->0 | 12 bits protocolFee 0->1 | 24 bits tick | 160 bits sqrtPriceX96
 *
 * Fields in the direction from the least significant bit:
 *
 * The current price
 * uint160 sqrtPriceX96;
 *
 * The current tick
 * int24 tick;
 *
 * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1
 * the maximum is 1000 - meaning the maximum protocol fee is 0.1%
 * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
 * uint24 protocolFee;
 *
 * The current LP fee of the pool. If the pool is dynamic, this does not include the dynamic fee flag.
 * uint24 lpFee;
 */
type CLSlot0 is bytes32;

using CLSlot0Library for CLSlot0 global;

/// @notice Library for getting and setting values in the Slot0 type
library CLSlot0Library {
    uint160 internal constant MASK_160_BITS = 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
    uint24 internal constant MASK_24_BITS = 0xFFFFFF;

    uint8 internal constant TICK_OFFSET = 160;
    uint8 internal constant PROTOCOL_FEE_OFFSET = 184;
    uint8 internal constant LP_FEE_OFFSET = 208;

    ////////////////////////////////////////////////////////////////////////////////////////
    // #### GETTERS ####
    ////////////////////////////////////////////////////////////////////////////////////////
    function sqrtPriceX96(CLSlot0 _packed) internal pure returns (uint160 _sqrtPriceX96) {
        assembly ("memory-safe") {
            _sqrtPriceX96 := and(MASK_160_BITS, _packed)
        }
    }

    function tick(CLSlot0 _packed) internal pure returns (int24 _tick) {
        assembly ("memory-safe") {
            _tick := signextend(2, shr(TICK_OFFSET, _packed))
        }
    }

    function protocolFee(CLSlot0 _packed) internal pure returns (uint24 _protocolFee) {
        assembly ("memory-safe") {
            _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed))
        }
    }

    function lpFee(CLSlot0 _packed) internal pure returns (uint24 _lpFee) {
        assembly ("memory-safe") {
            _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed))
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////
    // #### SETTERS ####
    ////////////////////////////////////////////////////////////////////////////////////////
    function setSqrtPriceX96(CLSlot0 _packed, uint160 _sqrtPriceX96) internal pure returns (CLSlot0 _result) {
        assembly ("memory-safe") {
            _result := or(and(not(MASK_160_BITS), _packed), and(MASK_160_BITS, _sqrtPriceX96))
        }
    }

    function setTick(CLSlot0 _packed, int24 _tick) internal pure returns (CLSlot0 _result) {
        assembly ("memory-safe") {
            _result := or(and(not(shl(TICK_OFFSET, MASK_24_BITS)), _packed), shl(TICK_OFFSET, and(MASK_24_BITS, _tick)))
        }
    }

    function setProtocolFee(CLSlot0 _packed, uint24 _protocolFee) internal pure returns (CLSlot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(
                    and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed),
                    shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee))
                )
        }
    }

    function setLpFee(CLSlot0 _packed, uint24 _lpFee) internal pure returns (CLSlot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee)))
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
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) {
        // Equivalent to:
        //   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:
        //   if (tick % tickSpacing != 0) revert TickMisaligned(tick, tickSpacing);  // ensure that the tick is spaced
        //   (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 = (1 << bitPos) - 1 + (1 << 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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "../../libraries/math/UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;

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

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

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256 amount1)
    {
        uint256 numerator = absDiff(sqrtRatioAX96, sqrtRatioBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity = uint256(liquidity);
        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
        assembly ("memory-safe") {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), and(roundUp, 0x1)))
        }
    }

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    error SafeCastOverflow();

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

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

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

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

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

    /// @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) _revertOverflow();
        return int128(int256(x));
    }
}

File 90 of 120 : FixedPoint128.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

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

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import "./FullMath.sol";
import "./SqrtPriceMath.sol";
import "../../libraries/LPFeeLibrary.sol";

/// @title Computes the result of a swap within ticks
/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
library SwapMath {
    uint256 internal constant MAX_FEE_PIPS = LPFeeLibrary.ONE_HUNDRED_PERCENT_FEE;

    /// @notice Computes the sqrt price target for the next swap step
    /// @param zeroForOne The direction of the swap, true for currency0 to currency1, false for currency1 to currency0
    /// @param sqrtPriceNextX96 The Q64.96 sqrt price for the next initialized tick
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value
    /// after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @return sqrtPriceTargetX96 The price target for the next swap step
    function getSqrtPriceTarget(bool zeroForOne, uint160 sqrtPriceNextX96, uint160 sqrtPriceLimitX96)
        internal
        pure
        returns (uint160 sqrtPriceTargetX96)
    {
        assembly ("memory-safe") {
            // a flag to toggle between sqrtPriceNextX96 and sqrtPriceLimitX96
            // when zeroForOne == true, nextOrLimit reduces to sqrtPriceNextX96 >= sqrtPriceLimitX96
            // sqrtPriceTargetX96 = max(sqrtPriceNextX96, sqrtPriceLimitX96)
            // when zeroForOne == false, nextOrLimit reduces to sqrtPriceNextX96 < sqrtPriceLimitX96
            // sqrtPriceTargetX96 = min(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceNextX96 := and(sqrtPriceNextX96, 0xffffffffffffffffffffffffffffffffffffffff)
            sqrtPriceLimitX96 := and(sqrtPriceLimitX96, 0xffffffffffffffffffffffffffffffffffffffff)
            let nextOrLimit := xor(lt(sqrtPriceNextX96, sqrtPriceLimitX96), and(zeroForOne, 0x1))
            let symDiff := xor(sqrtPriceNextX96, sqrtPriceLimitX96)
            sqrtPriceTargetX96 := xor(sqrtPriceLimitX96, mul(symDiff, nextOrLimit))
        }
    }

    /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
    /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
    /// @param sqrtRatioCurrentX96 The current sqrt price of the pool
    /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred
    /// @param liquidity The usable liquidity
    /// @param amountRemaining How much input or output amount is remaining to be swapped in/out
    /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip
    /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target
    /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap
    /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap
    /// @return feeAmount The amount of input that will be taken as a fee
    /// @dev feePips must be no larger than MAX_FEE_PIPS for this function. We ensure that before setting a fee using LPFeeLibrary.validate.
    function computeSwapStep(
        uint160 sqrtRatioCurrentX96,
        uint160 sqrtRatioTargetX96,
        uint128 liquidity,
        int256 amountRemaining,
        uint24 feePips
    ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) {
        unchecked {
            uint256 _feePips = feePips; // upcast once and cache
            bool zeroForOne = sqrtRatioCurrentX96 >= sqrtRatioTargetX96;
            bool exactIn = amountRemaining < 0;

            if (exactIn) {
                uint256 amountRemainingLessFee =
                    FullMath.mulDiv(uint256(-amountRemaining), MAX_FEE_PIPS - _feePips, MAX_FEE_PIPS);
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);
                if (amountRemainingLessFee >= amountIn) {
                    // `amountIn` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                    feeAmount = _feePips == MAX_FEE_PIPS
                        ? amountIn
                        : FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
                } else {
                    // exhaust the remaining amount
                    amountIn = amountRemainingLessFee;
                    sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(
                        sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne
                    );
                    // we didn't reach the target, so take the remainder of the maximum input as fee
                    feeAmount = uint256(-amountRemaining) - amountIn;
                }
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);
            } else {
                amountOut = zeroForOne
                    ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)
                    : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);
                if (uint256(amountRemaining) >= amountOut) {
                    // `amountOut` is capped by the target price
                    sqrtRatioNextX96 = sqrtRatioTargetX96;
                } else {
                    // cap the output amount to not exceed the remaining output amount
                    amountOut = uint256(amountRemaining);
                    sqrtRatioNextX96 =
                        SqrtPriceMath.getNextSqrtPriceFromOutput(sqrtRatioCurrentX96, liquidity, amountOut, zeroForOne);
                }
                amountIn = zeroForOne
                    ? SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true)
                    : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);
                // `feePips` cannot be `MAX_FEE_PIPS` for exact out
                feeAmount = FullMath.mulDivRoundingUp(amountIn, _feePips, MAX_FEE_PIPS - _feePips);
            }
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
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) {
                // store 0x93dafdf1, error SafeCastOverflow at memory 0 address and revert from pointer 28, to byte 32
                mstore(0x0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import "./math/UnsafeMath.sol";

library ProtocolFeeLibrary {
    /// @dev Increasing these values could lead to overflow in Pool.swap
    /// @notice Max protocol fee is 0.4% (4000 pips)
    uint16 public constant MAX_PROTOCOL_FEE = 4000;

    /// @notice Thresholds used for optimized bounds checks on protocol fees
    uint24 internal constant FEE_0_THRESHOLD = 4001;
    uint24 internal constant FEE_1_THRESHOLD = 4001 << 12;

    /// @notice the protocol fee is represented in hundredths of a bip
    uint256 internal constant PIPS_DENOMINATOR = 1_000_000;

    /// @notice Get the fee taken when swap token0 for token1
    /// @param self The composite protocol fee to get the single direction fee from
    /// @return The fee taken when swapping token0 for token1
    function getZeroForOneFee(uint24 self) internal pure returns (uint16) {
        return uint16(self & 0xfff);
    }

    /// @notice Get the fee taken when swap token1 for token0
    /// @param self The composite protocol fee to get the single direction fee from
    /// @return The fee taken when swapping token1 for token0
    function getOneForZeroFee(uint24 self) internal pure returns (uint16) {
        return uint16(self >> 12);
    }

    /// @notice Validate that the protocol fee is within bounds
    /// @param self The composite protocol fee to validate
    /// @return valid True if the fee is within bounds
    function validate(uint24 self) internal pure returns (bool valid) {
        // Equivalent to: getZeroForOneFee(self) <= MAX_PROTOCOL_FEE && getOneForZeroFee(self) <= MAX_PROTOCOL_FEE
        assembly ("memory-safe") {
            let isZeroForOneFeeOk := lt(and(self, 0xfff), FEE_0_THRESHOLD)
            let isOneForZeroFeeOk := lt(and(self, 0xfff000), FEE_1_THRESHOLD)
            valid := and(isZeroForOneFeeOk, isOneForZeroFeeOk)
        }
    }

    /// @notice The protocol fee is taken from the input amount first and then the LP fee is taken from the remaining
    // Equivalent to protocolFee + lpFee(1_000_000 - protocolFee) / 1_000_000 (rounded up)
    /// Also note the swap fee is capped at 1_000_000 (100%) for cl pool and 100_000 (10%) for bin pool
    /// @param self The single direction protocol fee to calculate the swap fee from
    /// @param lpFee The LP fee to calculate the swap fee from
    /// @return swapFee The composite swap fee
    function calculateSwapFee(uint16 self, uint24 lpFee) internal pure returns (uint24 swapFee) {
        // protocolFee + lpFee - (protocolFee * lpFee / 1_000_000)
        assembly ("memory-safe") {
            self := and(self, 0xfff)
            lpFee := and(lpFee, 0xffffff)
            let numerator := mul(self, lpFee)
            swapFee := sub(add(self, lpFee), div(numerator, PIPS_DENOMINATOR))
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice Library for handling lp fee setting from `PoolKey.fee`
/// It can be either static or dynamic, and upper 4 bits are used to store the flag:
/// 1. if the flag is set, then the fee is dynamic, it can be set and updated by hook
/// 2. otherwise if the flag is not set, then the fee is static, and the lower 20 bits are used to store the fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;

    /// @notice Thrown when the static/dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant OVERRIDE_MASK = 0xBFFFFF;

    /// @notice a dynamic fee pool must have exactly same value for fee field
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice the fee is represented in hundredths of a bip
    /// max fee varies between different pool types i.e. it's 100% for cl pool and 10% for bin pool
    uint24 public constant ONE_HUNDRED_PERCENT_FEE = 1_000_000;
    uint24 public constant TEN_PERCENT_FEE = 100_000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicLPFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    /// @param maxFee The maximum fee allowed for the pool
    function validate(uint24 self, uint24 maxFee) internal pure {
        if (self > maxFee) revert LPFeeTooLarge(self);
    }

    /// @notice gets the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the original value
    function getInitialLPFee(uint24 self) internal pure returns (uint24 initialFee) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicLPFee()) return 0;
        initialFee = self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @param maxFee The maximum fee allowed for the pool
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideAndValidate(uint24 self, uint24 maxFee) internal pure returns (uint24) {
        uint24 fee = self.removeOverrideFlag();
        fee.validate(maxFee);
        return fee;
    }
}

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

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

interface IProtocolFeeController {
    /// @notice Get the protocol fee for a pool given the conditions of this contract
    /// @param poolKey The pool key to identify the pool. The controller may want to use attributes on the pool
    ///   to determine the protocol fee, hence the entire key is needed.
    /// @return protocolFee The pool's protocol fee, expressed in hundredths of a bip. The upper 12 bits are for 1->0
    /// and the lower 12 are for 0->1. The maximum is 4000 - meaning the maximum protocol fee is 0.4%.
    /// the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
    function protocolFeeForPool(PoolKey memory poolKey) external view returns (uint24 protocolFee);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

/**
 * @dev BinSlot0 is a packed version of solidity structure.
 * Using the packaged version saves gas by not storing the structure fields in memory slots.
 *
 * Layout:
 * 184 bits empty | 24 bits lpFee | 12 bits protocolFee 1->0 | 12 bits protocolFee 0->1 | 24 bits activeId
 *
 * Fields in the direction from the least significant bit:
 *
 * The current activeId
 * uint24 activeId;
 *
 * Protocol fee, expressed in hundredths of a bip, upper 12 bits are for 1->0, and the lower 12 are for 0->1
 * the maximum is 1000 - meaning the maximum protocol fee is 0.1%
 * the protocolFee is taken from the input first, then the lpFee is taken from the remaining input
 * uint24 protocolFee;
 *
 * The current LP fee of the pool. If the pool is dynamic, this does not include the dynamic fee flag.
 * uint24 lpFee;
 */
type BinSlot0 is bytes32;

using BinSlot0Library for BinSlot0 global;

/// @notice Library for getting and setting values in the Slot0 type
library BinSlot0Library {
    uint24 internal constant MASK_24_BITS = 0xFFFFFF;

    uint8 internal constant PROTOCOL_FEE_OFFSET = 24;
    uint8 internal constant LP_FEE_OFFSET = 48;

    ////////////////////////////////////////////////////////////////////////////////////////
    // #### GETTERS ####
    ////////////////////////////////////////////////////////////////////////////////////////
    function activeId(BinSlot0 _packed) internal pure returns (uint24 _activeId) {
        assembly ("memory-safe") {
            _activeId := and(MASK_24_BITS, _packed)
        }
    }

    function protocolFee(BinSlot0 _packed) internal pure returns (uint24 _protocolFee) {
        assembly ("memory-safe") {
            _protocolFee := and(MASK_24_BITS, shr(PROTOCOL_FEE_OFFSET, _packed))
        }
    }

    function lpFee(BinSlot0 _packed) internal pure returns (uint24 _lpFee) {
        assembly ("memory-safe") {
            _lpFee := and(MASK_24_BITS, shr(LP_FEE_OFFSET, _packed))
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////
    // #### SETTERS ####
    ////////////////////////////////////////////////////////////////////////////////////////
    function setActiveId(BinSlot0 _packed, uint24 _activeId) internal pure returns (BinSlot0 _result) {
        assembly ("memory-safe") {
            _result := or(and(not(MASK_24_BITS), _packed), and(MASK_24_BITS, _activeId))
        }
    }

    function setProtocolFee(BinSlot0 _packed, uint24 _protocolFee) internal pure returns (BinSlot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(
                    and(not(shl(PROTOCOL_FEE_OFFSET, MASK_24_BITS)), _packed),
                    shl(PROTOCOL_FEE_OFFSET, and(MASK_24_BITS, _protocolFee))
                )
        }
    }

    function setLpFee(BinSlot0 _packed, uint24 _lpFee) internal pure returns (BinSlot0 _result) {
        assembly ("memory-safe") {
            _result :=
                or(and(not(shl(LP_FEE_OFFSET, MASK_24_BITS)), _packed), shl(LP_FEE_OFFSET, and(MASK_24_BITS, _lpFee)))
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {PackedUint128Math} from "./PackedUint128Math.sol";
import {Encoded} from "../../../libraries/math/Encoded.sol";

/// @notice This library contains functions to encode and decode the config of a pool and interact with the encoded bytes32.
library LiquidityConfigurations {
    using PackedUint128Math for bytes32;
    using PackedUint128Math for uint128;
    using Encoded for bytes32;

    error LiquidityConfigurations__InvalidConfig();

    uint256 private constant OFFSET_ID = 0;
    uint256 private constant OFFSET_DISTRIBUTION_Y = 24;
    uint256 private constant OFFSET_DISTRIBUTION_X = 88;

    uint256 private constant PRECISION = 1e18;

    /// @dev Encode the distributionX, distributionY and id into a single bytes32
    /// @param distributionX The distribution of the first token
    /// @param distributionY The distribution of the second token
    /// @param id The id of the pool
    /// @return config The encoded config as follows:
    /// [0 - 24[: id
    /// [24 - 88[: distributionY
    /// [88 - 152[: distributionX
    /// [152 - 256[: empty
    function encodeParams(uint64 distributionX, uint64 distributionY, uint24 id)
        internal
        pure
        returns (bytes32 config)
    {
        config = config.set(distributionX, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_X);
        config = config.set(distributionY, Encoded.MASK_UINT64, OFFSET_DISTRIBUTION_Y);
        config = config.set(id, Encoded.MASK_UINT24, OFFSET_ID);
    }

    /// @dev Decode the distributionX, distributionY and id from a single bytes32
    /// @param config The encoded config as follows:
    /// [0 - 24[: id
    /// [24 - 88[: distributionY
    /// [88 - 152[: distributionX
    /// [152 - 256[: empty
    /// @return distributionX The distribution of the first token
    /// @return distributionY The distribution of the second token
    /// @return id The id of the bin to add the liquidity to
    function decodeParams(bytes32 config)
        internal
        pure
        returns (uint64 distributionX, uint64 distributionY, uint24 id)
    {
        distributionX = config.decodeUint64(OFFSET_DISTRIBUTION_X);
        distributionY = config.decodeUint64(OFFSET_DISTRIBUTION_Y);
        id = config.decodeUint24(OFFSET_ID);

        if (uint256(config) > type(uint152).max || distributionX > PRECISION || distributionY > PRECISION) {
            revert LiquidityConfigurations__InvalidConfig();
        }
    }

    /// @dev Get the amounts and id from a config and amountsIn
    /// @param config The encoded config as follows:
    /// [0 - 24[: id
    /// [24 - 88[: distributionY
    /// [88 - 152[: distributionX
    /// [152 - 256[: empty
    /// @param amountsIn The amounts to distribute as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @return amounts The distributed amounts as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @return id The id of the bin to add the liquidity to
    function getAmountsAndId(bytes32 config, bytes32 amountsIn) internal pure returns (bytes32, uint24) {
        (uint64 distributionX, uint64 distributionY, uint24 id) = decodeParams(config);

        (uint128 x1, uint128 x2) = amountsIn.decode();

        assembly ("memory-safe") {
            x1 := div(mul(x1, distributionX), PRECISION)
            x2 := div(mul(x2, distributionY), PRECISION)
        }

        return (x1.encode(x2), id);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

/// @notice This library contains functions to encode and decode two uint128 into a single bytes32
///         and interact with the encoded bytes32.
library PackedUint128Math {
    using ProtocolFeeLibrary for uint24;
    using SafeCast for uint256;

    error PackedUint128Math__AddOverflow();
    error PackedUint128Math__SubUnderflow();

    uint256 private constant OFFSET = 128;
    uint256 private constant MASK_128 = 0xffffffffffffffffffffffffffffffff;
    uint256 private constant MASK_128_PLUS_ONE = MASK_128 + 1;

    /// @dev Encodes two uint128 into a single bytes32
    /// @param x1 The first uint128
    /// @param x2 The second uint128
    /// @return z The encoded bytes32 as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    function encode(uint128 x1, uint128 x2) internal pure returns (bytes32 z) {
        assembly ("memory-safe") {
            z := or(and(x1, MASK_128), shl(OFFSET, x2))
        }
    }

    /// @dev Encodes a uint128 into a single bytes32 as the first uint128
    /// @param x1 The uint128
    /// @return z The encoded bytes32 as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: empty
    function encodeFirst(uint128 x1) internal pure returns (bytes32 z) {
        assembly ("memory-safe") {
            z := and(x1, MASK_128)
        }
    }

    /// @dev Encodes a uint128 into a single bytes32 as the second uint128
    /// @param x2 The uint128
    // @return z The encoded bytes32 as follows:
    /// [0 - 128[: empty
    /// [128 - 256[: x2
    function encodeSecond(uint128 x2) internal pure returns (bytes32 z) {
        assembly ("memory-safe") {
            z := shl(OFFSET, x2)
        }
    }

    /// @dev Encodes a uint128 into a single bytes32 as the first or second uint128
    /// @param x The uint128
    /// @param first Whether to encode as the first or second uint128
    /// @return z The encoded bytes32 as follows:
    /// if first:
    /// [0 - 128[: x
    /// [128 - 256[: empty
    /// else:
    /// [0 - 128[: empty
    /// [128 - 256[: x
    function encode(uint128 x, bool first) internal pure returns (bytes32 z) {
        return first ? encodeFirst(x) : encodeSecond(x);
    }

    /// @dev Decodes a bytes32 into two uint128
    /// @param z The encoded bytes32 as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @return x1 The first uint128
    /// @return x2 The second uint128
    function decode(bytes32 z) internal pure returns (uint128 x1, uint128 x2) {
        assembly ("memory-safe") {
            x1 := and(z, MASK_128)
            x2 := shr(OFFSET, z)
        }
    }

    /// @dev Decodes a bytes32 into a uint128 as the first uint128
    /// @param z The encoded bytes32 as follows:
    /// [0 - 128[: x
    /// [128 - 256[: any
    /// @return x The first uint128
    function decodeX(bytes32 z) internal pure returns (uint128 x) {
        assembly ("memory-safe") {
            x := and(z, MASK_128)
        }
    }

    /// @dev Decodes a bytes32 into a uint128 as the second uint128
    /// @param z The encoded bytes32 as follows:
    /// [0 - 128[: any
    /// [128 - 256[: y
    /// @return y The second uint128
    function decodeY(bytes32 z) internal pure returns (uint128 y) {
        assembly ("memory-safe") {
            y := shr(OFFSET, z)
        }
    }

    /// @dev Decodes a bytes32 into a uint128 as the first or second uint128
    /// @param z The encoded bytes32 as follows:
    /// if first:
    ///   [0 - 128[: x1
    ///   [128 - 256[: empty
    /// else:
    ///   [0 - 128[: empty
    ///  [128 - 256[: x2
    /// @param first Whether to decode as the first or second uint128
    /// @return x The decoded uint128
    function decode(bytes32 z, bool first) internal pure returns (uint128 x) {
        return first ? decodeX(z) : decodeY(z);
    }

    /// @dev Adds two encoded bytes32, reverting on overflow on any of the uint128
    /// @param x The first bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y The second bytes32 encoded as follows:
    /// [0 - 128[: y1
    /// [128 - 256[: y2
    /// @return z The sum of x and y encoded as follows:
    /// [0 - 128[: x1 + y1
    /// [128 - 256[: x2 + y2
    function add(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        assembly ("memory-safe") {
            z := add(x, y)
        }

        if (z < x || uint128(uint256(z)) < uint128(uint256(x))) {
            revert PackedUint128Math__AddOverflow();
        }
    }

    /// @dev Adds an encoded bytes32 and two uint128, reverting on overflow on any of the uint128
    /// @param x The bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y1 The first uint128
    /// @param y2 The second uint128
    /// @return z The sum of x and y encoded as follows:
    /// [0 - 128[: x1 + y1
    /// [128 - 256[: x2 + y2
    function add(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
        return add(x, encode(y1, y2));
    }

    /// @dev Subtracts two encoded bytes32, reverting on underflow on any of the uint128
    /// @param x The first bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y The second bytes32 encoded as follows:
    /// [0 - 128[: y1
    /// [128 - 256[: y2
    /// @return z The difference of x and y encoded as follows:
    /// [0 - 128[: x1 - y1
    /// [128 - 256[: x2 - y2
    function sub(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        assembly ("memory-safe") {
            z := sub(x, y)
        }

        if (z > x || uint128(uint256(z)) > uint128(uint256(x))) {
            revert PackedUint128Math__SubUnderflow();
        }
    }

    /// @dev Subtracts an encoded bytes32 and two uint128, reverting on underflow on any of the uint128
    /// @param x The bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y1 The first uint128
    /// @param y2 The second uint128
    /// @return z The difference of x and y encoded as follows:
    /// [0 - 128[: x1 - y1
    /// [128 - 256[: x2 - y2
    function sub(bytes32 x, uint128 y1, uint128 y2) internal pure returns (bytes32) {
        return sub(x, encode(y1, y2));
    }

    /// @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
    /// @param x The first bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y The second bytes32 encoded as follows:
    /// [0 - 128[: y1
    /// [128 - 256[: y2
    /// @return x1 < y1 || x2 < y2
    function lt(bytes32 x, bytes32 y) internal pure returns (bool) {
        (uint128 x1, uint128 x2) = decode(x);
        (uint128 y1, uint128 y2) = decode(y);

        return x1 < y1 || x2 < y2;
    }

    /// @dev Returns whether any of the uint128 of x is strictly greater than the corresponding uint128 of y
    /// @param x The first bytes32 encoded as follows:
    /// [0 - 128[: x1
    /// [128 - 256[: x2
    /// @param y The second bytes32 encoded as follows:
    /// [0 - 128[: y1
    /// [128 - 256[: y2
    /// @return x1 < y1 || x2 < y2
    function gt(bytes32 x, bytes32 y) internal pure returns (bool) {
        (uint128 x1, uint128 x2) = decode(x);
        (uint128 y1, uint128 y2) = decode(y);

        return x1 > y1 || x2 > y2;
    }

    /// @dev given amount and protocolFee, calculate and return external protocol fee amt
    /// @param amount encoded bytes with (x, y)
    /// @param protocolFee Protocol fee from the swap, also denominated in hundredths of a bip
    /// @param swapFee The fee collected upon every swap in the pool (including protocol fee and LP fee), denominated in hundredths of a bip
    function getProtocolFeeAmt(bytes32 amount, uint24 protocolFee, uint24 swapFee) internal pure returns (bytes32 z) {
        if (protocolFee == 0 || swapFee == 0) return 0;

        (uint128 amountX, uint128 amountY) = decode(amount);
        uint16 fee0 = protocolFee.getZeroForOneFee();
        uint16 fee1 = protocolFee.getOneForZeroFee();

        uint128 feeForX;
        uint128 feeForY;
        unchecked {
            if (fee0 == 0) {
                feeForX = 0;
            } else if (fee0 == swapFee) {
                feeForX = amountX;
            } else {
                feeForX = (uint256(amountX) * fee0 / swapFee).safe128();
            }

            if (fee1 == 0) {
                feeForY = 0;
            } else if (fee1 == swapFee) {
                feeForY = amountY;
            } else {
                feeForY = (uint256(amountY) * fee1 / swapFee).safe128();
            }
        }

        return encode(feeForX, feeForY);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice Helper contract used for full precision calculations
library Uint256x256Math {
    error Uint256x256Math__MulShiftOverflow();
    error Uint256x256Math__MulDivOverflow();

    /// @notice Calculates floor(x*y/denominator) with full precision
    /// The result will be rounded down
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The denominator cannot be zero
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @param denominator The divisor as an uint256
    /// @return result The result as an uint256
    function mulDivRoundDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        (uint256 prod0, uint256 prod1) = _getMulProds(x, y);

        return _getEndOfDivRoundDown(x, y, denominator, prod0, prod1);
    }

    /// @notice Calculates ceil(x*y/denominator) with full precision
    /// The result will be rounded up
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The denominator cannot be zero
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @param denominator The divisor as an uint256
    /// @return result The result as an uint256
    function mulDivRoundUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        result = mulDivRoundDown(x, y, denominator);
        if (mulmod(x, y, denominator) != 0) result += 1;
    }

    /// @notice Calculates floor(x * y / 2**offset) with full precision
    /// The result will be rounded down
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The offset needs to be strictly lower than 256
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @param offset The offset as an uint256, can't be greater than 256
    /// @return result The result as an uint256
    function mulShiftRoundDown(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
        (uint256 prod0, uint256 prod1) = _getMulProds(x, y);

        if (prod0 != 0) result = prod0 >> offset;
        if (prod1 != 0) {
            // Make sure the result is less than 2^256.
            if (prod1 >= 1 << offset) revert Uint256x256Math__MulShiftOverflow();

            unchecked {
                result += prod1 << (256 - offset);
            }
        }
    }

    /// @notice Calculates floor(x * y / 2**offset) with full precision
    ///         The result will be rounded down
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The offset needs to be strictly lower than 256
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @param offset The offset as an uint256, can't be greater than 256
    /// @return result The result as an uint256
    function mulShiftRoundUp(uint256 x, uint256 y, uint8 offset) internal pure returns (uint256 result) {
        result = mulShiftRoundDown(x, y, offset);
        if (mulmod(x, y, 1 << offset) != 0) result += 1;
    }

    /// @notice Calculates floor(x << offset / y) with full precision
    /// The result will be rounded down
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The offset needs to be strictly lower than 256
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param offset The number of bit to shift x as an uint256
    /// @param denominator The divisor as an uint256
    /// @return result The result as an uint256
    function shiftDivRoundDown(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
        uint256 prod0;
        uint256 prod1;

        prod0 = x << offset; // Least significant 256 bits of the product
        unchecked {
            prod1 = x >> (256 - offset); // Most significant 256 bits of the product
        }

        return _getEndOfDivRoundDown(x, 1 << offset, denominator, prod0, prod1);
    }

    /// @notice Calculates ceil(x << offset / y) with full precision
    /// The result will be rounded up
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    /// Requirements:
    /// - The offset needs to be strictly lower than 256
    /// - The result must fit within uint256
    /// Caveats:
    /// - This function does not work with fixed-point numbers
    /// @param x The multiplicand as an uint256
    /// @param offset The number of bit to shift x as an uint256
    /// @param denominator The divisor as an uint256
    /// @return result The result as an uint256
    function shiftDivRoundUp(uint256 x, uint8 offset, uint256 denominator) internal pure returns (uint256 result) {
        result = shiftDivRoundDown(x, offset, denominator);
        if (mulmod(x, 1 << offset, denominator) != 0) result += 1;
    }

    /// @notice Helper function to return the result of `x * y` as 2 uint256
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @return prod0 The least significant 256 bits of the product
    /// @return prod1 The most significant 256 bits of the product
    function _getMulProds(uint256 x, uint256 y) private pure returns (uint256 prod0, uint256 prod1) {
        // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
        // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = prod1 * 2^256 + prod0.
        assembly ("memory-safe") {
            let mm := mulmod(x, y, not(0))
            prod0 := mul(x, y)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }
    }

    /// @notice Helper function to return the result of `x * y / denominator` with full precision
    /// @param x The multiplicand as an uint256
    /// @param y The multiplier as an uint256
    /// @param denominator The divisor as an uint256
    /// @param prod0 The least significant 256 bits of the product
    /// @param prod1 The most significant 256 bits of the product
    /// @return result The result as an uint256
    function _getEndOfDivRoundDown(uint256 x, uint256 y, uint256 denominator, uint256 prod0, uint256 prod1)
        private
        pure
        returns (uint256 result)
    {
        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            unchecked {
                result = prod0 / denominator;
            }
        } else {
            // Make sure the result is less than 2^256. Also prevents denominator == 0
            if (prod1 >= denominator) revert Uint256x256Math__MulDivOverflow();

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

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

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1
            // See https://cs.stackexchange.com/q/138556/92363
            unchecked {
                // Does not overflow because the denominator cannot be zero at this stage in the function
                uint256 lpotdod = denominator & (~denominator + 1);
                assembly ("memory-safe") {
                    // Divide denominator by lpotdod.
                    denominator := div(denominator, lpotdod)

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

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

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

                // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                // four bits. That is, denominator * inv = 1 mod 2^4
                uint256 inverse = (3 * denominator) ^ 2;

                // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                // in modular arithmetic, doubling the correct bits in each step
                inverse *= 2 - denominator * inverse; // inverse mod 2^8
                inverse *= 2 - denominator * inverse; // inverse mod 2^16
                inverse *= 2 - denominator * inverse; // inverse mod 2^32
                inverse *= 2 - denominator * inverse; // inverse mod 2^64
                inverse *= 2 - denominator * inverse; // inverse mod 2^128
                inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

/// @notice This library contains functions to interact with a tree of TreeUint24.
library TreeMath {
    using BitMath for uint256;

    /// @dev Returns true if the tree contains the id
    function contains(mapping(bytes32 => bytes32) storage level2, uint24 id) internal view returns (bool) {
        bytes32 leaf2 = bytes32(uint256(id) >> 8);

        return level2[leaf2] & bytes32(1 << (id & type(uint8).max)) != 0;
    }

    /// @dev Adds the id to the tree and returns true if the id was not already in the tree
    ///     It will also propagate the change to the parent levels.
    /// @return True if the id was not already in the tree
    function add(
        bytes32 level0,
        mapping(bytes32 => bytes32) storage level1,
        mapping(bytes32 => bytes32) storage level2,
        uint24 id
    ) internal returns (bool, bytes32) {
        bytes32 key2 = bytes32(uint256(id) >> 8);

        bytes32 leaves = level2[key2];
        bytes32 newLeaves = leaves | bytes32(1 << (id & type(uint8).max));

        if (leaves != newLeaves) {
            level2[key2] = newLeaves;

            if (leaves == 0) {
                bytes32 key1 = key2 >> 8;
                leaves = level1[key1];

                level1[key1] = leaves | bytes32(1 << (uint256(key2) & type(uint8).max));

                if (leaves == 0) level0 |= bytes32(1 << (uint256(key1) & type(uint8).max));
            }

            return (true, level0);
        }

        return (false, level0);
    }

    /// @dev Removes the id from the tree and returns true if the id was in the tree.
    ///     It will also propagate the change to the parent levels.
    /// @param id The id
    /// @return True if the id was in the tree
    function remove(
        bytes32 level0,
        mapping(bytes32 => bytes32) storage level1,
        mapping(bytes32 => bytes32) storage level2,
        uint24 id
    ) internal returns (bool, bytes32) {
        bytes32 key2 = bytes32(uint256(id) >> 8);

        bytes32 leaves = level2[key2];
        bytes32 newLeaves = leaves & ~bytes32(1 << (id & type(uint8).max));

        if (leaves != newLeaves) {
            level2[key2] = newLeaves;

            if (newLeaves == 0) {
                bytes32 key1 = key2 >> 8;
                newLeaves = level1[key1] & ~bytes32(1 << (uint256(key2) & type(uint8).max));

                level1[key1] = newLeaves;

                if (newLeaves == 0) level0 &= ~bytes32(1 << (uint256(key1) & type(uint8).max));
            }

            return (true, level0);
        }

        return (false, level0);
    }

    /// @dev Returns the first id in the tree that is lower than or equal to the given id.
    /// It will return type(uint24).max if there is no such id.
    /// @return The first id in the tree that is lower than or equal to the given id
    function findFirstRight(
        bytes32 level0,
        mapping(bytes32 => bytes32) storage level1,
        mapping(bytes32 => bytes32) storage level2,
        uint24 id
    ) internal view returns (uint24) {
        bytes32 leaves;

        bytes32 key2 = bytes32(uint256(id) >> 8);
        uint8 bit = uint8(id & type(uint8).max);

        if (bit != 0) {
            leaves = level2[key2];
            uint256 closestBit = _closestBitRight(leaves, bit);

            if (closestBit != type(uint256).max) return uint24((uint256(key2) << 8) | closestBit);
        }

        bytes32 key1 = key2 >> 8;
        bit = uint8(uint256(key2) & type(uint8).max);

        if (bit != 0) {
            leaves = level1[key1];
            uint256 closestBit = _closestBitRight(leaves, bit);

            if (closestBit != type(uint256).max) {
                key2 = bytes32((uint256(key1) << 8) | closestBit);
                leaves = level2[key2];

                return uint24((uint256(key2) << 8) | uint256(leaves).mostSignificantBit());
            }
        }

        bit = uint8(uint256(key1) & type(uint8).max);

        if (bit != 0) {
            leaves = level0;
            uint256 closestBit = _closestBitRight(leaves, bit);

            if (closestBit != type(uint256).max) {
                key1 = bytes32(closestBit);
                leaves = level1[key1];

                key2 = bytes32((uint256(key1) << 8) | uint256(leaves).mostSignificantBit());
                leaves = level2[key2];

                return uint24((uint256(key2) << 8) | uint256(leaves).mostSignificantBit());
            }
        }

        return type(uint24).max;
    }

    /// @dev Returns the first id in the tree that is higher than or equal to the given id.
    /// It will return 0 if there is no such id.
    /// @return The first id in the tree that is higher than or equal to the given id
    function findFirstLeft(
        bytes32 level0,
        mapping(bytes32 => bytes32) storage level1,
        mapping(bytes32 => bytes32) storage level2,
        uint24 id
    ) internal view returns (uint24) {
        bytes32 leaves;

        bytes32 key2 = bytes32(uint256(id) >> 8);
        uint8 bit = uint8(id & type(uint8).max);

        if (bit != type(uint8).max) {
            leaves = level2[key2];
            uint256 closestBit = _closestBitLeft(leaves, bit);

            if (closestBit != type(uint256).max) return uint24((uint256(key2) << 8) | closestBit);
        }

        bytes32 key1 = key2 >> 8;
        bit = uint8(uint256(key2) & type(uint8).max);

        if (bit != type(uint8).max) {
            leaves = level1[key1];
            uint256 closestBit = _closestBitLeft(leaves, bit);

            if (closestBit != type(uint256).max) {
                key2 = bytes32((uint256(key1) << 8) | closestBit);
                leaves = level2[key2];

                return uint24((uint256(key2) << 8) | uint256(leaves).leastSignificantBit());
            }
        }

        bit = uint8(uint256(key1) & type(uint8).max);

        if (bit != type(uint8).max) {
            leaves = level0;
            uint256 closestBit = _closestBitLeft(leaves, bit);

            if (closestBit != type(uint256).max) {
                key1 = bytes32(closestBit);
                leaves = level1[key1];

                key2 = bytes32((uint256(key1) << 8) | uint256(leaves).leastSignificantBit());
                leaves = level2[key2];

                return uint24((uint256(key2) << 8) | uint256(leaves).leastSignificantBit());
            }
        }

        return 0;
    }

    /// @dev Returns the first bit in the given leaves that is strictly lower than the given bit.
    ///     It will return type(uint256).max if there is no such bit.
    /// @param leaves The leaves
    /// @param bit The bit
    /// @return The first bit in the given leaves that is strictly lower than the given bit
    function _closestBitRight(bytes32 leaves, uint8 bit) private pure returns (uint256) {
        unchecked {
            return uint256(leaves).closestBitRight(bit - 1);
        }
    }

    /// @dev Returns the first bit in the given leaves that is strictly higher than the given bit.
    ///     It will return type(uint256).max if there is no such bit.
    /// @param leaves The leaves
    /// @param bit The bit
    /// @return The first bit in the given leaves that is strictly higher than the given bit
    function _closestBitLeft(bytes32 leaves, uint8 bit) private pure returns (uint256) {
        unchecked {
            return uint256(leaves).closestBitLeft(bit + 1);
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {Uint128x128Math} from "./math/Uint128x128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";

/// @notice This library contains functions to calculate prices
library PriceHelper {
    using Uint128x128Math for uint256;
    using Uint256x256Math for uint256;
    using SafeCast for uint256;

    int256 private constant REAL_ID_SHIFT = 1 << 23;

    /// @dev Calculates the price from the id and the bin step
    /// @param id The id
    /// @param binStep The bin step
    /// @return price The price as a 128.128-binary fixed-point number
    function getPriceFromId(uint24 id, uint16 binStep) internal pure returns (uint256 price) {
        uint256 base = getBase(binStep);
        int256 exponent = getExponent(id);

        price = base.pow(exponent);
    }

    /// @dev Calculates the id from the price and the bin step
    /// @param price The price as a 128.128-binary fixed-point number
    /// @param binStep The bin step
    /// @return id The id
    function getIdFromPrice(uint256 price, uint16 binStep) internal pure returns (uint24 id) {
        uint256 base = getBase(binStep);
        int256 realId = price.log2() / base.log2();

        unchecked {
            id = uint256(REAL_ID_SHIFT + realId).safe24();
        }
    }

    /// @dev Calculates the base from the bin step, which is `1 + binStep / BASIS_POINT_MAX`
    /// @param binStep The bin step
    /// @return base The base
    function getBase(uint16 binStep) internal pure returns (uint256) {
        unchecked {
            return Constants.SCALE + (uint256(binStep) << Constants.SCALE_OFFSET) / Constants.BASIS_POINT_MAX;
        }
    }

    /// @dev Calculates the exponent from the id, which is `id - REAL_ID_SHIFT`
    /// @param id The id
    /// @return exponent The exponent
    function getExponent(uint24 id) internal pure returns (int256) {
        unchecked {
            return int256(uint256(id)) - REAL_ID_SHIFT;
        }
    }

    /// @dev Converts a price with 18 decimals to a 128.128-binary fixed-point number
    /// @param price The price with 18 decimals
    /// @return price128x128 The 128.128-binary fixed-point number
    function convertDecimalPriceTo128x128(uint256 price) internal pure returns (uint256) {
        return price.shiftDivRoundDown(Constants.SCALE_OFFSET, Constants.PRECISION);
    }

    /// @dev Converts a 128.128-binary fixed-point number to a price with 18 decimals
    /// @param price128x128 The 128.128-binary fixed-point number
    /// @return price The price with 18 decimals
    function convert128x128PriceToDecimal(uint256 price128x128) internal pure returns (uint256) {
        return price128x128.mulShiftRoundDown(Constants.PRECISION, Constants.SCALE_OFFSET);
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {PackedUint128Math} from "./math/PackedUint128Math.sol";
import {Uint256x256Math} from "./math/Uint256x256Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {Constants} from "./Constants.sol";
import {BinPoolParametersHelper} from "./BinPoolParametersHelper.sol";
import {FeeHelper} from "./FeeHelper.sol";
import {PriceHelper} from "./PriceHelper.sol";
import {ProtocolFeeLibrary} from "../../libraries/ProtocolFeeLibrary.sol";

/// @notice This library contains functions to help interaction with bins.
library BinHelper {
    using PackedUint128Math for bytes32;
    using PackedUint128Math for uint128;
    using Uint256x256Math for uint256;
    using PriceHelper for uint24;
    using SafeCast for uint256;
    using BinPoolParametersHelper for bytes32;
    using FeeHelper for uint128;
    using ProtocolFeeLibrary for uint24;
    using ProtocolFeeLibrary for uint16;

    error BinHelper__CompositionFactorFlawed(uint24 id);
    error BinHelper__LiquidityOverflow();

    /// @dev Returns the amount of tokens that will be received when burning the given amount of liquidity
    /// @param binReserves The reserves of the bin
    /// @param amountToBurn The amount of liquidity to burn
    /// @param totalSupply The total supply of the liquidity book
    /// @return amountsOut The encoded amount of tokens that will be received
    function getAmountOutOfBin(bytes32 binReserves, uint256 amountToBurn, uint256 totalSupply)
        internal
        pure
        returns (bytes32 amountsOut)
    {
        (uint128 binReserveX, uint128 binReserveY) = binReserves.decode();

        uint128 amountXOutFromBin;
        uint128 amountYOutFromBin;

        if (binReserveX > 0) {
            amountXOutFromBin = (amountToBurn.mulDivRoundDown(binReserveX, totalSupply)).safe128();
        }

        if (binReserveY > 0) {
            amountYOutFromBin = (amountToBurn.mulDivRoundDown(binReserveY, totalSupply)).safe128();
        }

        amountsOut = amountXOutFromBin.encode(amountYOutFromBin);
    }

    /// @dev Returns the share and the effective amounts in when adding liquidity
    /// @param binReserves The reserves of the bin
    /// @param amountsIn The amounts of tokens to add
    /// @param price The price of the bin
    /// @param totalSupply The total supply of the liquidity book
    /// @return shares The share of the liquidity book that the user will receive
    /// @return effectiveAmountsIn The encoded effective amounts of tokens that the user will add.
    /// This is the amount of tokens that the user will actually add to the liquidity book,
    /// and will always be less than or equal to the amountsIn.
    function getSharesAndEffectiveAmountsIn(bytes32 binReserves, bytes32 amountsIn, uint256 price, uint256 totalSupply)
        internal
        pure
        returns (uint256 shares, bytes32 effectiveAmountsIn)
    {
        (uint256 x, uint256 y) = amountsIn.decode();

        uint256 userLiquidity = getLiquidity(x, y, price);
        if (totalSupply == 0 || userLiquidity == 0) return (userLiquidity, amountsIn);

        // current bin liquidity
        uint256 binLiquidity = getLiquidity(binReserves, price);
        if (binLiquidity == 0) return (userLiquidity, amountsIn);

        shares = userLiquidity.mulDivRoundDown(totalSupply, binLiquidity);
        uint256 effectiveLiquidity = shares.mulDivRoundUp(binLiquidity, totalSupply);

        if (userLiquidity > effectiveLiquidity) {
            uint256 deltaLiquidity = userLiquidity - effectiveLiquidity;

            // The other way might be more efficient, but as y is the quote asset, it is more valuable
            if (deltaLiquidity >= Constants.SCALE) {
                uint256 deltaY = deltaLiquidity >> Constants.SCALE_OFFSET;
                deltaY = deltaY > y ? y : deltaY;

                unchecked {
                    y -= deltaY;
                }
                deltaLiquidity -= deltaY << Constants.SCALE_OFFSET;
            }

            if (deltaLiquidity >= price) {
                uint256 deltaX = deltaLiquidity / price;
                deltaX = deltaX > x ? x : deltaX;

                unchecked {
                    x -= deltaX;
                }
            }

            amountsIn = uint128(x).encode(uint128(y));
        }

        return (shares, amountsIn);
    }

    /// @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
    /// @param amounts The amounts of tokens
    /// @param price The price of the bin
    /// @return liquidity The amount of liquidity
    function getLiquidity(bytes32 amounts, uint256 price) internal pure returns (uint256 liquidity) {
        (uint256 x, uint256 y) = amounts.decode();
        return getLiquidity(x, y, price);
    }

    /// @dev Returns the amount of liquidity following the constant sum formula `L = price * x + y`
    /// @param x The amount of the token X
    /// @param y The amount of the token Y
    /// @param price The price of the bin
    /// @return liquidity The amount of liquidity
    function getLiquidity(uint256 x, uint256 y, uint256 price) internal pure returns (uint256 liquidity) {
        if (x > 0) {
            // equivalent to
            //   liquidity = price * x;
            //   if (liquidity / x != price) revert BinHelper__LiquidityOverflow();
            assembly ("memory-safe") {
                liquidity := mul(price, x)
                if iszero(eq(div(liquidity, x), price)) {
                    mstore(0x00, 0x63f1e01f) // selector BinHelper__LiquidityOverflow
                    revert(0x1c, 0x04)
                }
            }
        }
        if (y > 0) {
            // equivalent to
            //   y <<= Constants.SCALE_OFFSET;
            //   liquidity += y;
            //   if (liquidity < y) revert BinHelper__LiquidityOverflow();
            uint8 offset = Constants.SCALE_OFFSET;
            assembly ("memory-safe") {
                y := shl(offset, y)
                liquidity := add(liquidity, y)

                // Check for overflow: if liquidity < y, revert with error
                if lt(liquidity, y) {
                    mstore(0x00, 0x63f1e01f) // selector BinHelper__LiquidityOverflow
                    revert(0x1c, 0x04)
                }
            }
        }

        return liquidity;
    }

    /// @dev Verify that the amounts are correct and that the composition factor is not flawed
    /// @param amounts The amounts of tokens
    /// @param activeId The id of the active bin
    /// @param id The id of the bin
    function verifyAmounts(bytes32 amounts, uint24 activeId, uint24 id) internal pure {
        if ((id < activeId && (amounts << 128) > 0) || (id > activeId && uint256(amounts) > type(uint128).max)) {
            revert BinHelper__CompositionFactorFlawed(id);
        }
    }

    /// @dev Returns the composition fees when adding liquidity to the active bin with a different
    ///      composition factor than the bin's one, as it does an implicit swap
    /// @param binReserves The reserves of the bin
    /// @param protocolFee 100 = 0.01%, 1000 = 0.1%
    /// @param lpFee 100 = 0.01%, 1000 = 0.1%
    /// @param amountsIn The amounts of tokens to add
    /// @param totalSupply The total supply of the liquidity book
    /// @param shares The share of the liquidity book that the user will receive
    /// @return feesAmount The encoded fees that will be charged (including protocol and LP fee)
    /// @return feeAmountToProtocol The encoded protocol fee that will be charged
    function getCompositionFeesAmount(
        bytes32 binReserves,
        uint24 protocolFee, // fee: 100 = 0.01%
        uint24 lpFee,
        bytes32 amountsIn,
        uint256 totalSupply,
        uint256 shares
    ) internal pure returns (bytes32 feesAmount, bytes32 feeAmountToProtocol) {
        if (shares == 0) return (0, 0);

        (uint128 amountX, uint128 amountY) = amountsIn.decode();
        (uint128 receivedAmountX, uint128 receivedAmountY) =
            getAmountOutOfBin(binReserves.add(amountsIn), shares, totalSupply + shares).decode();

        // if received more X than given X, then swap some Y for X
        if (receivedAmountX > amountX) {
            protocolFee = protocolFee.getOneForZeroFee();
            uint24 swapFee = uint16(protocolFee).calculateSwapFee(lpFee);

            uint128 amtSwapped = amountY - receivedAmountY;
            feesAmount = amtSwapped.getCompositionFee(swapFee).encodeSecond();
            feeAmountToProtocol = amtSwapped.getCompositionFee(protocolFee).encodeSecond();
        } else if (receivedAmountY > amountY) {
            protocolFee = protocolFee.getZeroForOneFee();
            uint24 swapFee = uint16(protocolFee).calculateSwapFee(lpFee);

            uint128 amtSwapped = amountX - receivedAmountX;
            feesAmount = amtSwapped.getCompositionFee(swapFee).encodeFirst();
            feeAmountToProtocol = amtSwapped.getCompositionFee(protocolFee).encodeFirst();
        }
    }

    /// @dev Returns whether the bin is empty (true) or not (false)
    /// @param binReserves The reserves of the bin
    /// @param isX Whether the reserve to check is the X reserve (true) or the Y reserve (false)
    /// @return Whether the bin is empty (true) or not (false)
    function isEmpty(bytes32 binReserves, bool isX) internal pure returns (bool) {
        return isX ? binReserves.decodeX() == 0 : binReserves.decodeY() == 0;
    }

    /// @dev Returns the amounts of tokens that will be added and removed from the bin during a exactOut swap
    ///     along with the fees that will be charged
    /// @param binReserves The reserves of the bin
    /// @param fee 100 = 0.01%, 1_000 = 0.1%
    /// @param binStep The step of the bin
    /// @param swapForY Whether the swap is for Y (true) or for X (false)
    /// @param activeId The id of the active bin
    /// @param amountsOutLeft The amounts of tokens out left
    /// @return amountsInWithFees The encoded amounts of tokens that will be added to the bin, including fees
    /// @return amountsOutOfBin The encoded amounts of tokens that will be removed from the bin
    /// @return totalFees The encoded fees that will be charged
    function getAmountsIn(
        bytes32 binReserves,
        uint24 fee,
        uint16 binStep,
        bool swapForY,
        uint24 activeId,
        bytes32 amountsOutLeft
    ) internal pure returns (bytes32 amountsInWithFees, bytes32 amountsOutOfBin, bytes32 totalFees) {
        uint256 price = activeId.getPriceFromId(binStep);
        uint128 binReserveOut = binReserves.decode(!swapForY);
        uint128 amountOutLeft128 = amountsOutLeft.decode(!swapForY);

        // amountOutOfBin = if bin reserve has > amountOut, then amountOutOfBin = amountOut
        uint128 amountOutOfBin = binReserveOut > amountOutLeft128 ? amountOutLeft128 : binReserveOut;

        uint128 amountInWithoutFee = swapForY
            ? uint256(amountOutOfBin).shiftDivRoundUp(Constants.SCALE_OFFSET, price).safe128()
            : uint256(amountOutOfBin).mulShiftRoundUp(price, Constants.SCALE_OFFSET).safe128();

        uint128 feeAmount = amountInWithoutFee.getFeeAmount(fee);
        uint128 amountIn = amountInWithoutFee + feeAmount;

        (amountsInWithFees, amountsOutOfBin, totalFees) = swapForY
            ? (amountIn.encodeFirst(), amountOutOfBin.encodeSecond(), feeAmount.encodeFirst())
            : (amountIn.encodeSecond(), amountOutOfBin.encodeFirst(), feeAmount.encodeSecond());
    }

    /// @dev Returns the amounts of tokens that will be added and removed from the bin during a exactIn swap
    ///     along with the fees that will be charged
    /// @param binReserves The reserves of the bin
    /// @param fee 100 = 0.01%, 1_000 = 0.1%
    /// @param binStep The step of the bin
    /// @param swapForY Whether the swap is for Y (true) or for X (false)
    /// @param activeId The id of the active bin
    /// @param amountsInLeft The amounts of tokens left to swap
    /// @return amountsInWithFees The encoded amounts of tokens that will be added to the bin, including fees
    /// @return amountsOutOfBin The encoded amounts of tokens that will be removed from the bin
    /// @return totalFees The encoded fees that will be charged
    function getAmountsOut(
        bytes32 binReserves,
        uint24 fee,
        uint16 binStep,
        bool swapForY, // swap `swapForY` and `activeId` to avoid stack too deep
        uint24 activeId,
        bytes32 amountsInLeft
    ) internal pure returns (bytes32 amountsInWithFees, bytes32 amountsOutOfBin, bytes32 totalFees) {
        uint256 price = activeId.getPriceFromId(binStep);

        uint128 binReserveOut = binReserves.decode(!swapForY);

        uint128 maxAmountIn = swapForY
            ? uint256(binReserveOut).shiftDivRoundUp(Constants.SCALE_OFFSET, price).safe128()
            : uint256(binReserveOut).mulShiftRoundUp(price, Constants.SCALE_OFFSET).safe128();

        uint128 maxFee = maxAmountIn.getFeeAmount(fee);

        maxAmountIn += maxFee;

        uint128 amountIn128 = amountsInLeft.decode(swapForY);
        uint128 fee128;
        uint128 amountOut128;

        if (amountIn128 >= maxAmountIn) {
            fee128 = maxFee;

            amountIn128 = maxAmountIn;
            amountOut128 = binReserveOut;
        } else {
            fee128 = amountIn128.getFeeAmountFrom(fee);

            uint256 amountIn = amountIn128 - fee128;

            amountOut128 = swapForY
                ? uint256(amountIn).mulShiftRoundDown(price, Constants.SCALE_OFFSET).safe128()
                : uint256(amountIn).shiftDivRoundDown(Constants.SCALE_OFFSET, price).safe128();

            if (amountOut128 > binReserveOut) amountOut128 = binReserveOut;
        }

        (amountsInWithFees, amountsOutOfBin, totalFees) = swapForY
            ? (amountIn128.encodeFirst(), amountOut128.encodeSecond(), fee128.encodeFirst())
            : (amountIn128.encodeSecond(), amountOut128.encodeFirst(), fee128.encodeSecond());
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title BinPosition
/// @notice Positions represent an owner address' share for a bin
library BinPosition {
    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct Info {
        // the amount of share owned by this position
        uint256 share;
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param binId The bin id where the position's liquidity is added
    /// @param salt A unique value to differentiate between multiple positions in the same binId, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, uint24 binId, bytes32 salt) internal pure returns (bytes32 key) {
        // dev same as `positionKey = keccak256(abi.encodePacked(binId, owner, salt))`
        // make salt, binId, owner to be tightly packed in memory
        assembly ("memory-safe") {
            mstore(0x0, or(shl(160, binId), and(owner, 0xffffffffffffffffffffffffffffffffffffffff))) // binId at [0x09,0x0c), owner at [0x0c, 0x20)
            mstore(0x20, salt) // salt at [0x20, 0x40)
            key := keccak256(0x09, 0x37)
        }
    }

    /// @notice Returns the Info 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 binId The bin id where the position's liquidity is added
    /// @param salt The salt to distinguish different positions for the same owner
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => Info) storage self, address owner, uint24 binId, bytes32 salt)
        internal
        view
        returns (BinPosition.Info storage position)
    {
        bytes32 key = calculatePositionKey(owner, binId, salt);
        position = self[key];
    }

    function addShare(Info storage self, uint256 share) internal {
        self.share += share;
    }

    function subShare(Info storage self, uint256 share) internal {
        self.share -= share;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice This library contains functions to safely cast uint256 to different uint types.
library SafeCast {
    error SafeCastOverflow();

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

    /// @dev Returns x on uint248 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint248
    function safe248(uint256 x) internal pure returns (uint248 y) {
        if ((y = uint248(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint240 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint240
    function safe240(uint256 x) internal pure returns (uint240 y) {
        if ((y = uint240(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint232 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint232
    function safe232(uint256 x) internal pure returns (uint232 y) {
        if ((y = uint232(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint224 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint224
    function safe224(uint256 x) internal pure returns (uint224 y) {
        if ((y = uint224(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint216 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint216
    function safe216(uint256 x) internal pure returns (uint216 y) {
        if ((y = uint216(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint208 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint208
    function safe208(uint256 x) internal pure returns (uint208 y) {
        if ((y = uint208(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint200 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint200
    function safe200(uint256 x) internal pure returns (uint200 y) {
        if ((y = uint200(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint192 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint192
    function safe192(uint256 x) internal pure returns (uint192 y) {
        if ((y = uint192(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint184 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint184
    function safe184(uint256 x) internal pure returns (uint184 y) {
        if ((y = uint184(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint176 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint176
    function safe176(uint256 x) internal pure returns (uint176 y) {
        if ((y = uint176(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint168 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint168
    function safe168(uint256 x) internal pure returns (uint168 y) {
        if ((y = uint168(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint160 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint160
    function safe160(uint256 x) internal pure returns (uint160 y) {
        if ((y = uint160(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint152 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint152
    function safe152(uint256 x) internal pure returns (uint152 y) {
        if ((y = uint152(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint144 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint144
    function safe144(uint256 x) internal pure returns (uint144 y) {
        if ((y = uint144(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint136 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint136
    function safe136(uint256 x) internal pure returns (uint136 y) {
        if ((y = uint136(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint128 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint128
    function safe128(uint256 x) internal pure returns (uint128 y) {
        if ((y = uint128(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint120 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint120
    function safe120(uint256 x) internal pure returns (uint120 y) {
        if ((y = uint120(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint112 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint112
    function safe112(uint256 x) internal pure returns (uint112 y) {
        if ((y = uint112(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint104 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint104
    function safe104(uint256 x) internal pure returns (uint104 y) {
        if ((y = uint104(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint96 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint96
    function safe96(uint256 x) internal pure returns (uint96 y) {
        if ((y = uint96(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint88 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint88
    function safe88(uint256 x) internal pure returns (uint88 y) {
        if ((y = uint88(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint80 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint80
    function safe80(uint256 x) internal pure returns (uint80 y) {
        if ((y = uint80(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint72 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint72
    function safe72(uint256 x) internal pure returns (uint72 y) {
        if ((y = uint72(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint64 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint64
    function safe64(uint256 x) internal pure returns (uint64 y) {
        if ((y = uint64(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint56 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint56
    function safe56(uint256 x) internal pure returns (uint56 y) {
        if ((y = uint56(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint48 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint48
    function safe48(uint256 x) internal pure returns (uint48 y) {
        if ((y = uint48(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint40 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint40
    function safe40(uint256 x) internal pure returns (uint40 y) {
        if ((y = uint40(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint32 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint32
    function safe32(uint256 x) internal pure returns (uint32 y) {
        if ((y = uint32(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint24 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint24
    function safe24(uint256 x) internal pure returns (uint24 y) {
        if ((y = uint24(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint16 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint16
    function safe16(uint256 x) internal pure returns (uint16 y) {
        if ((y = uint16(x)) != x) _revertOverflow();
    }

    /// @dev Returns x on uint8 and check that it does not overflow
    /// @param x The value as an uint256
    /// @return y The value as an uint8
    function safe8(uint256 x) internal pure returns (uint8 y) {
        if ((y = uint8(x)) != x) _revertOverflow();
    }

    /// @dev Return x on int128 and check that it does not overflow
    /// @param x The value as uint128
    /// @return y The value as int128
    function safeInt128(uint128 x) internal pure returns (int128 y) {
        if (x > uint128(type(int128).max)) _revertOverflow();
        y = int128(x);
    }
}

File 107 of 120 : Constants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice Set of constants for BinPool
library Constants {
    uint8 internal constant SCALE_OFFSET = 128;
    uint256 internal constant SCALE = 1 << SCALE_OFFSET;

    uint256 internal constant PRECISION = 1e18;
    uint256 internal constant SQUARED_PRECISION = PRECISION * PRECISION;

    uint256 internal constant BASIS_POINT_MAX = 10_000;

    // (2^256 - 1) / (2 * log(2**128) / log(1.0001))
    uint256 internal constant MAX_LIQUIDITY_PER_BIN =
        65251743116719673010965625540244653191619923014385985379600384103134737;
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

/// @notice Helper to calculate fees for BinPool
library FeeHelper {
    /// @dev Calculates the fee amount from the amount with fees, rounding up
    /// @param amountWithFees The amount with fees
    /// @param feeBips feeBips - 100 = 0.01%, 1_000 = 0.1%, 100_000 = 10% (max)
    /// @return feeAmount The fee amount
    function getFeeAmountFrom(uint128 amountWithFees, uint24 feeBips) internal pure returns (uint128) {
        unchecked {
            uint128 totalFee = uint128(feeBips) * 1e12;
            // Can't overflow, max(result) = (type(uint128).max * 0.1e18 + 1e18 - 1) / 1e18 < 2^128
            return uint128((uint256(amountWithFees) * totalFee + Constants.PRECISION - 1) / Constants.PRECISION);
        }
    }

    /// @dev Calculates the fee amount that will be charged, rounding up
    /// @param amount The amount
    /// @param feeBips feeBips - 100 = 0.01%, 1_000 = 0.1%, 100_000 = 10% (max)
    /// @return feeAmount The fee amount
    function getFeeAmount(uint128 amount, uint24 feeBips) internal pure returns (uint128) {
        unchecked {
            uint128 totalFee = uint128(feeBips) * 1e12;
            uint256 denominator = Constants.PRECISION - totalFee;
            // Can't overflow, max(result) = (type(uint128).max * 0.1e18 + (1e18 - 1)) / 0.9e18 < 2^128
            return uint128((uint256(amount) * totalFee + denominator - 1) / denominator);
        }
    }

    /// @notice Calculates the composition fee amount from the amount with fees, rounding down
    /// @dev Composition fee is higher than swapFee to ensure user do not does an implicit swap through mint to take advantage of lower fees
    /// @param amountWithFees The amount with fees
    /// @param feeBips The total fee, 100 = 0.01%, 10_000 = 1%, 100_000 = 10% (max)
    /// @return The amount with fees
    function getCompositionFee(uint128 amountWithFees, uint24 feeBips) internal pure returns (uint128) {
        unchecked {
            uint128 totalFee = uint128(feeBips) * 1e12;
            uint256 denominator = Constants.SQUARED_PRECISION; // 1e36
            // Can't overflow, max(result) = type(uint128).max * 0.1e18 * 1.1e18 / 1e36 <= 2^128 * 0.11e36 / 1e36 < 2^128
            return
                uint128((uint256(amountWithFees) * totalFee * (uint256(totalFee) + Constants.PRECISION)) / denominator);
        }
    }
}

//SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {Currency} from "infinity-core/src/types/Currency.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {IHooks} from "infinity-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "infinity-core/src/interfaces/IPoolManager.sol";

struct PathKey {
    Currency intermediateCurrency;
    uint24 fee;
    IHooks hooks;
    IPoolManager poolManager;
    bytes hookData;
    bytes32 parameters;
}

using PathKeyLibrary for PathKey global;

library PathKeyLibrary {
    /// @notice Get the pool and swap direction for a given PathKey
    /// @param params the given PathKey
    /// @param currencyIn the input currency
    /// @return poolKey the pool key of the swap
    /// @return zeroForOne the direction of the swap, true if currency0 is being swapped for currency1
    function getPoolAndSwapDirection(PathKey memory params, Currency currencyIn)
        internal
        pure
        returns (PoolKey memory poolKey, bool zeroForOne)
    {
        (Currency currency0, Currency currency1) = currencyIn < params.intermediateCurrency
            ? (currencyIn, params.intermediateCurrency)
            : (params.intermediateCurrency, currencyIn);

        zeroForOne = currencyIn == currency0;
        poolKey = PoolKey(currency0, currency1, params.hooks, params.poolManager, params.fee, params.parameters);
    }
}

File 110 of 120 : ICLRouterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Currency} from "infinity-core/src/types/Currency.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {PathKey} from "../../libraries/PathKey.sol";
import {IImmutableState} from "../../interfaces/IImmutableState.sol";

interface ICLRouterBase is IImmutableState {
    /// @notice Parameters for a single-hop exact-input swap
    struct CLSwapExactInputSingleParams {
        PoolKey poolKey;
        bool zeroForOne;
        uint128 amountIn;
        uint128 amountOutMinimum;
        bytes hookData;
    }

    /// @notice Parameters for a multi-hop exact-input swap
    struct CLSwapExactInputParams {
        Currency currencyIn;
        PathKey[] path;
        uint128 amountIn;
        uint128 amountOutMinimum;
    }

    /// @notice Parameters for a single-hop exact-output swap
    struct CLSwapExactOutputSingleParams {
        PoolKey poolKey;
        bool zeroForOne;
        uint128 amountOut;
        uint128 amountInMaximum;
        bytes hookData;
    }

    /// @notice Parameters for a multi-hop exact-output swap
    struct CLSwapExactOutputParams {
        Currency currencyOut;
        PathKey[] path;
        uint128 amountOut;
        uint128 amountInMaximum;
    }
}

File 111 of 120 : IBinRouterBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {Currency} from "infinity-core/src/types/Currency.sol";
import {PathKey} from "../../libraries/PathKey.sol";
import {IImmutableState} from "../../interfaces/IImmutableState.sol";

interface IBinRouterBase is IImmutableState {
    struct BinSwapExactInputSingleParams {
        PoolKey poolKey;
        bool swapForY;
        uint128 amountIn;
        uint128 amountOutMinimum;
        bytes hookData;
    }

    struct BinSwapExactInputParams {
        Currency currencyIn;
        PathKey[] path;
        uint128 amountIn;
        uint128 amountOutMinimum;
    }

    struct BinSwapExactOutputSingleParams {
        PoolKey poolKey;
        bool swapForY;
        uint128 amountOut;
        uint128 amountInMaximum;
        bytes hookData;
    }

    struct BinSwapExactOutputParams {
        Currency currencyOut;
        PathKey[] path;
        uint128 amountOut;
        uint128 amountInMaximum;
    }
}

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

import {PoolId} from "infinity-core/src/types/PoolId.sol";
import {PoolKey} from "infinity-core/src/types/PoolKey.sol";
import {Currency} from "infinity-core/src/types/Currency.sol";
import {IBinPoolManager} from "infinity-core/src/pool-bin/interfaces/IBinPoolManager.sol";
import {IPositionManager} from "../../interfaces/IPositionManager.sol";

interface IBinPositionManager is IPositionManager {
    error IdOverflows(int256);
    error IdSlippageCaught(uint256 activeIdDesired, uint256 idSlippage, uint24 activeId);
    error AddLiquidityInputActiveIdMismath();

    /// @notice BinAddLiquidityParams
    /// - amount0: Amount to send for token0
    /// - amount1: Amount to send for token1
    /// - amount0Max: Max amount to send for token0
    /// - amount1Max: Max amount to send for token1
    /// - activeIdDesired: Active id that user wants to add liquidity from
    /// - idSlippage: Number of id that are allowed to slip
    /// - deltaIds: List of delta ids to add liquidity (`deltaId = activeId - desiredId`)
    /// - distributionX: Distribution of tokenX with sum(distributionX) = 1e18 (100%) or 0 (0%)
    /// - distributionY: Distribution of tokenY with sum(distributionY) = 1e18 (100%) or 0 (0%)
    /// - to: Address of recipient
    /// - hookData: Data to pass to the hook
    struct BinAddLiquidityParams {
        PoolKey poolKey;
        uint128 amount0;
        uint128 amount1;
        uint128 amount0Max;
        uint128 amount1Max;
        uint256 activeIdDesired;
        uint256 idSlippage;
        int256[] deltaIds;
        uint256[] distributionX;
        uint256[] distributionY;
        address to;
        bytes hookData;
    }

    /// @notice BinRemoveLiquidityParams
    /// - amount0Min: Min amount to recieve for token0
    /// - amount1Min: Min amount to recieve for token1
    /// - ids: List of bin ids to remove liquidity
    /// - amounts: List of share amount to remove for each bin
    /// - from: Address of NFT holder to burn the NFT
    /// - hookData: Data to pass to the hook
    struct BinRemoveLiquidityParams {
        PoolKey poolKey;
        uint128 amount0Min;
        uint128 amount1Min;
        uint256[] ids;
        uint256[] amounts;
        address from;
        bytes hookData;
    }

    /// @notice BinAddLiquidityFromDeltasParams
    /// - amount0Max: Max amount to send for token0
    /// - amount1Max: Max amount to send for token1
    /// - activeIdDesired: Active id that user wants to add liquidity from
    /// - idSlippage: Number of id that are allowed to slip
    /// - deltaIds: List of delta ids to add liquidity (`deltaId = activeId - desiredId`)
    /// - distributionX: Distribution of tokenX with sum(distributionX) = 1e18 (100%) or 0 (0%)
    /// - distributionY: Distribution of tokenY with sum(distributionY) = 1e18 (100%) or 0 (0%)
    /// - to: Address of recipient
    /// - hookData: Data to pass to the hook
    struct BinAddLiquidityFromDeltasParams {
        PoolKey poolKey;
        uint128 amount0Max;
        uint128 amount1Max;
        uint256 activeIdDesired;
        uint256 idSlippage;
        int256[] deltaIds;
        uint256[] distributionX;
        uint256[] distributionY;
        address to;
        bytes hookData;
    }

    function binPoolManager() external view returns (IBinPoolManager);

    /// @notice Initialize a infinity PCS bin pool
    /// @dev If the pool is already initialized, this function will not revert
    /// @param key the PoolKey of the pool to initialize
    /// @param activeId the active bin id of the pool
    function initializePool(PoolKey memory key, uint24 activeId) external payable;

    /// @notice Return the position information associated with a given tokenId
    /// @dev Revert if non-existent tokenId
    /// @param tokenId Id of the token that represent position
    /// @return poolKey the pool key of the position
    /// @return binId the binId of the position
    function positions(uint256 tokenId) external view returns (PoolKey memory poolKey, uint24 binId);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
/// TODO after audits move this function to core's SafeCast.sol!
library SafeCastTemp {
    error SafeCastOverflow();

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

    /// @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) revert SafeCastOverflow();
        y = uint128(x);
    }

    /// @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) revert SafeCastOverflow();
        return int128(int256(x));
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
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 := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @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, add(not(x), 1))
            // 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))
        }
    }
}

File 116 of 120 : FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
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: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/**
 * @notice Helper contract used for decoding bytes32
 */
library Encoded {
    uint256 internal constant MASK_UINT1 = 0x1;
    uint256 internal constant MASK_UINT16 = 0xffff;
    uint256 internal constant MASK_UINT24 = 0xffffff;
    uint256 internal constant MASK_UINT64 = 0xffffffffffffffff;

    /**
     * @notice Internal function to set a value in an encoded bytes32 using a mask and offset
     * @dev This function can overflow
     * @param encoded The previous encoded value
     * @param value The value to encode
     * @param mask The mask
     * @param offset The offset
     * @return newEncoded The new encoded value
     */
    function set(bytes32 encoded, uint256 value, uint256 mask, uint256 offset)
        internal
        pure
        returns (bytes32 newEncoded)
    {
        assembly ("memory-safe") {
            newEncoded := and(encoded, not(shl(offset, mask)))
            newEncoded := or(newEncoded, shl(offset, and(value, mask)))
        }
    }

    /**
     * @notice Internal function to set a bool in an encoded bytes32 using an offset
     * @dev This function can overflow
     * @param encoded The previous encoded value
     * @param boolean The bool to encode
     * @param offset The offset
     * @return newEncoded The new encoded value
     */
    function setBool(bytes32 encoded, bool boolean, uint256 offset) internal pure returns (bytes32 newEncoded) {
        return set(encoded, boolean ? 1 : 0, MASK_UINT1, offset);
    }

    /**
     * @notice Internal function to decode a bytes32 sample using a mask and offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param mask The mask
     * @param offset The offset
     * @return value The decoded value
     */
    function decode(bytes32 encoded, uint256 mask, uint256 offset) internal pure returns (uint256 value) {
        assembly ("memory-safe") {
            value := and(shr(offset, encoded), mask)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a bool using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return boolean The decoded value as a bool
     */
    function decodeBool(bytes32 encoded, uint256 offset) internal pure returns (bool boolean) {
        assembly ("memory-safe") {
            boolean := and(shr(offset, encoded), MASK_UINT1)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint16 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint16(bytes32 encoded, uint256 offset) internal pure returns (uint16 value) {
        assembly ("memory-safe") {
            value := and(shr(offset, encoded), MASK_UINT16)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint24 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint24(bytes32 encoded, uint256 offset) internal pure returns (uint24 value) {
        assembly ("memory-safe") {
            value := and(shr(offset, encoded), MASK_UINT24)
        }
    }

    /**
     * @notice Internal function to decode a bytes32 sample into a uint64 using an offset
     * @dev This function can overflow
     * @param encoded The encoded value
     * @param offset The offset
     * @return value The decoded value
     */
    function decodeUint64(bytes32 encoded, uint256 offset) internal pure returns (uint64 value) {
        assembly ("memory-safe") {
            value := and(shr(offset, encoded), MASK_UINT64)
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

/// @notice Helper contract used for bit calculations
library BitMath {
    /// @dev Returns the index of the closest bit on the right of x that is non null
    /// @param x The value as a uint256
    /// @param bit The index of the bit to start searching at
    /// @return id The index of the closest non null bit on the right of x. If there is no closest bit, it returns max(uint256)
    function closestBitRight(uint256 x, uint8 bit) internal pure returns (uint256 id) {
        unchecked {
            uint256 shift = 255 - bit;
            x <<= shift;

            // can't overflow as it's non-zero and we shifted it by `_shift`
            return (x == 0) ? type(uint256).max : mostSignificantBit(x) - shift;
        }
    }

    /// @dev Returns the index of the closest bit on the left of x that is non null
    /// @param x The value as a uint256
    /// @param bit The index of the bit to start searching at
    /// @return id The index of the closest non null bit on the left of x.If there is no closest bit, it returns max(uint256)
    function closestBitLeft(uint256 x, uint8 bit) internal pure returns (uint256 id) {
        unchecked {
            x >>= bit;

            return (x == 0) ? type(uint256).max : leastSignificantBit(x) + bit;
        }
    }

    /// @dev Returns the index of the most significant bit of x. This function returns 0 if x is 0
    /// @param x The value as a uint256
    /// @return msb The index of the most significant bit of x
    function mostSignificantBit(uint256 x) internal pure returns (uint8 msb) {
        assembly ("memory-safe") {
            if gt(x, 0xffffffffffffffffffffffffffffffff) {
                x := shr(128, x)
                msb := 128
            }
            if gt(x, 0xffffffffffffffff) {
                x := shr(64, x)
                msb := add(msb, 64)
            }
            if gt(x, 0xffffffff) {
                x := shr(32, x)
                msb := add(msb, 32)
            }
            if gt(x, 0xffff) {
                x := shr(16, x)
                msb := add(msb, 16)
            }
            if gt(x, 0xff) {
                x := shr(8, x)
                msb := add(msb, 8)
            }
            if gt(x, 0xf) {
                x := shr(4, x)
                msb := add(msb, 4)
            }
            if gt(x, 0x3) {
                x := shr(2, x)
                msb := add(msb, 2)
            }
            if gt(x, 0x1) { msb := add(msb, 1) }
        }
    }

    /// @dev Returns the index of the least significant bit of x. This function returns 255 if x is 0
    /// @param x The value as a uint256
    /// @return lsb The index of the least significant bit of x
    function leastSignificantBit(uint256 x) internal pure returns (uint8 lsb) {
        assembly ("memory-safe") {
            let sx := shl(128, x)
            if iszero(iszero(sx)) {
                lsb := 128
                x := sx
            }
            sx := shl(64, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 64)
            }
            sx := shl(32, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 32)
            }
            sx := shl(16, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 16)
            }
            sx := shl(8, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 8)
            }
            sx := shl(4, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 4)
            }
            sx := shl(2, x)
            if iszero(iszero(sx)) {
                x := sx
                lsb := add(lsb, 2)
            }
            if iszero(iszero(shl(1, x))) { lsb := add(lsb, 1) }

            lsb := sub(255, lsb)
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

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

/// @notice Helper contract used for power and log calculations
library Uint128x128Math {
    using BitMath for uint256;

    error Uint128x128Math__LogUnderflow();
    error Uint128x128Math__PowUnderflow(uint256 x, int256 y);

    uint256 internal constant LOG_SCALE_OFFSET = 127;
    uint256 internal constant LOG_SCALE = 1 << LOG_SCALE_OFFSET;
    uint256 internal constant LOG_SCALE_SQUARED = LOG_SCALE * LOG_SCALE;

    /// @notice Calculates the binary logarithm of x.
    /// @dev Based on the iterative approximation algorithm.
    /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
    /// Requirements:
    /// - x must be greater than zero.
    /// Caveats:
    /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation
    /// Also because x is converted to an unsigned 129.127-binary fixed-point number during the operation to optimize the multiplication
    /// @param x The unsigned 128.128-binary fixed-point number for which to calculate the binary logarithm.
    /// @return result The binary logarithm as a signed 128.128-binary fixed-point number.
    function log2(uint256 x) internal pure returns (int256 result) {
        // Convert x to a unsigned 129.127-binary fixed-point number to optimize the multiplication.
        // If we use an offset of 128 bits, y would need 129 bits and y**2 would would overflow and we would have to
        // use mulDiv, by reducing x to 129.127-binary fixed-point number we assert that y will use 128 bits, and we
        // can use the regular multiplication

        if (x == 1) return -128;
        if (x == 0) revert Uint128x128Math__LogUnderflow();

        x >>= 1;

        unchecked {
            // This works because log2(x) = -log2(1/x).
            int256 sign;
            if (x >= LOG_SCALE) {
                sign = 1;
            } else {
                sign = -1;
                // Do the fixed-point inversion inline to save gas
                x = LOG_SCALE_SQUARED / x;
            }

            // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
            uint256 n = (x >> LOG_SCALE_OFFSET).mostSignificantBit();

            // The integer part of the logarithm as a signed 129.127-binary fixed-point number. The operation can't overflow
            // because n is maximum 255, LOG_SCALE_OFFSET is 127 bits and sign is either 1 or -1.
            result = int256(n) << LOG_SCALE_OFFSET;

            // This is y = x * 2^(-n).
            uint256 y = x >> n;

            // If y = 1, the fractional part is zero.
            if (y != LOG_SCALE) {
                // Calculate the fractional part via the iterative approximation.
                // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
                for (int256 delta = int256(1 << (LOG_SCALE_OFFSET - 1)); delta > 0; delta >>= 1) {
                    y = (y * y) >> LOG_SCALE_OFFSET;

                    // Is y^2 > 2 and so in the range [2,4)?
                    if (y >= 1 << (LOG_SCALE_OFFSET + 1)) {
                        // Add the 2^(-m) factor to the logarithm.
                        result += delta;

                        // Corresponds to z/2 on Wikipedia.
                        y >>= 1;
                    }
                }
            }
            // Convert x back to unsigned 128.128-binary fixed-point number
            result = (result * sign) << 1;
        }
    }

    /// @notice Returns the value of x^y. It calculates `1 / x^abs(y)` if x is bigger than 2^128.
    ///     At the end of the operations, we invert the result if needed.
    /// @param x The unsigned 128.128-binary fixed-point number for which to calculate the power
    /// @param y A relative number without any decimals, needs to be between ]2^21; 2^21[
    function pow(uint256 x, int256 y) internal pure returns (uint256 result) {
        bool invert;
        uint256 absY;

        if (y == 0) return Constants.SCALE;

        assembly ("memory-safe") {
            absY := y
            if slt(absY, 0) {
                absY := sub(0, absY)
                invert := iszero(invert)
            }
        }

        if (absY < 0x100000) {
            result = Constants.SCALE;
            assembly ("memory-safe") {
                let squared := x
                if gt(x, 0xffffffffffffffffffffffffffffffff) {
                    squared := div(not(0), squared)
                    invert := iszero(invert)
                }

                if and(absY, 0x1) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x2) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x4) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x8) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x10) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x20) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x40) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x80) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x100) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x200) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x400) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x800) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x1000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x2000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x4000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x8000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x10000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x20000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x40000) { result := shr(128, mul(result, squared)) }
                squared := shr(128, mul(squared, squared))
                if and(absY, 0x80000) { result := shr(128, mul(result, squared)) }
            }
        }

        // revert if y is too big or if x^y underflowed
        if (result == 0) revert Uint128x128Math__PowUnderflow(x, y);

        return invert ? type(uint256).max / result : result;
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
pragma solidity ^0.8.0;

import {Encoded} from "../../libraries/math/Encoded.sol";

/// @title Bin Pool Pair Parameter Helper Library
/// @dev This library contains functions to get and set parameters of a pair
/// The parameters are stored in a single bytes32 variable in the following format:
/// [0 - 16[: reserve for hooks
/// [16 - 31[: binStep (16 bits)
/// [32 - 256[: unused
library BinPoolParametersHelper {
    using Encoded for bytes32;

    uint256 internal constant OFFSET_BIN_STEP = 16;
    uint256 internal constant OFFSET_MOST_SIGNIFICANT_UNUSED_BITS = 32;

    /// @dev Get binstep from the encoded pair parameters
    /// @param params The encoded pair parameters, as follows:
    /// [0 - 15[: bitmap for hooks registration
    /// [16 - 31[: binSteps (16 bits)
    /// [32 - 256[: unused
    /// @return binStep The binStep
    function getBinStep(bytes32 params) internal pure returns (uint16 binStep) {
        binStep = params.decodeUint16(OFFSET_BIN_STEP);
    }

    /**
     * @dev Helper method to set bin step in the encoded pair parameter
     * @return The new encoded pair parameter
     */
    function setBinStep(bytes32 params, uint16 binStep) internal pure returns (bytes32) {
        return params.set(binStep, Encoded.MASK_UINT16, OFFSET_BIN_STEP);
    }
}

Settings
{
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "@openzeppelin/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/",
    "openzeppelin-contracts/=lib/infinity-periphery/lib/infinity-core/lib/openzeppelin-contracts/",
    "solmate/=lib/infinity-periphery/lib/infinity-core/lib/solmate/",
    "infinity-periphery/=lib/infinity-periphery/",
    "infinity-core/=lib/infinity-periphery/lib/infinity-core/",
    "permit2/=lib/infinity-periphery/lib/permit2/",
    "pancake-create3-factory/=lib/pancake-create3-factory/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 20000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"components":[{"internalType":"address","name":"permit2","type":"address"},{"internalType":"address","name":"weth9","type":"address"},{"internalType":"address","name":"v2Factory","type":"address"},{"internalType":"address","name":"v3Factory","type":"address"},{"internalType":"address","name":"v3Deployer","type":"address"},{"internalType":"bytes32","name":"v2InitCodeHash","type":"bytes32"},{"internalType":"bytes32","name":"v3InitCodeHash","type":"bytes32"},{"internalType":"address","name":"stableFactory","type":"address"},{"internalType":"address","name":"stableInfo","type":"address"},{"internalType":"address","name":"infiVault","type":"address"},{"internalType":"address","name":"infiClPoolManager","type":"address"},{"internalType":"address","name":"infiBinPoolManager","type":"address"},{"internalType":"address","name":"v3NFTPositionManager","type":"address"},{"internalType":"address","name":"infiClPositionManager","type":"address"},{"internalType":"address","name":"infiBinPositionManager","type":"address"}],"internalType":"struct RouterParameters","name":"params","type":"tuple"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"BalanceTooLow","type":"error"},{"inputs":[],"name":"ContractLocked","type":"error"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"DeltaNotNegative","type":"error"},{"inputs":[{"internalType":"Currency","name":"currency","type":"address"}],"name":"DeltaNotPositive","type":"error"},{"inputs":[],"name":"ETHNotAccepted","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[{"internalType":"uint256","name":"commandIndex","type":"uint256"},{"internalType":"bytes","name":"message","type":"bytes"}],"name":"ExecutionFailed","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FromAddressIsNotOwner","type":"error"},{"inputs":[],"name":"InputLengthMismatch","type":"error"},{"inputs":[],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InsufficientETH","type":"error"},{"inputs":[],"name":"InsufficientToken","type":"error"},{"inputs":[{"internalType":"bytes4","name":"action","type":"bytes4"}],"name":"InvalidAction","type":"error"},{"inputs":[],"name":"InvalidBips","type":"error"},{"inputs":[{"internalType":"uint256","name":"commandType","type":"uint256"}],"name":"InvalidCommandType","type":"error"},{"inputs":[],"name":"InvalidEthSender","type":"error"},{"inputs":[],"name":"InvalidPath","type":"error"},{"inputs":[],"name":"InvalidPoolAddress","type":"error"},{"inputs":[],"name":"InvalidPoolLength","type":"error"},{"inputs":[],"name":"InvalidReserves","type":"error"},{"inputs":[],"name":"LengthMismatch","type":"error"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"NotAuthorizedForToken","type":"error"},{"inputs":[],"name":"NotVault","type":"error"},{"inputs":[],"name":"OnlyAddLiqudityAllowed","type":"error"},{"inputs":[],"name":"OnlyMintAllowed","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":"SafeCastOverflow","type":"error"},{"inputs":[],"name":"SliceOutOfBounds","type":"error"},{"inputs":[],"name":"StableInvalidPath","type":"error"},{"inputs":[],"name":"StableTooLittleReceived","type":"error"},{"inputs":[],"name":"StableTooMuchRequested","type":"error"},{"inputs":[{"internalType":"uint256","name":"minAmountOutReceived","type":"uint256"},{"internalType":"uint256","name":"amountReceived","type":"uint256"}],"name":"TooLittleReceived","type":"error"},{"inputs":[{"internalType":"uint256","name":"maxAmountInRequested","type":"uint256"},{"internalType":"uint256","name":"amountRequested","type":"uint256"}],"name":"TooMuchRequested","type":"error"},{"inputs":[],"name":"TransactionDeadlinePassed","type":"error"},{"inputs":[],"name":"UnsafeCast","type":"error"},{"inputs":[{"internalType":"uint256","name":"action","type":"uint256"}],"name":"UnsupportedAction","type":"error"},{"inputs":[],"name":"V2InvalidPath","type":"error"},{"inputs":[],"name":"V2TooLittleReceived","type":"error"},{"inputs":[],"name":"V2TooMuchRequested","type":"error"},{"inputs":[],"name":"V3InvalidAmountOut","type":"error"},{"inputs":[],"name":"V3InvalidCaller","type":"error"},{"inputs":[],"name":"V3InvalidSwap","type":"error"},{"inputs":[],"name":"V3TooLittleReceived","type":"error"},{"inputs":[],"name":"V3TooMuchRequested","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","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":"address","name":"factory","type":"address"},{"indexed":true,"internalType":"address","name":"info","type":"address"}],"name":"SetStableSwap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"INFI_BIN_POSITION_MANAGER","outputs":[{"internalType":"contract IPositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"INFI_CL_POSITION_MANAGER","outputs":[{"internalType":"contract IPositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"V3_POSITION_MANAGER","outputs":[{"internalType":"contract IV3NonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"binPoolManager","outputs":[{"internalType":"contract IBinPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"clPoolManager","outputs":[{"internalType":"contract ICLPoolManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"commands","type":"bytes"},{"internalType":"bytes[]","name":"inputs","type":"bytes[]"}],"name":"execute","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"commands","type":"bytes"},{"internalType":"bytes[]","name":"inputs","type":"bytes[]"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"execute","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"lockAcquired","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"msgSender","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"pancakeV3SwapCallback","outputs":[],"stateMutability":"nonpayable","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":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_info","type":"address"}],"name":"setStableSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stableSwapFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stableSwapInfo","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"contract IVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

610220604052346103d657604051601f61630d38819003918201601f19168301916001600160401b038311848410176103c2578084926101e0946040528339810103126103d6576040516101e081016001600160401b038111828210176103c25760405261006c826103da565b815261007a602083016103da565b906020810191825261008e604084016103da565b9260408201938452806100a3606082016103da565b606084019081526100b6608083016103da565b906080850191825260a08301519060a0860191825260c08401519160c087019283526100e460e086016103da565b988960e08901526100f861010087016103da565b98896101008a015261010d61012088016103da565b98896101208201528761012361014082016103da565b806101408401526101756101c06101666101a061015761018061014961016089016103da565b97886101608b0152016103da565b9d61018088019e8f52016103da565b9c6101a086019d8e52016103da565b6101c08481019182526001600160a01b039d8e16608052918d1660a052918c1660c05291518b166101005291518a1660e05291518916610120529151610140529151871661016052915161018052915185166101a052915184169052905182166101e05251166102005233156103af57600180546001600160a01b03199081169091555f805433928116831782556040519492916001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a3600280546001600160a01b0319166001600160a01b03928316179055600380546001600160a81b03191692909116919091179055615f1e90816103ef82396080518181816086015281816101cb0152818161034401528181612bbd01528181615440015281816154f7015281816155e50152615796015260a05181818161077e015281816130c50152615eb9015260c051818181610d9e0152818161315f0152615c19015260e0518181816024015281816125f9015261276b015261010051818181611c98015281816129640152613a56015261012051818181611ff801528181612215015261431d015261014051818181611fd70152818161223701526142fc01526101605181505061018051818181610b930152818161132401526116d801526101a051818181610bb40152818161134601526116b701526101c05181818161054601528181612ce10152612dcd01526101e05181818161044b015261322c01526102005181818161073b015261335f0152f35b631e4fbdf760e01b5f525f60045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b5f80fd5b51906001600160a01b03821682036103d65756fe60808060405260043610156100ae575b50361561001a575f80fd5b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000163314158061007b575b61005357005b7f38bbd576000000000000000000000000000000000000000000000000000000005f5260045ffd5b506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633141561004d565b5f3560e01c9081631a6ae42514610d815750806323a69e7514610ad657806324856bc314610a2757806324dec034146109565780633593564c1461081e5780633f4ba83a146107a2578063406793611461075f5780634a7babb91461071c57806357c79961146106f65780635c975abb146106d1578063715018a61461063a57806379ba50971461056a578063817122dc146105275780638456cb59146104945780638da5cb5b1461046f578063980b444d1461042c578063ab6291fe14610309578063b85aa7af146102e3578063d737d0c71461029e578063e30c397814610278578063f2fde38b146101f35763fbfa77cf146101ac575f61000f565b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b5f80fd5b346101ef5760206003193601126101ef576001600160a01b03610214610e21565b61021c6139ff565b16807fffffffffffffffffffffffff000000000000000000000000000000000000000060015416176001556001600160a01b035f54167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227005f80a3005b346101ef575f6003193601126101ef5760206001600160a01b0360015416604051908152f35b346101ef575f6003193601126101ef5760207f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c6001600160a01b0360405191168152f35b346101ef575f6003193601126101ef5760206001600160a01b0360035416604051908152f35b346101ef5760206003193601126101ef5760043567ffffffffffffffff81116101ef5761033a903690600401610dc2565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001633036104045761037391613c9e565b908183036103dc575f5b8381106103b0576103ac604051610395602082610eb9565b5f8152604051918291602083526020830190610e4b565b0390f35b806103d66103c16001938789611081565b3560f81c6103d083878761110b565b91614533565b0161037d565b7faaad13f7000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f62df0545000000000000000000000000000000000000000000000000000000005f5260045ffd5b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b346101ef575f6003193601126101ef5760206001600160a01b035f5416604051908152f35b346101ef575f6003193601126101ef576104ac6139ff565b6104b4611493565b6104bc611493565b740100000000000000000000000000000000000000007fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff60035416176003557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b346101ef575f6003193601126101ef57336001600160a01b03600154160361060e577fffffffffffffffffffffffff0000000000000000000000000000000000000000600154166001555f54337fffffffffffffffffffffffff00000000000000000000000000000000000000008216175f556001600160a01b033391167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b7f118cdaa7000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b346101ef575f6003193601126101ef576106526139ff565b7fffffffffffffffffffffffff0000000000000000000000000000000000000000600154166001555f6001600160a01b0381547fffffffffffffffffffffffff000000000000000000000000000000000000000081168355167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346101ef575f6003193601126101ef57602060ff60035460a01c166040519015158152f35b346101ef575f6003193601126101ef5760206001600160a01b0360025416604051908152f35b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b346101ef575f6003193601126101ef576107ba6139ff565b6107c2613a12565b6107ca613a12565b7fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff600354166003557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b60606003193601126101ef5760043567ffffffffffffffff81116101ef5761084a903690600401610dc2565b60243567ffffffffffffffff81116101ef5761086a903690600401610df0565b91604435421161092e57333014610923576001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c166108fb576108d693337f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d610f6a565b5f7f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d005b7f6f5ffb7e000000000000000000000000000000000000000000000000000000005f5260045ffd5b61092c93610f6a565b005b7f5bf6f916000000000000000000000000000000000000000000000000000000005f5260045ffd5b346101ef5760406003193601126101ef5761096f610e21565b602435906001600160a01b0382168092036101ef576001600160a01b03906109956139ff565b1680151580610a1e575b156101ef57807fffffffffffffffffffffffff00000000000000000000000000000000000000006002541617600255817fffffffffffffffffffffffff000000000000000000000000000000000000000060035416176003557f26e41379222b54b0470031bc11852ad23058ffb8983f7cc0e18257d6f7afca9d5f80a3005b5081151561099f565b60406003193601126101ef5760043567ffffffffffffffff81116101ef57610a53903690600401610dc2565b60243567ffffffffffffffff81116101ef57610a73903690600401610df0565b91333014610923576001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c166108fb576108d693337f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d610f6a565b346101ef5760606003193601126101ef5760243560043560443567ffffffffffffffff81116101ef57610b0d903690600401610dc2565b5f831391821580610d77575b610d4f578181016040828203126101ef5781359067ffffffffffffffff82116101ef57610b47918301610ef8565b506020810135916001600160a01b0383168093036101ef57610b6891611126565b90601790602b8310610d27578035968760601c95610bd862ffffff8585013560601c9a60481c168a897f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000611186565b6001600160a01b0333911603610cff5715610cf557508685105b15610c065750505061092c9350339161126c565b91935091939482602b0180602b11610cc8578410610c6657508282116101ef5781019103907f80000000000000000000000000000000000000000000000000000000000000008410156101ef5761092c93610c613391610f3e565b6112f7565b925050507faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6929291925c8211610ca05761092c92339161126c565b7f739dbe52000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b9550848710610bf2565b7f32b13d91000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f3b99b53d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f316cf0eb000000000000000000000000000000000000000000000000000000005f5260045ffd5b505f851315610b19565b346101ef575f6003193601126101ef576020906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168152f35b9181601f840112156101ef5782359167ffffffffffffffff83116101ef57602083818601950101116101ef57565b9181601f840112156101ef5782359167ffffffffffffffff83116101ef576020808501948460051b0101116101ef57565b600435906001600160a01b03821682036101ef57565b35906001600160a01b03821682036101ef57565b90601f19601f602080948051918291828752018686015e5f8582860101520116010190565b60c0810190811067ffffffffffffffff821117610e8c57604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b90601f601f19910116810190811067ffffffffffffffff821117610e8c57604052565b67ffffffffffffffff8111610e8c57601f01601f191660200190565b81601f820112156101ef57803590610f0f82610edc565b92610f1d6040519485610eb9565b828452602083830101116101ef57815f926020809301838601378301015290565b7f80000000000000000000000000000000000000000000000000000000000000008114610cc8575f0390565b919290610f75611493565b808203611059575f5b818110610f8c575050505050565b610f97818386611081565b35610fcf610fa683868961110b565b907fff000000000000000000000000000000000000000000000000000000000000008416611609565b919015908161102e575b50610fe75750600101610f7e565b9061102a6040519283927f2c4029e90000000000000000000000000000000000000000000000000000000084526004840152604060248401526044830190610e4b565b0390fd5b7f8000000000000000000000000000000000000000000000000000000000000000915016155f610fd9565b7fff633a38000000000000000000000000000000000000000000000000000000005f5260045ffd5b9082101561108d570190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b9035907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1813603018212156101ef570180359067ffffffffffffffff82116101ef576020019181360383136101ef57565b9082101561108d576111229160051b8101906110ba565b9091565b909163ffffffff82351682019263ffffffff8435169260208086019585010191011061114e57565b633b99b53d5f526004601cfd5b909163ffffffff60608301351682019263ffffffff8435169260208086019585010191011061114e57565b929161125091926001600160a01b039586821687841611611257575b62ffffff908760405193816020860196168652166040840152166060820152606081526111d0608082610eb9565b519020611242604051938492602084019687917fffffffffffffffffffffffffffffffffffffffff000000000000000000000000605594927fff00000000000000000000000000000000000000000000000000000000000000855260601b166001840152601583015260358201520190565b03601f198101835282610eb9565b5190201690565b9091906111a2565b91908201809211610cc857565b909291906001600160a01b038416300361128c5761128a9350613aec565b565b91926001600160a01b0384116112af576001600160a01b0361128a941692613a4a565b7fc4bd89a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b601f8260209493601f1993818652868601375f8582860101520116010190565b939290602b8210610d27578235938460601c92601785013560601c9380851094859760481c62ffffff16907f0000000000000000000000000000000000000000000000000000000000000000927f00000000000000000000000000000000000000000000000000000000000000009361136f94611186565b6001600160a01b031692845f146040966001600160a01b0380956113cc5f9661141f95611478576401000276a4925b846113b88e51978f948995602087015260608601916112d7565b91168d83015203601f198101855284610eb9565b89519b8c998a9889977f128acb080000000000000000000000000000000000000000000000000000000089521660048801526024870152604486015216606484015260a0608484015260a4830190610e4b565b03925af1801561146d575f925f9161143657509192565b9250506040823d604011611465575b8161145260409383610eb9565b810103126101ef57602082519201519192565b3d9150611445565b6040513d5f823e3d90fd5b73fffd8963efd1fc6a506488495d951d5263988d259261139e565b60ff60035460a01c166114a257565b7fd93c0665000000000000000000000000000000000000000000000000000000005f5260045ffd5b3d156114f4573d906114db82610edc565b916114e96040519384610eb9565b82523d5f602084013e565b606090565b359062ffffff821682036101ef57565b60a080916001600160a01b0361151e82610e37565b1684526001600160a01b0361153560208301610e37565b1660208501526001600160a01b0361154f60408301610e37565b1660408501526001600160a01b0361156960608301610e37565b16606085015262ffffff61157f608083016114f9565b1660808501520135910152565b908160209103126101ef575190565b359065ffffffffffff821682036101ef57565b65ffffffffffff611603606080936001600160a01b036115cd82610e37565b1686526001600160a01b036115e460208301610e37565b166020870152836115f76040830161159b565b1660408701520161159b565b16910152565b90926001916060919060f81c603f1660218110156133d0576010811015612b5f576008811015611f4b578061199857506116486020860135948661115b565b93909560808101355f14611992577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c5b6116838235613bcf565b90869880977f80000000000000000000000000000000000000000000000000000000000000008a14611903575b50509697957f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000006017995b602b8b8101808211610cc8578b10159c7f80000000000000000000000000000000000000000000000000000000000000008110156101ef578d156118fc5730905b8c83116101ef578d92878035948560601c9082013560601c8082109660481c62ffffff169061176c928a8c611186565b6001600160a01b031691855f149461181c6001600160a01b03936117c75f946040996118e1576401000276a49b5b876117b38c519586948e602087015260608601916112d7565b91168b83015203601f198101835282610eb9565b8488519a8b98899788967f128acb080000000000000000000000000000000000000000000000000000000088521660048701528b6024870152604486015216606484015260a0608484015260a4830190610e4b565b03925af190811561146d575f905f926118a5575b61184093501561189e5750610f3e565b9a1561185c573092898b116101ef578a809101990398926116fb565b505050509295909350604091945091013511611876579190565b7f39d35496000000000000000000000000000000000000000000000000000000005f5260045ffd5b9050610f3e565b9150506040823d82116118d9575b816118c060409383610eb9565b810103126101ef57816020611840935191015191611830565b3d91506118b3565b73fffd8963efd1fc6a506488495d951d5263988d259b61179a565b869061173c565b60149192995010610d27576020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301523560601c5afa90811561146d575f91611960575b50965f806116b0565b90506020813d60201161198a575b8161197b60209383610eb9565b810103126101ef57515f611957565b3d915061196e565b30611679565b91949093909160018103611ac75750906119b76020820135928261115b565b608083013515611ac0577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c915b60406119f18535613bcf565b9401357faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6925d7f80000000000000000000000000000000000000000000000000000000000000008510156101ef57611a4b93610c6186610f3e565b90919015611ab15750611a5d90610f3e565b03611a89575f7faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6925d9190565b7fd4e0248e000000000000000000000000000000000000000000000000000000005f5260045ffd5b611abb9150610f3e565b611a5d565b30916119e5565b60028103611b155750611b1191604081013591507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c611b0a6020830135613bcf565b9135613a4a565b9190565b909491929060038103611ce457505050803581019263ffffffff60208301351682019063ffffffff8235169260208084019385010191011061114e577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c91604051916001600160a01b0360208401947f2a2d80d10000000000000000000000000000000000000000000000000000000086521660248401526060604484015260e483019580357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1823603018112156101ef5781016020813591019767ffffffffffffffff82116101ef578160071b360389136101ef5781906060608488015252610104850197905f5b818110611cc657505050926112425f96978294611c8b946040886001600160a01b03611c4f60208e9d9c01610e37565b1660a4880152013560c48601527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8584030160648601526112d7565b5190826001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af190611cc36114ca565b90565b90919860808082611cd96001948e6115ae565b019a01929101611c1f565b919450919060048103611e2d5750611cff6020820135613bcf565b906001600160a01b038060408301351691351680155f14611d67575047908110611d3f5780611d2f575b50509190565b611d3891613dee565b5f80611d29565b7f6a12f104000000000000000000000000000000000000000000000000000000005f5260045ffd5b91604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481875afa92831561146d575f93611df9575b508210611dd15781611dc0575b5050509190565b611dc992613d36565b5f8080611db9565b7f675cae38000000000000000000000000000000000000000000000000000000005f5260045ffd5b9092506020813d602011611e25575b81611e1560209383610eb9565b810103126101ef5751915f611dac565b3d9150611e08565b60058103611e545750806040611b1192013590611e4d6020820135613bcf565b9035613aec565b60068103611f2057506040810135906001600160a01b03611e786020830135613bcf565b91351680611e945750611e8e611b1192476144f1565b90613dee565b906040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481865afa90811561146d575f91611eec575b50611b1193611ee6916144f1565b91613d36565b90506020813d602011611f18575b81611f0760209383610eb9565b810103126101ef5751611b11611ed8565b3d9150611efa565b7fd76a1e9e000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b919490939091600881036121c45750611f6960208301359183613c45565b906080840135156121bd577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c915b611fa28535613bcf565b92821561108d57611fb282613c24565b836001101561108d57611fd461201c91611fce60208601613c24565b90615363565b907f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000615381565b9485816121a3575b5050505f198201828111610cc85761204d6120486001600160a01b03928585613c14565b613c24565b1693604051927f70a082310000000000000000000000000000000000000000000000000000000084526001600160a01b038516928360048601526020856024818a5afa94851561146d575f95612165575b50946120ae929160209596614116565b6024604051809581937f70a0823100000000000000000000000000000000000000000000000000000000835260048301525afa91821561146d575f92612130575b5060406120ff9293013592613c38565b10612108579190565b7f849eaf98000000000000000000000000000000000000000000000000000000005f5260045ffd5b91506020823d60201161215d575b8161214b60209383610eb9565b810103126101ef5790519060406120ef565b3d915061213e565b92919450946020833d60201161219b575b8161218360209383610eb9565b810103126101ef5791519194919390916120ae61209e565b3d9150612176565b6121b5926121b085613c24565b61126c565b5f8085612024565b3091611f98565b600981036124ad57506121d79082613c45565b9091906080820135156124a6577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c925b6122128335613bcf565b917f0000000000000000000000000000000000000000000000000000000000000000947f0000000000000000000000000000000000000000000000000000000000000000945f956002851061247e576020820135975f198601868111610cc8579190825b6122cc575050506040013586116122a457821561108d57611b11958561229f926121b085613c24565b614116565b7f8ab0bc16000000000000000000000000000000000000000000000000000000005f5260045ffd5b90919897505f19890197898911610cc8576122ee6120486123109a8989613c14565b6123056122ff6120488d8b8b613c14565b82615363565b8186869d939d615381565b90604051907f0902f1ac0000000000000000000000000000000000000000000000000000000082526060826004816001600160a01b0387165afa91821561146d575f905f9361242e575b506001600160a01b036dffffffffffffffffffffffffffff8082931694169d169116145f146124285799905b9980158015612420575b6123f8578261239e916144a7565b916127108302928084046127101490151715610cc8576123bd91613c38565b6126f78102908082046126f71490151715610cc8576123db916144ba565b60018101809111610cc8576123f09099613e73565b919082612276565b7f7b9c8916000000000000000000000000000000000000000000000000000000005f5260045ffd5b508115612390565b90612386565b6dffffffffffffffffffffffffffff8094506001600160a01b03925061246b839260603d8111612477575b6124638183610eb9565b8101906140e0565b5095909350505061235a565b503d612459565b7f20db8267000000000000000000000000000000000000000000000000000000005f5260045ffd5b3092612208565b93949193909290600a81036125945750505063ffffffff60c08301351682019063ffffffff823516908360208085019484010191011061114e5760a0611c8b5f9461124286957f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c956040519586946001600160a01b0360208701997f2b67b570000000000000000000000000000000000000000000000000000000008b5216602487015261255f60448701826115ae565b6001600160a01b0361257360808301610e37565b1660c4870152013560e48501526101006101048501526101248401916112d7565b91949390929091600b810361274c5750506125b460208201359135613bcf565b90807f8000000000000000000000000000000000000000000000000000000000000000810361271d575050475b5f90806125ef575050509190565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001692833b156101ef576040517fd0e30db00000000000000000000000000000000000000000000000000000000081525f8160048186895af1801561146d57612701575b506001600160a01b031690308203612674575b50611db9565b60446020928460405196879485937fa9059cbb000000000000000000000000000000000000000000000000000000008552600485015260248401525af19081156126f557506126c6575b80808061266e565b6126e79060203d6020116126ee575b6126df8183610eb9565b810190613c86565b505f6126be565b503d6126d5565b604051903d90823e3d90fd5b61270e9193505f90610eb9565b5f916001600160a01b0361265b565b4710156125e1577f6a12f104000000000000000000000000000000000000000000000000000000005f5260045ffd5b600c810361289c5750506127608135613bcf565b906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481855afa92831561146d575f93612867575b50602001358210611d3f57816127e6575050509190565b803b156101ef575f80916024604051809481937f2e1a7d4d0000000000000000000000000000000000000000000000000000000083528760048401525af1801561146d57612857575b50306001600160a01b03831603612847575b80611db9565b61285091613dee565b5f80612841565b5f61286191610eb9565b5f61282f565b9092506020813d602011612894575b8161288360209383610eb9565b810103126101ef57519160206127cf565b3d9150612876565b9094919390600d8103612a71575083358401928335956128c46020808701978703018861125f565b11610d275793946001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c1694905f5b8181101561295257866001600160a01b0361291c60208460071b8a0101613c24565b160361292a576001016128fa565b7fe7002877000000000000000000000000000000000000000000000000000000005f5260045ffd5b50929591945092506001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690813b156101ef576040517f0d58b1db000000000000000000000000000000000000000000000000000000008152602060048201526024810184905292839160448301915f5b8181106129f75750505091815f81819503925af1801561146d576129ed57509190565b5f611b1191610eb9565b919350916080806001926001600160a01b03612a1288610e37565b1681526001600160a01b03612a2960208901610e37565b1660208201526001600160a01b03612a4360408901610e37565b1660408201526001600160a01b03612a5d60608901610e37565b1660608201520194019101918593926129ca565b919450929150600e8103611f205750604051907f70a082310000000000000000000000000000000000000000000000000000000082526001600160a01b0381351660048301526020826024816001600160a01b0384860135165afa91821561146d575f92612b2a575b50604001351180612aea57159190565b91506040517fa328167200000000000000000000000000000000000000000000000000000000602082015260048152612b24602482610eb9565b91159190565b9091506020813d602011612b57575b81612b4660209383610eb9565b810103126101ef5751906040612ada565b3d9150612b39565b91949093909160108103612c625750612bb0915f9160405193849283927f815483190000000000000000000000000000000000000000000000000000000084526020600485015260248401916112d7565b0381836001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af1801561146d57612bee57509190565b3d805f833e612bfd8183610eb9565b8101906020818303126101ef5780519067ffffffffffffffff82116101ef570181601f820112156101ef578051612c3381610edc565b92612c416040519485610eb9565b818452602082840101116101ef575f928160208094018483015e0101529190565b80929495506011919350145f14612d375750907fffffffff000000000000000000000000000000000000000000000000000000008135167f7ac2ff7b000000000000000000000000000000000000000000000000000000008103612d0c5750815f92918392604051928392833781018381520390826001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af190611cc36114ca565b7ff801e525000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6012810361305157507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c917fffffffff000000000000000000000000000000000000000000000000000000008135167f0c49ccbe0000000000000000000000000000000000000000000000000000000081148015613028575b8015612fff575b15612d0c575060048101356001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001693604051907f6352211e000000000000000000000000000000000000000000000000000000008252826004830152602082602481895afa91821561146d575f92612fc3575b506001600160a01b038116916001600160a01b0381168314928315612f2b575b508215612eae575b505015612e83575091815f809481946040519384928337810182815203925af190611cc36114ca565b7fbb25d4c5000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6040517fe985e9c50000000000000000000000000000000000000000000000000000000081526001600160a01b039182166004820152911660248201529050602081604481885afa90811561146d575f91612f0c575b505f80612e5a565b612f25915060203d6020116126ee576126df8183610eb9565b5f612f04565b9092506040517f081812fc0000000000000000000000000000000000000000000000000000000081528460048201526020816024818b5afa801561146d575f90612f83575b6001600160a01b0391501614915f612e52565b506020813d602011612fbb575b81612f9d60209383610eb9565b810103126101ef57612fb66001600160a01b03916140b1565b612f70565b3d9150612f90565b9091506020813d602011612ff7575b81612fdf60209383610eb9565b810103126101ef57612ff0906140b1565b905f612e32565b3d9150612fd2565b507f42966c68000000000000000000000000000000000000000000000000000000008114612db8565b507ffc6f7865000000000000000000000000000000000000000000000000000000008114612db1565b601381036130ef5750505f80916040516001600160a01b0360c060208301937f8b0c1b220000000000000000000000000000000000000000000000000000000085526130a06024850182611509565b01351660e482015260e481526130b861010482610eb9565b5190826001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af16111226114ca565b601481036131895750505f809160405162ffffff60c060208301937fdc2ab18c00000000000000000000000000000000000000000000000000000000855261313a6024850182611509565b01351660e482015260e4815261315261010482610eb9565b5190826001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af16111226114ca565b601581036132c257507fffffffff000000000000000000000000000000000000000000000000000000008235167fdd46508f000000000000000000000000000000000000000000000000000000008103612d0c5750806004116101ef576132006131fa600319830160048501611126565b90611126565b5f5b818110613257575050505f9182914791816040519283928337810184815203916001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af190611cc36114ca565b613262818385611081565b3560f81c80159081156132b7575b81156132ac575b5061328457600101613202565b7f5d1d0f9f000000000000000000000000000000000000000000000000000000005f5260045ffd5b60039150145f613277565b600181149150613270565b60168103611f2057507fffffffff000000000000000000000000000000000000000000000000000000008235167fdd46508f000000000000000000000000000000000000000000000000000000008103612d0c5750806004116101ef576133336131fa600319830160048501611126565b5f5b81811061338a575050505f9182914791816040519283928337810184815203916001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af190611cc36114ca565b601a613397828486611081565b3560f81c146133a857600101613335565b7f103b4710000000000000000000000000000000000000000000000000000000005f5260045ffd5b91949093929091602181036135275750506133ec929350613c9e565b906134306040949394519360208501957f24856bc30000000000000000000000000000000000000000000000000000000087526040602487015260648601916112d7565b917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc848403016044850152808352602083019060208160051b85010193835f917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe182360301905b8484106134cc575050505050505091816134bd5f9493859403601f198101835282610eb9565b519082305af190611cc36114ca565b90919293949596601f198282030187528735838112156101ef578401906020823592019167ffffffffffffffff81116101ef5780360383136101ef5761351860209283926001956112d7565b99019701959401929190613497565b90929190602281036137675750602081013561354f6135468484613c45565b91909484613c69565b949060a085013515613761577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c5b6135888635613bcf565b9480151580613737575b613715575b50505f198201828111610cc8576135ba6120486001600160a01b03928587613c14565b1695604051927f70a082310000000000000000000000000000000000000000000000000000000084523060048501526020846024818b5afa93841561146d575f946136df575b5061360b9394613e7f565b6040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481885afa90811561146d575f916136ac575b5060409161365b91613c38565b920135821061368457306001600160a01b0382160361367b575050509190565b611dc992613aec565b7fcd7d97e4000000000000000000000000000000000000000000000000000000005f5260045ffd5b90506020813d6020116136d7575b816136c760209383610eb9565b810103126101ef5751604061364e565b3d91506136ba565b93506020843d60201161370d575b816136fa60209383610eb9565b810103126101ef5761360b935193613600565b3d91506136ed565b831561108d576137309161372886613c24565b90309161126c565b5f80613597565b507f8000000000000000000000000000000000000000000000000000000000000000811415613592565b3061357e565b60238103611f2057509081602061378e930135916137858183613c45565b94909183613c69565b94909260a0810135156139f8577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c935b6001600160a01b0360025416966001600160a01b036003541697600286106139d0576137ea86613e5b565b6137f76040519182610eb9565b86815261380387613e5b565b91601f196020830193013684375f1988019a888c11610cc8578a6138278d85613bbb565b528b805b6138d057505050511561108d575192604081013584116138a85761384f9035613bcf565b95851561108d5761386e936138679161372887613c24565b8484613e7f565b306001600160a01b03841603613888575b50505050509190565b61389e946138999261204892613c14565b613aec565b5f8080808061387f565b7fbf1e94da000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f19810190808211610cc85761390f8a6138fc612048848f6138f6612048898388613c14565b94613c14565b613907858c8c613c14565b359187614fc1565b93919061391c8489613bbb565b51916001600160a01b03604051967fca4bc7140000000000000000000000000000000000000000000000000000000088521660048701526024860152604485015260648401525f19608484015260208360a481875afa92831561146d575f9361399b575b509161398f6139959387613bbb565b52613e73565b8061382b565b92506020833d82116139c8575b816139b560209383610eb9565b810103126101ef5791519161398f613980565b3d91506139a8565b7fa22caccc000000000000000000000000000000000000000000000000000000005f5260045ffd5b30936137bf565b6001600160a01b035f5416330361060e57565b60ff60035460a01c1615613a2257565b7f8dfc202b000000000000000000000000000000000000000000000000000000005f5260045ffd5b91926001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691823b156101ef575f6001600160a01b039384829681608496816040519b8c9a8b997f36c78516000000000000000000000000000000000000000000000000000000008b521660048a01521660248801521660448601521660648401525af1801561146d57613ae25750565b5f61128a91610eb9565b9091906001600160a01b031680613b07575061128a91613dee565b7f80000000000000000000000000000000000000000000000000000000000000008214613b39575b9161128a92613d36565b9050604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481855afa801561146d575f90613b87575b90925090613b2f565b506020833d602011613bb3575b81613ba160209383610eb9565b810103126101ef5761128a9251613b7e565b3d9150613b94565b805182101561108d5760209160051b010190565b6001600160a01b03811660018103613c085750507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c90565b600203611cc357503090565b919081101561108d5760051b0190565b356001600160a01b03811681036101ef5790565b91908203918211610cc857565b916060830135830191613c6260208435958186019503018561125f565b11610d2757565b916080830135830191613c6260208435958186019503018561125f565b908160209103126101ef575180151581036101ef5790565b604081351891606082019363ffffffff6040840135169363ffffffe0601f8601169060608201602086013518179084019260608401359463ffffffff861694641fffffffe0608082019760051b1680915f925b808410613d0957506080925001019101101761114e57565b90916020809163ffffffe0601f60808089890101359b848d18179b88010135011601019301929190613cf1565b5f91826044926020956001600160a01b03604051947fa9059cbb00000000000000000000000000000000000000000000000000000000865216600485015260248401525af13d15601f3d1160015f511416171615613d9057565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f5452414e534645525f4641494c454400000000000000000000000000000000006044820152fd5b5f80809381935af115613dfd57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4554485f5452414e534645525f4641494c4544000000000000000000000000006044820152fd5b67ffffffffffffffff8111610e8c5760051b60200190565b8015610cc8575f190190565b919092805f19850103614089575f5b818110613e9c575050505050565b80613eb36120486001600160a01b03938888613c14565b613ee0613ec7612048600185018a8a613c14565b84600254169083613ed986898b613c14565b3592614fc1565b9490919216604051947f70a08231000000000000000000000000000000000000000000000000000000008652306004870152602086602481855afa95861561146d575f96614056575b505f6044602092826001600160a01b03604051927f095ea7b300000000000000000000000000000000000000000000000000000000845216958660048401528a60248401525af13d15601f3d1160015f511416171615613ff857803b156101ef575f928360849260405197889586947f5b41b9080000000000000000000000000000000000000000000000000000000086526004860152602485015260448401528160648401525af191821561146d57600192613fe8575b5001613e8e565b5f613ff291610eb9565b5f613fe1565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f415050524f56455f4641494c45440000000000000000000000000000000000006044820152fd5b9095506020813d8211614081575b8161407160209383610eb9565b810103126101ef5751945f613f29565b3d9150614064565b7ff8637a39000000000000000000000000000000000000000000000000000000005f5260045ffd5b51906001600160a01b03821682036101ef57565b51906dffffffffffffffffffffffffffff821682036101ef57565b908160609103126101ef576140f4816140c5565b916040614103602084016140c5565b92015163ffffffff811681036101ef5790565b916002821061447f57811561108d5761412e83613c24565b826001101561108d5761414a90611fce60208697959601613c24565b50925f198101937ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe8201955f90602093601f198501965b8884106141945750505050505050505050565b6141a2612048858486613c14565b946001600160a01b036141bc612048600188018688613c14565b921695604051917f0902f1ac0000000000000000000000000000000000000000000000000000000083526060836004818b5afa91821561146d57895f945f94614439575b506001600160a01b03806dffffffffffffffffffffffffffff80602496979816971693169416841494855f146144335791935b604051938480927f70a082310000000000000000000000000000000000000000000000000000000082528d60048301525afa91821561146d575f92614404575b50808203928115928380156143fc575b6123f857826126f786029586046126f71491141715610cc8576142a690846144a7565b916127108202918204612710141715610cc8576142cc926142c69161125f565b906144ba565b90156143f5575f90915b8b8610156143ec57906142f761434192611fce61204860028a01888a613c14565b8193917f00000000000000000000000000000000000000000000000000000000000000007f0000000000000000000000000000000000000000000000000000000000000000615381565b915b96604051906143528a83610eb9565b5f82528b368b840137803b156101ef576143c0945f8094604051978895869485937f022c0d9f000000000000000000000000000000000000000000000000000000008552600485015260248401526001600160a01b0389166044840152608060648401526084830190610e4b565b03925af191821561146d576001926143dc575b50930192614181565b5f6143e691610eb9565b5f6143d3565b5087905f614343565b5f916142d6565b508115614283565b9091508981813d831161442c575b61441c8183610eb9565b810103126101ef5751905f614273565b503d614412565b93614233565b6dffffffffffffffffffffffffffff955060249394506001600160a01b0386614470829360603d8111612477576124638183610eb9565b50989098979650505050614200565b7fae52ad0c000000000000000000000000000000000000000000000000000000005f5260045ffd5b81810292918115918404141715610cc857565b81156144c4570490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b612710821161450b5761271091614507916144a7565b0490565b7fdeaa01e6000000000000000000000000000000000000000000000000000000005f5260045ffd5b929190600b841015614a5e57600784036146ae5761455292935061591c565b6020810190614561828261592a565b90505f9261456e83613c24565b9061457b60408501615850565b906fffffffffffffffffffffffffffffffff821615614695575b92915f915b83831061461b5750505050506060016fffffffffffffffffffffffffffffffff806145c483615850565b1692169182106145d2575050565b6145ec6fffffffffffffffffffffffffffffffff91615850565b7f4e86d23a000000000000000000000000000000000000000000000000000000005f521660045260245260445ffd5b8496506fffffffffffffffffffffffffffffffff614679916146606146508661464a61467e9798999a8c61592a565b9061597e565b9561465b36886159be565b615cb0565b61466d60808801886110ba565b949093165f0391615d99565b615c91565b94600161468b8793613c24565b919493019161459a565b90506146a86146a3836153f0565b615ac7565b90614595565b600684036147a8576146c1929350615841565b6146cd60e08201615850565b6fffffffffffffffffffffffffffffffff811615614755575b614738614679610100926147176fffffffffffffffffffffffffffffffff61471060c0880161586d565b9216610f3e565b906147266101208701876110ba565b929091614733368961587a565b615d99565b91016fffffffffffffffffffffffffffffffff806145c483615850565b5061476260c0820161586d565b1561478d576101006147386146796147846146a361477f86613c24565b6153f0565b925050506146e6565b6101006147386146796147846146a361477f60208701613c24565b60098403614911576147bb92935061591c565b60208101906147ca828261592a565b5f9391506147da60408401615850565b6147e384613c24565b916fffffffffffffffffffffffffffffffff8216156148fd575b92919290815b61488057505050506060016fffffffffffffffffffffffffffffffff8061482983615850565b169216918211614837575050565b6148516fffffffffffffffffffffffffffffffff91615850565b7f79cb628f000000000000000000000000000000000000000000000000000000005f521660045260245260445ffd5b829395506fffffffffffffffffffffffffffffffff6148dc916148c26148b76148ad6148e696978a61592a565b5f1989019161597e565b9861465b368b6159be565b906148d060808b018b6110ba565b94909316911590615d99565b600f0b5f03615ac7565b935f196148f38692613c24565b9392019081614803565b905061490b6146a383615746565b906147fd565b60088414614948575050505b7f5cda29d7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b614953929350615841565b61495f60e08201615850565b6fffffffffffffffffffffffffffffffff8116156149e1575b6149c46146796149bf6fffffffffffffffffffffffffffffffff610100946149a260c0880161586d565b6149b06101208901896110ba565b9390921690614733368a61587a565b6158ed565b91016fffffffffffffffffffffffffffffffff8061482983615850565b506149ee60c0820161586d565b15614a32576101006149c46146796149bf6fffffffffffffffffffffffffffffffff614a276146a3614a2260208901613c24565b615746565b945050505050614978565b6101006149c46146796149bf6fffffffffffffffffffffffffffffffff614a276146a3614a2288613c24565b6018841115614def57601d8403614b5f57614a7a92935061591c565b6020810190614a89828261592a565b90505f92614a9683613c24565b90614aa360408501615850565b906fffffffffffffffffffffffffffffffff821615614b46575b92915f915b838310614aec5750505050506060016fffffffffffffffffffffffffffffffff806145c483615850565b849650614b1561467991614b0d6146508661464a614b2f9798999a8c61592a565b929091615b0c565b5f03600f0b614b2760808701876110ba565b939092615b48565b946001614b3c8793613c24565b9194930191614ac2565b9050614b59614b54836153f0565b615d7c565b90614abd565b601c8403614c2857614b72929350615841565b614b7e60e08201615850565b6fffffffffffffffffffffffffffffffff811615614bda575b61473861467961010092614bb96149bf614bb360c0880161586d565b92615b0c565b90614bc86101208701876110ba565b929091614bd5368961587a565b615b48565b50614be760c0820161586d565b15614c0d57610100614738614679614c04614b5461477f86613c24565b92505050614b97565b610100614738614679614c04614b5461477f60208701613c24565b601f8403614d1c57614c3b92935061591c565b6020810190614c4a828261592a565b5f939150614c5a60408401615850565b614c6384613c24565b916fffffffffffffffffffffffffffffffff821615614d08575b92919290815b614ca957505050506060016fffffffffffffffffffffffffffffffff8061482983615850565b82939550614ce790614cd0614cc86148b76148ad614cf196978a61592a565b919092615b0c565b614cdd60808a018a6110ba565b9390921590615b48565b5f03600f0b615c91565b935f19614cfe8692613c24565b9392019081614c83565b9050614d166146a383615746565b90614c7d565b601e8414614d2c5750505061491d565b614d37929350615841565b614d4360e08201615850565b6fffffffffffffffffffffffffffffffff811615614d9a575b6149c46146796149bf61010093614d7e614d7860c0880161586d565b91615b0c565b90614d8d6101208801886110ba565b929091614bd5368a61587a565b50614da760c0820161586d565b15614dd4576101006149c46146796149bf614dca6146a3614a2260208801613c24565b9350505050614d5c565b6101006149c46146796149bf614dca6146a3614a2287613c24565b92600c8103614e735750614e039192615733565b90614e0d81615746565b91808311614e4357509061128a917f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c906155d3565b90507f79cb628f000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b600f8103614ef65750614e869192615733565b90614e90816153f0565b91808310614ec657509061128a917f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c906154e5565b90507f4e86d23a000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b600b8103614f4f5750614f0d9061128a92936153d8565b15614f4457614f3e827f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c92615592565b916155d3565b614f3e823092615592565b600e8103614f825750614f76614f6c614f7c9261128a94956153d8565b9282949291613bcf565b9261557e565b916154e5565b9260108414614f935750505061491d565b61128a929350614fa9614fb292614f7c926153d8565b92919390613bcf565b91614fbc846153f0565b6144f1565b92939290915f8080600288036151495750506040517f400f7a1e0000000000000000000000000000000000000000000000000000000081526001600160a01b03858116600483015292831660248201529495506080928592604492508391165afa91821561146d575f926150b9575b506001600160a01b03806020840151169116145f146150b05760ff5f5b1691826150a0576001600160a01b0360ff60015b16925116905b6001600160a01b0382161561507857565b7fda6a56c3000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b0360ff5f615061565b60ff600161504d565b9091506080813d608011615141575b816150d560809383610eb9565b810103126101ef57604051906080820182811067ffffffffffffffff821117610e8c576151359160609160405261510b816140b1565b8452615119602082016140b1565b602085015261512a604082016140b1565b6040850152016140b1565b6060820152905f615030565b3d91506150c8565b94909593919660031461515f575b505050615067565b9195909492935060a060405180967f923093cb000000000000000000000000000000000000000000000000000000008252816001600160a01b03816151c08c89600484019092916001600160a01b0360209181604085019616845216910152565b0392165afa94851561146d575f956152c2575b506001600160a01b038060208701511692168281145f1461526e5750506001600160a01b035f955b1690810361521b5750506001600160a01b035f925b5116905f8080615157565b60408401516001600160a01b031681036152415750506001600160a01b03600192615210565b6001600160a01b03606085939501511614615265575b6001600160a01b0390615210565b60029250615257565b60408601516001600160a01b031681036152945750506001600160a01b036001956151fb565b6001600160a01b03606087989398015116146152b9575b6001600160a01b03906151fb565b600295506152ab565b90945060a0813d60a01161535b575b816152de60a09383610eb9565b810103126101ef576040519060a0820182811067ffffffffffffffff821117610e8c5761534f91608091604052615314816140b1565b8452615322602082016140b1565b6020850152615333604082016140b1565b6040850152615344606082016140b1565b6060850152016140b1565b6080820152935f6151d3565b3d91506152d1565b6001600160a01b0382166001600160a01b038216105f146111225791565b91611250906001600160a01b03947fffffffffffffffffffffffffffffffffffffffff0000000000000000000000006040519181602084019460601b16845260601b166034820152602881526111d0604882610eb9565b9060601161114e578035916040602083013592013590565b6040517fa54b28310000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b038216602482015290602082806044810103816001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165afa91821561146d575f926154b1575b505f821261547c575090565b6001600160a01b03907f4c085bf1000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b9091506020813d6020116154dd575b816154cd60209383610eb9565b810103126101ef5751905f615470565b3d91506154c0565b90918015615579576001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016803b156101ef575f92836064926001600160a01b03948560405198899788967f0b0d9c0900000000000000000000000000000000000000000000000000000000885216600487015216602485015260448401525af1801561146d57613ae25750565b505050565b908161558e57611cc391506153f0565b5090565b907f800000000000000000000000000000000000000000000000000000000000000082036155c457611cc39150615a3d565b8161558e57611cc39150615746565b5f91831561572d576001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001691823b156101ef576001600160a01b03604051917fa584119400000000000000000000000000000000000000000000000000000000835216908160048201525f8160248183885af1801561146d57615718575b50806156cb5750506020906004604051809581937f11da60b40000000000000000000000000000000000000000000000000000000083525af19081156126f557506156a05750565b6156c19060203d6020116156c4575b6156b98183610eb9565b81019061158c565b50565b503d6156af565b839483602094936156db9361126c565b6004604051809581937f11da60b40000000000000000000000000000000000000000000000000000000083525af19081156126f557506156a05750565b6157259194505f90610eb9565b5f925f615658565b50505050565b919060401161114e576020823592013590565b6040517fa54b28310000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b038216602482015290602082806044810103816001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165afa91821561146d575f9261580d575b505f82136157d85750611cc390610f3e565b6001600160a01b03907f3351b260000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b9091506020813d602011615839575b8161582960209383610eb9565b810103126101ef5751905f6157c6565b3d915061581c565b906101601161114e5780350190565b356fffffffffffffffffffffffffffffffff811681036101ef5790565b3580151581036101ef5790565b91908260c09103126101ef5760405161589281610e70565b60a08082946158a081610e37565b84526158ae60208201610e37565b60208501526158bf60408201610e37565b60408501526158d060608201610e37565b60608501526158e1608082016114f9565b60808501520135910152565b600f0b7fffffffffffffffffffffffffffffffff800000000000000000000000000000008114610cc8575f0390565b9060a01161114e5780350190565b9035907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1813603018212156101ef570180359067ffffffffffffffff82116101ef57602001918160051b360383136101ef57565b919081101561108d5760051b810135907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff41813603018212156101ef570190565b91909160c0818403126101ef57604051906159d882610e70565b81936159e382610e37565b83526159f1602083016114f9565b6020840152615a0260408301610e37565b6040840152615a1360608301610e37565b606084015260808201359167ffffffffffffffff83116101ef576158e160a0939284938301610ef8565b6001600160a01b031680615a5057504790565b6020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301525afa90811561146d575f91615a98575090565b90506020813d602011615abf575b81615ab360209383610eb9565b810103126101ef575190565b3d9150615aa6565b906fffffffffffffffffffffffffffffffff8216809203615ae457565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffd5b6fffffffffffffffffffffffffffffffff166f7fffffffffffffffffffffffffffffff8111615b3b57600f0b90565b6393dafdf15f526004601cfd5b615be590615c0c60209396949560405197889485947f911a63b7000000000000000000000000000000000000000000000000000000008652600486019060a080916001600160a01b0381511684526001600160a01b0360208201511660208501526001600160a01b0360408201511660408501526001600160a01b03606082015116606085015262ffffff60808201511660808501520151910152565b1515968760c4850152600f0b958660e48501526101206101048501526101248401916112d7565b03815f6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af192831561146d575f93615c5d575b505f1303615c5757600f0b90565b60801d90565b9092506020813d602011615c89575b81615c7960209383610eb9565b810103126101ef5751915f615c49565b3d9150615c6c565b5f81600f0b12615ae4576fffffffffffffffffffffffffffffffff1690565b905f60a0604051615cc081610e70565b82815282602082015282604082015282606082015282608082015201526001600160a01b038251166001600160a01b038216918183105f14615d6c576001600160a01b03905b16809214926001600160a01b036040820151166001600160a01b03606083015116906001600160a01b0360a062ffffff6020860151169401519460405196615d4d88610e70565b875216602086015260408501526060840152608083015260a082015291565b506001600160a01b038291615d06565b906fffffffffffffffffffffffffffffffff8216918203615b3b57565b909390928415615ef6576401000276a4935b60405195606087019287841067ffffffffffffffff851117610e8c576020946001600160a01b03615eac93615e8296604052151598898b52878b018981528260408d01921682526040519b8c9889987fcd0cc1ce000000000000000000000000000000000000000000000000000000008a5260048a019060a080916001600160a01b0381511684526001600160a01b0360208201511660208501526001600160a01b0360408201511660408501526001600160a01b03606082015116606085015262ffffff60808201511660808501520151910152565b51151560c48801525160e487015251166101048501526101406101248501526101448401916112d7565b03815f6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000165af192831561146d575f93615c5d57505f1303615c5757600f0b90565b73fffd8963efd1fc6a506488495d951d5263988d2593615dab56fea164736f6c634300081a000a00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c768000000000000000000000000420000000000000000000000000000000000000600000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e0000000000000000000000000bfbcf9fa4f9c56b0f40a671ad40e0805a09186500000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c957224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e200000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f00000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a900000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f436400000000000000000000000055f4c8aba71a1e923edc303eb4feff14608cc2260000000000000000000000003d311d6283dd8ab90bb0031835c8e606349e2850

Deployed Bytecode

0x60808060405260043610156100ae575b50361561001a575f80fd5b6001600160a01b037f0000000000000000000000004200000000000000000000000000000000000006163314158061007b575b61005357005b7f38bbd576000000000000000000000000000000000000000000000000000000005f5260045ffd5b506001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c41633141561004d565b5f3560e01c9081631a6ae42514610d815750806323a69e7514610ad657806324856bc314610a2757806324dec034146109565780633593564c1461081e5780633f4ba83a146107a2578063406793611461075f5780634a7babb91461071c57806357c79961146106f65780635c975abb146106d1578063715018a61461063a57806379ba50971461056a578063817122dc146105275780638456cb59146104945780638da5cb5b1461046f578063980b444d1461042c578063ab6291fe14610309578063b85aa7af146102e3578063d737d0c71461029e578063e30c397814610278578063f2fde38b146101f35763fbfa77cf146101ac575f61000f565b346101ef575f6003193601126101ef5760206040516001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4168152f35b5f80fd5b346101ef5760206003193601126101ef576001600160a01b03610214610e21565b61021c6139ff565b16807fffffffffffffffffffffffff000000000000000000000000000000000000000060015416176001556001600160a01b035f54167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227005f80a3005b346101ef575f6003193601126101ef5760206001600160a01b0360015416604051908152f35b346101ef575f6003193601126101ef5760207f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c6001600160a01b0360405191168152f35b346101ef575f6003193601126101ef5760206001600160a01b0360035416604051908152f35b346101ef5760206003193601126101ef5760043567ffffffffffffffff81116101ef5761033a903690600401610dc2565b6001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c41633036104045761037391613c9e565b908183036103dc575f5b8381106103b0576103ac604051610395602082610eb9565b5f8152604051918291602083526020830190610e4b565b0390f35b806103d66103c16001938789611081565b3560f81c6103d083878761110b565b91614533565b0161037d565b7faaad13f7000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f62df0545000000000000000000000000000000000000000000000000000000005f5260045ffd5b346101ef575f6003193601126101ef5760206040516001600160a01b037f00000000000000000000000055f4c8aba71a1e923edc303eb4feff14608cc226168152f35b346101ef575f6003193601126101ef5760206001600160a01b035f5416604051908152f35b346101ef575f6003193601126101ef576104ac6139ff565b6104b4611493565b6104bc611493565b740100000000000000000000000000000000000000007fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff60035416176003557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b346101ef575f6003193601126101ef5760206040516001600160a01b037f00000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f4364168152f35b346101ef575f6003193601126101ef57336001600160a01b03600154160361060e577fffffffffffffffffffffffff0000000000000000000000000000000000000000600154166001555f54337fffffffffffffffffffffffff00000000000000000000000000000000000000008216175f556001600160a01b033391167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b7f118cdaa7000000000000000000000000000000000000000000000000000000005f523360045260245ffd5b346101ef575f6003193601126101ef576106526139ff565b7fffffffffffffffffffffffff0000000000000000000000000000000000000000600154166001555f6001600160a01b0381547fffffffffffffffffffffffff000000000000000000000000000000000000000081168355167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346101ef575f6003193601126101ef57602060ff60035460a01c166040519015158152f35b346101ef575f6003193601126101ef5760206001600160a01b0360025416604051908152f35b346101ef575f6003193601126101ef5760206040516001600160a01b037f0000000000000000000000003d311d6283dd8ab90bb0031835c8e606349e2850168152f35b346101ef575f6003193601126101ef5760206040516001600160a01b037f000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b168152f35b346101ef575f6003193601126101ef576107ba6139ff565b6107c2613a12565b6107ca613a12565b7fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff600354166003557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b60606003193601126101ef5760043567ffffffffffffffff81116101ef5761084a903690600401610dc2565b60243567ffffffffffffffff81116101ef5761086a903690600401610df0565b91604435421161092e57333014610923576001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c166108fb576108d693337f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d610f6a565b5f7f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d005b7f6f5ffb7e000000000000000000000000000000000000000000000000000000005f5260045ffd5b61092c93610f6a565b005b7f5bf6f916000000000000000000000000000000000000000000000000000000005f5260045ffd5b346101ef5760406003193601126101ef5761096f610e21565b602435906001600160a01b0382168092036101ef576001600160a01b03906109956139ff565b1680151580610a1e575b156101ef57807fffffffffffffffffffffffff00000000000000000000000000000000000000006002541617600255817fffffffffffffffffffffffff000000000000000000000000000000000000000060035416176003557f26e41379222b54b0470031bc11852ad23058ffb8983f7cc0e18257d6f7afca9d5f80a3005b5081151561099f565b60406003193601126101ef5760043567ffffffffffffffff81116101ef57610a53903690600401610dc2565b60243567ffffffffffffffff81116101ef57610a73903690600401610df0565b91333014610923576001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c166108fb576108d693337f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085d610f6a565b346101ef5760606003193601126101ef5760243560043560443567ffffffffffffffff81116101ef57610b0d903690600401610dc2565b5f831391821580610d77575b610d4f578181016040828203126101ef5781359067ffffffffffffffff82116101ef57610b47918301610ef8565b506020810135916001600160a01b0383168093036101ef57610b6891611126565b90601790602b8310610d27578035968760601c95610bd862ffffff8585013560601c9a60481c168a897f6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e27f00000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c9611186565b6001600160a01b0333911603610cff5715610cf557508685105b15610c065750505061092c9350339161126c565b91935091939482602b0180602b11610cc8578410610c6657508282116101ef5781019103907f80000000000000000000000000000000000000000000000000000000000000008410156101ef5761092c93610c613391610f3e565b6112f7565b925050507faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6929291925c8211610ca05761092c92339161126c565b7f739dbe52000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b9550848710610bf2565b7f32b13d91000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f3b99b53d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f316cf0eb000000000000000000000000000000000000000000000000000000005f5260045ffd5b505f851315610b19565b346101ef575f6003193601126101ef576020906001600160a01b037f000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a9168152f35b9181601f840112156101ef5782359167ffffffffffffffff83116101ef57602083818601950101116101ef57565b9181601f840112156101ef5782359167ffffffffffffffff83116101ef576020808501948460051b0101116101ef57565b600435906001600160a01b03821682036101ef57565b35906001600160a01b03821682036101ef57565b90601f19601f602080948051918291828752018686015e5f8582860101520116010190565b60c0810190811067ffffffffffffffff821117610e8c57604052565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b90601f601f19910116810190811067ffffffffffffffff821117610e8c57604052565b67ffffffffffffffff8111610e8c57601f01601f191660200190565b81601f820112156101ef57803590610f0f82610edc565b92610f1d6040519485610eb9565b828452602083830101116101ef57815f926020809301838601378301015290565b7f80000000000000000000000000000000000000000000000000000000000000008114610cc8575f0390565b919290610f75611493565b808203611059575f5b818110610f8c575050505050565b610f97818386611081565b35610fcf610fa683868961110b565b907fff000000000000000000000000000000000000000000000000000000000000008416611609565b919015908161102e575b50610fe75750600101610f7e565b9061102a6040519283927f2c4029e90000000000000000000000000000000000000000000000000000000084526004840152604060248401526044830190610e4b565b0390fd5b7f8000000000000000000000000000000000000000000000000000000000000000915016155f610fd9565b7fff633a38000000000000000000000000000000000000000000000000000000005f5260045ffd5b9082101561108d570190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b9035907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1813603018212156101ef570180359067ffffffffffffffff82116101ef576020019181360383136101ef57565b9082101561108d576111229160051b8101906110ba565b9091565b909163ffffffff82351682019263ffffffff8435169260208086019585010191011061114e57565b633b99b53d5f526004601cfd5b909163ffffffff60608301351682019263ffffffff8435169260208086019585010191011061114e57565b929161125091926001600160a01b039586821687841611611257575b62ffffff908760405193816020860196168652166040840152166060820152606081526111d0608082610eb9565b519020611242604051938492602084019687917fffffffffffffffffffffffffffffffffffffffff000000000000000000000000605594927fff00000000000000000000000000000000000000000000000000000000000000855260601b166001840152601583015260358201520190565b03601f198101835282610eb9565b5190201690565b9091906111a2565b91908201809211610cc857565b909291906001600160a01b038416300361128c5761128a9350613aec565b565b91926001600160a01b0384116112af576001600160a01b0361128a941692613a4a565b7fc4bd89a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b601f8260209493601f1993818652868601375f8582860101520116010190565b939290602b8210610d27578235938460601c92601785013560601c9380851094859760481c62ffffff16907f6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2927f00000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c99361136f94611186565b6001600160a01b031692845f146040966001600160a01b0380956113cc5f9661141f95611478576401000276a4925b846113b88e51978f948995602087015260608601916112d7565b91168d83015203601f198101855284610eb9565b89519b8c998a9889977f128acb080000000000000000000000000000000000000000000000000000000089521660048801526024870152604486015216606484015260a0608484015260a4830190610e4b565b03925af1801561146d575f925f9161143657509192565b9250506040823d604011611465575b8161145260409383610eb9565b810103126101ef57602082519201519192565b3d9150611445565b6040513d5f823e3d90fd5b73fffd8963efd1fc6a506488495d951d5263988d259261139e565b60ff60035460a01c166114a257565b7fd93c0665000000000000000000000000000000000000000000000000000000005f5260045ffd5b3d156114f4573d906114db82610edc565b916114e96040519384610eb9565b82523d5f602084013e565b606090565b359062ffffff821682036101ef57565b60a080916001600160a01b0361151e82610e37565b1684526001600160a01b0361153560208301610e37565b1660208501526001600160a01b0361154f60408301610e37565b1660408501526001600160a01b0361156960608301610e37565b16606085015262ffffff61157f608083016114f9565b1660808501520135910152565b908160209103126101ef575190565b359065ffffffffffff821682036101ef57565b65ffffffffffff611603606080936001600160a01b036115cd82610e37565b1686526001600160a01b036115e460208301610e37565b166020870152836115f76040830161159b565b1660408701520161159b565b16910152565b90926001916060919060f81c603f1660218110156133d0576010811015612b5f576008811015611f4b578061199857506116486020860135948661115b565b93909560808101355f14611992577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c5b6116838235613bcf565b90869880977f80000000000000000000000000000000000000000000000000000000000000008a14611903575b50509697957f00000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c97f6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e26017995b602b8b8101808211610cc8578b10159c7f80000000000000000000000000000000000000000000000000000000000000008110156101ef578d156118fc5730905b8c83116101ef578d92878035948560601c9082013560601c8082109660481c62ffffff169061176c928a8c611186565b6001600160a01b031691855f149461181c6001600160a01b03936117c75f946040996118e1576401000276a49b5b876117b38c519586948e602087015260608601916112d7565b91168b83015203601f198101835282610eb9565b8488519a8b98899788967f128acb080000000000000000000000000000000000000000000000000000000088521660048701528b6024870152604486015216606484015260a0608484015260a4830190610e4b565b03925af190811561146d575f905f926118a5575b61184093501561189e5750610f3e565b9a1561185c573092898b116101ef578a809101990398926116fb565b505050509295909350604091945091013511611876579190565b7f39d35496000000000000000000000000000000000000000000000000000000005f5260045ffd5b9050610f3e565b9150506040823d82116118d9575b816118c060409383610eb9565b810103126101ef57816020611840935191015191611830565b3d91506118b3565b73fffd8963efd1fc6a506488495d951d5263988d259b61179a565b869061173c565b60149192995010610d27576020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301523560601c5afa90811561146d575f91611960575b50965f806116b0565b90506020813d60201161198a575b8161197b60209383610eb9565b810103126101ef57515f611957565b3d915061196e565b30611679565b91949093909160018103611ac75750906119b76020820135928261115b565b608083013515611ac0577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c915b60406119f18535613bcf565b9401357faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6925d7f80000000000000000000000000000000000000000000000000000000000000008510156101ef57611a4b93610c6186610f3e565b90919015611ab15750611a5d90610f3e565b03611a89575f7faf28d9864a81dfdf71cab65f4e5d79a0cf9b083905fb8971425e6cb581b3f6925d9190565b7fd4e0248e000000000000000000000000000000000000000000000000000000005f5260045ffd5b611abb9150610f3e565b611a5d565b30916119e5565b60028103611b155750611b1191604081013591507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c611b0a6020830135613bcf565b9135613a4a565b9190565b909491929060038103611ce457505050803581019263ffffffff60208301351682019063ffffffff8235169260208084019385010191011061114e577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c91604051916001600160a01b0360208401947f2a2d80d10000000000000000000000000000000000000000000000000000000086521660248401526060604484015260e483019580357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1823603018112156101ef5781016020813591019767ffffffffffffffff82116101ef578160071b360389136101ef5781906060608488015252610104850197905f5b818110611cc657505050926112425f96978294611c8b946040886001600160a01b03611c4f60208e9d9c01610e37565b1660a4880152013560c48601527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc8584030160648601526112d7565b5190826001600160a01b037f00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c768165af190611cc36114ca565b90565b90919860808082611cd96001948e6115ae565b019a01929101611c1f565b919450919060048103611e2d5750611cff6020820135613bcf565b906001600160a01b038060408301351691351680155f14611d67575047908110611d3f5780611d2f575b50509190565b611d3891613dee565b5f80611d29565b7f6a12f104000000000000000000000000000000000000000000000000000000005f5260045ffd5b91604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481875afa92831561146d575f93611df9575b508210611dd15781611dc0575b5050509190565b611dc992613d36565b5f8080611db9565b7f675cae38000000000000000000000000000000000000000000000000000000005f5260045ffd5b9092506020813d602011611e25575b81611e1560209383610eb9565b810103126101ef5751915f611dac565b3d9150611e08565b60058103611e545750806040611b1192013590611e4d6020820135613bcf565b9035613aec565b60068103611f2057506040810135906001600160a01b03611e786020830135613bcf565b91351680611e945750611e8e611b1192476144f1565b90613dee565b906040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481865afa90811561146d575f91611eec575b50611b1193611ee6916144f1565b91613d36565b90506020813d602011611f18575b81611f0760209383610eb9565b810103126101ef5751611b11611ed8565b3d9150611efa565b7fd76a1e9e000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b919490939091600881036121c45750611f6960208301359183613c45565b906080840135156121bd577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c915b611fa28535613bcf565b92821561108d57611fb282613c24565b836001101561108d57611fd461201c91611fce60208601613c24565b90615363565b907f57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d7f00000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e615381565b9485816121a3575b5050505f198201828111610cc85761204d6120486001600160a01b03928585613c14565b613c24565b1693604051927f70a082310000000000000000000000000000000000000000000000000000000084526001600160a01b038516928360048601526020856024818a5afa94851561146d575f95612165575b50946120ae929160209596614116565b6024604051809581937f70a0823100000000000000000000000000000000000000000000000000000000835260048301525afa91821561146d575f92612130575b5060406120ff9293013592613c38565b10612108579190565b7f849eaf98000000000000000000000000000000000000000000000000000000005f5260045ffd5b91506020823d60201161215d575b8161214b60209383610eb9565b810103126101ef5790519060406120ef565b3d915061213e565b92919450946020833d60201161219b575b8161218360209383610eb9565b810103126101ef5791519194919390916120ae61209e565b3d9150612176565b6121b5926121b085613c24565b61126c565b5f8085612024565b3091611f98565b600981036124ad57506121d79082613c45565b9091906080820135156124a6577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c925b6122128335613bcf565b917f00000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e947f57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d945f956002851061247e576020820135975f198601868111610cc8579190825b6122cc575050506040013586116122a457821561108d57611b11958561229f926121b085613c24565b614116565b7f8ab0bc16000000000000000000000000000000000000000000000000000000005f5260045ffd5b90919897505f19890197898911610cc8576122ee6120486123109a8989613c14565b6123056122ff6120488d8b8b613c14565b82615363565b8186869d939d615381565b90604051907f0902f1ac0000000000000000000000000000000000000000000000000000000082526060826004816001600160a01b0387165afa91821561146d575f905f9361242e575b506001600160a01b036dffffffffffffffffffffffffffff8082931694169d169116145f146124285799905b9980158015612420575b6123f8578261239e916144a7565b916127108302928084046127101490151715610cc8576123bd91613c38565b6126f78102908082046126f71490151715610cc8576123db916144ba565b60018101809111610cc8576123f09099613e73565b919082612276565b7f7b9c8916000000000000000000000000000000000000000000000000000000005f5260045ffd5b508115612390565b90612386565b6dffffffffffffffffffffffffffff8094506001600160a01b03925061246b839260603d8111612477575b6124638183610eb9565b8101906140e0565b5095909350505061235a565b503d612459565b7f20db8267000000000000000000000000000000000000000000000000000000005f5260045ffd5b3092612208565b93949193909290600a81036125945750505063ffffffff60c08301351682019063ffffffff823516908360208085019484010191011061114e5760a0611c8b5f9461124286957f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c956040519586946001600160a01b0360208701997f2b67b570000000000000000000000000000000000000000000000000000000008b5216602487015261255f60448701826115ae565b6001600160a01b0361257360808301610e37565b1660c4870152013560e48501526101006101048501526101248401916112d7565b91949390929091600b810361274c5750506125b460208201359135613bcf565b90807f8000000000000000000000000000000000000000000000000000000000000000810361271d575050475b5f90806125ef575050509190565b6001600160a01b037f00000000000000000000000042000000000000000000000000000000000000061692833b156101ef576040517fd0e30db00000000000000000000000000000000000000000000000000000000081525f8160048186895af1801561146d57612701575b506001600160a01b031690308203612674575b50611db9565b60446020928460405196879485937fa9059cbb000000000000000000000000000000000000000000000000000000008552600485015260248401525af19081156126f557506126c6575b80808061266e565b6126e79060203d6020116126ee575b6126df8183610eb9565b810190613c86565b505f6126be565b503d6126d5565b604051903d90823e3d90fd5b61270e9193505f90610eb9565b5f916001600160a01b0361265b565b4710156125e1577f6a12f104000000000000000000000000000000000000000000000000000000005f5260045ffd5b600c810361289c5750506127608135613bcf565b906001600160a01b037f000000000000000000000000420000000000000000000000000000000000000616604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481855afa92831561146d575f93612867575b50602001358210611d3f57816127e6575050509190565b803b156101ef575f80916024604051809481937f2e1a7d4d0000000000000000000000000000000000000000000000000000000083528760048401525af1801561146d57612857575b50306001600160a01b03831603612847575b80611db9565b61285091613dee565b5f80612841565b5f61286191610eb9565b5f61282f565b9092506020813d602011612894575b8161288360209383610eb9565b810103126101ef57519160206127cf565b3d9150612876565b9094919390600d8103612a71575083358401928335956128c46020808701978703018861125f565b11610d275793946001600160a01b037f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c1694905f5b8181101561295257866001600160a01b0361291c60208460071b8a0101613c24565b160361292a576001016128fa565b7fe7002877000000000000000000000000000000000000000000000000000000005f5260045ffd5b50929591945092506001600160a01b037f00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c7681690813b156101ef576040517f0d58b1db000000000000000000000000000000000000000000000000000000008152602060048201526024810184905292839160448301915f5b8181106129f75750505091815f81819503925af1801561146d576129ed57509190565b5f611b1191610eb9565b919350916080806001926001600160a01b03612a1288610e37565b1681526001600160a01b03612a2960208901610e37565b1660208201526001600160a01b03612a4360408901610e37565b1660408201526001600160a01b03612a5d60608901610e37565b1660608201520194019101918593926129ca565b919450929150600e8103611f205750604051907f70a082310000000000000000000000000000000000000000000000000000000082526001600160a01b0381351660048301526020826024816001600160a01b0384860135165afa91821561146d575f92612b2a575b50604001351180612aea57159190565b91506040517fa328167200000000000000000000000000000000000000000000000000000000602082015260048152612b24602482610eb9565b91159190565b9091506020813d602011612b57575b81612b4660209383610eb9565b810103126101ef5751906040612ada565b3d9150612b39565b91949093909160108103612c625750612bb0915f9160405193849283927f815483190000000000000000000000000000000000000000000000000000000084526020600485015260248401916112d7565b0381836001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4165af1801561146d57612bee57509190565b3d805f833e612bfd8183610eb9565b8101906020818303126101ef5780519067ffffffffffffffff82116101ef570181601f820112156101ef578051612c3381610edc565b92612c416040519485610eb9565b818452602082840101116101ef575f928160208094018483015e0101529190565b80929495506011919350145f14612d375750907fffffffff000000000000000000000000000000000000000000000000000000008135167f7ac2ff7b000000000000000000000000000000000000000000000000000000008103612d0c5750815f92918392604051928392833781018381520390826001600160a01b037f00000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f4364165af190611cc36114ca565b7ff801e525000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6012810361305157507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c917fffffffff000000000000000000000000000000000000000000000000000000008135167f0c49ccbe0000000000000000000000000000000000000000000000000000000081148015613028575b8015612fff575b15612d0c575060048101356001600160a01b037f00000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f43641693604051907f6352211e000000000000000000000000000000000000000000000000000000008252826004830152602082602481895afa91821561146d575f92612fc3575b506001600160a01b038116916001600160a01b0381168314928315612f2b575b508215612eae575b505015612e83575091815f809481946040519384928337810182815203925af190611cc36114ca565b7fbb25d4c5000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b6040517fe985e9c50000000000000000000000000000000000000000000000000000000081526001600160a01b039182166004820152911660248201529050602081604481885afa90811561146d575f91612f0c575b505f80612e5a565b612f25915060203d6020116126ee576126df8183610eb9565b5f612f04565b9092506040517f081812fc0000000000000000000000000000000000000000000000000000000081528460048201526020816024818b5afa801561146d575f90612f83575b6001600160a01b0391501614915f612e52565b506020813d602011612fbb575b81612f9d60209383610eb9565b810103126101ef57612fb66001600160a01b03916140b1565b612f70565b3d9150612f90565b9091506020813d602011612ff7575b81612fdf60209383610eb9565b810103126101ef57612ff0906140b1565b905f612e32565b3d9150612fd2565b507f42966c68000000000000000000000000000000000000000000000000000000008114612db8565b507ffc6f7865000000000000000000000000000000000000000000000000000000008114612db1565b601381036130ef5750505f80916040516001600160a01b0360c060208301937f8b0c1b220000000000000000000000000000000000000000000000000000000085526130a06024850182611509565b01351660e482015260e481526130b861010482610eb9565b5190826001600160a01b037f000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b165af16111226114ca565b601481036131895750505f809160405162ffffff60c060208301937fdc2ab18c00000000000000000000000000000000000000000000000000000000855261313a6024850182611509565b01351660e482015260e4815261315261010482610eb9565b5190826001600160a01b037f000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a9165af16111226114ca565b601581036132c257507fffffffff000000000000000000000000000000000000000000000000000000008235167fdd46508f000000000000000000000000000000000000000000000000000000008103612d0c5750806004116101ef576132006131fa600319830160048501611126565b90611126565b5f5b818110613257575050505f9182914791816040519283928337810184815203916001600160a01b037f00000000000000000000000055f4c8aba71a1e923edc303eb4feff14608cc226165af190611cc36114ca565b613262818385611081565b3560f81c80159081156132b7575b81156132ac575b5061328457600101613202565b7f5d1d0f9f000000000000000000000000000000000000000000000000000000005f5260045ffd5b60039150145f613277565b600181149150613270565b60168103611f2057507fffffffff000000000000000000000000000000000000000000000000000000008235167fdd46508f000000000000000000000000000000000000000000000000000000008103612d0c5750806004116101ef576133336131fa600319830160048501611126565b5f5b81811061338a575050505f9182914791816040519283928337810184815203916001600160a01b037f0000000000000000000000003d311d6283dd8ab90bb0031835c8e606349e2850165af190611cc36114ca565b601a613397828486611081565b3560f81c146133a857600101613335565b7f103b4710000000000000000000000000000000000000000000000000000000005f5260045ffd5b91949093929091602181036135275750506133ec929350613c9e565b906134306040949394519360208501957f24856bc30000000000000000000000000000000000000000000000000000000087526040602487015260648601916112d7565b917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc848403016044850152808352602083019060208160051b85010193835f917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe182360301905b8484106134cc575050505050505091816134bd5f9493859403601f198101835282610eb9565b519082305af190611cc36114ca565b90919293949596601f198282030187528735838112156101ef578401906020823592019167ffffffffffffffff81116101ef5780360383136101ef5761351860209283926001956112d7565b99019701959401929190613497565b90929190602281036137675750602081013561354f6135468484613c45565b91909484613c69565b949060a085013515613761577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c5b6135888635613bcf565b9480151580613737575b613715575b50505f198201828111610cc8576135ba6120486001600160a01b03928587613c14565b1695604051927f70a082310000000000000000000000000000000000000000000000000000000084523060048501526020846024818b5afa93841561146d575f946136df575b5061360b9394613e7f565b6040517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152602081602481885afa90811561146d575f916136ac575b5060409161365b91613c38565b920135821061368457306001600160a01b0382160361367b575050509190565b611dc992613aec565b7fcd7d97e4000000000000000000000000000000000000000000000000000000005f5260045ffd5b90506020813d6020116136d7575b816136c760209383610eb9565b810103126101ef5751604061364e565b3d91506136ba565b93506020843d60201161370d575b816136fa60209383610eb9565b810103126101ef5761360b935193613600565b3d91506136ed565b831561108d576137309161372886613c24565b90309161126c565b5f80613597565b507f8000000000000000000000000000000000000000000000000000000000000000811415613592565b3061357e565b60238103611f2057509081602061378e930135916137858183613c45565b94909183613c69565b94909260a0810135156139f8577f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c935b6001600160a01b0360025416966001600160a01b036003541697600286106139d0576137ea86613e5b565b6137f76040519182610eb9565b86815261380387613e5b565b91601f196020830193013684375f1988019a888c11610cc8578a6138278d85613bbb565b528b805b6138d057505050511561108d575192604081013584116138a85761384f9035613bcf565b95851561108d5761386e936138679161372887613c24565b8484613e7f565b306001600160a01b03841603613888575b50505050509190565b61389e946138999261204892613c14565b613aec565b5f8080808061387f565b7fbf1e94da000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f19810190808211610cc85761390f8a6138fc612048848f6138f6612048898388613c14565b94613c14565b613907858c8c613c14565b359187614fc1565b93919061391c8489613bbb565b51916001600160a01b03604051967fca4bc7140000000000000000000000000000000000000000000000000000000088521660048701526024860152604485015260648401525f19608484015260208360a481875afa92831561146d575f9361399b575b509161398f6139959387613bbb565b52613e73565b8061382b565b92506020833d82116139c8575b816139b560209383610eb9565b810103126101ef5791519161398f613980565b3d91506139a8565b7fa22caccc000000000000000000000000000000000000000000000000000000005f5260045ffd5b30936137bf565b6001600160a01b035f5416330361060e57565b60ff60035460a01c1615613a2257565b7f8dfc202b000000000000000000000000000000000000000000000000000000005f5260045ffd5b91926001600160a01b037f00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c7681691823b156101ef575f6001600160a01b039384829681608496816040519b8c9a8b997f36c78516000000000000000000000000000000000000000000000000000000008b521660048a01521660248801521660448601521660648401525af1801561146d57613ae25750565b5f61128a91610eb9565b9091906001600160a01b031680613b07575061128a91613dee565b7f80000000000000000000000000000000000000000000000000000000000000008214613b39575b9161128a92613d36565b9050604051917f70a08231000000000000000000000000000000000000000000000000000000008352306004840152602083602481855afa801561146d575f90613b87575b90925090613b2f565b506020833d602011613bb3575b81613ba160209383610eb9565b810103126101ef5761128a9251613b7e565b3d9150613b94565b805182101561108d5760209160051b010190565b6001600160a01b03811660018103613c085750507f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c90565b600203611cc357503090565b919081101561108d5760051b0190565b356001600160a01b03811681036101ef5790565b91908203918211610cc857565b916060830135830191613c6260208435958186019503018561125f565b11610d2757565b916080830135830191613c6260208435958186019503018561125f565b908160209103126101ef575180151581036101ef5790565b604081351891606082019363ffffffff6040840135169363ffffffe0601f8601169060608201602086013518179084019260608401359463ffffffff861694641fffffffe0608082019760051b1680915f925b808410613d0957506080925001019101101761114e57565b90916020809163ffffffe0601f60808089890101359b848d18179b88010135011601019301929190613cf1565b5f91826044926020956001600160a01b03604051947fa9059cbb00000000000000000000000000000000000000000000000000000000865216600485015260248401525af13d15601f3d1160015f511416171615613d9057565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f5452414e534645525f4641494c454400000000000000000000000000000000006044820152fd5b5f80809381935af115613dfd57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4554485f5452414e534645525f4641494c4544000000000000000000000000006044820152fd5b67ffffffffffffffff8111610e8c5760051b60200190565b8015610cc8575f190190565b919092805f19850103614089575f5b818110613e9c575050505050565b80613eb36120486001600160a01b03938888613c14565b613ee0613ec7612048600185018a8a613c14565b84600254169083613ed986898b613c14565b3592614fc1565b9490919216604051947f70a08231000000000000000000000000000000000000000000000000000000008652306004870152602086602481855afa95861561146d575f96614056575b505f6044602092826001600160a01b03604051927f095ea7b300000000000000000000000000000000000000000000000000000000845216958660048401528a60248401525af13d15601f3d1160015f511416171615613ff857803b156101ef575f928360849260405197889586947f5b41b9080000000000000000000000000000000000000000000000000000000086526004860152602485015260448401528160648401525af191821561146d57600192613fe8575b5001613e8e565b5f613ff291610eb9565b5f613fe1565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f415050524f56455f4641494c45440000000000000000000000000000000000006044820152fd5b9095506020813d8211614081575b8161407160209383610eb9565b810103126101ef5751945f613f29565b3d9150614064565b7ff8637a39000000000000000000000000000000000000000000000000000000005f5260045ffd5b51906001600160a01b03821682036101ef57565b51906dffffffffffffffffffffffffffff821682036101ef57565b908160609103126101ef576140f4816140c5565b916040614103602084016140c5565b92015163ffffffff811681036101ef5790565b916002821061447f57811561108d5761412e83613c24565b826001101561108d5761414a90611fce60208697959601613c24565b50925f198101937ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe8201955f90602093601f198501965b8884106141945750505050505050505050565b6141a2612048858486613c14565b946001600160a01b036141bc612048600188018688613c14565b921695604051917f0902f1ac0000000000000000000000000000000000000000000000000000000083526060836004818b5afa91821561146d57895f945f94614439575b506001600160a01b03806dffffffffffffffffffffffffffff80602496979816971693169416841494855f146144335791935b604051938480927f70a082310000000000000000000000000000000000000000000000000000000082528d60048301525afa91821561146d575f92614404575b50808203928115928380156143fc575b6123f857826126f786029586046126f71491141715610cc8576142a690846144a7565b916127108202918204612710141715610cc8576142cc926142c69161125f565b906144ba565b90156143f5575f90915b8b8610156143ec57906142f761434192611fce61204860028a01888a613c14565b8193917f57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d7f00000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e615381565b915b96604051906143528a83610eb9565b5f82528b368b840137803b156101ef576143c0945f8094604051978895869485937f022c0d9f000000000000000000000000000000000000000000000000000000008552600485015260248401526001600160a01b0389166044840152608060648401526084830190610e4b565b03925af191821561146d576001926143dc575b50930192614181565b5f6143e691610eb9565b5f6143d3565b5087905f614343565b5f916142d6565b508115614283565b9091508981813d831161442c575b61441c8183610eb9565b810103126101ef5751905f614273565b503d614412565b93614233565b6dffffffffffffffffffffffffffff955060249394506001600160a01b0386614470829360603d8111612477576124638183610eb9565b50989098979650505050614200565b7fae52ad0c000000000000000000000000000000000000000000000000000000005f5260045ffd5b81810292918115918404141715610cc857565b81156144c4570490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b612710821161450b5761271091614507916144a7565b0490565b7fdeaa01e6000000000000000000000000000000000000000000000000000000005f5260045ffd5b929190600b841015614a5e57600784036146ae5761455292935061591c565b6020810190614561828261592a565b90505f9261456e83613c24565b9061457b60408501615850565b906fffffffffffffffffffffffffffffffff821615614695575b92915f915b83831061461b5750505050506060016fffffffffffffffffffffffffffffffff806145c483615850565b1692169182106145d2575050565b6145ec6fffffffffffffffffffffffffffffffff91615850565b7f4e86d23a000000000000000000000000000000000000000000000000000000005f521660045260245260445ffd5b8496506fffffffffffffffffffffffffffffffff614679916146606146508661464a61467e9798999a8c61592a565b9061597e565b9561465b36886159be565b615cb0565b61466d60808801886110ba565b949093165f0391615d99565b615c91565b94600161468b8793613c24565b919493019161459a565b90506146a86146a3836153f0565b615ac7565b90614595565b600684036147a8576146c1929350615841565b6146cd60e08201615850565b6fffffffffffffffffffffffffffffffff811615614755575b614738614679610100926147176fffffffffffffffffffffffffffffffff61471060c0880161586d565b9216610f3e565b906147266101208701876110ba565b929091614733368961587a565b615d99565b91016fffffffffffffffffffffffffffffffff806145c483615850565b5061476260c0820161586d565b1561478d576101006147386146796147846146a361477f86613c24565b6153f0565b925050506146e6565b6101006147386146796147846146a361477f60208701613c24565b60098403614911576147bb92935061591c565b60208101906147ca828261592a565b5f9391506147da60408401615850565b6147e384613c24565b916fffffffffffffffffffffffffffffffff8216156148fd575b92919290815b61488057505050506060016fffffffffffffffffffffffffffffffff8061482983615850565b169216918211614837575050565b6148516fffffffffffffffffffffffffffffffff91615850565b7f79cb628f000000000000000000000000000000000000000000000000000000005f521660045260245260445ffd5b829395506fffffffffffffffffffffffffffffffff6148dc916148c26148b76148ad6148e696978a61592a565b5f1989019161597e565b9861465b368b6159be565b906148d060808b018b6110ba565b94909316911590615d99565b600f0b5f03615ac7565b935f196148f38692613c24565b9392019081614803565b905061490b6146a383615746565b906147fd565b60088414614948575050505b7f5cda29d7000000000000000000000000000000000000000000000000000000005f5260045260245ffd5b614953929350615841565b61495f60e08201615850565b6fffffffffffffffffffffffffffffffff8116156149e1575b6149c46146796149bf6fffffffffffffffffffffffffffffffff610100946149a260c0880161586d565b6149b06101208901896110ba565b9390921690614733368a61587a565b6158ed565b91016fffffffffffffffffffffffffffffffff8061482983615850565b506149ee60c0820161586d565b15614a32576101006149c46146796149bf6fffffffffffffffffffffffffffffffff614a276146a3614a2260208901613c24565b615746565b945050505050614978565b6101006149c46146796149bf6fffffffffffffffffffffffffffffffff614a276146a3614a2288613c24565b6018841115614def57601d8403614b5f57614a7a92935061591c565b6020810190614a89828261592a565b90505f92614a9683613c24565b90614aa360408501615850565b906fffffffffffffffffffffffffffffffff821615614b46575b92915f915b838310614aec5750505050506060016fffffffffffffffffffffffffffffffff806145c483615850565b849650614b1561467991614b0d6146508661464a614b2f9798999a8c61592a565b929091615b0c565b5f03600f0b614b2760808701876110ba565b939092615b48565b946001614b3c8793613c24565b9194930191614ac2565b9050614b59614b54836153f0565b615d7c565b90614abd565b601c8403614c2857614b72929350615841565b614b7e60e08201615850565b6fffffffffffffffffffffffffffffffff811615614bda575b61473861467961010092614bb96149bf614bb360c0880161586d565b92615b0c565b90614bc86101208701876110ba565b929091614bd5368961587a565b615b48565b50614be760c0820161586d565b15614c0d57610100614738614679614c04614b5461477f86613c24565b92505050614b97565b610100614738614679614c04614b5461477f60208701613c24565b601f8403614d1c57614c3b92935061591c565b6020810190614c4a828261592a565b5f939150614c5a60408401615850565b614c6384613c24565b916fffffffffffffffffffffffffffffffff821615614d08575b92919290815b614ca957505050506060016fffffffffffffffffffffffffffffffff8061482983615850565b82939550614ce790614cd0614cc86148b76148ad614cf196978a61592a565b919092615b0c565b614cdd60808a018a6110ba565b9390921590615b48565b5f03600f0b615c91565b935f19614cfe8692613c24565b9392019081614c83565b9050614d166146a383615746565b90614c7d565b601e8414614d2c5750505061491d565b614d37929350615841565b614d4360e08201615850565b6fffffffffffffffffffffffffffffffff811615614d9a575b6149c46146796149bf61010093614d7e614d7860c0880161586d565b91615b0c565b90614d8d6101208801886110ba565b929091614bd5368a61587a565b50614da760c0820161586d565b15614dd4576101006149c46146796149bf614dca6146a3614a2260208801613c24565b9350505050614d5c565b6101006149c46146796149bf614dca6146a3614a2287613c24565b92600c8103614e735750614e039192615733565b90614e0d81615746565b91808311614e4357509061128a917f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c906155d3565b90507f79cb628f000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b600f8103614ef65750614e869192615733565b90614e90816153f0565b91808310614ec657509061128a917f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c906154e5565b90507f4e86d23a000000000000000000000000000000000000000000000000000000005f5260045260245260445ffd5b600b8103614f4f5750614f0d9061128a92936153d8565b15614f4457614f3e827f0e87e1788ebd9ed6a7e63c70a374cd3283e41cad601d21fbe27863899ed4a7085c92615592565b916155d3565b614f3e823092615592565b600e8103614f825750614f76614f6c614f7c9261128a94956153d8565b9282949291613bcf565b9261557e565b916154e5565b9260108414614f935750505061491d565b61128a929350614fa9614fb292614f7c926153d8565b92919390613bcf565b91614fbc846153f0565b6144f1565b92939290915f8080600288036151495750506040517f400f7a1e0000000000000000000000000000000000000000000000000000000081526001600160a01b03858116600483015292831660248201529495506080928592604492508391165afa91821561146d575f926150b9575b506001600160a01b03806020840151169116145f146150b05760ff5f5b1691826150a0576001600160a01b0360ff60015b16925116905b6001600160a01b0382161561507857565b7fda6a56c3000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b0360ff5f615061565b60ff600161504d565b9091506080813d608011615141575b816150d560809383610eb9565b810103126101ef57604051906080820182811067ffffffffffffffff821117610e8c576151359160609160405261510b816140b1565b8452615119602082016140b1565b602085015261512a604082016140b1565b6040850152016140b1565b6060820152905f615030565b3d91506150c8565b94909593919660031461515f575b505050615067565b9195909492935060a060405180967f923093cb000000000000000000000000000000000000000000000000000000008252816001600160a01b03816151c08c89600484019092916001600160a01b0360209181604085019616845216910152565b0392165afa94851561146d575f956152c2575b506001600160a01b038060208701511692168281145f1461526e5750506001600160a01b035f955b1690810361521b5750506001600160a01b035f925b5116905f8080615157565b60408401516001600160a01b031681036152415750506001600160a01b03600192615210565b6001600160a01b03606085939501511614615265575b6001600160a01b0390615210565b60029250615257565b60408601516001600160a01b031681036152945750506001600160a01b036001956151fb565b6001600160a01b03606087989398015116146152b9575b6001600160a01b03906151fb565b600295506152ab565b90945060a0813d60a01161535b575b816152de60a09383610eb9565b810103126101ef576040519060a0820182811067ffffffffffffffff821117610e8c5761534f91608091604052615314816140b1565b8452615322602082016140b1565b6020850152615333604082016140b1565b6040850152615344606082016140b1565b6060850152016140b1565b6080820152935f6151d3565b3d91506152d1565b6001600160a01b0382166001600160a01b038216105f146111225791565b91611250906001600160a01b03947fffffffffffffffffffffffffffffffffffffffff0000000000000000000000006040519181602084019460601b16845260601b166034820152602881526111d0604882610eb9565b9060601161114e578035916040602083013592013590565b6040517fa54b28310000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b038216602482015290602082806044810103816001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4165afa91821561146d575f926154b1575b505f821261547c575090565b6001600160a01b03907f4c085bf1000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b9091506020813d6020116154dd575b816154cd60209383610eb9565b810103126101ef5751905f615470565b3d91506154c0565b90918015615579576001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c416803b156101ef575f92836064926001600160a01b03948560405198899788967f0b0d9c0900000000000000000000000000000000000000000000000000000000885216600487015216602485015260448401525af1801561146d57613ae25750565b505050565b908161558e57611cc391506153f0565b5090565b907f800000000000000000000000000000000000000000000000000000000000000082036155c457611cc39150615a3d565b8161558e57611cc39150615746565b5f91831561572d576001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c41691823b156101ef576001600160a01b03604051917fa584119400000000000000000000000000000000000000000000000000000000835216908160048201525f8160248183885af1801561146d57615718575b50806156cb5750506020906004604051809581937f11da60b40000000000000000000000000000000000000000000000000000000083525af19081156126f557506156a05750565b6156c19060203d6020116156c4575b6156b98183610eb9565b81019061158c565b50565b503d6156af565b839483602094936156db9361126c565b6004604051809581937f11da60b40000000000000000000000000000000000000000000000000000000083525af19081156126f557506156a05750565b6157259194505f90610eb9565b5f925f615658565b50505050565b919060401161114e576020823592013590565b6040517fa54b28310000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b038216602482015290602082806044810103816001600160a01b037f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4165afa91821561146d575f9261580d575b505f82136157d85750611cc390610f3e565b6001600160a01b03907f3351b260000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b9091506020813d602011615839575b8161582960209383610eb9565b810103126101ef5751905f6157c6565b3d915061581c565b906101601161114e5780350190565b356fffffffffffffffffffffffffffffffff811681036101ef5790565b3580151581036101ef5790565b91908260c09103126101ef5760405161589281610e70565b60a08082946158a081610e37565b84526158ae60208201610e37565b60208501526158bf60408201610e37565b60408501526158d060608201610e37565b60608501526158e1608082016114f9565b60808501520135910152565b600f0b7fffffffffffffffffffffffffffffffff800000000000000000000000000000008114610cc8575f0390565b9060a01161114e5780350190565b9035907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1813603018212156101ef570180359067ffffffffffffffff82116101ef57602001918160051b360383136101ef57565b919081101561108d5760051b810135907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff41813603018212156101ef570190565b91909160c0818403126101ef57604051906159d882610e70565b81936159e382610e37565b83526159f1602083016114f9565b6020840152615a0260408301610e37565b6040840152615a1360608301610e37565b606084015260808201359167ffffffffffffffff83116101ef576158e160a0939284938301610ef8565b6001600160a01b031680615a5057504790565b6020602491604051928380927f70a082310000000000000000000000000000000000000000000000000000000082523060048301525afa90811561146d575f91615a98575090565b90506020813d602011615abf575b81615ab360209383610eb9565b810103126101ef575190565b3d9150615aa6565b906fffffffffffffffffffffffffffffffff8216809203615ae457565b7f93dafdf1000000000000000000000000000000000000000000000000000000005f5260045ffd5b6fffffffffffffffffffffffffffffffff166f7fffffffffffffffffffffffffffffff8111615b3b57600f0b90565b6393dafdf15f526004601cfd5b615be590615c0c60209396949560405197889485947f911a63b7000000000000000000000000000000000000000000000000000000008652600486019060a080916001600160a01b0381511684526001600160a01b0360208201511660208501526001600160a01b0360408201511660408501526001600160a01b03606082015116606085015262ffffff60808201511660808501520151910152565b1515968760c4850152600f0b958660e48501526101206101048501526101248401916112d7565b03815f6001600160a01b037f000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a9165af192831561146d575f93615c5d575b505f1303615c5757600f0b90565b60801d90565b9092506020813d602011615c89575b81615c7960209383610eb9565b810103126101ef5751915f615c49565b3d9150615c6c565b5f81600f0b12615ae4576fffffffffffffffffffffffffffffffff1690565b905f60a0604051615cc081610e70565b82815282602082015282604082015282606082015282608082015201526001600160a01b038251166001600160a01b038216918183105f14615d6c576001600160a01b03905b16809214926001600160a01b036040820151166001600160a01b03606083015116906001600160a01b0360a062ffffff6020860151169401519460405196615d4d88610e70565b875216602086015260408501526060840152608083015260a082015291565b506001600160a01b038291615d06565b906fffffffffffffffffffffffffffffffff8216918203615b3b57565b909390928415615ef6576401000276a4935b60405195606087019287841067ffffffffffffffff851117610e8c576020946001600160a01b03615eac93615e8296604052151598898b52878b018981528260408d01921682526040519b8c9889987fcd0cc1ce000000000000000000000000000000000000000000000000000000008a5260048a019060a080916001600160a01b0381511684526001600160a01b0360208201511660208501526001600160a01b0360408201511660408501526001600160a01b03606082015116606085015262ffffff60808201511660808501520151910152565b51151560c48801525160e487015251166101048501526101406101248501526101448401916112d7565b03815f6001600160a01b037f000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b165af192831561146d575f93615c5d57505f1303615c5757600f0b90565b73fffd8963efd1fc6a506488495d951d5263988d2593615dab56fea164736f6c634300081a000a

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

00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c768000000000000000000000000420000000000000000000000000000000000000600000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e0000000000000000000000000bfbcf9fa4f9c56b0f40a671ad40e0805a09186500000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c957224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e200000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f00000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f000000000000000000000000238a358808379702088667322f80ac48bad5e6c4000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a900000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f436400000000000000000000000055f4c8aba71a1e923edc303eb4feff14608cc2260000000000000000000000003d311d6283dd8ab90bb0031835c8e606349e2850

-----Decoded View---------------
Arg [0] : params (tuple):
Arg [1] : permit2 (address): 0x31c2F6fcFf4F8759b3Bd5Bf0e1084A055615c768
Arg [2] : weth9 (address): 0x4200000000000000000000000000000000000006
Arg [3] : v2Factory (address): 0x02a84c1b3BBD7401a5f7fa98a384EBC70bB5749E
Arg [4] : v3Factory (address): 0x0BFbCF9fa4f9C56B0F40a671Ad40E0805A091865
Arg [5] : v3Deployer (address): 0x41ff9AA7e16B8B1a8a8dc4f0eFacd93D02d071c9
Arg [6] : v2InitCodeHash (bytes32): 0x57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d
Arg [7] : v3InitCodeHash (bytes32): 0x6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2
Arg [8] : stableFactory (address): 0x64D74e1EAAe3176744b5767b93B7Bee39Cf7898F
Arg [9] : stableInfo (address): 0x64D74e1EAAe3176744b5767b93B7Bee39Cf7898F
Arg [10] : infiVault (address): 0x238a358808379702088667322f80aC48bAd5e6c4
Arg [11] : infiClPoolManager (address): 0xa0FfB9c1CE1Fe56963B0321B32E7A0302114058b
Arg [12] : infiBinPoolManager (address): 0xC697d2898e0D09264376196696c51D7aBbbAA4a9
Arg [13] : v3NFTPositionManager (address): 0x46A15B0b27311cedF172AB29E4f4766fbE7F4364
Arg [14] : infiClPositionManager (address): 0x55f4c8abA71A1e923edC303eb4fEfF14608cC226
Arg [15] : infiBinPositionManager (address): 0x3D311D6283Dd8aB90bb0031835C8e606349e2850


-----Encoded View---------------
15 Constructor Arguments found :
Arg [0] : 00000000000000000000000031c2f6fcff4f8759b3bd5bf0e1084a055615c768
Arg [1] : 0000000000000000000000004200000000000000000000000000000000000006
Arg [2] : 00000000000000000000000002a84c1b3bbd7401a5f7fa98a384ebc70bb5749e
Arg [3] : 0000000000000000000000000bfbcf9fa4f9c56b0f40a671ad40e0805a091865
Arg [4] : 00000000000000000000000041ff9aa7e16b8b1a8a8dc4f0efacd93d02d071c9
Arg [5] : 57224589c67f3f30a6b0d7a1b54cf3153ab84563bc609ef41dfb34f8b2974d2d
Arg [6] : 6ce8eb472fa82df5469c6ab6d485f17c3ad13c8cd7af59b3d4a8026c5ce0f7e2
Arg [7] : 00000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f
Arg [8] : 00000000000000000000000064d74e1eaae3176744b5767b93b7bee39cf7898f
Arg [9] : 000000000000000000000000238a358808379702088667322f80ac48bad5e6c4
Arg [10] : 000000000000000000000000a0ffb9c1ce1fe56963b0321b32e7a0302114058b
Arg [11] : 000000000000000000000000c697d2898e0d09264376196696c51d7abbbaa4a9
Arg [12] : 00000000000000000000000046a15b0b27311cedf172ab29e4f4766fbe7f4364
Arg [13] : 00000000000000000000000055f4c8aba71a1e923edc303eb4feff14608cc226
Arg [14] : 0000000000000000000000003d311d6283dd8ab90bb0031835c8e606349e2850


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
0xd9C500DfF816a1Da21A48A732d3498Bf09dc9AEB
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.