Skip to content
Verified contractExactMIT

UniswapV3DexModule

Address0x10573bbfabf42c58af5963da79eb456d462d40b1
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,136,381
Creation transaction
0x4b0201c0f7…01ee7955b4

contracts/swap/UniswapV3DexModule.sol

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

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

/**
 * @title  UniswapV3DexModule
 * @notice Uniswap V3 module for UniversalRouter
 * @dev    - Supports 1-hop and 2-hop routes (via hub tokens).
 *         - Uses a QuoterV2-compatible contract for pricing (prefers StaticQuoterV2).
 *         - Executes swaps via Uniswap V3 ISwapRouter's exactInput.
 */

/* ──────────── External interfaces ──────────── */

interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

interface ISwapRouterV3 {
    struct ExactInputParams {
        bytes   path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}

/**
 * @dev Quoter interface aligned with our StaticQuoterV2 (normal view returns),
 *      but still works with Uniswap's QuoterV2 (revert-with-data) via try/catch fallback.
 */
interface IQuoterV2 {
    struct QuoteExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24  fee;
        uint256 amountIn;
        uint160 sqrtPriceLimitX96; // 0 = no limit
    }

    function quoteExactInput(bytes memory path, uint256 amountIn)
        external
        view
        returns (
            uint256 amountOut,
            uint160[] memory sqrtPriceX96AfterList,
            uint32[]  memory initializedTicksCrossedList,
            uint256   gasEstimate
        );

    function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
        external
        view
        returns (
            uint256 amountOut,
            uint160 sqrtPriceX96After,
            uint32  initializedTicksCrossed,
            uint256 gasEstimate
        );
}

interface IUniswapV3Pool {
    function liquidity() external view returns (uint128);
}

/* ──────────── Aggregator interfaces ───────────── */

interface IDexModule {
    function getBestRoute(
        address           tokenIn,
        address           tokenOut,
        uint256           amountIn
    ) external view returns (
        DexRoute memory   route,
        Quote[] memory    bestRoute,
        uint256           amountOut
    );

    function swapRoute(
        DexRoute calldata route,
        address           to
    ) external returns (
        uint256           amountOut
    );
}

/// @notice Serialized route container; each hop is ABI-encoded
struct DexRoute {
    bytes[] data;
}

/// @notice Quote for a hop or a complete route
struct Quote {
    address tokenIn;
    address tokenOut;
    address pool;      // v3 pool
    uint24  fee;       // v3 fee tier
    uint256 amountIn;
    uint256 amountOut;
}

/// @notice Decoded hop for UI/debugging
struct RouteStep {
    address tokenIn;
    address tokenOut;
    address pool;
    uint24  fee;
    uint256 amountIn;
}

/// @notice Quoted candidate (pool + fee + out)
struct QuoteCand { 
    address pool; 
    uint24 fee; 
    uint256 out; 
}

/// @notice Pool candidate (pool + fee + liquidity)
struct PoolCand {
    address pool;
    uint24  fee;
    uint128 liq;
}

/// @notice Pool info listing
struct PoolInfo {
    address pool;
    uint24  fee;
    uint128 liquidity;
}

/* ──────────── Constants & small utils ─────────── */

/**
 * @title   V3Path
 * @notice  Helpers for V3 path encoding
 */
library V3Path {
    function _u24(uint24 v) internal pure returns (bytes memory b) {
        b = abi.encodePacked(bytes1(uint8(v >> 16)), bytes1(uint8(v >> 8)), bytes1(uint8(v)));
    }
}

/* ────────────────── Dex module ────────────────── */

contract UniswapV3DexModule is IDexModule, Ownable {
    using SafeERC20 for IERC20;
    using V3Path for uint24;

    // Immutable addresses (Ethereum Mainnet)
    IUniswapV3Factory public constant FACTORY = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984);
    ISwapRouterV3     public constant ROUTER  = ISwapRouterV3(    0xE592427A0AEce92De3Edee1F18E0157C05861564);

    // Quoter is passed in constructor (set it to your StaticQuoterV2)
    IQuoterV2 public immutable QUOTER;

    // Tokens / HUBs
    address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address public constant DAI  = 0x6B175474E89094C44Da98b954EedeAC495271d0F;

    address[] private HUB_TOKENS = [WETH, USDC, USDT, DAI];

    // Common fee tiers to probe
    uint24[4] private ALL_FEES = [100, 500, 3000, 10000];

    constructor(address quoter) Ownable(msg.sender) {
        require(quoter != address(0), "V3: quoter=0");
        QUOTER = IQuoterV2(quoter);
    }

    /* ───────────────── External VIEW ──────────────── */

    /**
     * @notice  Discover the best route between two tokens for a given amountIn
     * @param   tokenIn   Input token
     * @param   tokenOut  Output token
     * @param   amountIn  Input amount
     * @return  route Serialized route data (1–2 hops)
     * @return  bestRoute List of hop quotes for the chosen route (1 or 2 items)
     * @return  amountOut Expected output for the chosen route
     */
    function getBestRoute(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external view override returns (DexRoute memory route, Quote[] memory bestRoute, uint256 amountOut) {
        require(tokenIn != address(0) && tokenOut != address(0), "UniswapV3: zero addr");
        require(tokenIn != tokenOut, "UniswapV3: same token");
        require(amountIn > 0, "UniswapV3: zero amountIn");
        
        // 1-hop: Top1 by liquidity across ALL_FEES + a single quote
        QuoteCand memory d = _bestPoolAndQuote_AllFees_Top1_S(tokenIn, tokenOut, amountIn);

        if (_isHub(tokenIn) && _isHub(tokenOut)) {
            if (d.pool != address(0) && d.out > 0) {
                // The best is a direct 1-hop
                route.data = new bytes[](1);
                route.data[0] = abi.encode(tokenIn, tokenOut, d.pool, d.fee, amountIn);

                bestRoute = new Quote[](1);
                bestRoute[0] = Quote({
                    tokenIn: tokenIn,
                    tokenOut: tokenOut,
                    pool: d.pool,
                    fee: d.fee,
                    amountIn: amountIn,
                    amountOut: d.out
                });
                amountOut = d.out;
                return (route, bestRoute, amountOut);
            } 
            
            revert("UniswapV3: no route");
        }

        // 2-hop: Via hubs, Top1 on each hop among ALL_FEES
        (DexRoute memory r2, Quote[] memory q2, uint256 out2) =
            _bestTwoHopRoute_AllFees_Top1(tokenIn, tokenOut, amountIn);

        if (d.pool != address(0) && d.out > 0 && d.out >= out2) {
            route.data = new bytes[](1);
                route.data[0] = abi.encode(tokenIn, tokenOut, d.pool, d.fee, amountIn);

                bestRoute = new Quote[](1);
                bestRoute[0] = Quote({
                    tokenIn: tokenIn,
                    tokenOut: tokenOut,
                    pool: d.pool,
                    fee: d.fee,
                    amountIn: amountIn,
                    amountOut: d.out
                });
                amountOut = d.out;
        } else if (out2 > 0) {
            // best 2-hop
            route = r2;
            bestRoute = q2;
            amountOut = out2;
        } else {
            revert("UniswapV3: no route");
        }
    }

    /**
     * @notice  Lists all existing pools for a pair across default fee tiers, including liquidity
     * @param   tokenIn First token
     * @param   tokenOut Second token
     * @return  items Array of {pool, fee, liquidity} for discovered pools
     */
    function getAllRoutes(address tokenIn, address tokenOut)
        external
        view
        returns (PoolInfo[] memory items)
    {
        (address a, address b) = _sortTokens(tokenIn, tokenOut);

        PoolInfo[] memory tmp = new PoolInfo[](ALL_FEES.length);
        uint256 found;

        for (uint256 i; i < ALL_FEES.length; ) {
            uint24 f = ALL_FEES[i];
            address p = FACTORY.getPool(a, b, f);
            if (p != address(0)) {
                uint128 L = IUniswapV3Pool(p).liquidity();
                tmp[found] = PoolInfo({ pool: p, fee: f, liquidity: L });
                unchecked { ++found; }
            }
            unchecked { ++i; }
        }

        assembly { mstore(tmp, found) }
        items = tmp;
    }

    /**
     * @notice  Simulate a 1-hop exact-input swap for a given pool fee
     * @param   tokenIn Input token
     * @param   tokenOut Output token
     * @param   fee V3 fee tier
     * @param   amountIn Input amount
     * @return  amountOut Quoted output amount
     */
    function quoteExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24  fee,
        uint256 amountIn
    ) external view returns (uint256 amountOut) {
        (amountOut,, ,) = _safeQuoteSingle(IQuoterV2.QuoteExactInputSingleParams({
            tokenIn: tokenIn,
            tokenOut: tokenOut,
            fee: fee,
            amountIn: amountIn,
            sqrtPriceLimitX96: 0
        }));
    }

    /**
     * @notice  Simulate a multi-hop exact-input swap for an arbitrary V3 path
     * @param   path V3-encoded path
     * @param   amountIn Input amount for the first hop
     * @return  amountOut Quoted total output amount
     */
    function quoteExactInput(bytes memory path, uint256 amountIn)
        external
        view
        returns (uint256 amountOut)
    {
        (amountOut,, ,) = _safeQuote(path, amountIn);
    }

    /**
     * @notice  Simulate a route (1–2 hops) encoded as {DexRoute}
     * @param   route Serialized route (each hop ABI-encoded as (tokenIn, tokenOut, pool, fee, amountIn))
     * @return  amountOut Quoted total output amount
     */
    function quoteExactInput(DexRoute calldata route)
        external
        view
        returns (uint256 amountOut)
    {
        require(route.data.length == 1 || route.data.length == 2, "UniswapV3: bad route");
        (,,,, uint256 amountIn) =
            abi.decode(route.data[0], (address, address, address, uint24, uint256));
        bytes memory path = _buildPath(route);
        (amountOut,, ,) = _safeQuote(path, amountIn);
    }

    /**
     * @notice  Decode a serialized route into human-readable steps (for UI/debugging)
     * @param   route Serialized route
     * @return  steps Array of {RouteStep}
     */
    function decodeRoute(DexRoute calldata route)
        external
        pure
        returns (RouteStep[] memory steps)
    {
        uint256 len = route.data.length;
        steps = new RouteStep[](len);
        for (uint256 n; n < len; ++n) {
            (address tokenIn, address tokenOut, address pool, uint24 fee, uint256 amountIn) =
                abi.decode(route.data[n], (address, address, address, uint24, uint256));

            steps[n] = RouteStep({
                tokenIn:  tokenIn,
                tokenOut: tokenOut,
                pool:     pool,
                fee:      fee,
                amountIn: amountIn
            });
        }
    }

    /* ─────────────────── Additions ────────────────── */

    /**
     * @notice  Return the best-liquidity pool for a pair (fee tiers auto-selected by pair type)
     * @param   tokenA First token
     * @param   tokenB Second token
     * @return  pool Best pool by liquidity (or address(0) if none)
     * @return  fee  Fee tier for the best pool (0 if none)
     */
    function getPoolForPair(address tokenA, address tokenB)
        external
        view
        returns (address pool, uint24 fee)
    {
        return _bestPoolForPair(tokenA, tokenB, _feesForPair(tokenA, tokenB));
    }

    /**
     * @notice  Same as {getPoolForPair} but with a custom list of fee tiers to probe
     * @param   tokenA First token
     * @param   tokenB Second token
     * @param   fees Fee tiers to consider
     * @return  pool Best pool by liquidity (or address(0) if none)
     * @return  fee  Fee tier for the best pool (0 if none)
     */
    function getPoolForPairWithFees(address tokenA, address tokenB, uint24[] memory fees)
        external
        view
        returns (address pool, uint24 fee)
    {
        return _bestPoolForPair(tokenA, tokenB, fees);
    }

    /* ──────────── External STATE-CHANGING ─────────── */

    /**
     * @notice  Execute the passed route (1–2 hop) via Uniswap V3 Router
     * @dev     amountOutMinimum = 0, slippage control — at the external level (minOut)
     * @param   route Serialized route previously returned by getBestRoute
     * @param   to Recipient of the final tokens
     * @return  amountOut Actual amountOut after execution
     */
    function swapRoute(
        DexRoute calldata route,
        address to
    ) external override returns (uint256 amountOut) {
        require(to != address(0), "UniswapV3: bad recipient");
        require(route.data.length == 1 || route.data.length == 2, "UniswapV3: only 1-2 hops");

        // fetch first hop to pull amountIn
        (address tokenIn,, , , uint256 amountIn) =
            abi.decode(route.data[0], (address, address, address, uint24, uint256));
        require(amountIn > 0, "UniswapV3: zero amountIn");

        _pullToken(tokenIn, amountIn);
        _smartApprove(tokenIn, address(ROUTER), amountIn);

        // build path
        bytes memory path = _buildPath(route);

        amountOut = ROUTER.exactInput(
            ISwapRouterV3.ExactInputParams({
                path: path,
                recipient: to,
                deadline: block.timestamp,
                amountIn: amountIn,
                amountOutMinimum: 0
            })
        );
    }

    /* ──────────────── Internal VIEW ─────────────── */

    /**
     * @notice  Find the top-liquidity pool among default fees and quote it once
     * @param   tokenIn  Input token
     * @param   tokenOut Output token
     * @param   amountIn Input amount
     * @return  q Quoted candidate {pool, fee, out} or empty (pool=0) if none
     */
    function _bestPoolAndQuote_AllFees_Top1_S(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) internal view returns (QuoteCand memory q) {
        PoolCand memory best;
        (address a, address b) = _sortTokens(tokenIn, tokenOut);
        for (uint8 i; i < ALL_FEES.length; ) {
            uint24 f = ALL_FEES[i];
            address p = FACTORY.getPool(a, b, f);
            if (p != address(0)) {
                uint128 L = IUniswapV3Pool(p).liquidity();
                if (L > best.liq) { best = PoolCand({ pool: p, fee: f, liq: L }); }
            }
            unchecked { ++i; }
        }
        if (best.pool == address(0)) return q; // empty (out=0)
        (uint256 out,, ,) = _safeQuote(abi.encodePacked(tokenIn, best.fee._u24(), tokenOut), amountIn);
        q = QuoteCand({ pool: best.pool, fee: best.fee, out: out });
    }

    /**
     * @notice  Discover the best 2-hop route via hub tokens (top1 per hop by liquidity)
     * @param   tokenIn  Input token
     * @param   tokenOut Output token
     * @param   amountIn Input amount
     * @return  route Serialized route with two hops (or empty if none)
     * @return  bestRoute Hop quotes for the chosen 2-hop route (or empty)
     * @return  amountOut Total output for the 2-hop route (0 if none)
     */
    function _bestTwoHopRoute_AllFees_Top1(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) internal view returns (
        DexRoute memory route,
        Quote[] memory bestRoute,
        uint256 amountOut
    ) {
        QuoteCand memory bestQ; // final hop1
        Quote memory bestHop0;
        Quote memory bestHop1;

        address[] memory hubs = HUB_TOKENS;
        for (uint256 h; h < hubs.length; ) {
            address hub = hubs[h];
            if (hub != tokenIn && hub != tokenOut) {
                QuoteCand memory q0 = _bestPoolAndQuote_AllFees_Top1_S(tokenIn, hub, amountIn);
                if (q0.pool != address(0) && q0.out != 0) {
                    QuoteCand memory q1 = _bestPoolAndQuote_AllFees_Top1_S(hub, tokenOut, q0.out);
                    if (q1.pool != address(0) && q1.out > bestQ.out) {
                        bestQ = q1;
                        bestHop0 = Quote({
                            tokenIn:  tokenIn,
                            tokenOut: hub,
                            pool:     q0.pool,
                            fee:      q0.fee,
                            amountIn: amountIn,
                            amountOut:q0.out
                        });
                        bestHop1 = Quote({
                            tokenIn:  hub,
                            tokenOut: tokenOut,
                            pool:     q1.pool,
                            fee:      q1.fee,
                            amountIn: q0.out,
                            amountOut:q1.out
                        });
                    }
                }
            }
            unchecked { ++h; }
        }

        if (bestQ.out == 0) {
            route.data = new bytes[](0);
            bestRoute  = new Quote[](0);
            amountOut  = 0;
            return (route, bestRoute, amountOut);
        }

        route.data = new bytes[](2);
        route.data[0] = abi.encode(bestHop0.tokenIn, bestHop0.tokenOut, bestHop0.pool, bestHop0.fee, bestHop0.amountIn);
        route.data[1] = abi.encode(bestHop1.tokenIn, bestHop1.tokenOut, bestHop1.pool, bestHop1.fee, bestHop1.amountIn);

        bestRoute = new Quote[](2);
        bestRoute[0] = bestHop0;
        bestRoute[1] = bestHop1;
        amountOut = bestQ.out;
    }

    /* ──────────────── Internal HELPERS ─────────────── */

    /**
     * @notice  Build a v3 path from a serialized route (1–2 hop)
     * @dev     Checks the number of hops (only 1 or 2). The path starts with the tokenIn of the first hop
     * @param   route DexRoute (bytes representation of hops)
     * @return  path Constructed v3 path
     */
    function _buildPath(DexRoute calldata route) internal pure returns (bytes memory path) {
        uint256 hops = route.data.length;
        require(hops >= 1 && hops <= 2, "UniswapV3: bad hops");

        // read first token
        (address tokenIn,, , ,) = abi.decode(route.data[0], (address, address, address, uint24, uint256));
        path = abi.encodePacked(tokenIn);

        for (uint256 i; i < hops; ++i) {
            (, address tokenOut,, uint24 fee,) =
                abi.decode(route.data[i], (address, address, address, uint24, uint256));
            path = bytes.concat(path, fee._u24(), abi.encodePacked(tokenOut));
        }
    }

    /**
     * @notice  Check if a token belongs to the hub set
     * @param   token Token address
     * @return  True if token is a hub token
     */
    function _isHub(address token) internal view returns (bool) {
        for (uint256 i; i < HUB_TOKENS.length; ++i) {
            if (HUB_TOKENS[i] == token) return true;
        }
        return false;
    }
    
    /**
     * @notice  Transfer the specified amount of tokens from the user to the contract
     * @param   token    ERC20 address
     * @param   amount   Amount to transfer
     */
    function _pullToken(address token, uint256 amount) internal {
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice  Safely set allowance for a spender, handling non-standard ERC20s.
     * @param   token    ERC20 token address
     * @param   spender  Allowance spender (e.g., the Uniswap router)
     * @param   amount   Minimum required allowance amount
     */
    function _smartApprove (address token, address spender, uint256 amount) internal {
        if (IERC20(token).allowance(address(this), spender) < amount) {
            IERC20(token).forceApprove(spender, type(uint256).max);
        }
    }

    /**
     * @notice  Find the best-liquidity pool for a pair over given fee tiers
     * @param   tokenA   First token
     * @param   tokenB   Second token
     * @param   fees     Fee tiers to consider
     * @return  bestPool Pool with the highest liquidity (or address(0))
     * @return  bestFee  Matching fee tier (or 0)
     */
    function _bestPoolForPair(address tokenA, address tokenB, uint24[] memory fees)
        internal
        view
        returns (address bestPool, uint24 bestFee)
    {
        (address a, address b) = _sortTokens(tokenA, tokenB);
        uint256 n = fees.length;
        uint128 bestLiq;

        for (uint256 i; i < n; ) {
            address p = FACTORY.getPool(a, b, fees[i]);
            if (p != address(0)) {
                uint128 L = IUniswapV3Pool(p).liquidity();
                if (L > bestLiq) {
                    bestLiq = L;
                    bestPool = p;
                    bestFee = fees[i];
                }
            }
            unchecked { ++i; }
        }
        // If not found, returns (address(0), 0)
    }

    /**
     * @notice  Sort two token addresses ascending
     * @param   x First  token
     * @param   y Second token
     * @return  a Lower  address (token0)
     * @return  b Higher address (token1)
     */
    function _sortTokens(address x, address y) internal pure returns (address a, address b) {
        require(x != address(0) && y != address(0), "UniswapV3: zero addr");
        require(x != y, "UniswapV3: same token");
        (a, b) = x < y ? (x, y) : (y, x);
    }

    /**
     * @notice  Select default fee tiers for a pair type (stable-stable vs. other)
     * @param   a Token  A
     * @param   b Token  B
     * @return  f Fee    array (2 items)
     */
    function _feesForPair(address a, address b) internal pure returns (uint24[] memory f) {
        bool aStable = (a == USDC || a == USDT || a == DAI);
        bool bStable = (b == USDC || b == USDT || b == DAI);
        if (aStable && bStable) {
            f = new uint24[](2); f[0] = 100; f[1] = 500;
        } else {
            f = new uint24[](2); f[0] = 500; f[1] = 3000;
        }
    }

    /* ───────────────── Quote helpers ───────────────── */

    /**
     * @notice  Try to quote a multi-hop path via a view-return quoter first; fallback to Uniswap's revert-data format
     * @param   path        V3-encoded path
     * @param   amountIn    Input amount
     * @return  amountOut   Quoted output
     * @return  s           Sqrt(P) after each hop (may be empty if v1-only)
     * @return  t           Initialized ticks crossed per hop (may be empty if v1-only)
     * @return  gasEstimate Compatibility value (0 for StaticQuoterV2)
     */
    function _safeQuote(bytes memory path, uint256 amountIn)
        internal
        view
        returns (uint256 amountOut, uint160[] memory s, uint32[] memory t, uint256 gasEstimate)
    {
        // Fast path: StaticQuoterV2 returns normally
        try QUOTER.quoteExactInput(path, amountIn) returns (
            uint256 a,
            uint160[] memory s2,
            uint32[]  memory t2,
            uint256   g
        ) {
            return (a, s2, t2, g);
        } catch (bytes memory ret) {
            // Fallback: Uniswap QuoterV2 returns via revert(data)
            if (ret.length > 4) {
                bytes memory data = _stripSelector(ret);

                // v2 Tuple
                try this._decodeQuoteMulti(data) returns (uint256 a2, uint160[] memory s3, uint32[] memory t3, uint256 g3) {
                    return (a2, s3, t3, g3);
                } catch { /* ignore */ }

                // v1 Amount-only (very rare)
                try this._decodeAmountOnly(data) returns (uint256 aOnly) {
                    return (aOnly, new uint160[](0), new uint32[](0), 0);
                } catch { /* ignore */ }
            }
            // Corrected default return for dynamic arrays
            return (0, new uint160[](0), new uint32[](0), 0);
        }
    }

    /**
     * @notice  Try to quote a single-hop via a view-return quoter; fallback to Uniswap's revert-data format
     * @param   params See {IQuoterV2.QuoteExactInputSingleParams}
     * @return  amountOut   Quoted output
     * @return  spAfter     Sqrt(P) after swap (0 if v1-only)
     * @return  ticks       Initialized ticks crossed (0 if v1-only)
     * @return  gasEstimate Compatibility value (0 for StaticQuoterV2)
     */
    function _safeQuoteSingle(IQuoterV2.QuoteExactInputSingleParams memory params)
        internal
        view
        returns (uint256 amountOut, uint160 spAfter, uint32 ticks, uint256 gasEstimate)
    {
        // Fast path: StaticQuoterV2
        try QUOTER.quoteExactInputSingle(params) returns (uint256 a, uint160 s, uint32 c, uint256 g) {
            return (a, s, c, g);
        } catch (bytes memory ret) {
            // Fallback: Uniswap QuoterV2 revert(data)
            if (ret.length > 4) {
                bytes memory data = _stripSelector(ret);

                // v2 Tuple
                try this._decodeQuoteSingleV2(data) returns (uint256 a2, uint160 s2, uint32 c2, uint256 g2) {
                    return (a2, s2, c2, g2);
                } catch { /* ignore */ }

                // v1 Amount-only
                try this._decodeAmountOnly(data) returns (uint256 aOnly) {
                    return (aOnly, 0, 0, 0);
                } catch { /* ignore */ }
            }
            return (0, 0, 0, 0);
        }
    }

    /* ────────── Revert-data decoding helpers ───────── */

    /**
     * @notice  Strip the first 4 bytes (function selector) from revert data
     * @param   revertData Raw revert data
     * @return  out Revert payload without selector
     */
    function _stripSelector(bytes memory revertData) private pure returns (bytes memory out) {
        if (revertData.length <= 4) return "";
        out = new bytes(revertData.length - 4);
        for (uint256 i = 0; i < out.length; ++i) {
            out[i] = revertData[i + 4];
        }
    }

    /**
     * @notice  Decode a QuoterV2 multi-hop tuple from revert data.
     * @param   data ABI-encoded tuple.
     * @return  amountOut   a
     * @return  s           sqrtPriceAfter list
     * @return  t           ticksCrossed list
     * @return  gasEstimate gas
     */
    function _decodeQuoteMulti(bytes memory data)
        external
        pure
        returns (uint256 amountOut, uint160[] memory s, uint32[] memory t, uint256 gasEstimate)
    {
        return abi.decode(data, (uint256, uint160[], uint32[], uint256));
    }

    /**
     * @notice  Decode a QuoterV2 single-hop tuple from revert data.
     * @param   data ABI-encoded tuple.
     * @return  amountOut
     * @return  sqrtAfter
     * @return  ticksCrossed
     * @return  gasEstimate
     */
    function _decodeQuoteSingleV2(bytes memory data)
        external
        pure
        returns (uint256, uint160, uint32, uint256)
    {
        return abi.decode(data, (uint256, uint160, uint32, uint256));
    }

    /**
     * @notice  Decode a legacy v1 amount-only value from revert data.
     * @param   data      ABI-encoded uint256.
     * @return  amountOut Decoded amount.
     */
    function _decodeAmountOnly(bytes memory data) external pure returns (uint256) {
        return abi.decode(data, (uint256));
    }
}

@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/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";

@openzeppelin/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";

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

    /**
     * @dev 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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @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 _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * 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 {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev 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 rely 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 rely 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}.
     * Opposedly, 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 high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

@openzeppelin/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

@openzeppelin/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);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.