Skip to content
Verified contractPartialGPL-2.0-or-later

MixedQuoter

Address0x144d44602db4eab59fa4db668643fb7c363e88bf
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,348,564
Creation transaction
0x38813291b2…ae6ba4ff6f

src/MixedQuoter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity 0.8.26;

import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {
    CurrencyLibrary,
    Currency,
    equals
} from "squadswap-v4-core/src/types/Currency.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {TickMath} from "squadswap-v4-core/src/pool-cl/libraries/TickMath.sol";
import {IQuoter} from "./interfaces/IQuoter.sol";
import {ICLQuoter} from "./pool-cl/interfaces/ICLQuoter.sol";
import {IBinQuoter} from "./pool-bin/interfaces/IBinQuoter.sol";
import {ISquadSwapV3Pool} from "./interfaces/external/ISquadSwapV3Pool.sol";
import {
    ISquadV3SwapCallback
} from "./interfaces/external/ISquadSwapV3SwapCallback.sol";
import {V3PoolTicksCounter} from "./libraries/external/V3PoolTicksCounter.sol";
import {
    V3SmartRouterHelper
} from "./libraries/external/V3SmartRouterHelper.sol";
import {IMixedQuoter} from "./interfaces/IMixedQuoter.sol";
import {MixedQuoterActions} from "./libraries/MixedQuoterActions.sol";
import {MixedQuoterRecorder} from "./libraries/MixedQuoterRecorder.sol";
import {Multicall} from "./base/Multicall.sol";

error StableSwapNotSupported();

/// @title Provides on chain quotes for squadswap, V3, V2, Stable and MixedRoute exact input swaps
/// @notice Allows getting the expected amount out for a given swap without executing the swap
/// @notice Does not support exact output swaps since using the contract balance between exactOut swaps is not supported
/// @dev These functions are not gas efficient and should _not_ be called on chain. Instead, optimistically execute
/// the swap and check the amounts in the callback.
contract MixedQuoter is IMixedQuoter, ISquadV3SwapCallback, Multicall {
    using SafeCast for *;
    using V3PoolTicksCounter for ISquadSwapV3Pool;

    address constant ZERO_ADDRESS = address(0);

    address public immutable WETH9;
    address public immutable factoryV3;
    address public immutable factoryV2;
    address public immutable factoryStable;

    ICLQuoter public immutable clQuoter;
    IBinQuoter public immutable binQuoter;

    constructor(
        address _factoryV3,
        address _factoryV2,
        address _factoryStable,
        address _WETH9,
        ICLQuoter _clQuoter,
        IBinQuoter _binQuoter
    ) {
        if (
            _factoryV3 == ZERO_ADDRESS ||
            _factoryV2 == ZERO_ADDRESS ||
            _WETH9 == ZERO_ADDRESS ||
            address(_clQuoter) == ZERO_ADDRESS ||
            address(_binQuoter) == ZERO_ADDRESS
        ) {
            revert INVALID_ADDRESS();
        }
        factoryV3 = _factoryV3;
        WETH9 = _WETH9;
        factoryV2 = _factoryV2;
        factoryStable = _factoryStable;
        clQuoter = _clQuoter;
        binQuoter = _binQuoter;
    }

    /**
     * V3 *************************************************
     */

    /// @inheritdoc ISquadV3SwapCallback
    function squadV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes memory data
    ) external view override {
        require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
        (address tokenIn, address tokenOut, uint24 fee) = abi.decode(
            data,
            (address, address, uint24)
        );
        V3SmartRouterHelper.verifyCallback(factoryV3, tokenIn, tokenOut, fee);

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

        ISquadSwapV3Pool pool = V3SmartRouterHelper.getPool(
            factoryV3,
            tokenIn,
            tokenOut,
            fee
        );
        (uint160 v3SqrtPriceX96After, int24 tickAfter, , , , , ) = pool.slot0();

        if (isExactInput) {
            assembly ("memory-safe") {
                let ptr := mload(0x40)
                mstore(ptr, amountReceived)
                mstore(add(ptr, 0x20), v3SqrtPriceX96After)
                mstore(add(ptr, 0x40), tickAfter)
                revert(ptr, 0x60)
            }
        } else {
            /// since we don't support exactOutput, revert here
            revert("Exact output quote not supported");
        }
    }

    /// @dev Parses a revert reason that should contain the numeric quote
    function parseRevertReason(
        bytes memory reason
    )
        private
        pure
        returns (uint256 amount, uint160 sqrtPriceX96After, int24 tickAfter)
    {
        if (reason.length != 0x60) {
            if (reason.length < 0x44) revert("Unexpected error");
            assembly ("memory-safe") {
                reason := add(reason, 0x04)
            }
            revert(abi.decode(reason, (string)));
        }
        return abi.decode(reason, (uint256, uint160, int24));
    }

    function handleV3Revert(
        bytes memory reason,
        ISquadSwapV3Pool pool,
        uint256 gasEstimate
    )
        private
        view
        returns (
            uint256 amount,
            uint160 sqrtPriceX96After,
            uint32 initializedTicksCrossed,
            uint256
        )
    {
        int24 tickBefore;
        int24 tickAfter;
        (, tickBefore, , , , , ) = pool.slot0();
        (amount, sqrtPriceX96After, tickAfter) = parseRevertReason(reason);

        initializedTicksCrossed = pool.countInitializedTicksCrossed(
            tickBefore,
            tickAfter
        );

        return (
            amount,
            sqrtPriceX96After,
            initializedTicksCrossed,
            gasEstimate
        );
    }

    /// @dev Fetch an exactIn quote for a V3 Pool on chain
    function quoteExactInputSingleV3(
        QuoteExactInputSingleV3Params memory params
    )
        public
        override
        returns (
            uint256 amountOut,
            uint160 sqrtPriceX96After,
            uint32 initializedTicksCrossed,
            uint256 gasEstimate
        )
    {
        bool zeroForOne = params.tokenIn < params.tokenOut;
        ISquadSwapV3Pool pool = V3SmartRouterHelper.getPool(
            factoryV3,
            params.tokenIn,
            params.tokenOut,
            params.fee
        );

        uint256 gasBefore = gasleft();
        try
            pool.swap(
                address(this), // address(0) might cause issues with some tokens
                zeroForOne,
                params.amountIn.toInt256(),
                params.sqrtPriceLimitX96 == 0
                    ? (
                        zeroForOne
                            ? TickMath.MIN_SQRT_RATIO + 1
                            : TickMath.MAX_SQRT_RATIO - 1
                    )
                    : params.sqrtPriceLimitX96,
                abi.encode(params.tokenIn, params.tokenOut, params.fee)
            )
        {} catch (bytes memory reason) {
            gasEstimate = gasBefore - gasleft();
            return handleV3Revert(reason, pool, gasEstimate);
        }
    }

    /**
     * V2 *************************************************
     */

    /// @dev Fetch an exactIn quote for a V2 pair on chain
    function quoteExactInputSingleV2(
        QuoteExactInputSingleV2Params memory params
    ) public view override returns (uint256 amountOut, uint256 gasEstimate) {
        return quoteExactInputSingleV2WithAccumulation(params, 0, 0);
    }

    /// @dev Fetch an exactIn quote for a V2 pair on chain with token accumulation
    function quoteExactInputSingleV2WithAccumulation(
        QuoteExactInputSingleV2Params memory params,
        uint256 accTokenInAmount,
        uint256 accTokenOutAmount
    ) internal view returns (uint256 amountOut, uint256 gasEstimate) {
        uint256 gasBefore = gasleft();
        (uint256 reserveIn, uint256 reserveOut) = V3SmartRouterHelper
            .getReserves(factoryV2, params.tokenIn, params.tokenOut);
        amountOut = V3SmartRouterHelper.getAmountOut(
            params.amountIn,
            reserveIn + accTokenInAmount,
            reserveOut - accTokenOutAmount
        );
        gasEstimate = gasBefore - gasleft();
    }

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

    /// @dev StableSwap desteklenmiyor
    function quoteExactInputSingleStable(
        QuoteExactInputSingleStableParams memory
    ) public view override returns (uint256, uint256) {
        revert StableSwapNotSupported();
    }

    /**
     * Mixed *************************************************
     */
    /// @dev All swap results will influence the outcome of subsequent swaps within the same pool
    function quoteMixedExactInputSharedContext(
        address[] calldata paths,
        bytes calldata actions,
        bytes[] calldata params,
        uint256 amountIn
    ) external override returns (uint256 amountOut, uint256 gasEstimate) {
        return
            quoteMixedExactInputWithContext(
                paths,
                actions,
                params,
                amountIn,
                true
            );
    }

    function quoteMixedExactInput(
        address[] calldata paths,
        bytes calldata actions,
        bytes[] calldata params,
        uint256 amountIn
    ) external override returns (uint256 amountOut, uint256 gasEstimate) {
        return
            quoteMixedExactInputWithContext(
                paths,
                actions,
                params,
                amountIn,
                false
            );
    }

    /// @dev if withContext is false, each swap is isolated and does not influence the outcome of subsequent swaps within the same pool
    /// @dev if withContext is true, all swap results will influence the outcome of subsequent swaps within the same pool
    /// @dev if withContext is true, non-squadswap pools (v3, v2, ss) only support one swap direction for same pool
    function quoteMixedExactInputWithContext(
        address[] calldata paths,
        bytes calldata actions,
        bytes[] calldata params,
        uint256 amountIn,
        bool withContext
    ) private returns (uint256 amountOut, uint256 gasEstimate) {
        uint256 numActions = actions.length;
        if (numActions == 0) revert NoActions();
        if (numActions != params.length || numActions != paths.length - 1)
            revert InputLengthMismatch();

        for (uint256 actionIndex = 0; actionIndex < numActions; actionIndex++) {
            uint256 gasEstimateForCurAction;
            address tokenIn = paths[actionIndex];
            address tokenOut = paths[actionIndex + 1];
            if (tokenIn == tokenOut) revert InvalidPath();

            uint256 action = uint256(uint8(actions[actionIndex]));
            if (action == MixedQuoterActions.V2_EXACT_INPUT_SINGLE) {
                (tokenIn, tokenOut) = convertNativeToWETH(tokenIn, tokenOut);
                // params[actionIndex] is zero bytes
                if (!withContext) {
                    (
                        amountIn,
                        gasEstimateForCurAction
                    ) = quoteExactInputSingleV2(
                            QuoteExactInputSingleV2Params({
                                tokenIn: tokenIn,
                                tokenOut: tokenOut,
                                amountIn: amountIn
                            })
                        );
                } else {
                    bool zeroForOne = tokenIn < tokenOut;
                    bytes32 poolHash = MixedQuoterRecorder.getV2PoolHash(
                        tokenIn,
                        tokenOut
                    );
                    // update v2 pool swap direction, only allow one direction in one transaction
                    MixedQuoterRecorder.setAndCheckSwapDirection(
                        poolHash,
                        zeroForOne
                    );
                    (
                        uint256 accAmountIn,
                        uint256 accAmountOut
                    ) = MixedQuoterRecorder.getPoolSwapTokenAccumulation(
                            poolHash,
                            zeroForOne
                        );

                    uint256 swapAmountOut;
                    (
                        swapAmountOut,
                        gasEstimateForCurAction
                    ) = quoteExactInputSingleV2WithAccumulation(
                            QuoteExactInputSingleV2Params({
                                tokenIn: tokenIn,
                                tokenOut: tokenOut,
                                amountIn: amountIn
                            }),
                            accAmountIn,
                            accAmountOut
                        );
                    MixedQuoterRecorder.setPoolSwapTokenAccumulation(
                        poolHash,
                        amountIn + accAmountIn,
                        swapAmountOut + accAmountOut,
                        zeroForOne
                    );
                    amountIn = swapAmountOut;
                }
            } else if (action == MixedQuoterActions.V3_EXACT_INPUT_SINGLE) {
                (tokenIn, tokenOut) = convertNativeToWETH(tokenIn, tokenOut);
                // params[actionIndex]: abi.encode(fee)
                uint24 fee = abi.decode(params[actionIndex], (uint24));
                if (!withContext) {
                    (
                        amountIn,
                        ,
                        ,
                        gasEstimateForCurAction
                    ) = quoteExactInputSingleV3(
                            QuoteExactInputSingleV3Params({
                                tokenIn: tokenIn,
                                tokenOut: tokenOut,
                                amountIn: amountIn,
                                fee: fee,
                                sqrtPriceLimitX96: 0
                            })
                        );
                } else {
                    bool zeroForOne = tokenIn < tokenOut;
                    bytes32 poolHash = MixedQuoterRecorder.getV3PoolHash(
                        tokenIn,
                        tokenOut,
                        fee
                    );
                    // update v3 pool swap direction, only allow one direction in one transaction
                    MixedQuoterRecorder.setAndCheckSwapDirection(
                        poolHash,
                        zeroForOne
                    );
                    (
                        uint256 accAmountIn,
                        uint256 accAmountOut
                    ) = MixedQuoterRecorder.getPoolSwapTokenAccumulation(
                            poolHash,
                            zeroForOne
                        );

                    uint256 swapAmountOut;
                    amountIn += accAmountIn;
                    (
                        swapAmountOut,
                        ,
                        ,
                        gasEstimateForCurAction
                    ) = quoteExactInputSingleV3(
                            QuoteExactInputSingleV3Params({
                                tokenIn: tokenIn,
                                tokenOut: tokenOut,
                                amountIn: amountIn,
                                fee: fee,
                                sqrtPriceLimitX96: 0
                            })
                        );
                    MixedQuoterRecorder.setPoolSwapTokenAccumulation(
                        poolHash,
                        amountIn,
                        swapAmountOut,
                        zeroForOne
                    );
                    amountIn = swapAmountOut - accAmountOut;
                }
            } else if (
                action == MixedQuoterActions.INFI_CL_EXACT_INPUT_SINGLE
            ) {
                QuoteMixedInfiExactInputSingleParams memory clParams = abi
                    .decode(
                        params[actionIndex],
                        (QuoteMixedInfiExactInputSingleParams)
                    );
                (tokenIn, tokenOut) = convertWETHToInfiNativeCurrency(
                    clParams.poolKey,
                    tokenIn,
                    tokenOut
                );
                bool zeroForOne = tokenIn < tokenOut;
                checkInfiPoolKeyCurrency(
                    clParams.poolKey,
                    zeroForOne,
                    tokenIn,
                    tokenOut
                );

                IQuoter.QuoteExactSingleParams memory swapParams = IQuoter
                    .QuoteExactSingleParams({
                        poolKey: clParams.poolKey,
                        zeroForOne: zeroForOne,
                        exactAmount: amountIn.toUint128(),
                        hookData: clParams.hookData
                    });
                // will execute all swap history of same squadswap pool in one transaction if withContext is true
                if (withContext) {
                    bytes32 poolHash = MixedQuoterRecorder.getInfiCLPoolHash(
                        clParams.poolKey
                    );
                    bytes memory swapListBytes = MixedQuoterRecorder
                        .getInfiPoolSwapList(poolHash);
                    IQuoter.QuoteExactSingleParams[] memory swapHistoryList;
                    uint256 swapHistoryListLength;
                    if (swapListBytes.length > 0) {
                        swapHistoryList = abi.decode(
                            swapListBytes,
                            (IQuoter.QuoteExactSingleParams[])
                        );

                        swapHistoryListLength = swapHistoryList.length;
                    }
                    IQuoter.QuoteExactSingleParams[]
                        memory swapList = new IQuoter.QuoteExactSingleParams[](
                            swapHistoryListLength + 1
                        );
                    for (uint256 i = 0; i < swapHistoryListLength; i++) {
                        swapList[i] = swapHistoryList[i];
                    }
                    swapList[swapHistoryListLength] = swapParams;

                    (amountIn, gasEstimateForCurAction) = clQuoter
                        .quoteExactInputSingleList(swapList);
                    swapListBytes = abi.encode(swapList);
                    MixedQuoterRecorder.setInfiPoolSwapList(
                        poolHash,
                        swapListBytes
                    );
                } else {
                    (amountIn, gasEstimateForCurAction) = clQuoter
                        .quoteExactInputSingle(swapParams);
                }
            } else if (
                action == MixedQuoterActions.INFI_BIN_EXACT_INPUT_SINGLE
            ) {
                QuoteMixedInfiExactInputSingleParams memory binParams = abi
                    .decode(
                        params[actionIndex],
                        (QuoteMixedInfiExactInputSingleParams)
                    );
                (tokenIn, tokenOut) = convertWETHToInfiNativeCurrency(
                    binParams.poolKey,
                    tokenIn,
                    tokenOut
                );
                bool zeroForOne = tokenIn < tokenOut;
                checkInfiPoolKeyCurrency(
                    binParams.poolKey,
                    zeroForOne,
                    tokenIn,
                    tokenOut
                );

                IQuoter.QuoteExactSingleParams memory swapParams = IQuoter
                    .QuoteExactSingleParams({
                        poolKey: binParams.poolKey,
                        zeroForOne: zeroForOne,
                        exactAmount: amountIn.toUint128(),
                        hookData: binParams.hookData
                    });
                // will execute all swap history of same squadswap pool in one transaction if withContext is true
                if (withContext) {
                    bytes32 poolHash = MixedQuoterRecorder.getInfiBinPoolHash(
                        binParams.poolKey
                    );
                    bytes memory swapListBytes = MixedQuoterRecorder
                        .getInfiPoolSwapList(poolHash);
                    IQuoter.QuoteExactSingleParams[] memory swapHistoryList;
                    uint256 swapHistoryListLength;
                    if (swapListBytes.length > 0) {
                        swapHistoryList = abi.decode(
                            swapListBytes,
                            (IQuoter.QuoteExactSingleParams[])
                        );

                        swapHistoryListLength = swapHistoryList.length;
                    }
                    IQuoter.QuoteExactSingleParams[]
                        memory swapList = new IQuoter.QuoteExactSingleParams[](
                            swapHistoryListLength + 1
                        );
                    for (uint256 i = 0; i < swapHistoryListLength; i++) {
                        swapList[i] = swapHistoryList[i];
                    }
                    swapList[swapHistoryListLength] = swapParams;

                    (amountIn, gasEstimateForCurAction) = binQuoter
                        .quoteExactInputSingleList(swapList);
                    swapListBytes = abi.encode(swapList);
                    MixedQuoterRecorder.setInfiPoolSwapList(
                        poolHash,
                        swapListBytes
                    );
                } else {
                    (amountIn, gasEstimateForCurAction) = binQuoter
                        .quoteExactInputSingle(swapParams);
                }
            } else if (action == MixedQuoterActions.SS_2_EXACT_INPUT_SINGLE) {
                revert StableSwapNotSupported();
            } else if (action == MixedQuoterActions.SS_3_EXACT_INPUT_SINGLE) {
                revert StableSwapNotSupported();
            } else {
                revert UnsupportedAction(action);
            }
            gasEstimate += gasEstimateForCurAction;
        }

        return (amountIn, gasEstimate);
    }

    /// @dev Check if the poolKey currency matches the tokenIn and tokenOut
    function checkInfiPoolKeyCurrency(
        PoolKey memory poolKey,
        bool isZeroForOne,
        address tokenIn,
        address tokenOut
    ) private pure {
        Currency currency0;
        Currency currency1;
        if (isZeroForOne) {
            currency0 = Currency.wrap(tokenIn);
            currency1 = Currency.wrap(tokenOut);
        } else {
            currency0 = Currency.wrap(tokenOut);
            currency1 = Currency.wrap(tokenIn);
        }
        if (
            !equals(poolKey.currency0, currency0) ||
            !equals(poolKey.currency1, currency1)
        ) {
            revert InvalidPoolKeyCurrency();
        }
    }

    /// @notice Convert WETH to native currency for squadswap pools
    /// @dev for example, quote route are v3 WETH pool[token0, WETH] and squadswap native pool[NATIVE,token1]
    /// paths is [token0, WETH, token1], we need to convert WETH to NATIVE when quote squadswap pool
    function convertWETHToInfiNativeCurrency(
        PoolKey memory poolKey,
        address tokenIn,
        address tokenOut
    ) private view returns (address, address) {
        if (poolKey.currency0.isNative()) {
            if (tokenIn == WETH9) {
                tokenIn = Currency.unwrap(CurrencyLibrary.NATIVE);
            }
            if (tokenOut == WETH9) {
                tokenOut = Currency.unwrap(CurrencyLibrary.NATIVE);
            }
        }
        return (tokenIn, tokenOut);
    }

    /// @dev Convert native currency to WETH for Non-SquadSwapV4 pools.
    /// For example, quote route are squadswap native pool[NATIVE, token0] and v3 WETH pool[WETH, token1].
    //// paths is [token0, NATIVE, token1], we need to convert NATIVE to WETH when quote v3 pool
    function convertNativeToWETH(
        address tokenIn,
        address tokenOut
    ) private view returns (address, address) {
        if (Currency.wrap(tokenIn).isNative()) {
            tokenIn = WETH9;
        }
        if (Currency.wrap(tokenOut).isNative()) {
            tokenOut = WETH9;
        }
        return (tokenIn, tokenOut);
    }
}

../squadswap-v4-core/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        /// @solidity memory-safe-assembly
        assembly {
            u := iszero(iszero(b))
        }
    }
}

../squadswap-v4-core/src/interfaces/IERC20Minimal.sol

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

/// @title Minimal ERC20 interface for SquadSwapV4
/// @notice Contains a subset of the full ERC20 interface that is used in SquadSwapV4
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);
}

../squadswap-v4-core/src/interfaces/IHooks.sol

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

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

../squadswap-v4-core/src/interfaces/IPoolManager.sol

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

../squadswap-v4-core/src/libraries/CustomRevert.sol

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

../squadswap-v4-core/src/pool-cl/libraries/TickMath.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
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;
        }
    }
}

../squadswap-v4-core/src/types/Currency.sol

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

../squadswap-v4-core/src/types/PoolId.sol

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

../squadswap-v4-core/src/types/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;
}

src/base/Multicall.sol

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

import {IMulticall} from "../interfaces/IMulticall.sol";

/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(
        bytes[] calldata data
    ) external payable override returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(
                data[i]
            );

            if (!success) {
                // bubble up the revert reason
                assembly ("memory-safe") {
                    revert(add(result, 0x20), mload(result))
                }
            }

            results[i] = result;
        }
    }
}

src/interfaces/IMixedQuoter.sol

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

import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";

/// @title MixedQuoter Interface
/// @notice Supports quoting the calculated amounts for exact input swaps. Is specialized for routes containing a mix of Stable, V2, V3 liquidity, squadswap liquidity.
/// @notice For each pool also tells you the number of initialized ticks crossed and the sqrt price of the pool after the swap.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IMixedQuoter {
    error INVALID_ADDRESS();
    error InputLengthMismatch();
    error InvalidPath();
    error InvalidPoolKeyCurrency();
    error NoActions();
    error UnsupportedAction(uint256 action);

    struct QuoteMixedInfiExactInputSingleParams {
        PoolKey poolKey;
        bytes hookData;
    }

    struct QuoteExactInputSingleV3Params {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint24 fee;
        uint160 sqrtPriceLimitX96;
    }

    struct QuoteExactInputSingleV2Params {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
    }

    struct QuoteExactInputSingleStableParams {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 flag;
    }

    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @param paths The path of the swap, i.e. each token pair in the path
    /// @param actions The actions to take for each pair in the path
    /// @param params The params for each action in the path
    /// SS_2_EXACT_INPUT_SINGLE params are zero bytes
    /// SS_3_EXACT_INPUT_SINGLE params are zero bytes
    /// V2_EXACT_INPUT_SINGLE params are zero bytes
    /// V3_EXACT_INPUT_SINGLE params are encoded as `uint24 fee`
    /// INFI_CL_EXACT_INPUT_SINGLE params are encoded as `QuoteMixedInfiExactInputSingleParams`
    /// INFI_EXACT_INPUT_SINGLE params are encoded as `QuoteMixedInfiExactInputSingleParams`
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteMixedExactInput(
        address[] calldata paths,
        bytes calldata actions,
        bytes[] calldata params,
        uint256 amountIn
    ) external returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @dev All swap results will influence the outcome of subsequent swaps within the same pool
    /// @param paths The path of the swap, i.e. each token pair in the path
    /// @param actions The actions to take for each pair in the path
    /// @param params The params for each action in the path
    /// SS_2_EXACT_INPUT_SINGLE params are zero bytes
    /// SS_3_EXACT_INPUT_SINGLE params are zero bytes
    /// V2_EXACT_INPUT_SINGLE params are zero bytes
    /// V3_EXACT_INPUT_SINGLE params are encoded as `uint24 fee`
    /// INFI_CL_EXACT_INPUT_SINGLE params are encoded as `QuoteMixedInfiExactInputSingleParams`
    /// INFI_EXACT_INPUT_SINGLE params are encoded as `QuoteMixedInfiExactInputSingleParams`
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteMixedExactInputSharedContext(
        address[] calldata paths,
        bytes calldata actions,
        bytes[] calldata params,
        uint256 amountIn
    ) external returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactInputSingleParams`
    /// tokenIn The token being swapped in
    /// tokenOut The token being swapped out
    /// fee The fee of the token pool to consider for the pair
    /// amountIn The desired input amount
    /// sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountOut The amount of `tokenOut` that would be received
    /// @return sqrtPriceX96After The sqrt price of the pool after the swap
    /// @return initializedTicksCrossed The number of initialized ticks that the swap crossed
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactInputSingleV3(QuoteExactInputSingleV3Params memory params)
        external
        returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single V2 pool
    /// @param params The params for the quote, encoded as `QuoteExactInputSingleV2Params`
    /// tokenIn The token being swapped in
    /// tokenOut The token being swapped out
    /// amountIn The desired input amount
    /// @return amountOut The amount of `tokenOut` that would be received
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactInputSingleV2(QuoteExactInputSingleV2Params memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single Stable pool
    /// @param params The params for the quote, encoded as `QuoteExactInputSingleStableParams`
    /// tokenIn The token being swapped in
    /// tokenOut The token being swapped out
    /// amountIn The desired input amount
    /// flag The token amount in a single Stable pool. 2 for 2pool, 3 for 3pool
    /// @return amountOut The amount of `tokenOut` that would be received
    /// @return gasEstimate The estimate of the gas that the swap consumes
    function quoteExactInputSingleStable(QuoteExactInputSingleStableParams memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @dev ExactOutput swaps are not supported by this new Quoter which is specialized for supporting routes
    ///      crossing Stable, V2 liquidity pairs and V3 pools.
    /// @deprecated quoteExactOutputSingle and exactOutput. Use QuoterV2 instead.
}

src/interfaces/IMulticall.sol

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

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` is passed onto all subcalls, even if a previous subcall has consumed the ether.
    /// Subcalls can instead use `address(this).value` to see the available ETH, and consume it using {value: x}.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

src/interfaces/IQuoter.sol

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

import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PathKey} from "../libraries/PathKey.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {PoolId} from "squadswap-v4-core/src/types/PoolId.sol";

/// @title IQuoter
/// @notice Supports quoting the delta amounts from exact input or exact output swaps.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoter {
    error NotEnoughLiquidity(PoolId poolId);
    error NotSelf();
    error UnexpectedCallSuccess();

    struct QuoteExactSingleParams {
        PoolKey poolKey;
        bool zeroForOne;
        uint128 exactAmount;
        bytes hookData;
    }

    struct QuoteExactParams {
        Currency exactCurrency;
        PathKey[] path;
        uint128 exactAmount;
    }
}

src/interfaces/external/ISquadSwapFactory.sol

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

/// @title ISquadSwapFactory
/// @notice Interface for the SquadSwapFactory contract
interface ISquadSwapFactory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function createPair(address tokenA, address tokenB) external returns (address pair);
}

src/interfaces/external/ISquadSwapPair.sol

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

/// @title ISquadSwapPair
/// @notice Interface for the SquadSwapV4 V2 Pair
/// https://github.com/squadswap/squadswap-swap-core-v2/blob/master/contracts/interfaces/ISquadSwapPair.sol
interface ISquadSwapPair {
    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;
}

src/interfaces/external/ISquadSwapV3Factory.sol

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

/// @title ISquadSwapV3Factory
/// @notice Interface for the SquadSwapV3Factory contract
interface ISquadSwapV3Factory {
    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(address tokenA, address tokenB, uint24 fee) external returns (address pool);
}

src/interfaces/external/ISquadSwapV3Pool.sol

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

/// @title ISquadSwapV3Pool
/// @notice Interface for the SquadSwapV3Pool contract
interface ISquadSwapV3Pool {
    /// @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 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 Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of ISquadSwapV3SwapCallback#squadswapV3SwapCallback
    /// @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);
}

src/interfaces/external/ISquadSwapV3SwapCallback.sol

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

/// @title ISquadSwapV3SwapCallback
/// @notice Callback for ISquadSwapV3PoolActions#swap
/// @dev Any contract that calls ISquadSwapV3PoolActions#swap must implement this interface.
interface ISquadV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via ISquadSwapV3Pool#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 SquadSwapV3Pool deployed by the canonical SquadSwapV3Factory.
    /// 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 ISquadSwapV3PoolActions#swap call
    function squadV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

src/interfaces/external/IStableSwapFactory.sol

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

/// @title IStableSwapFactory
/// @notice Interface for the StableSwapFactory contract
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);

    function createSwapPair(address _tokenA, address _tokenB, uint256 _A, uint256 _fee, uint256 _admin_fee) external;
}

src/libraries/MixedQuoterActions.sol

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

/// @notice Library to define different mixed quoter actions.
library MixedQuoterActions {
    // ExactInput actions
    // SS means stable swap
    uint256 constant SS_2_EXACT_INPUT_SINGLE = 0x00;
    uint256 constant SS_3_EXACT_INPUT_SINGLE = 0x01;
    uint256 constant V2_EXACT_INPUT_SINGLE = 0x02;
    uint256 constant V3_EXACT_INPUT_SINGLE = 0x03;

    // INFI means squadswap
    uint256 constant INFI_CL_EXACT_INPUT_SINGLE = 0x04;
    uint256 constant INFI_BIN_EXACT_INPUT_SINGLE = 0x05;
}

src/libraries/MixedQuoterRecorder.sol

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2024 PancakeSwap
// Copyright (C) 2025 SquadSwap
pragma solidity 0.8.26;

import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";

/// @dev Record all token accumulation and swap direction of the transaction for non-squadswap pools.
/// @dev Record squadswap swap history list for squadswap pools.
library MixedQuoterRecorder {
    /// @dev uint256 internal constant SWAP_DIRECTION = uint256(keccak256("MIXED_QUOTER_SWAP_DIRECTION")) - 1;
    uint256 internal constant SWAP_DIRECTION =
        0x420071594cddc2905acbd674683749db4c139d373cc290ba8d49c75296a9f1f9;

    /// @dev uint256 internal constant SWAP_TOKEN0_ACCUMULATION = uint256(keccak256("MIXED_QUOTER_SWAP_TOKEN0_ACCUMULATION")) - 1;
    uint256 internal constant SWAP_TOKEN0_ACCUMULATION =
        0x6859b060ba2f84c00df66c40e8848222c89b2fcc89d5edc84074b9878818ea86;

    /// @dev uint256 internal constant SWAP_TOKEN1_ACCUMULATION = uint256(keccak256("MIXED_QUOTER_SWAP_TOKEN1_ACCUMULATION")) - 1;
    uint256 internal constant SWAP_TOKEN1_ACCUMULATION =
        0x8039a0cfe43b448f327ddf378771d67fba431d4dbc5c8f9531fa80f8a45125e9;

    /// @dev uint256 internal SWAP_SS = uint256(keccak256("MIXED_QUOTER_SWAP_SS")) - 1;
    uint256 internal constant SWAP_SS =
        0x0b6c8b64c3ab4ac7b96ca59ae1454278ba2d62c99873c03d98ae968df846210a;

    /// @dev uint256 internal SWAP_V2 = uint256(keccak256("MIXED_QUOTER_SWAP_V2")) - 1;
    uint256 internal constant SWAP_V2 =
        0xfb50ad98219c08ac49c2f2012c28ee455be42a0adc9a9a5df9e0882de4cf56b5;

    /// @dev uint256 internal constant SWAP_V3 = uint256(keccak256("MIXED_QUOTER_SWAP_V3")) - 1;
    uint256 internal constant SWAP_V3 =
        0xd9d373c35d602baa7832c86d4af60fe46a2e18634c87bebc20d0050afb7633b3;

    /// @dev uint256 internal constant SWAP_INFI_CL = uint256(keccak256("MIXED_QUOTER_SWAP_INFI_CL")) - 1;
    uint256 internal constant SWAP_INFI_CL =
        0x4feb57dd10cb5162909904ca541d6f7c45508b5d9792044648a6eba88f79d97;

    /// @dev uint256 internal constant SWAP_INFI_BIN = uint256(keccak256("MIXED_QUOTER_SWAP_INFI_BIN")) - 1;
    uint256 internal constant SWAP_INFI_BIN =
        0x5f3e6018e8b2ccef782c927f292822290a80de8ee586b625fcd9a2e443bf80b1;

    /// @dev uint256 internal constant SWAP_INFI_LIST = uint256(keccak256("MIXED_QUOTER_SWAP_INFI_LIST")) - 1;
    uint256 internal constant SWAP_INFI_LIST =
        0x32f6ae18dd733261edd4a84eefa6e2b1fe927f73449d02df9df6ca8eaba3b6df;

    enum SwapDirection {
        NONE,
        ZeroForOne,
        OneForZero
    }

    error INVALID_SWAP_DIRECTION();

    /// @dev Record and check the swap direction of the transaction.
    /// @dev Only support one direction for same non-squadswap pool in one transaction.
    /// @param poolHash The hash of the pool.
    /// @param isZeroForOne The direction of the swap.
    function setAndCheckSwapDirection(
        bytes32 poolHash,
        bool isZeroForOne
    ) internal {
        uint256 swapDirection = isZeroForOne
            ? uint256(SwapDirection.ZeroForOne)
            : uint256(SwapDirection.OneForZero);

        uint256 currentDirection = getSwapDirection(poolHash);
        if (currentDirection == uint256(SwapDirection.NONE)) {
            uint256 directionSlot = uint256(
                keccak256(abi.encode(poolHash, SWAP_DIRECTION))
            );
            assembly ("memory-safe") {
                tstore(directionSlot, swapDirection)
            }
        } else if (currentDirection != swapDirection) {
            revert INVALID_SWAP_DIRECTION();
        }
    }

    /// @dev Get the swap direction of the transaction.
    /// @param poolHash The hash of the pool.
    /// @return swapDirection The direction of the swap.
    function getSwapDirection(
        bytes32 poolHash
    ) internal view returns (uint256 swapDirection) {
        uint256 directionSlot = uint256(
            keccak256(abi.encode(poolHash, SWAP_DIRECTION))
        );
        assembly ("memory-safe") {
            swapDirection := tload(directionSlot)
        }
    }

    /// @dev Record the swap token accumulation of the pool.
    /// @param poolHash The hash of the pool.
    /// @param amountIn The amount of tokenIn.
    /// @param amountOut The amount of tokenOut.
    /// @param isZeroForOne The direction of the swap.
    function setPoolSwapTokenAccumulation(
        bytes32 poolHash,
        uint256 amountIn,
        uint256 amountOut,
        bool isZeroForOne
    ) internal {
        uint256 token0Slot = uint256(
            keccak256(abi.encode(poolHash, SWAP_TOKEN0_ACCUMULATION))
        );
        uint256 token1Slot = uint256(
            keccak256(abi.encode(poolHash, SWAP_TOKEN1_ACCUMULATION))
        );
        uint256 amount0;
        uint256 amount1;
        if (isZeroForOne) {
            amount0 = amountIn;
            amount1 = amountOut;
        } else {
            amount0 = amountOut;
            amount1 = amountIn;
        }
        assembly ("memory-safe") {
            tstore(token0Slot, amount0)
            tstore(token1Slot, amount1)
        }
    }

    // @dev Get the swap token accumulation of the pool.
    // @param poolHash The hash of the pool.
    // @param isZeroForOne The direction of the swap.
    // @return accAmountIn The accumulation amount of tokenIn.
    // @return accAmountOut The accumulation amount of tokenOut.
    function getPoolSwapTokenAccumulation(
        bytes32 poolHash,
        bool isZeroForOne
    ) internal view returns (uint256, uint256) {
        uint256 token0Slot = uint256(
            keccak256(abi.encode(poolHash, SWAP_TOKEN0_ACCUMULATION))
        );
        uint256 token1Slot = uint256(
            keccak256(abi.encode(poolHash, SWAP_TOKEN1_ACCUMULATION))
        );
        uint256 amount0;
        uint256 amount1;
        assembly ("memory-safe") {
            amount0 := tload(token0Slot)
            amount1 := tload(token1Slot)
        }
        if (isZeroForOne) {
            return (amount0, amount1);
        } else {
            return (amount1, amount0);
        }
    }

    /// @dev Record the swap history list of squadswap pool.
    /// @param poolHash The hash of the pool.
    /// @param swapListBytes The swap history list bytes.
    function setInfiPoolSwapList(
        bytes32 poolHash,
        bytes memory swapListBytes
    ) internal {
        uint256 swapListSlot = uint256(
            keccak256(abi.encode(poolHash, SWAP_INFI_LIST))
        );
        assembly ("memory-safe") {
            // save the length of the bytes
            tstore(swapListSlot, mload(swapListBytes))

            // save data in next slot
            let dataSlot := add(swapListSlot, 1)
            for {
                let i := 0
            } lt(i, mload(swapListBytes)) {
                i := add(i, 32)
            } {
                tstore(
                    add(dataSlot, div(i, 32)),
                    mload(add(swapListBytes, add(0x20, i)))
                )
            }
        }
    }

    /// @dev Get the swap history list of squadswap pool.
    /// @param poolHash The hash of the pool.
    /// @return swapListBytes The swap history list bytes.
    function getInfiPoolSwapList(
        bytes32 poolHash
    ) internal view returns (bytes memory swapListBytes) {
        uint256 swapListSlot = uint256(
            keccak256(abi.encode(poolHash, SWAP_INFI_LIST))
        );
        assembly ("memory-safe") {
            // get the length of the bytes
            let length := tload(swapListSlot)
            swapListBytes := mload(0x40)
            mstore(swapListBytes, length)
            let dataSlot := add(swapListSlot, 1)
            for {
                let i := 0
            } lt(i, length) {
                i := add(i, 32)
            } {
                mstore(
                    add(swapListBytes, add(0x20, i)),
                    tload(add(dataSlot, div(i, 32)))
                )
            }
            mstore(0x40, add(swapListBytes, add(0x20, length)))
        }
    }

    /// @dev Get the stable swap pool hash.
    /// @param token0 The address of token0.
    /// @param token1 The address of token1.
    /// @return poolHash The hash of the pool.
    function getSSPoolHash(
        address token0,
        address token1
    ) internal pure returns (bytes32) {
        if (token0 == token1) revert();
        (token0, token1) = token0 < token1
            ? (token0, token1)
            : (token1, token0);
        return keccak256(abi.encode(token0, token1, SWAP_SS));
    }

    /// @dev Get the v2 pool hash.
    /// @param token0 The address of token0.
    /// @param token1 The address of token1.
    /// @return poolHash The hash of the pool.
    function getV2PoolHash(
        address token0,
        address token1
    ) internal pure returns (bytes32) {
        if (token0 == token1) revert();
        (token0, token1) = token0 < token1
            ? (token0, token1)
            : (token1, token0);
        return keccak256(abi.encode(token0, token1, SWAP_V2));
    }

    /// @dev Get the v3 pool hash.
    /// @param token0 The address of token0.
    /// @param token1 The address of token1.
    /// @param fee The fee of the pool.
    function getV3PoolHash(
        address token0,
        address token1,
        uint24 fee
    ) internal pure returns (bytes32) {
        if (token0 == token1) revert();
        (token0, token1) = token0 < token1
            ? (token0, token1)
            : (token1, token0);
        return keccak256(abi.encode(token0, token1, fee, SWAP_V3));
    }

    /// @dev Get the squadswap cl pool hash.
    /// @param key The pool key.
    /// @return poolHash The hash of the pool.
    function getInfiCLPoolHash(
        PoolKey memory key
    ) internal pure returns (bytes32) {
        return keccak256(abi.encode(key, SWAP_INFI_CL));
    }

    /// @dev Get the squadswap bin pool hash.
    /// @param key The pool key.
    /// @return poolHash The hash of the pool.
    function getInfiBinPoolHash(
        PoolKey memory key
    ) internal pure returns (bytes32) {
        return keccak256(abi.encode(key, SWAP_INFI_BIN));
    }
}

src/libraries/PathKey.sol

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

import {Currency} from "squadswap-v4-core/src/types/Currency.sol";
import {PoolKey} from "squadswap-v4-core/src/types/PoolKey.sol";
import {IHooks} from "squadswap-v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "squadswap-v4-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
        );
    }
}

src/libraries/external/V3PoolTicksCounter.sol

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

import {ISquadSwapV3Pool} from "../../interfaces/external/ISquadSwapV3Pool.sol";

/// @dev Copy from https://github.com/squadswap/squadswap-v3-contracts/blob/main/projects/router/contracts/libraries/PoolTicksCounter.sol
library V3PoolTicksCounter {
    /// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.
    /// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the
    /// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do
    /// want to count tickAfter. The opposite is true if we are swapping downwards.
    function countInitializedTicksCrossed(ISquadSwapV3Pool self, int24 tickBefore, int24 tickAfter)
        internal
        view
        returns (uint32 initializedTicksCrossed)
    {
        int16 wordPosLower;
        int16 wordPosHigher;
        uint8 bitPosLower;
        uint8 bitPosHigher;
        bool tickBeforeInitialized;
        bool tickAfterInitialized;

        {
            // Get the key and offset in the tick bitmap of the active tick before and after the swap.
            int16 wordPos = int16((tickBefore / self.tickSpacing()) >> 8);
            uint8 bitPos = uint8(uint24((tickBefore / self.tickSpacing()) % 256));

            int16 wordPosAfter = int16((tickAfter / self.tickSpacing()) >> 8);
            uint8 bitPosAfter = uint8(uint24((tickAfter / self.tickSpacing()) % 256));

            // In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.
            // If the initializable tick after the swap is initialized, our original tickAfter is a
            // multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized
            // and we shouldn't count it.
            tickAfterInitialized = ((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0)
                && ((tickAfter % self.tickSpacing()) == 0) && (tickBefore > tickAfter);

            // In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.
            // Use the same logic as above to decide whether we should count tickBefore or not.
            tickBeforeInitialized = ((self.tickBitmap(wordPos) & (1 << bitPos)) > 0)
                && ((tickBefore % self.tickSpacing()) == 0) && (tickBefore < tickAfter);

            if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {
                wordPosLower = wordPos;
                bitPosLower = bitPos;
                wordPosHigher = wordPosAfter;
                bitPosHigher = bitPosAfter;
            } else {
                wordPosLower = wordPosAfter;
                bitPosLower = bitPosAfter;
                wordPosHigher = wordPos;
                bitPosHigher = bitPos;
            }
        }

        // Count the number of initialized ticks crossed by iterating through the tick bitmap.
        // Our first mask should include the lower tick and everything to its left.
        uint256 mask = type(uint256).max << bitPosLower;
        while (wordPosLower <= wordPosHigher) {
            // If we're on the final tick bitmap page, ensure we only count up to our
            // ending tick.
            if (wordPosLower == wordPosHigher) {
                mask = mask & (type(uint256).max >> (255 - bitPosHigher));
            }

            uint256 masked = self.tickBitmap(wordPosLower) & mask;
            initializedTicksCrossed += countOneBits(masked);
            wordPosLower++;
            // Reset our mask so we consider all bits on the next iteration.
            mask = type(uint256).max;
        }

        if (tickAfterInitialized) {
            initializedTicksCrossed -= 1;
        }

        if (tickBeforeInitialized) {
            initializedTicksCrossed -= 1;
        }

        return initializedTicksCrossed;
    }

    function countOneBits(uint256 x) private pure returns (uint16) {
        uint16 bits = 0;
        while (x != 0) {
            bits++;
            x &= (x - 1);
        }
        return bits;
    }
}

src/libraries/external/V3SmartRouterHelper.sol

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

import {IStableSwapFactory} from "../../interfaces/external/IStableSwapFactory.sol";
import {ISquadSwapPair} from "../../interfaces/external/ISquadSwapPair.sol";
import {ISquadSwapV3Pool} from "../../interfaces/external/ISquadSwapV3Pool.sol";
import {ISquadSwapFactory} from "../../interfaces/external/ISquadSwapFactory.sol";
import {ISquadSwapV3Factory} from "../../interfaces/external/ISquadSwapV3Factory.sol";

/// @dev Copy from https://github.com/squadswap/squadswap-v3-contracts/blob/main/projects/router/contracts/libraries/SmartRouterHelper.sol
library V3SmartRouterHelper {
    /**
     * 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;
        }

        require(swapContract != address(0), "getStableInfo: invalid pool address");
    }

    /**
     * V2 *************************************************
     */

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        require(tokenA != tokenB);
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0));
    }

    /// @dev SquadSwapV4 is a multichain DEX, we have different factories on different chains.
    /// If we use the CREATE2 rule to calculate the pool address, we need to update the INIT_CODE_HASH for each chain.
    /// And quoter functions are not gas efficient and should _not_ be called on chain.
    function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
        (address token0, address token1) = sortTokens(tokenA, tokenB);
        return ISquadSwapFactory(factory).getPair(token0, token1);
    }

    // fetches and sorts the reserves for a pair
    function getReserves(address factory, address tokenA, address tokenB)
        internal
        view
        returns (uint256 reserveA, uint256 reserveB)
    {
        (address token0,) = sortTokens(tokenA, tokenB);
        (uint256 reserve0, uint256 reserve1,) = ISquadSwapPair(pairFor(factory, tokenA, tokenB)).getReserves();
        (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
    }

    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountOut)
    {
        require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT");
        require(reserveIn > 0 && reserveOut > 0);
        uint256 amountInWithFee = amountIn * 9975;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = reserveIn * 10000 + amountInWithFee;
        amountOut = numerator / denominator;
    }

    // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        internal
        pure
        returns (uint256 amountIn)
    {
        require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT");
        require(reserveIn > 0 && reserveOut > 0);
        uint256 numerator = reserveIn * amountOut * 10000;
        uint256 denominator = (reserveOut - amountOut) * 9975;
        amountIn = (numerator / denominator) + 1;
    }

    // performs chained getAmountIn calculations on any number of pairs
    function getAmountsIn(address factory, uint256 amountOut, address[] memory path)
        internal
        view
        returns (uint256[] memory amounts)
    {
        require(path.length >= 2);
        amounts = new uint256[](path.length);
        amounts[amounts.length - 1] = amountOut;
        for (uint256 i = path.length - 1; i > 0; i--) {
            (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
            amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
        }
    }

    /**
     * V3 *************************************************
     */

    /// @notice Returns the pool for the given token pair and fee. The pool contract may or may not exist.
    /// @dev SquadSwapV4 is a multichain DEX, we have different factories on different chains.
    /// If we use the CREATE2 rule to calculate the pool address, we need to update the INIT_CODE_HASH for each chain.
    /// And quoter functions are not gas efficient and should _not_ be called on chain.
    function getPool(address factory, address tokenA, address tokenB, uint24 fee)
        internal
        view
        returns (ISquadSwapV3Pool)
    {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return ISquadSwapV3Pool(ISquadSwapV3Factory(factory).getPool(tokenA, tokenB, fee));
    }

    /// @notice Returns the address of a valid SquadSwapV4 V3 Pool
    /// @param factory The contract address of the SquadSwapV4 V3 factory
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The V3 pool contract address
    function verifyCallback(address factory, address tokenA, address tokenB, uint24 fee)
        internal
        view
        returns (ISquadSwapV3Pool pool)
    {
        pool = getPool(factory, tokenA, tokenB, fee);
        require(msg.sender == address(pool));
    }
}

src/pool-bin/interfaces/IBinQuoter.sol

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

import {IQuoter} from "../../interfaces/IQuoter.sol";

/// @title IBinQuoter Interface
/// @notice Supports quoting the delta amounts for exact input or exact output swaps.
/// @notice For each pool also tells you the estimation of gas cost for the swap.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IBinQuoter is IQuoter {
    /// @notice Returns the delta amounts for a given exact input swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams`
    /// poolKey The key for identifying a Bin pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired input amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountOut The output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInputSingle(QuoteExactSingleParams memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the last swap delta amounts for a given exact input in a list of swap
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams[]`
    /// poolKey The key for identifying a Bin pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired input amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountOut The last swap output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInputSingleList(QuoteExactSingleParams[] memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the delta amounts along the swap path for a given exact input swap
    /// @param params the params for the quote, encoded as 'QuoteExactParams'
    /// currencyIn The input currency of the swap
    /// path The path of the swap encoded as PathKeys that contains currency, fee, and hook info
    /// exactAmount The desired input amount
    /// @return amountOut The output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInput(QuoteExactParams memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the delta amounts for a given exact output swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams`
    /// poolKey The key for identifying a Bin pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired output amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountIn The input quote for the exactOut swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactOutputSingle(QuoteExactSingleParams memory params)
        external
        returns (uint256 amountIn, uint256 gasEstimate);

    /// @notice Returns the delta amounts along the swap path for a given exact output swap
    /// @param params the params for the quote, encoded as 'QuoteExactParams'
    /// currencyOut The output currency of the swap
    /// path The path of the swap encoded as PathKeys that contains currency, fee, and hook info
    /// exactAmount The desired output amount
    /// @return amountIn The input quote for the exactOut swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactOutput(QuoteExactParams memory params)
        external
        returns (uint256 amountIn, uint256 gasEstimate);
}

src/pool-cl/interfaces/ICLQuoter.sol

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

import {IQuoter} from "../../interfaces/IQuoter.sol";

/// @title ICLQuoter Interface
/// @notice Supports quoting the delta amounts for exact input or exact output swaps.
/// @notice For each pool also tells you the estimation of gas cost for the swap.
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface ICLQuoter is IQuoter {
    /// @notice Returns the delta amounts for a given exact input swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams`
    /// poolKey The key for identifying a squadswap pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired input amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountOut The output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInputSingle(QuoteExactSingleParams memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the last swap delta amounts for a given exact input in a list of swap
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams[]`
    /// poolKey The key for identifying a squadswap pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired input amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountOut The last swap output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInputSingleList(QuoteExactSingleParams[] memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the delta amounts along the swap path for a given exact input swap
    /// @param params the params for the quote, encoded as 'QuoteExactParams'
    /// currencyIn The input currency of the swap
    /// path The path of the swap encoded as PathKeys that contains currency, fee, tickSpacing, and hook info
    /// exactAmount The desired input amount
    /// @return amountOut The output quote for the exactIn swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactInput(QuoteExactParams memory params)
        external
        returns (uint256 amountOut, uint256 gasEstimate);

    /// @notice Returns the delta amounts for a given exact output swap of a single pool
    /// @param params The params for the quote, encoded as `QuoteExactSingleParams`
    /// poolKey The key for identifying a squadswap pool
    /// zeroForOne If the swap is from currency0 to currency1
    /// exactAmount The desired output amount
    /// hookData arbitrary hookData to pass into the associated hooks
    /// @return amountIn The input quote for the exactOut swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactOutputSingle(QuoteExactSingleParams memory params)
        external
        returns (uint256 amountIn, uint256 gasEstimate);

    /// @notice Returns the delta amounts along the swap path for a given exact output swap
    /// @param params the params for the quote, encoded as 'QuoteExactParams'
    /// currencyOut The output currency of the swap
    /// path The path of the swap encoded as PathKeys that contains currency, fee, tickSpacing, and hook info
    /// exactAmount The desired output amount
    /// @return amountIn The input quote for the exactOut swap
    /// @return gasEstimate Estimated gas units used for the swap
    function quoteExactOutput(QuoteExactParams memory params)
        external
        returns (uint256 amountIn, uint256 gasEstimate);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1000000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "lib/pancake-create3-factory/=lib/pancake-create3-factory/",
    "squadswap-create3-factory/=lib/pancake-create3-factory/",
    "ds-test/=../squadswap-v4-core/lib/forge-std/lib/ds-test/src/",
    "forge-std/=../squadswap-v4-core/lib/forge-std/src/",
    "openzeppelin-contracts/=../squadswap-v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/=../squadswap-v4-core/lib/openzeppelin-contracts/",
    "solmate/=../squadswap-v4-core/lib/solmate/",
    "permit2/=lib/permit2/",
    "squadswap-v4-core/=../squadswap-v4-core/",
    "erc4626-tests/=lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=/Users/tan/Desktop/pcsv4/squadswap-v4-core/lib/forge-gas-snapshot/src/",
    "pancake-create3-factory/=lib/pancake-create3-factory/",
    "script/=../squadswap-v4-core/script/",
    "test/=../squadswap-v4-core/test/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.