SushiSwapV2DexModule

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/swap/SushiSwapV2DexModule.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.30;\r
\r
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\r
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";\r
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";\r
\r
/**\r
 * @title  SushiSwapV2DexModule\r
 * @author Andrei Averin — CTO dsf.finance\r
 * @notice Uniswap‑V2‑style (SushiSwap) module for UniversalRouter\r
 * @dev    Supports 1‑hop and 2‑hop routes (via hub tokens) and executes swaps\r
 */\r
\r
/* ──────────── External interfaces ──────────── */\r
\r
interface IUniswapV2Pair {\r
    function token0() external view returns (address);\r
    function token1() external view returns (address);\r
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\r
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;\r
}\r
\r
interface IUniswapV2Factory {\r
    function getPair(address tokenA, address tokenB) external view returns (address pair);\r
}\r
\r
/* ──────────── Aggregator interfaces ──────────── */\r
\r
interface IDexModule {\r
    /**\r
     * @notice  Compute the best 1-hop and 2-hop routes.\r
     * @param   tokenIn       Input token\r
     * @param   tokenOut      Output token\r
     * @param   amountIn      Input amount\r
     * @return  best1HopRoute Serialized 1-hop route\r
     * @return  amountOut1Hop Quoted 1-hop output\r
     * @return  best2HopRoute Serialized 2-hop route\r
     * @return  amountOut2Hop Quoted 2-hop output\r
     */\r
    function getBestRoute(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) external view returns (\r
        DexRoute memory best1HopRoute,\r
        uint256 amountOut1Hop,\r
        DexRoute memory best2HopRoute,\r
        uint256 amountOut2Hop\r
    );\r
\r
    /**\r
     * @notice  Execute a previously returned route with a slippage check based on a percentage.\r
     * @param   route     Serialized route\r
     * @param   to        Recipient of the final tokens\r
     * @param   percent   Percentage (0-100) of amountIn from the route to be swapped\r
     * @return  amountOut Actual output received\r
     */\r
    function swapRoute(\r
        DexRoute calldata route,\r
        address to,\r
        uint256 percent\r
    ) external returns (\r
        uint256 amountOut\r
    );\r
\r
    /**\r
     * @notice  Simulate a route (1–2 hops) encoded as {DexRoute}.\r
     * @param   route     Serialized route\r
     * @param   percent   Percentage (0-100) of amountIn from the route to be simulated\r
     * @return  amountOut Quoted total output amount\r
     */\r
    function simulateRoute(\r
        DexRoute calldata route,\r
        uint256 percent\r
    ) external view returns (uint256 amountOut);\r
}\r
\r
struct DexRoute {\r
    bytes[] data;\r
}\r
\r
struct Quote {\r
    address tokenIn;\r
    address tokenOut;\r
    address pair;\r
    uint256 amountIn;\r
    uint256 amountOut;\r
}\r
\r
struct RouteStep {\r
    address tokenIn;\r
    address tokenOut;\r
    address pair;\r
    uint256 amountIn;\r
}\r
\r
/* ───────────────── Math helper ───────────────── */\r
\r
library UniMath {\r
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountOut) {\r
        require(amountIn > 0, "UNI: INSUFF_INPUT");\r
        require(reserveIn > 0 && reserveOut > 0, "UNI: INSUFF_LIQ");\r
        uint256 amountInWithFee = amountIn * 997;\r
        uint256 numerator = amountInWithFee * reserveOut;\r
        uint256 denominator = reserveIn * 1000 + amountInWithFee;\r
        amountOut = numerator / denominator;\r
    }\r
}\r
\r
/* ────────────────── Dex module ───────────────── */\r
\r
contract SushiSwapV2DexModule is IDexModule, Ownable {\r
    using SafeERC20 for IERC20;\r
\r
    // Immutable addresses\r
    IUniswapV2Factory public constant FACTORY = IUniswapV2Factory(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac); // SushiSwap\r
\r
    address public constant WETH  = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\r
    address public constant USDC  = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;\r
\r
    address[] private HUB_TOKENS = [WETH, USDC];\r
\r
    constructor() Ownable(msg.sender) {}\r
\r
    /* ──────────────── External VIEW ─────────────── */\r
\r
    /**\r
     * @inheritdoc IDexModule\r
     */\r
    function getBestRoute(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) external view override returns (\r
        DexRoute memory best1HopRoute,\r
        uint256 amountOut1Hop,\r
        DexRoute memory best2HopRoute,\r
        uint256 amountOut2Hop\r
    ) {\r
        require(tokenIn != tokenOut, "Sushi: identical");\r
        require(amountIn > 0, "Sushi: zero amountIn");\r
\r
        // 1. Get the best 1-hop route\r
        (best1HopRoute, amountOut1Hop) = _getBestOneHop(tokenIn, tokenOut, amountIn);\r
\r
        // 2. Get the best 2-hop route\r
        (best2HopRoute, amountOut2Hop) = _getBestTwoHop(tokenIn, tokenOut, amountIn);\r
\r
        require(amountOut1Hop > 0 || amountOut2Hop > 0, "Sushi: no route");\r
    }\r
\r
    /**\r
     * @inheritdoc IDexModule\r
     */\r
    function simulateRoute(\r
        DexRoute calldata route,\r
        uint256 percent\r
    ) external view override returns (uint256 amountOut) {\r
        require(route.data.length > 0, "Sushi: empty route");\r
        require(percent > 0 && percent <= 100, "Sushi: bad percent");\r
\r
        // 1. Read the original amountIn from the first hop\r
        // Route data is: abi.encode(tokenIn, tokenOut, pair, amountIn)\r
        (, , , uint256 originalAmountIn) =\r
            abi.decode(route.data[0], (address, address, address, uint256));\r
        require(originalAmountIn > 0, "Sushi: zero original amountIn");\r
\r
        // 2. Calculate the actual amount to simulate\r
        uint256 actualAmountIn = (originalAmountIn * percent) / 100;\r
        require(actualAmountIn > 0, "Sushi: zero actual amountIn");\r
\r
        // 3. Simulate the path with the actual amount\r
        amountOut = _quoteRoute(route, actualAmountIn);\r
    }\r
\r
    /**\r
     * @notice Returns all possible swap routes (1-hop and 2-hop via HUB_TOKENS)\r
     * @param  tokenIn Address of the input token\r
     * @param  tokenOut Address of the output token\r
     * @param  amountIn Amount of input tokens\r
     * @return routes Array of possible routes, each route is an array of quotes for its hops\r
     */\r
    function getAllRoutes(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) external view returns (Quote[][] memory routes) {\r
        require(tokenIn != tokenOut, "Sushi: identical");\r
\r
        (Quote[][] memory r1, uint256 n1) = _collectDirectQuotes(tokenIn, tokenOut, amountIn);\r
        (Quote[][] memory r2, uint256 n2) = _collectTwoHopQuotes(tokenIn, tokenOut, amountIn);\r
\r
        routes = new Quote[][](n1 + n2);\r
\r
        // copy direct\r
        for (uint256 i; i < n1; ) {\r
            routes[i] = r1[i];\r
            unchecked { ++i; }\r
        }\r
        // copy two-hop\r
        for (uint256 j; j < n2; ) {\r
            routes[n1 + j] = r2[j];\r
            unchecked { ++j; }\r
        }\r
    }\r
\r
    /**\r
     * @notice Decodes a serialized DexRoute into array of RouteStep structs\r
     * @param  route DexRoute containing encoded hops\r
     * @return steps Decoded array of route steps\r
     */\r
    function decodeRoute(DexRoute calldata route)\r
        external\r
        pure\r
        returns (RouteStep[] memory steps)\r
    {\r
        uint256 len = route.data.length;\r
        steps = new RouteStep[](len);\r
\r
        for (uint256 n; n < len; ++n) {\r
            (address tokenIn, address tokenOut, address pair, uint256 amountIn) =\r
                abi.decode(route.data[n], (address, address, address, uint256));\r
\r
            steps[n] = RouteStep({\r
                tokenIn: tokenIn,\r
                tokenOut: tokenOut,\r
                pair: pair,\r
                amountIn: amountIn\r
            });\r
        }\r
    }\r
\r
    /* ─────────── External STATE-CHANGING ────────── */\r
\r
    /**\r
     * @inheritdoc IDexModule\r
     */\r
    function swapRoute(DexRoute calldata route, address to, uint256 percent)\r
        external\r
        override\r
        returns (uint256 amountOut)\r
    {\r
        uint256 hops = route.data.length;\r
        require(hops > 0, "Sushi: empty route");\r
        require(to != address(0), "Sushi: bad recipient");\r
        require(percent > 0 && percent <= 100, "Sushi: bad percent");\r
\r
        address lastOut;\r
        for (uint256 n; n < hops; ++n) {\r
            // Read all route parameters from the encoded hop\r
            (address tokenIn, address tokenOut, address pair, uint256 routeAmountIn) =\r
                abi.decode(route.data[n], (address,address,address,uint256));\r
\r
            uint256 amountIn;\r
            if (n == 0) {\r
                // Calculate the actual amount based on percent\r
                uint256 actualAmountIn = (routeAmountIn * percent) / 100;\r
                require(actualAmountIn > 0, "Sushi: zero actual amountIn");\r
\r
                // Pull token and check for FOT (using the actual amount)\r
                uint256 beforePull = IERC20(tokenIn).balanceOf(address(this));\r
                _pullToken(tokenIn, actualAmountIn); // uses safeTransferFrom\r
                uint256 received = IERC20(tokenIn).balanceOf(address(this)) - beforePull;\r
                require(received == actualAmountIn, "FOT_IN_MOD");\r
\r
                amountIn = actualAmountIn; // Use the percentage amount\r
            } else {\r
                // strict chain continuation\r
                require(tokenIn == lastOut, "Sushi: path mismatch");\r
                amountIn = IERC20(tokenIn).balanceOf(address(this));\r
                require(amountIn > 0, "Sushi: empty hop");\r
            }\r
\r
            amountOut = _swapStrict(pair, tokenIn, tokenOut, amountIn);\r
            lastOut = tokenOut;\r
        }\r
\r
        _deliverToken(lastOut, to, amountOut);\r
    }\r
\r
    /**\r
     * @notice Performs a strict swap on the V2 pair, ensuring no fees are charged for transfers (FOT)\r
     *         when entering and exiting the pool.\r
     * @dev    1. First, checks that the pool has received *strictly* amountIn.\r
     *         2. Then performs the swap.\r
     *         3. Finally, checks that the contract has received *strictly* amountOut.\r
     *         (It is assumed that the token is already on the module's balance).\r
     * @param  pair       Address of the Uniswap V2 pair (or SushiSwap, PancakeSwap, etc.).\r
     * @param  tokenIn    Address of the input token.\r
     * @param  tokenOut   Address of the output token.\r
     * @param  amountIn   Amount of the input token that should be transferred to the pool.\r
     * @return amountOut  Amount of the output token actually received by the module.\r
     */\r
    function _swapStrict(address pair, address tokenIn, address tokenOut, uint256 amountIn)\r
        internal\r
        returns (uint256 amountOut)\r
    {\r
        require(pair != address(0), "Sushi: bad pair");\r
        (uint112 r0, uint112 r1,) = IUniswapV2Pair(pair).getReserves();\r
        require(r0 != 0 && r1 != 0, "Sushi: empty reserves");\r
\r
        (address token0,) = _sort(tokenIn, tokenOut);\r
        (uint256 reserveIn, uint256 reserveOut) = tokenIn == token0 ? (r0, r1) : (r1, r0);\r
\r
        // The pool must receive EXACTLY amountIn (FOT prohibition when transferring to the pool)\r
        uint256 beforePair = IERC20(tokenIn).balanceOf(pair);\r
        IERC20(tokenIn).safeTransfer(pair, amountIn);\r
        uint256 got = IERC20(tokenIn).balanceOf(pair) - beforePair;\r
        require(got == amountIn, "FOT_TO_PAIR"); // FOT ban when transferring to the pool\r
\r
        // We consider the expected output\r
        amountOut = UniMath.getAmountOut(amountIn, reserveIn, reserveOut);\r
\r
        // Swap and verify that the module received EXACTLY amountOut (FOT prohibition at the output)\r
        uint256 beforeOut = IERC20(tokenOut).balanceOf(address(this));\r
        (uint256 amount0Out, uint256 amount1Out) =\r
            tokenIn == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));\r
        IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), new bytes(0));\r
        uint256 gotOut = IERC20(tokenOut).balanceOf(address(this)) - beforeOut;\r
        require(gotOut == amountOut, "FOT_OUT_MOD"); // FOT ban upon receipt from the pool\r
    }\r
\r
    /* ─────────────────── ADMIN  ─────────────────── */\r
\r
    /**\r
     * @notice Sets the set of hub tokens for 2-hop search.\r
     * @dev    Does not check for duplicates/validity — admin responsibility.\r
     * @param  hubs Array of hub token addresses.\r
     */\r
    function setHubTokens(address[] calldata hubs) external onlyOwner {\r
        HUB_TOKENS = hubs;\r
    }\r
\r
    /* ────────────── Internal helpers ────────────── */\r
\r
    /**\r
     * @notice Returns the address of the pair for (a,b) via the factory\r
     * @dev    Call to FACTORY.getPair(a,b)\r
     *         If the pair does not exist, returns address(0)\r
     * @param  a Address of token A\r
     * @param  b Address of token B\r
     * @return Address of the pair or 0\r
     */\r
    function _pair(address a, address b) internal view returns (address) {\r
        return FACTORY.getPair(a, b);\r
    }\r
\r
    /**\r
     * @notice Quotes the output for the pair (tokenIn, tokenOut) using the Uniswap V2 formula\r
     * @param  tokenIn   Input token\r
     * @param  tokenOut  Output token\r
     * @param  amountIn  Input amount\r
     * @return amountOut Expected output; 0 if there is no pair/liquidity\r
     */\r
    function _quote(address tokenIn, address tokenOut, uint256 amountIn) internal view returns (uint256 amountOut) {\r
        address pair = _pair(tokenIn, tokenOut);\r
        if (pair == address(0) || amountIn == 0) return 0;\r
        (uint112 r0, uint112 r1,) = IUniswapV2Pair(pair).getReserves();\r
        if (r0 == 0 || r1 == 0) return 0;\r
        (address token0,) = _sort(tokenIn, tokenOut);\r
        (uint256 reserveIn, uint256 reserveOut) = tokenIn == token0 ? (r0, r1) : (r1, r0);\r
        if (reserveIn == 0 || reserveOut == 0) return 0;\r
        amountOut = UniMath.getAmountOut(amountIn, reserveIn, reserveOut);\r
    }\r
\r
    /**\r
     * @notice Performs a single swap on a V2 pair\r
     * @param  pair      UniswapV2Pair pair address\r
     * @param  tokenIn   Input token\r
     * @param  tokenOut  Output token\r
     * @param  amountIn  Input amount\r
     * @return amountOut The amount of tokenOut received\r
     */\r
    function _swap(address pair, address tokenIn, address tokenOut, uint256 amountIn) internal returns (uint256 amountOut) {\r
        require(pair != address(0), "Sushi: bad pair");\r
        (uint112 r0, uint112 r1,) = IUniswapV2Pair(pair).getReserves();\r
        require(r0 != 0 && r1 != 0, "Sushi: empty reserves");\r
        (address token0,) = _sort(tokenIn, tokenOut);\r
        (uint256 reserveIn, uint256 reserveOut) = tokenIn == token0 ? (r0, r1) : (r1, r0);\r
        amountOut = UniMath.getAmountOut(amountIn, reserveIn, reserveOut);\r
        (uint256 amount0Out,uint256 amount1Out) = tokenIn == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0));\r
        IERC20(tokenIn).safeTransfer(pair, amountIn);\r
        IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), new bytes(0));\r
    }\r
\r
    /**\r
     * @notice Transfers tokens from the user to the contract\r
     * @param  token The token to be received\r
     * @param  amount The number of tokens\r
     */\r
    function _pullToken(address token, uint256 amount) internal {\r
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);\r
    }\r
\r
    /**\r
     * @notice Sends a token to the user\r
     * @param  token The token to be sent\r
     * @param  to The recipient\r
     * @param  amount The number of tokens\r
     */\r
    function _deliverToken(address token, address to, uint256 amount) internal {\r
        IERC20(token).safeTransfer(to, amount);\r
    }\r
\r
    /**\r
     * @notice Sorts two token addresses in ascending order.\r
     * @dev    UniswapV2 invariant: token0 < token1 by address.\r
     * @param  a Address of token A.\r
     * @param  b Address of token B.\r
     * @return first  Smaller address.\r
     * @return second Larger address.\r
     */\r
    function _sort(address a, address b) internal pure returns (address, address) {\r
        require(a != b, "Sushi: same");\r
        return a < b ? (a, b) : (b, a);\r
    }\r
\r
    /**\r
     * @notice Finds the best direct (1-hop) route and quotes it.\r
     * @dev    Uses _quote to calculate the output and encodes the route in DexRoute format.\r
     * @param  tokenIn     Input token address.\r
     * @param  tokenOut    Output token address.\r
     * @param  amountIn    Input token amount for quoting.\r
     * @return route       Serialized 1-hop route (DexRoute).\r
     * @return amountOut   Quoted output token amount.\r
     */\r
     function _getBestOneHop(address tokenIn, address tokenOut, uint256 amountIn)\r
        internal view returns (DexRoute memory route, uint256 amountOut)\r
    {\r
        uint256 out = _quote(tokenIn, tokenOut, amountIn);\r
        if (out == 0) return (DexRoute(new bytes[](0)), 0);\r
\r
        address p = _pair(tokenIn, tokenOut);\r
        bytes[] memory data = new bytes[](1);\r
        data[0] = abi.encode(tokenIn, tokenOut, p, amountIn);\r
        return (DexRoute(data), out);\r
    }\r
\r
    /**\r
     * @notice Finds the best 2-hop route through configured HUB_TOKENS.\r
     * @dev    Searches for the hub that gives the maximum output. The input amount for hop 2 is encoded as 0\r
     *         to indicate that the current contract balance (output from hop 1) should be used.\r
     * @param  tokenIn     The address of the input token.\r
     * @param  tokenOut    Address of the output token.\r
     * @param  amountIn    Input token amount for quotation.\r
     * @return route       Serialized 2-hop route (DexRoute).\r
     * @return amountOut   Quoted output token amount.\r
     */\r
    function _getBestTwoHop(address tokenIn, address tokenOut, uint256 amountIn)\r
        internal view returns (DexRoute memory route, uint256 amountOut)\r
    {\r
        uint256 bestOut;\r
        address bestHub;\r
\r
        for (uint256 i; i < HUB_TOKENS.length;) {\r
            address hub = HUB_TOKENS[i];\r
            if (hub != tokenIn && hub != tokenOut) {\r
                uint256 out1 = _quote(tokenIn, hub, amountIn);\r
                if (out1 != 0) {\r
                    uint256 out2 = _quote(hub, tokenOut, out1);\r
                    if (out2 > bestOut) {\r
                        bestOut = out2;\r
                        bestHub = hub;\r
                    }\r
                }\r
            }\r
            unchecked { ++i; }\r
        }\r
\r
        if (bestOut > 0) {\r
            address p1 = _pair(tokenIn, bestHub);\r
            address p2 = _pair(bestHub, tokenOut);\r
            bytes[] memory data = new bytes[](2);\r
            data[0] = abi.encode(tokenIn, bestHub, p1, amountIn);\r
            // amountIn for the second hop is encoded as 0, to be read as the balance after hop 1\r
            data[1] = abi.encode(bestHub, tokenOut, p2, uint256(0));\r
            return (DexRoute(data), bestOut);\r
        }\r
        return (DexRoute(new bytes[](0)), 0);\r
    }\r
\r
    /**\r
     * @notice Quotes a 1- or 2-hop route with a specified input volume.\r
     * @dev    Used by the simulateRoute function to calculate partial swap.\r
     * @param  route      Serialized route (DexRoute).\r
     * @param  amountIn   Input token volume for the first hop.\r
     * @return amountOut  Total quoted output token volume.\r
     */\r
    function _quoteRoute(DexRoute calldata route, uint256 amountIn)\r
        internal\r
        view\r
        returns (uint256 amountOut)\r
    {\r
        uint256 hops = route.data.length;\r
        require(hops == 1 || hops == 2, "Sushi: bad hops");\r
\r
        // Hop 0\r
        (address tokenIn0, address tokenOut0, , ) =\r
            abi.decode(route.data[0], (address, address, address, uint256));\r
\r
        uint256 hop0Out = _quote(tokenIn0, tokenOut0, amountIn);\r
        if (hop0Out == 0) return 0;\r
\r
        if (hops == 1) {\r
            return hop0Out;\r
        }\r
\r
        // Hop 1 (if 2 hops)\r
        (address tokenIn1, address tokenOut1, , ) =\r
            abi.decode(route.data[1], (address, address, address, uint256));\r
\r
        // Ensure path consistency: the output of hop0 must be the input of hop1\r
        require(tokenIn1 == tokenOut0, "Sushi: path mismatch");\r
\r
        // Quote the second hop with the output of the first hop\r
        amountOut = _quote(tokenIn1, tokenOut1, hop0Out);\r
        return amountOut;\r
    }\r
\r
    /**\r
     * @notice Collects all direct (1-hop) quotes.\r
     * @dev    Returns either an empty list (if there are no pairs/no liquids) or an array of one route-quote.\r
     * @param  tokenIn  Input token.\r
     * @param  tokenOut Output token.\r
     * @param  amountIn Input amount.\r
     * @return routes Array of routes (each is an array of Quote). For 1-hop, the size of the inner array = 1.\r
     * @return count  Number of routes (0 or 1).\r
     */\r
    function _collectDirectQuotes(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) internal view returns (Quote[][] memory routes, uint256 count) {\r
        uint256 out = _quote(tokenIn, tokenOut, amountIn);\r
        if (out == 0) {\r
            // Return empty arrays if no route is found\r
            return (new Quote[][](0), 0);\r
        }\r
\r
        // A direct route has one hop, which is an array of one quote\r
        Quote[] memory q = new Quote[](1);\r
        address p = _pair(tokenIn, tokenOut);\r
\r
        q[0] = Quote({\r
            tokenIn: tokenIn,\r
            tokenOut: tokenOut,\r
            pair: p,\r
            amountIn: amountIn,\r
            amountOut: out\r
        });\r
\r
        // routes is an array of routes; in this case, one route\r
        routes = new Quote[][](1);\r
        routes[0] = q;\r
        count = 1;\r
    }\r
\r
    /**\r
     * @notice Collects all 2-hop quotes via HUB_TOKENS.\r
     * @param  tokenIn  Input token.\r
     * @param  tokenOut Output token.\r
     * @param  amountIn Input amount.\r
     * @return routes Array of 2-hop routes; each element is an array of 2 Quotes.\r
     * @return count  How many routes were collected.\r
     */\r
    function _collectTwoHopQuotes(\r
        address tokenIn,\r
        address tokenOut,\r
        uint256 amountIn\r
    ) internal view returns (Quote[][] memory routes, uint256 count) {\r
        // Maximum candidates equals the number of hubs (some may be discarded)\r
        Quote[][] memory tmp = new Quote[][](HUB_TOKENS.length);\r
        uint256 c;\r
\r
        for (uint256 i; i < HUB_TOKENS.length; ) {\r
            address hub = HUB_TOKENS[i];\r
            if (hub != tokenIn && hub != tokenOut) {\r
                // hop1\r
                uint256 out1 = _quote(tokenIn, hub, amountIn);\r
                if (out1 != 0) {\r
                    // hop2\r
                    uint256 out2 = _quote(hub, tokenOut, out1);\r
                    if (out2 != 0) {\r
                        // Create an array for a single two-hop route\r
                        Quote[] memory q = new Quote[](2);\r
\r
                        address p1 = _pair(tokenIn, hub);\r
                        address p2 = _pair(hub, tokenOut);\r
\r
                        q[0] = Quote({\r
                            tokenIn: tokenIn,\r
                            tokenOut: hub,\r
                            pair: p1,\r
                            amountIn: amountIn,\r
                            amountOut: out1\r
                        });\r
\r
                        q[1] = Quote({\r
                            tokenIn: hub,\r
                            tokenOut: tokenOut,\r
                            pair: p2,\r
                            amountIn: out1,\r
                            amountOut: out2\r
                        });\r
\r
                        tmp[c] = q;\r
                        unchecked { ++c; }\r
                    }\r
                }\r
            }\r
            unchecked { ++i; }\r
        }\r
\r
        // shrink\r
        routes = new Quote[][](c);\r
        for (uint256 k; k < c; ) {\r
            routes[k] = tmp[k];\r
            unchecked { ++k; }\r
        }\r
        count = c;\r
    }\r
}\r
"
    },
    "@openzeppelin/contracts/access/Ownable.sol": {
      "content": "// 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/token/ERC20/utils/SafeERC20.sol": {
      "content": "// 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/token/ERC20/IERC20.sol": {
      "content": "// 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/interfaces/IERC1363.sol": {
      "content": "// 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/utils/Context.sol": {
      "content": "// 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/interfaces/IERC165.sol": {
      "content": "// 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": {
      "content": "// 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/utils/introspection/IERC165.sol": {
      "content": "// 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);
}
"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 200
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "abi"
        ]
      }
    },
    "remappings": []
  }
}}

Tags:
ERC20, ERC165, Multisig, Swap, Liquidity, Multi-Signature, Factory|addr:0xbdcdabd2019f01da14620c2f95b6f4907e66eb55|verified:true|block:23537083|tx:0x600339d272cc5ae9d1859df7d5242dc0de346b3f205e38594a68f0a28e11b945|first_check:1759996746

Submitted on: 2025-10-09 09:59:06

Comments

Log in to comment.

No comments yet.