Skip to content
Verified contractExactMIT

Router

Address0x4df3b7c7d63261368489b330c36913ceee5d0044
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,257,209
Creation transaction
0x6126af3223…19641ff321

src/Router.sol

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

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

import { IMaverickV2Pool } from "./interfaces/IMaverickV2Pool.sol";
import {
    CLSwapParams,
    IBinPoolManager,
    ICLPoolManager,
    IVault,
    InfinityPoolKey
} from "./interfaces/IPancakeInfinity.sol";
import { IRouter } from "./interfaces/IRouter.sol";
import { IUniswapV3Pool } from "./interfaces/IUniswapV3Pool.sol";
import { BalanceDelta, Currency, IPoolManager, PoolKey, SwapParams as V4SwapParams } from "./interfaces/IUniswapV4.sol";

/// @dev Minimal view of the hosting {Pot}: the engine a flash callback runs in. The Router always
///      executes as a delegatecall in the Pot's context, so `IPot(address(this)).inFlightEngine()`
///      reads the engine the Pot's in-flight `cook` is executing — the one the callback was written
///      for, since the engine is a `cook` argument rather than a constant.
interface IPot {
    function inFlightEngine() external view returns (address);
}

/// @title Router
/// @notice The Pot's swap surface: one exact-input method per callback venue family, and {flash}.
/// @dev Generation 4. See {IRouter} for the contract every swap method shares, and
///      `docs/router-gen4.md` for why the surface is shaped this way.
///
///      HOW A SWAP IS PAID. Every venue here sends its output and then calls back to be paid. Before
///      calling the venue, the swap records in transient storage which venue may call back and what
///      it may be paid: `tokenIn`, at most `amountIn`. The callback refuses any other caller and
///      consumes the record before anything else runs, so one swap pays at most once.
///
///      NAMESPACE. Every transient slot below lives in the EXECUTING account's namespace, which under
///      a {Pot} is shared with everything that delegatecalls into it, the Sauce engine included. A
///      program running in the Pot must derive its own transient keys by hashing and must not write
///      these. The "SauceRouter.*" preimages name a contract that no longer exists; each string IS
///      its slot, so they are opaque identifiers rather than names to keep current.
contract Router is IRouter {
    using SafeERC20 for IERC20;

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

    /// @notice A callback came from an address that is not the venue the in-flight swap is driving.
    error UnauthorizedCallback();
    /// @notice A swap method was called by anything but the Pot itself.
    error UnauthorizedCaller();
    /// @notice A venue's deltas do not describe an exact-input swap: it asked to be paid on the output
    ///         lane, or reported owing input. Both lanes are as the venue reported them — the V3
    ///         family reports what the Pot owes as positive, V4 and Infinity as negative.
    error SettleDeltasNotExactInput(int256 inputDelta, int256 outputDelta);
    /// @notice A venue asked for more `tokenIn` than `amountIn`.
    error InputExceedsAuthorized(uint256 requested, uint256 authorized);
    /// @notice `amountIn` does not fit the venue's signed amount as a positive exact input.
    error AmountInTooLarge(uint256 amountIn);
    /// @notice {flash} was handed no program to run.
    error EmptyProgram();
    /// @notice {flash}'s `swap` is not a call to one of the five swap methods.
    error UnknownSwap(bytes4 selector);

    /// @notice The key's currency for the requested direction is not the token the caller named.
    error InputTokenMismatch(address named, address keyed);

    /// @notice An unlock/lock payload whose slices do not lie inside it.
    /// @dev Its own error rather than {UnauthorizedCallback}: the sender gates raise that one, so
    ///      sharing it left the tamper tests unable to tell "bounds check fired" from "sender check
    ///      fired" by the revert data alone.
    error PayloadOutOfBounds();
    /// @notice The venue handed back a callback program other than the one {flash} armed.
    error CallbackMismatch();
    /// @notice The venue of a {flash} swap never called back, so its callback program never ran.
    error CallbackNotRun();

    // =============================================================================
    // Constants
    // =============================================================================

    /// @dev The sqrt-price range of a V3/V4/Infinity CL pool (Uniswap V3 TickMath, ticks ±887272).
    ///      A price limit of 0 means none, and becomes the boundary one step inside this range.
    uint160 internal constant MIN_SQRT_RATIO = 4_295_128_739;
    uint160 internal constant MAX_SQRT_RATIO = 1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_342;

    /// @dev Maverick's callback-funding mode needs non-empty swap data; empty data selects its
    ///      pre-paid mode, which never calls back. A plain swap sends this one byte.
    bytes internal constant MAVERICK_CALLBACK_MODE = hex"01";

    /// @dev V3 context: [0] the pool (the gate), [1] `tokenIn` with `zeroForOne` in bit 160,
    ///      [2] `amountIn`, the most the callback may pay.
    bytes32 private constant V3_CONTEXT_SLOT = keccak256("SauceRouter.v3Context");
    /// @dev Maverick context: [0] the pool (the gate), [1] `tokenIn`, [2] `amountIn`.
    bytes32 private constant MAVERICK_CONTEXT_SLOT = keccak256("SauceRouter.maverickV2Context");
    /// @dev The PoolManager the in-flight V4 unlock was sent to.
    bytes32 private constant V4_CONTEXT_SLOT = keccak256("SauceRouter.v4Context");
    /// @dev The Vault the in-flight Infinity lock was sent to.
    bytes32 private constant INFINITY_CONTEXT_SLOT = keccak256("SauceRouter.infinityContext");
    /// @dev `keccak256` of the program {flash} armed, or 0. The program itself travels through the
    ///      venue — see {flash} — so only its hash is held here.
    bytes32 private constant CALLBACK_SLOT = keccak256("SauceRouter.flashFragment");

    // =============================================================================
    // Modifiers
    // =============================================================================

    /// @dev Under a {Pot}'s delegatecall `address(this)` is the Pot, so only code executing as the Pot
    ///      — a program its owner cooked — passes. Pools, tokens and outside callers do not.
    modifier onlySelf() {
        if (msg.sender != address(this)) {
            revert UnauthorizedCaller();
        }
        _;
    }

    receive() external payable { }

    // =============================================================================
    // Swaps
    // =============================================================================

    /// @inheritdoc IRouter
    function swapV3(
        address pool,
        address tokenIn,
        bool zeroForOne,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        address recipient
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        return _swapV3(pool, tokenIn, zeroForOne, amountIn, sqrtPriceLimitX96, recipient, "");
    }

    /// @inheritdoc IRouter
    function swapMaverickV2(
        address pool,
        address tokenIn,
        bool tokenAIn,
        uint256 amountIn,
        int32 tickLimit,
        address recipient
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        return _swapMaverickV2(pool, tokenIn, tokenAIn, amountIn, tickLimit, recipient, MAVERICK_CALLBACK_MODE);
    }

    /// @inheritdoc IRouter
    function swapV4(
        address poolManager,
        PoolKey calldata,
        address,
        bool,
        uint256 amountIn,
        uint160,
        address
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        return _unlock(poolManager, amountIn);
    }

    /// @inheritdoc IRouter
    function swapInfinityCL(
        address vault,
        InfinityPoolKey calldata,
        address,
        bool,
        uint256 amountIn,
        uint160,
        address
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        return _lock(vault, amountIn, uint256(type(int256).max));
    }

    /// @inheritdoc IRouter
    function swapInfinityBin(
        address vault,
        InfinityPoolKey calldata,
        address,
        bool,
        uint256 amountIn,
        address
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        return _lock(vault, amountIn, uint256(uint128(type(int128).max)));
    }

    /// @inheritdoc IRouter
    /// @dev The program rides the venue's own callback channel: the `data` argument a V3 or Maverick
    ///      pool hands back to its callback, and for V4 and Infinity the unlock/lock payload, which is
    ///      this call's calldata. A venue forwards those bytes, but nothing stops a dishonest one
    ///      from forwarding others, and the callback runs them AS THE POT. So {flash} records the
    ///      program's hash before the swap, and the callback runs only bytes matching it, clearing
    ///      the record first. Carrying the hash rather than the program in transient storage costs
    ///      one slot however long the program is.
    ///
    ///      `swap` is decoded and dispatched here rather than re-entered, so the swap runs through
    ///      the same internal path its plain method does, with the program as its venue data.
    function flash(
        bytes calldata callback,
        bytes calldata swap
    ) external onlySelf returns (uint256 amountInUsed, uint256 amountOut) {
        if (callback.length == 0) {
            revert EmptyProgram();
        }
        bytes32 slot = CALLBACK_SLOT;
        bytes32 armed;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, callback.offset, callback.length)
            armed := keccak256(ptr, callback.length)
            tstore(slot, armed)
        }

        if (swap.length < 4) {
            revert UnknownSwap(bytes4(swap));
        }
        bytes4 selector = bytes4(swap);
        bytes calldata args = swap[4:];
        if (selector == IRouter.swapV3.selector) {
            (address pool, address tokenIn, bool zeroForOne, uint256 amountIn, uint160 limit, address recipient) =
                abi.decode(args, (address, address, bool, uint256, uint160, address));
            (amountInUsed, amountOut) = _swapV3(pool, tokenIn, zeroForOne, amountIn, limit, recipient, callback);
        } else if (selector == IRouter.swapMaverickV2.selector) {
            (address pool, address tokenIn, bool tokenAIn, uint256 amountIn, int32 tickLimit, address recipient) =
                abi.decode(args, (address, address, bool, uint256, int32, address));
            (amountInUsed, amountOut) =
                _swapMaverickV2(pool, tokenIn, tokenAIn, amountIn, tickLimit, recipient, callback);
        } else if (selector == IRouter.swapV4.selector) {
            (address poolManager,,,, uint256 amountIn) = abi.decode(args, (address, PoolKey, address, bool, uint256));
            (amountInUsed, amountOut) = _unlock(poolManager, amountIn);
        } else if (selector == IRouter.swapInfinityCL.selector) {
            (address vault,,,, uint256 amountIn) = abi.decode(args, (address, InfinityPoolKey, address, bool, uint256));
            (amountInUsed, amountOut) = _lock(vault, amountIn, uint256(type(int256).max));
        } else if (selector == IRouter.swapInfinityBin.selector) {
            (address vault,,,, uint256 amountIn) = abi.decode(args, (address, InfinityPoolKey, address, bool, uint256));
            (amountInUsed, amountOut) = _lock(vault, amountIn, uint256(uint128(type(int128).max)));
        } else {
            revert UnknownSwap(selector);
        }

        // Still armed means no callback ran it: the venue never called back, or was never called
        // (a zero `amountIn`).
        assembly ("memory-safe") {
            armed := tload(slot)
        }
        if (armed != 0) {
            revert CallbackNotRun();
        }
    }

    // =============================================================================
    // Uniswap V3 family
    // =============================================================================

    function _swapV3(
        address pool,
        address tokenIn,
        bool zeroForOne,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        address recipient,
        bytes memory data
    ) private returns (uint256 amountInUsed, uint256 amountOut) {
        uint256 paid;
        if (amountIn == 0) {
            return (0, 0);
        }
        // Positive is exact input to the V3 family; an `amountIn` past int256's range would wrap into
        // a negative amount, which the pool reads as an exact output.
        if (amountIn > uint256(type(int256).max)) {
            revert AmountInTooLarge(amountIn);
        }
        bytes32 slot = V3_CONTEXT_SLOT;
        assembly ("memory-safe") {
            tstore(slot, pool)
            tstore(add(slot, 1), or(tokenIn, shl(160, zeroForOne)))
            tstore(add(slot, 2), amountIn)
            // Cleared, not merely written by the callback: a pool that never calls back must leave
            // zero here rather than the previous leg's figure.
            tstore(add(slot, 3), 0)
        }

        (int256 amount0, int256 amount1) = IUniswapV3Pool(pool)
            .swap(recipient, zeroForOne, int256(amountIn), _priceLimit(sqrtPriceLimitX96, zeroForOne), data);

        // The callback closed the gate; close it again for a pool that never called back.
        assembly ("memory-safe") {
            tstore(slot, 0)
        }

        (int256 inputDelta, int256 outputDelta) = zeroForOne ? (amount0, amount1) : (amount1, amount0);
        if (inputDelta < 0 || outputDelta > 0) {
            revert SettleDeltasNotExactInput(inputDelta, outputDelta);
        }
        // `amountInUsed` IS WHAT THIS ROUTER PAID, not what the pool reports it took. The callback
        // pays whatever `inputDelta` the pool asks for there, and nothing ties that to the deltas
        // returned here: a dishonest pool can take the full `amountIn` in the callback and then
        // return (0, 0), which passes the check above. A consumer splitting an aggregate across
        // legs with `remaining -= amountInUsed` would re-offer input the Pot has already spent,
        // and an output-only floor cannot see it.
        assembly ("memory-safe") {
            paid := tload(add(slot, 3))
        }
        return (paid, uint256(-outputDelta));
    }

    /// @notice Uniswap V3 swap callback. Guarded by {_handleV3Callback}.
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        _handleV3Callback(amount0Delta, amount1Delta, data);
    }

    /// @notice PancakeSwap V3 swap callback. Guarded by {_handleV3Callback}.
    function pancakeV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        _handleV3Callback(amount0Delta, amount1Delta, data);
    }

    /// @notice Algebra swap callback (Camelot V3, QuickSwap V3 and other Algebra forks). Algebra's
    ///         pool `swap` has Uniswap V3's selector; only the re-entry is renamed.
    function algebraSwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        _handleV3Callback(amount0Delta, amount1Delta, data);
    }

    /// @notice Synthra V3 swap callback: a Uniswap V3 fork with Uniswap's pool selectors and a
    ///         renamed re-entry taking Uniswap's arguments.
    function synthraV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        _handleV3Callback(amount0Delta, amount1Delta, data);
    }

    /// @notice UnitFlow V3 swap callback: the same shape as Synthra's.
    function unitFlowV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external {
        _handleV3Callback(amount0Delta, amount1Delta, data);
    }

    /// @dev The one handler behind all five V3-family names. In order:
    ///        1. `msg.sender` must be the pool the in-flight swap is driving.
    ///        2. The gate is closed before anything else runs, so the record pays ONE callback; a
    ///           second, under any of the five names, is refused.
    ///        3. Only the requested input lane is paid, only in `tokenIn`, never more than
    ///           `amountIn`. WHICH lane is the input is the direction the swap recorded, never read
    ///           off the deltas, so the pool cannot choose it.
    ///        4. A {flash} program runs after all of that and before the payment, so it pays out of
    ///           what the Pot holds by then. Every field is in locals first, so a nested swap inside
    ///           the program can reuse the record without changing this payment.
    function _handleV3Callback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) private {
        bytes32 slot = V3_CONTEXT_SLOT;
        address expectedPool;
        assembly ("memory-safe") {
            expectedPool := tload(slot)
        }
        if (msg.sender != expectedPool) {
            revert UnauthorizedCallback();
        }
        uint256 packed;
        uint256 allowance;
        assembly ("memory-safe") {
            tstore(slot, 0)
            packed := tload(add(slot, 1))
            allowance := tload(add(slot, 2))
        }

        (int256 inputDelta, int256 outputDelta) =
            (packed >> 160) != 0 ? (amount0Delta, amount1Delta) : (amount1Delta, amount0Delta);
        if (outputDelta > 0) {
            revert SettleDeltasNotExactInput(inputDelta, outputDelta);
        }
        // `allowance` is at most int256's maximum: the swap refused anything larger.
        if (inputDelta > int256(allowance)) {
            revert InputExceedsAuthorized(uint256(inputDelta), allowance);
        }

        _runCallback(data);

        // RECORDED UNCONDITIONALLY, and only the transfer is guarded. Writing this inside the
        // guard leaves a zero-paying leg reporting whatever is already in the slot — which, inside
        // a flash whose program runs a nested leg of its own, is that leg's payment, in that leg's
        // token. {_swapV3} must report zero for a leg that moved nothing.
        assembly ("memory-safe") {
            tstore(add(slot, 3), inputDelta)
        }
        if (inputDelta > 0) {
            IERC20(address(uint160(packed))).safeTransfer(msg.sender, uint256(inputDelta));
        }
    }

    // =============================================================================
    // Maverick V2
    // =============================================================================

    function _swapMaverickV2(
        address pool,
        address tokenIn,
        bool tokenAIn,
        uint256 amountIn,
        int32 tickLimit,
        address recipient,
        bytes memory data
    ) private returns (uint256 amountInUsed, uint256 amountOut) {
        if (amountIn == 0) {
            return (0, 0);
        }
        bytes32 slot = MAVERICK_CONTEXT_SLOT;
        assembly ("memory-safe") {
            tstore(slot, pool)
            tstore(add(slot, 1), tokenIn)
            tstore(add(slot, 2), amountIn)
            tstore(add(slot, 3), 0)
        }

        // `exactOutput` is the one place this venue could be asked for an exact output, and it is a
        // constant.
        (amountInUsed, amountOut) = IMaverickV2Pool(pool)
            .swap(
                recipient,
                IMaverickV2Pool.SwapParams({
                    amount: amountIn, tokenAIn: tokenAIn, exactOutput: false, tickLimit: tickLimit
                }),
                data
            );

        // As for {_swapV3}: the pool's `amountIn` is its own claim, while the callback pays what
        // the pool asked for there. Report what left the Pot.
        assembly ("memory-safe") {
            tstore(slot, 0)
            amountInUsed := tload(add(slot, 3))
        }
    }

    /// @notice Maverick V2 swap callback.
    /// @dev Guarded like {_handleV3Callback}: the in-flight pool only, once, at most `amountIn`. The
    ///      token paid is the swap's `tokenIn`, never the token this callback names.
    function maverickV2SwapCallback(
        IERC20,
        uint256 amountIn,
        uint256,
        bytes calldata data
    ) external {
        bytes32 slot = MAVERICK_CONTEXT_SLOT;
        address expectedPool;
        assembly ("memory-safe") {
            expectedPool := tload(slot)
        }
        if (msg.sender != expectedPool) {
            revert UnauthorizedCallback();
        }
        address tokenIn;
        uint256 allowance;
        assembly ("memory-safe") {
            tstore(slot, 0)
            tokenIn := tload(add(slot, 1))
            allowance := tload(add(slot, 2))
        }
        if (amountIn > allowance) {
            revert InputExceedsAuthorized(amountIn, allowance);
        }

        _runCallback(data);

        // Recorded unconditionally, for the reason {_handleV3Callback} gives.
        assembly ("memory-safe") {
            tstore(add(slot, 3), amountIn)
        }
        // Zero is free here too, as it is for V3 (`inputDelta > 0`) and V4/Infinity (`owed != 0`):
        // a token that rejects a zero-value transfer must not fail a swap that moved nothing.
        if (amountIn != 0) {
            IERC20(tokenIn).safeTransfer(msg.sender, amountIn);
        }
    }

    // =============================================================================
    // Uniswap V4 and PancakeSwap Infinity (flash accounting)
    // =============================================================================

    /// @dev The unlock payload is this call's own calldata — a `swapV4` call, or a {flash} call
    ///      carrying one — so the arguments are encoded once, by the program, and decoded once, in
    ///      {unlockCallback}.
    function _unlock(
        address poolManager,
        uint256 amountIn
    ) private returns (uint256 amountInUsed, uint256 amountOut) {
        if (amountIn == 0) {
            return (0, 0);
        }
        // Negative is exact input to V4; past int256's range the negation would not be negative.
        if (amountIn > uint256(type(int256).max)) {
            revert AmountInTooLarge(amountIn);
        }
        bytes32 slot = V4_CONTEXT_SLOT;
        assembly ("memory-safe") {
            tstore(slot, poolManager)
        }
        bytes memory result = IPoolManager(poolManager).unlock(msg.data);
        assembly ("memory-safe") {
            tstore(slot, 0)
        }
        return abi.decode(result, (uint256, uint256));
    }

    /// @dev {_unlock}'s Infinity twin: the lock payload is this call's calldata. `maxAmountIn` is the
    ///      largest input the pool type's signed amount carries as a negative.
    function _lock(
        address vault,
        uint256 amountIn,
        uint256 maxAmountIn
    ) private returns (uint256 amountInUsed, uint256 amountOut) {
        if (amountIn == 0) {
            return (0, 0);
        }
        if (amountIn > maxAmountIn) {
            revert AmountInTooLarge(amountIn);
        }
        bytes32 slot = INFINITY_CONTEXT_SLOT;
        assembly ("memory-safe") {
            tstore(slot, vault)
        }
        bytes memory result = IVault(vault).lock(msg.data);
        assembly ("memory-safe") {
            tstore(slot, 0)
        }
        return abi.decode(result, (uint256, uint256));
    }

    /// @notice Uniswap V4 unlock callback: swap, take the output, run any {flash} program, settle.
    /// @dev `msg.sender` must be the manager the in-flight swap unlocked, and it is answered once: the
    ///      record is consumed before the swap. TRUST, as in generation 3: the payload is the
    ///      manager's to forward and is decoded, not pinned. The canonical PoolManager forwards it
    ///      verbatim, so against it the only adversary is a hook, and {_settleExactInput} refuses what
    ///      a hook could ask for beyond the swap. A program naming any OTHER manager trusts it with
    ///      every balance and allowance the Pot holds, since such a manager can forge the key, and so
    ///      the currency paid.
    function unlockCallback(
        bytes calldata data
    ) external returns (bytes memory) {
        address expected;
        bytes32 slot = V4_CONTEXT_SLOT;
        assembly ("memory-safe") {
            expected := tload(slot)
        }
        if (msg.sender != expected) {
            revert UnauthorizedCallback();
        }
        // Consumed before the swap, as the V3 and Maverick gates are: one unlock, one callback.
        assembly ("memory-safe") {
            tstore(slot, 0)
        }

        (bytes4 selector, bytes calldata args, bytes calldata callback) = _payload(data);
        // The structural check `lockAcquired` performs for its two pool types, which this family
        // skipped: a manager forwarding a `swapInfinityBin`- or `flash`-shaped payload was
        // mis-decoded as a six-tuple rather than refused. Same trust boundary either way, but one
        // comparison says so.
        if (selector != IRouter.swapV4.selector) {
            revert UnknownSwap(selector);
        }
        (
            ,
            PoolKey memory key,
            address tokenIn,
            bool zeroForOne,
            uint256 amountIn,
            uint160 sqrtPriceLimitX96,
            address recipient
        ) = abi.decode(args, (address, PoolKey, address, bool, uint256, uint160, address));

        BalanceDelta delta = IPoolManager(msg.sender)
            .swap(
                key,
                V4SwapParams({
                    zeroForOne: zeroForOne,
                    amountSpecified: -int256(amountIn),
                    sqrtPriceLimitX96: _priceLimit(sqrtPriceLimitX96, zeroForOne)
                }),
                ""
            );
        return
            _settleExactInput(key.currency0, key.currency1, tokenIn, zeroForOne, delta, amountIn, recipient, callback);
    }

    /// @notice PancakeSwap Infinity lock callback, for both pool types: the payload's selector says
    ///         which. Otherwise {unlockCallback}'s, Vault for PoolManager, trust included — the swap
    ///         goes to the manager named in the key, which the Vault forwards.
    function lockAcquired(
        bytes calldata data
    ) external returns (bytes memory) {
        address expected;
        bytes32 slot = INFINITY_CONTEXT_SLOT;
        assembly ("memory-safe") {
            expected := tload(slot)
        }
        if (msg.sender != expected) {
            revert UnauthorizedCallback();
        }
        // Consumed before the swap, as the V3 and Maverick gates are: one lock, one callback.
        assembly ("memory-safe") {
            tstore(slot, 0)
        }

        (bytes4 selector, bytes calldata args, bytes calldata callback) = _payload(data);
        InfinityPoolKey memory key;
        address tokenIn;
        bool zeroForOne;
        uint256 amountIn;
        address recipient;
        BalanceDelta delta;
        if (selector == IRouter.swapInfinityCL.selector) {
            uint160 sqrtPriceLimitX96;
            (, key, tokenIn, zeroForOne, amountIn, sqrtPriceLimitX96, recipient) =
                abi.decode(args, (address, InfinityPoolKey, address, bool, uint256, uint160, address));
            delta = ICLPoolManager(key.poolManager)
                .swap(
                    key,
                    CLSwapParams({
                        zeroForOne: zeroForOne,
                        amountSpecified: -int256(amountIn),
                        sqrtPriceLimitX96: _priceLimit(sqrtPriceLimitX96, zeroForOne)
                    }),
                    ""
                );
        } else if (selector == IRouter.swapInfinityBin.selector) {
            (, key, tokenIn, zeroForOne, amountIn, recipient) =
                abi.decode(args, (address, InfinityPoolKey, address, bool, uint256, address));
            delta = IBinPoolManager(key.poolManager).swap(key, zeroForOne, -int128(int256(amountIn)), "");
        } else {
            revert UnknownSwap(selector);
        }
        return
            _settleExactInput(key.currency0, key.currency1, tokenIn, zeroForOne, delta, amountIn, recipient, callback);
    }

    /// @dev The swap call inside an unlock/lock payload, and the {flash} program riding with it. The
    ///      payload is the entry point's calldata: a swap call, or a {flash} call wrapping one.
    ///
    ///      The offsets are read raw because Solidity decodes `bytes` only into memory. They are the
    ///      ABI head of a {flash} call this Router already accepted, so they were bounds-checked on
    ///      the way in; a payload a manager altered is held to the same bounds here, and a slice that
    ///      would start or end outside `data` is refused.
    function _payload(
        bytes calldata data
    ) private pure returns (bytes4 selector, bytes calldata args, bytes calldata callback) {
        selector = bytes4(data);
        if (selector != IRouter.flash.selector) {
            return (selector, data[4:], data[0:0]);
        }
        bytes calldata swap;
        bool inBounds;
        assembly ("memory-safe") {
            // An ABI head's offsets count from the arguments, which start after the selector. Each
            // slice is measured from there and held to what is left after it, so no sum can wrap and
            // every slice lies inside `data`. A failed term zeroes `inBounds`, so the terms after it
            // may compute garbage without mattering.
            let head := add(data.offset, 4)
            let size := sub(data.length, 4)
            inBounds := gt(size, 63)
            let rel := calldataload(head)
            inBounds := and(inBounds, iszero(gt(rel, sub(size, 32))))
            callback.length := calldataload(add(head, rel))
            callback.offset := add(add(head, rel), 32)
            inBounds := and(inBounds, iszero(gt(callback.length, sub(sub(size, rel), 32))))
            rel := calldataload(add(head, 32))
            inBounds := and(inBounds, iszero(gt(rel, sub(size, 32))))
            swap.length := calldataload(add(head, rel))
            swap.offset := add(add(head, rel), 32)
            inBounds := and(inBounds, iszero(gt(swap.length, sub(sub(size, rel), 32))))
            inBounds := and(inBounds, iszero(lt(swap.length, 4)))
        }
        if (!inBounds) {
            revert PayloadOutOfBounds();
        }
        return (bytes4(swap), swap[4:], callback);
    }

    /// @dev Settle one exact-input swap's deltas, V4 and Infinity alike (the Vault answers the same
    ///      `take`/`sync`/`settle` as the PoolManager, which is `msg.sender` here):
    ///        1. The input lane must be owed and the output lane owing, and the input owed must not
    ///           exceed `amountIn`. A hook's return delta can move either lane; what it moves past an
    ///           exact input is refused rather than paid.
    ///        2. TAKE the output, then run any {flash} program, then SETTLE the input. The manager
    ///           checks deltas only when the unlock/lock exits, so for a plain swap the order is
    ///           immaterial; for a flash it is what lets the program spend the output to raise the
    ///           input, and the exit check is what fails a program that left the Pot short.
    function _settleExactInput(
        Currency currency0,
        Currency currency1,
        address tokenIn,
        bool zeroForOne,
        BalanceDelta delta,
        uint256 amountIn,
        address recipient,
        bytes calldata callback
    ) private returns (bytes memory) {
        int256 amount0;
        int256 amount1;
        // BalanceDelta packs amount0 in the upper 128 bits and amount1 in the lower.
        assembly ("memory-safe") {
            amount0 := sar(128, delta)
            amount1 := signextend(15, delta)
        }
        (int256 inputDelta, int256 outputDelta) = zeroForOne ? (amount0, amount1) : (amount1, amount0);
        if (inputDelta > 0 || outputDelta < 0) {
            revert SettleDeltasNotExactInput(inputDelta, outputDelta);
        }
        uint256 owed = uint256(-inputDelta);
        if (owed > amountIn) {
            revert InputExceedsAuthorized(owed, amountIn);
        }
        uint256 out = uint256(outputDelta);
        (Currency currencyIn, Currency currencyOut) = zeroForOne ? (currency0, currency1) : (currency1, currency0);
        // WHICH TOKEN LEAVES THE POT IS THE CALLER'S TO NAME, as it is for V3 and Maverick. Without
        // this, `zeroForOne` alone picks it: a key sorted on a different view of the pair than the
        // caller's — a native-keyed pool whose caller sorted the wrapped token — flips the
        // direction, and the Pot settles up to `amountIn` of the currency it did not mean to sell,
        // which for a pair of unequal decimals is not even a comparable amount.
        if (Currency.unwrap(currencyIn) != tokenIn) {
            revert InputTokenMismatch(tokenIn, Currency.unwrap(currencyIn));
        }

        IPoolManager manager = IPoolManager(msg.sender);
        if (out != 0) {
            manager.take(currencyOut, recipient, out);
        }

        _runCallback(callback);

        if (owed != 0) {
            address token = Currency.unwrap(currencyIn);
            if (token == address(0)) {
                // Native input: the manager credits `msg.value`, and the Pot must already hold it.
                manager.settle{ value: owed }();
            } else {
                manager.sync(currencyIn);
                IERC20(token).safeTransfer(address(manager), owed);
                manager.settle();
            }
        }
        return abi.encode(owed, out);
    }

    // =============================================================================
    // Shared
    // =============================================================================

    /// @dev Run the program {flash} armed, if it is the one this venue handed back. Unarmed — every
    ///      plain swap — this is one transient read and venue data is never run. Armed, the program
    ///      must hash to the armed value; the record is cleared BEFORE it runs, so a nested callback
    ///      cannot run it again and {flash} can see that it ran. It runs by delegatecall into the
    ///      in-flight cook's engine, as the Pot, and its revert is bubbled.
    function _runCallback(
        bytes calldata callback
    ) private {
        bytes32 slot = CALLBACK_SLOT;
        bytes32 armed;
        assembly ("memory-safe") {
            armed := tload(slot)
        }
        if (armed == 0) {
            return;
        }
        // Read before the program is copied out: the call writes from the free memory pointer. No
        // engine is a host that is not mid-cook; a delegatecall to it would succeed having run
        // nothing, so the swap would be paid as though the program had.
        address engine = IPot(address(this)).inFlightEngine();
        if (engine == address(0)) {
            revert CallbackNotRun();
        }
        bool matches;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, callback.offset, callback.length)
            matches := eq(keccak256(ptr, callback.length), armed)
            if matches {
                tstore(slot, 0)
                if iszero(delegatecall(gas(), engine, ptr, callback.length, 0, 0)) {
                    returndatacopy(ptr, 0, returndatasize())
                    revert(ptr, returndatasize())
                }
            }
        }
        if (!matches) {
            revert CallbackMismatch();
        }
    }

    /// @dev A price limit of 0 means none: the boundary one step inside the sqrt-price range, on the
    ///      side the swap walks toward.
    function _priceLimit(
        uint160 sqrtPriceLimitX96,
        bool zeroForOne
    ) private pure returns (uint160) {
        if (sqrtPriceLimitX96 != 0) {
            return sqrtPriceLimitX96;
        }
        return zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1;
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/interfaces/IMaverickV2Pool.sol

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

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

/// @title IMaverickV2Pool
/// @notice Minimal interface for Maverick V2 pool swaps
interface IMaverickV2Pool {
    struct SwapParams {
        uint256 amount;
        bool tokenAIn;
        bool exactOutput;
        int32 tickLimit;
    }

    /// @notice Execute a swap (callback pattern — pool calls maverickV2SwapCallback)
    /// @param recipient Address to receive output tokens
    /// @param params Swap parameters
    /// @param data Callback data
    /// @return amountIn Amount of input tokens consumed
    /// @return amountOut Amount of output tokens received
    function swap(
        address recipient,
        SwapParams calldata params,
        bytes calldata data
    ) external returns (uint256 amountIn, uint256 amountOut);

    /// @notice Get tokenA address
    function tokenA() external view returns (address);

    /// @notice Get tokenB address
    function tokenB() external view returns (address);
}

/// @title IMaverickV2SwapCallback
/// @notice Callback interface for Maverick V2 pool swaps
interface IMaverickV2SwapCallback {
    /// @notice Called by Maverick V2 pool during swap execution
    /// @param tokenIn Input token the pool expects to be paid
    /// @param amountIn Amount of input tokens to pay
    /// @param amountOut Amount of output tokens received
    /// @param data Callback data
    function maverickV2SwapCallback(
        IERC20 tokenIn,
        uint256 amountIn,
        uint256 amountOut,
        bytes calldata data
    ) external;
}

src/interfaces/IPancakeInfinity.sol

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

import { BalanceDelta, Currency } from "./IUniswapV4.sol";

/// @title PancakeSwap Infinity Core Types
/// @notice Minimal call surface for PancakeSwap Infinity (BSC/Base) swaps: the singleton Vault
///         (flash accounting + lock) and the CL / Bin pool managers.
/// @dev Signatures frozen against `pancakeswap/infinity-core` sources and re-verified against the
///      DEPLOYED BSC runtime bytecode (block 108,129,542) — every selector below was located in the
///      corresponding contract's dispatcher and, where noted, exercised live:
///        Vault 0x238a358808379702088667322f80aC48bAd5e6c4:
///          lock(bytes)                              = 0x81548319  (present; exercised via CLQuoter)
///          sync(address)                            = 0xa5841194  (present)
///          settle()                                 = 0x11da60b4  (present; payable)
///          settleFor(address)                       = 0x3dd45adb  (present)
///          take(address,address,uint256)            = 0x0b0d9c09  (present)
///          currencyDelta(address,address)           = 0xa54b2831  (present)
///          isAppRegistered(address)                 = 0x8403be91  (probed true for BOTH managers)
///        CLPoolManager 0xa0FfB9c1CE1Fe56963B0321B32E7A0302114058b:
///          swap((address,address,address,address,uint24,bytes32),(bool,int256,uint160),bytes)
///                                                   = 0xcd0cc1ce  (present)
///          getSlot0(bytes32)                        = 0xc815641c  (probed: USDT/Beat -> fee 67)
///          getLiquidity(bytes32)                    = 0xfa6793d5  (present)
///          getPoolTickInfo(bytes32,int24)           = 0x5aa208a4  (present)
///          poolIdToPoolKey(bytes32)                 = 0x0e2d484a  (probed: full 6-field key)
///        BinPoolManager 0xC697d2898e0D09264376196696c51D7aBbbAA4a9:
///          swap((address,address,address,address,uint24,bytes32),bool,int128,bytes)
///                                                   = 0x911a63b7  (present)
///          getSlot0(bytes32)                        = 0xc815641c  (probed: lisUSD/USD1 activeId)
///          poolIdToPoolKey(bytes32)                 = 0x0e2d484a  (probed)
///        Callback: lockAcquired(bytes)              = 0xab6291fe  (line-verified ILockCallback.sol;
///          clear of every selector the surviving {Pot} dispatches natively — cook(address,bytes)
///          = 0xb38dbf14, owner() = 0x8da5cb5b, router() = 0xf887ea40, inFlightEngine() = 0x9fd004e1,
///          the three the gate added: gateSalt() = 0xeb77129b, userSalt() = 0x0ef44173,
///          kitchen() = 0xba0909dd, and the settable Router's setRouter(address) = 0xc0d78655.
///          Three retired selectors are kept alongside so the check also covers a Pot deployed
///          before a rename — cook(bytes[]) = 0xbcb485b8, cook(bytes) = 0x8cba9fca and
///          v12Runtime() = 0x7c84f8b4 — but the eight above are the live set, and a new Router
///          function must be checked against THEM.
///          RouterInfinity.t.sol asserts the live set from `Pot.cook.selector` rather than from
///          this list, so the executable gate cannot drift from the comment.)
///      PoolId = keccak256(abi.encode(key)) — reproduced on-chain for USDT/Beat
///      (0xb2842060…92be) and lisUSD/USD1 (0x87a668db…4ee4).

/// @notice Pool key identifying a PancakeSwap Infinity pool (CL or Bin)
/// @dev 6 fields — unlike Uniswap V4 the key carries the pool manager itself and packs
///      tickSpacing/binStep + the hook-permission bitmap into `parameters`.
struct InfinityPoolKey {
    Currency currency0; // Lower currency address (sorted); address(0) = native BNB/ETH
    Currency currency1; // Higher currency address
    address hooks; // Hooks contract (address(0) = hookless)
    address poolManager; // CLPoolManager or BinPoolManager — part of the key
    uint24 fee; // Static LP fee in hundredths of a bip, or 0x800000 = dynamic
    bytes32 parameters; // low 16 bits: hook-callback bitmap; CL bits[16..39] tickSpacing (int24);
    // Bin bits[16..31] binStep (uint16)
}

/// @notice Swap parameters for the Infinity CL pool manager
/// @dev NEGATIVE amountSpecified = exact input (verified in CLPool.sol:
///      `bool exactInput = params.amountSpecified < 0;`)
struct CLSwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

/// @title IVault
/// @notice PancakeSwap Infinity singleton Vault — flash accounting + single-locker lock
interface IVault {
    /// @notice Acquire the lock; the Vault re-enters `lockAcquired(data)` on msg.sender and
    ///         reverts CurrencyNotSettled unless every delta is settled when the callback returns
    function lock(
        bytes calldata data
    ) external returns (bytes memory result);

    /// @notice Checkpoint an ERC20 balance BEFORE transferring tokens in (skip for native)
    function sync(
        Currency currency
    ) external;

    /// @notice Pay what is owed (after transferring in; native via msg.value)
    function settle() external payable returns (uint256 paid);

    /// @notice Pay what is owed, crediting `recipient`'s delta
    function settleFor(
        address recipient
    ) external payable returns (uint256 paid);

    /// @notice Pull output owed to the locker
    function take(
        Currency currency,
        address to,
        uint256 amount
    ) external;

    /// @notice View of the open delta for a settler/currency pair
    function currencyDelta(
        address settler,
        Currency currency
    ) external view returns (int256);
}

/// @title ICLPoolManager
/// @notice PancakeSwap Infinity concentrated-liquidity pool manager (V4-class tick walk)
interface ICLPoolManager {
    /// @notice Execute a swap inside the Vault lock; deltas are reported to the Vault
    function swap(
        InfinityPoolKey memory key,
        CLSwapParams memory params,
        bytes calldata hookData
    ) external returns (BalanceDelta delta);

    /// @notice Slot0 of a pool by id — dynamic-fee pools report lpFee = 0 here
    /// @dev protocolFee is packed 12+12 bits per direction (zeroForOne = fee & 0xfff)
    function getSlot0(
        bytes32 id
    ) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);

    /// @notice Recover the full 6-field key from a pool id (populated at initialize)
    function poolIdToPoolKey(
        bytes32 id
    ) external view returns (InfinityPoolKey memory key);
}

/// @title IBinPoolManager
/// @notice PancakeSwap Infinity Liquidity-Book-style bin pool manager
interface IBinPoolManager {
    /// @notice Execute a swap inside the Vault lock; NEGATIVE amountSpecified = exact input
    /// @param swapForY true = tokenX (currency0) in, tokenY (currency1) out
    function swap(
        InfinityPoolKey memory key,
        bool swapForY,
        int128 amountSpecified,
        bytes calldata hookData
    ) external returns (BalanceDelta delta);

    /// @notice Slot0 of a bin pool by id (no sqrt-price concept — active bin id)
    function getSlot0(
        bytes32 id
    ) external view returns (uint24 activeId, uint24 protocolFee, uint24 lpFee);

    /// @notice Recover the full 6-field key from a pool id (populated at initialize)
    function poolIdToPoolKey(
        bytes32 id
    ) external view returns (InfinityPoolKey memory key);
}

/// @title ILockCallback
/// @notice Callback interface for Vault.lock() — the Infinity analogue of V4's IUnlockCallback
interface ILockCallback {
    /// @notice Called by the Vault on the lock() caller, forwarding `data` verbatim
    function lockAcquired(
        bytes calldata data
    ) external returns (bytes memory result);
}

src/interfaces/IRouter.sol

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

import { IMaverickV2SwapCallback } from "./IMaverickV2Pool.sol";
import { ILockCallback, InfinityPoolKey } from "./IPancakeInfinity.sol";
import { IUnlockCallback, PoolKey } from "./IUniswapV4.sol";

// ============================================
// Callback Interfaces
// ============================================

/// @title IUniswapV3SwapCallback
/// @notice Callback interface for Uniswap V3 pool swaps
interface IUniswapV3SwapCallback {
    /// @notice Called by Uniswap V3 pools during swap execution
    /// @param amount0Delta The amount of token0 owed (positive) or received (negative)
    /// @param amount1Delta The amount of token1 owed (positive) or received (negative)
    /// @param data Arbitrary data passed through by the caller
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

/// @title IPancakeV3SwapCallback
/// @notice Callback interface for PancakeSwap V3 pool swaps
interface IPancakeV3SwapCallback {
    /// @notice Called by PancakeSwap V3 pools during swap execution
    /// @param amount0Delta The amount of token0 owed (positive) or received (negative)
    /// @param amount1Delta The amount of token1 owed (positive) or received (negative)
    /// @param data Arbitrary data passed through by the caller
    function pancakeV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

/// @title IAlgebraSwapCallback
/// @notice Callback interface for Algebra pool swaps (Camelot V3, QuickSwap V3 and other forks)
interface IAlgebraSwapCallback {
    /// @notice Called by Algebra pools during swap execution, with Uniswap V3's arguments
    /// @param amount0Delta The amount of token0 owed (positive) or received (negative)
    /// @param amount1Delta The amount of token1 owed (positive) or received (negative)
    /// @param data Arbitrary data passed through by the caller
    function algebraSwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

/// @title ISynthraV3SwapCallback
/// @notice Callback interface for Synthra V3 pool swaps (a Uniswap V3 fork)
interface ISynthraV3SwapCallback {
    /// @notice Called by Synthra V3 pools during swap execution, with Uniswap V3's arguments
    /// @param amount0Delta The amount of token0 owed (positive) or received (negative)
    /// @param amount1Delta The amount of token1 owed (positive) or received (negative)
    /// @param data Arbitrary data passed through by the caller
    function synthraV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

/// @title IUnitFlowV3SwapCallback
/// @notice Callback interface for UnitFlow V3 pool swaps (a Uniswap V3 fork)
interface IUnitFlowV3SwapCallback {
    /// @notice Called by UnitFlow V3 pools during swap execution, with Uniswap V3's arguments
    /// @param amount0Delta The amount of token0 owed (positive) or received (negative)
    /// @param amount1Delta The amount of token1 owed (positive) or received (negative)
    /// @param data Arbitrary data passed through by the caller
    function unitFlowV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

/// @title IRouter
/// @notice The swap surface a {Pot} delegatecalls: one exact-input method per callback venue family,
///         and {flash} to run a program fragment inside any of them.
/// @dev Only venues that call back mid-swap are here: a Sauce program cannot answer a pool's call
///      into the Pot, so the Router must. Venues that are paid first (Uniswap V2, Curve, Balancer
///      V2, DODO V2, Trader Joe LB, WOOFi) are called by the program directly.
///
///      Every swap method shares one contract:
///        - Only the Pot itself may call it (`msg.sender == address(this)`), so only a program the
///          Pot's owner cooked. The Pot pays: there is no payer argument.
///        - `amountIn` is unsigned and is always the EXACT INPUT. No method can express an exact
///          output, and an `amountIn` a venue's signed amount cannot carry reverts
///          {AmountInTooLarge} rather than wrapping into one.
///        - The venue is paid only in `tokenIn`, only once, and never more than `amountIn`. A
///          venue that stops early (a price or tick limit) is paid what it took, and the rest stays
///          in the Pot.
///        - `amountIn == 0` returns `(0, 0)` without touching the venue, so a leg a split sized to
///          zero costs nothing.
///        - It returns what the venue reported: `amountInUsed`, the input it took, and
///          `amountOut`, the output it sent to `recipient`. Neither is a balance reading, so a
///          fee-on-transfer token delivers less than `amountOut`.
///
///      V4 and Infinity swaps send their pool's hooks empty `hookData`. A pool whose hooks need data
///      is out of reach, as it was in generation 3: the argument cost every leg 1.1k-1.7k gas and no
///      consumer routes such a pool (`docs/router-gen4.md`).
///
///      The callbacks it inherits are how venues re-enter: the V3 family under each name it uses
///      (Uniswap, PancakeSwap, Algebra, Synthra, UnitFlow), Uniswap V4's unlock, PancakeSwap
///      Infinity's Vault lock and Maverick V2's swap callback. Each refuses a caller that is not the
///      venue its in-flight swap is driving.
interface IRouter is
    IUniswapV3SwapCallback,
    IPancakeV3SwapCallback,
    IAlgebraSwapCallback,
    ISynthraV3SwapCallback,
    IUnitFlowV3SwapCallback,
    IUnlockCallback,
    ILockCallback,
    IMaverickV2SwapCallback
{
    /// @notice Swap on any pool with Uniswap V3's `swap` selector: Uniswap V3, PancakeSwap V3,
    ///         Algebra, Synthra V3 and UnitFlow V3. The name the pool calls back under is how the
    ///         forks differ, and every one is answered.
    /// @param pool The pool. It is not validated: an honest pool that is not a `tokenIn` pool, or
    ///        is asked the wrong direction, fails its own balance check; a dishonest one can take at
    ///        most `amountIn` of `tokenIn`.
    /// @param tokenIn The token the pool is paid in. Named here rather than read from the pool, so
    ///        the pool cannot choose which of the Pot's tokens it is paid in.
    /// @param zeroForOne True to sell the pool's token0 for its token1.
    /// @param sqrtPriceLimitX96 The price the swap stops at; 0 for none.
    /// @param recipient Where the pool sends the output.
    function swapV3(
        address pool,
        address tokenIn,
        bool zeroForOne,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        address recipient
    ) external returns (uint256 amountInUsed, uint256 amountOut);

    /// @notice Swap on a Uniswap V4 pool through its PoolManager's unlock.
    /// @param poolManager The chain's PoolManager. The unlock callback must come from it.
    /// @param key The pool. The zero address is the native token, which the Pot must already hold.
    /// @param tokenIn The token the pool is paid in, named rather than taken from `zeroForOne`, as
    ///        for {swapV3}. It must equal `key.currency0` when `zeroForOne` and `key.currency1`
    ///        otherwise, or the swap reverts {InputTokenMismatch} — so a key sorted on a different
    ///        view of the pair than the caller's (a native-keyed pool the caller sorted as wrapped)
    ///        is refused rather than settling the other currency.
    /// @param sqrtPriceLimitX96 The price the swap stops at; 0 for none.
    /// @param recipient Where the output is taken to.
    function swapV4(
        address poolManager,
        PoolKey calldata key,
        address tokenIn,
        bool zeroForOne,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        address recipient
    ) external returns (uint256 amountInUsed, uint256 amountOut);

    /// @notice Swap on a Maverick V2 pool, paid through its swap callback.
    /// @dev Maverick fills up to `tickLimit` and keeps nothing it did not swap: the callback pays
    ///      exactly the input the pool used, which is why this venue is here rather than paid first.
    /// @param pool The pool; not validated, as for {swapV3}.
    /// @param tokenIn The token the pool is paid in, named rather than read, as for {swapV3}. The
    ///        token the pool's callback names is ignored.
    /// @param tokenAIn True to sell the pool's tokenA for its tokenB.
    /// @param tickLimit Signed Maverick tick passed to the pool unchanged: tokenA-in walks up to it,
    ///        tokenB-in down to it. Zero is a tick, not "no limit"; `type(int32).max` (tokenA in) or
    ///        `type(int32).min` (tokenB in) is the full range.
    /// @param recipient Where the pool sends the output.
    function swapMaverickV2(
        address pool,
        address tokenIn,
        bool tokenAIn,
        uint256 amountIn,
        int32 tickLimit,
        address recipient
    ) external returns (uint256 amountInUsed, uint256 amountOut);

    /// @notice Swap on a PancakeSwap Infinity CL pool through the Vault's lock.
    /// @param vault The chain's Infinity Vault. The lock callback must come from it; the swap is
    ///        sent to `key.poolManager`.
    /// @param key The pool.
    /// @param tokenIn The token the pool is paid in, held to the key's currencies as in {swapV4}.
    /// @param sqrtPriceLimitX96 The price the swap stops at; 0 for none.
    /// @param recipient Where the output is taken to.
    function swapInfinityCL(
        address vault,
        InfinityPoolKey calldata key,
        address tokenIn,
        bool zeroForOne,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96,
        address recipient
    ) external returns (uint256 amountInUsed, uint256 amountOut);

    /// @notice Swap on a PancakeSwap Infinity Bin pool through the Vault's lock.
    /// @dev Bin pools take no price limit. `amountIn` must fit an `int128`.
    /// @param tokenIn The token the pool is paid in, held to the key's currencies as in {swapV4}.
    /// @param swapForY True to sell `key.currency0` (tokenX) for `key.currency1` (tokenY).
    function swapInfinityBin(
        address vault,
        InfinityPoolKey calldata key,
        address tokenIn,
        bool swapForY,
        uint256 amountIn,
        address recipient
    ) external returns (uint256 amountInUsed, uint256 amountOut);

    /// @notice Run `swap`, and inside its venue's callback run `callback`: a flash swap.
    /// @dev `swap` is the complete calldata of one of the five swap methods above. Its venue sends
    ///      the output first; `callback` then runs as a program in the in-flight cook's engine,
    ///      after the venue is authenticated and before the Router pays it, and pays out of what the
    ///      Pot holds by then. A callback that leaves the Pot short fails the payment, and the whole
    ///      swap reverts.
    ///
    ///      The program travels through the venue, as the data its callback hands back, and runs only
    ///      if it hashes to what this call recorded; anything else reverts {CallbackMismatch}.
    ///      Reverts {CallbackNotRun} if the venue never called back, which includes a swap of zero
    ///      and a Maverick swap that filled nothing, so a flash leg cannot be skipped silently.
    ///      Returns what `swap` returns.
    /// @param callback A self-contained program for the engine the in-flight cook is running.
    /// @param swap `abi.encodeCall` of `swapV3`, `swapV4`, `swapMaverickV2`, `swapInfinityCL` or
    ///        `swapInfinityBin`.
    function flash(
        bytes calldata callback,
        bytes calldata swap
    ) external returns (uint256 amountInUsed, uint256 amountOut);
}

src/interfaces/IUniswapV3Pool.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

interface IUniswapV3Pool {
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint32 feeProtocol,
            bool unlocked
        );

    function liquidity() external view returns (uint128);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);

    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

src/interfaces/IUniswapV4.sol

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

/// @title Uniswap V4 Core Types
/// @notice Core types used across Uniswap V4 contracts

/// @dev Currency is a wrapper around address for type safety
type Currency is address;

/// @dev PoolId is the hash of the PoolKey
type PoolId is bytes32;

/// @notice Struct representing a pool key for identifying a V4 pool
/// @dev Pools are identified by their PoolKey, not by a contract address
struct PoolKey {
    Currency currency0; // Lower currency address (sorted)
    Currency currency1; // Higher currency address (sorted)
    uint24 fee; // LP fee in hundredths of a bip (i.e. 3000 = 0.30%)
    int24 tickSpacing; // Tick spacing for the pool
    address hooks; // Hooks contract address (address(0) for no hooks)
}

/// @title IStateView
/// @notice Interface for reading Uniswap V4 pool state
interface IStateView {
    /// @notice Get the slot0 state of a pool
    /// @param poolId The ID of the pool
    /// @return sqrtPriceX96 The current sqrt price
    /// @return tick The current tick
    /// @return protocolFee The protocol fee
    /// @return lpFee The LP fee
    function getSlot0(
        PoolId poolId
    ) external view returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee);

    /// @notice Get the liquidity of a pool
    /// @param poolId The ID of the pool
    /// @return liquidity The current liquidity
    function getLiquidity(
        PoolId poolId
    ) external view returns (uint128 liquidity);
}

/// @title IV4Quoter
/// @notice Interface for quoting Uniswap V4 swaps
interface IV4Quoter {
    /// @notice Parameters for quoting an exact input single swap
    struct QuoteExactSingleParams {
        PoolKey poolKey;
        bool zeroForOne;
        uint128 exactAmount;
        bytes hookData;
    }

    /// @notice Quote an exact input single swap
    /// @param params The quote parameters
    /// @return amountOut The expected output amount
    /// @return gasEstimate The estimated gas cost
    function quoteExactInputSingle(
        QuoteExactSingleParams memory params
    ) external returns (uint256 amountOut, uint256 gasEstimate);
}

/// @title ExactInputSingleParams for SAUCE inline encoding
/// @notice Modified struct with bytes32 amountIn for SAUCE opcode injection
/// @dev Used instead of abi.encodePacked for cleaner V4 swap encoding
struct ExactInputSingleParamsInline {
    PoolKey poolKey;
    bool zeroForOne;
    bytes32 amountInInline; // SAUCE inline opcode placeholder
    uint128 amountOutMinimum;
    bytes hookData;
}

/// @title IUniversalRouter
/// @notice Interface for Uniswap's Universal Router execute with deadline
interface IUniversalRouter {
    /// @notice Execute a sequence of commands with deadline
    /// @param commands A byte array of commands to execute
    /// @param inputs An array of byte arrays containing inputs for each command
    /// @param deadline The deadline by which the transaction must be executed
    function execute(
        bytes calldata commands,
        bytes[] calldata inputs,
        uint256 deadline
    ) external payable;
}

/// @title IPermit2
/// @notice Minimal interface for Permit2 allowance-based transfers
interface IPermit2 {
    /// @notice Approve a spender to transfer tokens via Permit2
    /// @param token The token to approve
    /// @param spender The spender address
    /// @param amount The amount to approve
    /// @param expiration The expiration timestamp
    function approve(
        address token,
        address spender,
        uint160 amount,
        uint48 expiration
    ) external;
}

/// @title Universal Router Commands for V4
/// @notice Command bytes for Universal Router V4 operations
library V4Commands {
    // V4 swap commands (0x10 range)
    uint8 internal constant V4_SWAP = 0x10;

    // V4 Actions (encoded in inputs)
    uint8 internal constant SWAP_EXACT_IN_SINGLE = 0x06;
    uint8 internal constant SETTLE = 0x09; // settle(currency, amount, payerIsUser)
    uint8 internal constant SETTLE_ALL = 0x0c;
    uint8 internal constant TAKE_ALL = 0x0d;
}

/// @title PoolIdLibrary
/// @notice Library for computing PoolId from PoolKey
library PoolIdLibrary {
    /// @notice Compute the PoolId from a PoolKey
    /// @param poolKey The pool key
    /// @return The computed PoolId
    function toId(
        PoolKey memory poolKey
    ) internal pure returns (PoolId) {
        return PoolId.wrap(keccak256(abi.encode(poolKey)));
    }
}

/// @title CurrencyLibrary
/// @notice Library for Currency type operations
library CurrencyLibrary {
    Currency internal constant NATIVE = Currency.wrap(address(0));

    function unwrap(
        Currency currency
    ) internal pure returns (address) {
        return Currency.unwrap(currency);
    }

    function wrap(
        address addr
    ) internal pure returns (Currency) {
        return Currency.wrap(addr);
    }
}

// =============================================================================
// V4 PoolManager Direct Swap Interfaces (for SauceRouter)
// =============================================================================

/// @dev BalanceDelta is a packed int256 with amount0 in UPPER 128 bits and amount1 in LOWER 128 bits
type BalanceDelta is int256;

/// @title BalanceDeltaLibrary
/// @notice Library for extracting amounts from BalanceDelta
/// @dev BalanceDelta packs two int128 values: amount0 in UPPER 128 bits, amount1 in LOWER 128 bits
library BalanceDeltaLibrary {
    /// @notice Get the amount0 from the BalanceDelta (upper 128 bits)
    function amount0(
        BalanceDelta delta
    ) internal pure returns (int128 _amount0) {
        // Use arithmetic shift right (sar) to extract upper 128 bits and preserve sign
        assembly ("memory-safe") {
            _amount0 := sar(128, delta)
        }
    }

    /// @notice Get the amount1 from the BalanceDelta (lower 128 bits)
    function amount1(
        BalanceDelta delta
    ) internal pure returns (int128 _amount1) {
        // Use signextend on byte 15 to extract lower 128 bits with sign preservation
        assembly ("memory-safe") {
            _amount1 := signextend(15, delta)
        }
    }
}

/// @notice Parameters for the swap function
struct SwapParams {
    bool zeroForOne; // Direction of swap: true for currency0 -> currency1
    int256 amountSpecified; // NEGATIVE for exact input, positive for exact output
    uint160 sqrtPriceLimitX96; // Price limit for the swap
}

/// @title IPoolManager
/// @notice Interface for Uniswap V4 PoolManager direct interactions
interface IPoolManager {
    /// @notice Unlock the pool manager to perform operations
    /// @dev Caller must implement IUnlockCallback
    /// @param data Data to pass to the unlock callback
    /// @return result The result from unlockCallback
    function unlock(
        bytes calldata data
    ) external returns (bytes memory result);

    /// @notice Execute a swap on a pool
    /// @param key The pool to swap on
    /// @param params The swap parameters
    /// @param hookData Data to pass to hooks
    /// @return swapDelta The balance delta from the swap (packed amount0, amount1)
    function swap(
        PoolKey memory key,
        SwapParams memory params,
        bytes calldata hookData
    ) external returns (BalanceDelta swapDelta);

    /// @notice Sync a currency to prepare for settlement
    /// @dev Must be called before transferring tokens to the PoolManager for settlement
    /// @param currency The currency to sync
    function sync(
        Currency currency
    ) external;

    /// @notice Take tokens from the PoolManager (positive delta)
    /// @param currency The currency to take
    /// @param to The recipient address
    /// @param amount The amount to take
    function take(
        Currency currency,
        address to,
        uint256 amount
    ) external;

    /// @notice Settle a currency balance (negative delta)
    /// @dev Tokens must be transferred to PoolManager before calling
    /// @return paid The amount that was settled
    function settle() external payable returns (uint256 paid);

    /// @notice Get the current delta for a caller and currency
    /// @param caller The caller address
    /// @param currency The currency
    /// @return The current delta
    function currencyDelta(
        address caller,
        Currency currency
    ) external view returns (int256);
}

/// @title IUnlockCallback
/// @notice Callback interface for PoolManager.unlock()
interface IUnlockCallback {
    /// @notice Called by the pool manager on msg.sender when unlock is called
    /// @param data The data passed to unlock()
    /// @return result Any data to return to the caller of unlock()
    function unlockCallback(
        bytes calldata data
    ) external returns (bytes memory result);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "foundry-huff-neo/=lib/foundry-huff-neo/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.