Skip to content
Verified contractPartialMIT

Router

Address0x11fca254429ab77689b3f45e7d4fc13700fdee05
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,290,359
Creation transaction
0x4e84c71df8…8f8ec38b34

src/Router.sol

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

import { IAdapter } from "./interfaces/IAdapter.sol";
import { IRouter } from "./interfaces/IRouter.sol";
import { IPoolManager } from "./interfaces/venues/IPoolManager.sol";
import { IUniswapV2Pair } from "./interfaces/venues/IUniswapV2Pair.sol";
import { IUniswapV3Pool } from "./interfaces/venues/IUniswapV3Pool.sol";
import { IWETH9 } from "./interfaces/venues/IWETH9.sol";
import { RouteCodec } from "./libraries/RouteCodec.sol";
import { SafeERC20Min } from "./libraries/SafeERC20Min.sol";

/// @title Router (RFC 2026-10-15)
/// @notice `execute(endpoints, route)` over a FIXED set of protocols compiled into this code,
///         each named by an 8-bit id (0 is never assigned). Per leg: bind the pool, execute.
///         Per hop: its `tokenInIndex` must be the previous hop's output (Q22), so a route is a
///         chain of hops and splits live inside a hop, across legs. Core legs (V2 / V3 / V4) run
///         here; every other leg is a `call` (never `delegatecall`) to the id's adapter, an
///         immutable address.
///
///         Only this pair's `JITSettler` (`SETTLER`) may call `execute` (Q20).
///
///         Fully immutable: no owner, no pause, no pins, no storage (transient guards only);
///         adapters are fixed in the constructor. Adding a venue = deploying a new `JITSettler` +
///         `Router` pair, except a new pool under an existing adapter family (a universe change
///         only: the family's legs carry the pool address).
///
///         Holds nothing between calls: every hop spends this contract's whole balance of its
///         `tokenIn`; `execute` pays its whole `tokenOut` balance to `SETTLER`, then any balance
///         left of the route's `tokenIn` or an intermediate token (split rounding, a partial
///         fill) to `endpoints.recipient` (Q21).
contract Router is IRouter {
    using SafeERC20Min for address;

    // ── Protocol ids (published in docs/protocol-ids.md; never renumbered in one Router) ──
    uint8 public constant UNI_V2 = 1; // core V2: factory + init hash + 30 bps
    uint8 public constant SUSHI_V2 = 2; // core V2
    uint8 public constant UNI_V3 = 16; // core V3: leg carries fee 24
    uint8 public constant UNI_V4 = 32; // core V4, hookless: fee 24 | tickSpacing 24
    uint8 public constant UNI_V4_STABLE_PAIR = 33; // core V4, `STABLE_PAIR_HOOK`
    uint8 public constant CURVE_NG = 96; // adapter: pool 160; flags = i 4 | j 4
    uint8 public constant CURVE_LEGACY = 97; // adapter: pool 160; flags = i 4 | j 4
    uint8 public constant FLUID = 101; // adapter: pool 160
    uint8 public constant EKUBO_V3 = 104; // adapter: config 256; the adapter holds the core
    uint8 public constant EKUBO_V1 = 105; // adapter: config 256
    uint8 public constant FERMI = 224; // pAMM adapter: venue 160 (Q26)
    uint8 public constant TEMPEST = 225; // pAMM adapter: venue 160
    uint8 public constant BEBOP = 226; // pAMM adapter: venue 160

    // ── Core deployments (constants: the binding is arithmetic, no factory call) ─
    address public constant UNI_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
    bytes32 public constant UNI_V2_HASH =
        0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f;
    address public constant SUSHI_V2_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
    bytes32 public constant SUSHI_V2_HASH =
        0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303;
    address public constant UNI_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
    bytes32 public constant UNI_V3_HASH =
        0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
    address public constant POOL_MANAGER = 0x000000000004444c5dc75cB358380D2e3dE08A90;
    address public constant STABLE_PAIR_HOOK = 0x0000113dCf4ADd69999Fad8F20F2b63F979bfcC0;
    address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    uint256 internal constant V2_FEE_BPS = 30;
    /// @dev V3 and V4 share TickMath's bounds; one inside each so an exact-in swap never stops on
    ///      the limit before the input is spent.
    uint160 internal constant MIN_SQRT_PRICE_PLUS_ONE = 4295128740;
    uint160 internal constant MAX_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970341;

    // ── Token table (intermediate hops' tokenOut, by 16-bit index) ───────────
    // Compiled into the code: a new table is a new pair. A token outside it is posted in full
    // after `RouteCodec.TOKEN_ESCAPE`. Read by `tokenAt`: a fixed-depth branch over these
    // constants (index 16 one compare, the rest four), no memory.
    uint256 public constant TOKEN_COUNT = 17;
    address internal constant T0_WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    address internal constant T1_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    address internal constant T2_USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    address internal constant T3_DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
    address internal constant T4_WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
    address internal constant T5_USDE = 0x4c9EDD5852cd905f086C759E8383e09bff1E68B3;
    address internal constant T6_SUSDE = 0x9D39A5DE30e57443BfF2A8307A4256c8797A3497;
    address internal constant T7_USDS = 0xdC035D45d973E3EC169d2276DDab16f1e407384F;
    address internal constant T8_SUSDS = 0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD;
    address internal constant T9_PYUSD = 0x6c3ea9036406852006290770BEdFcAbA0e23A0e8;
    address internal constant T10_CBBTC = 0xcbB7C0000aB88B473b1f5aFd9ef808440eed33Bf;
    address internal constant T11_WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0;
    address internal constant T12_STETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84;
    address internal constant T13_WEETH = 0xCd5fE23C85820F7B72D0926FC9b05b43E359b7ee;
    address internal constant T14_RLUSD = 0x8292Bb45bf1Ee4d140127049757C2E0fF06317eD;
    address internal constant T15_USDG = 0xe343167631d89B6Ffc58B88d6b7fB0228795491D;
    address internal constant T16_XAUT = 0x68749665FF8D2d112Fa859AA293F07A622782F38;

    // ── Settler and adapters (immutable; a change is a new pair) ─────────────
    struct Adapters {
        address curve;
        address fluid;
        address ekubo;
        address pamm;
    }

    /// @notice The only caller of `execute`: this pair's `JITSettler` (Q20).
    address public immutable SETTLER;
    address public immutable ADAPTER_CURVE;
    address public immutable ADAPTER_FLUID;
    address public immutable ADAPTER_EKUBO;
    address public immutable ADAPTER_PAMM;

    error NotSettler();
    error UnknownProtocol(uint8 protocolId);
    /// @dev Not RouteCodec v5, or no hop.
    error BadVersion();
    error BadTokenIndex(uint256 hop, uint256 index);
    error UnknownToken(uint256 index);
    error SameToken();
    /// @dev A callback or ETH transfer from anyone but the venue this contract is using now.
    error NotPool();
    /// @dev An adapter leg left this contract's `tokenOut` balance where it was.
    error NoOutput(uint256 hop, uint256 leg);

    struct Leg {
        uint8 protocolId;
        uint24 share; // of the hop's input, in 2^-24; the last leg takes the remainder
        uint8 flags;
        /// @dev Right-aligned: V3 fee; V4 fee << 24 | tickSpacing; Ekubo the raw config.
        uint256 params;
        /// @dev Derived (V2, V3), carried (Curve, Fluid, pAMM), `POOL_MANAGER` (V4) or 0 (Ekubo).
        address pool;
    }

    struct Hop {
        address tokenIn;
        address tokenOut;
        Leg[] legs;
    }

    // hex of "RouterV3Pool" / "RouterV4Unlock"
    uint256 private constant _V3_POOL_SLOT = 0x526f757465725633506f6f6c;
    uint256 private constant _V4_UNLOCK_SLOT = 0x526f757465725634556e6c6f636b;

    constructor(address settler, Adapters memory a) {
        SETTLER = settler;
        ADAPTER_CURVE = a.curve;
        ADAPTER_FLUID = a.fluid;
        ADAPTER_EKUBO = a.ekubo;
        ADAPTER_PAMM = a.pamm;
    }

    /// @dev ETH arrives only from unwrapping WETH (native V4 input) or a V4 native `take`.
    receive() external payable {
        if (msg.sender != WETH && msg.sender != POOL_MANAGER) revert NotPool();
    }

    // ── Execute ──────────────────────────────────────────────────────────────

    /// @inheritdoc IRouter
    function execute(Endpoints calldata endpoints, uint256[] calldata route) external {
        if (msg.sender != SETTLER) revert NotSettler();
        if (endpoints.tokenIn == endpoints.tokenOut) revert SameToken();

        (Hop[] memory hops, bool usesV4) = _decode(route, endpoints);

        // One V4 unlock per route: when any leg is V4, the whole route runs inside it.
        if (usesV4) {
            assembly ("memory-safe") {
                tstore(_V4_UNLOCK_SLOT, 1)
            }
            IPoolManager(POOL_MANAGER).unlock(abi.encode(hops));
        } else {
            _run(hops);
        }

        // Returns nothing: `JITSettler` measures what arrives (`routedGrossOut`).
        uint256 out = endpoints.tokenOut.balanceOf(address(this));
        if (out != 0) endpoints.tokenOut.safeTransfer(SETTLER, out);

        // Q21: hop h's tokenIn is the route's tokenIn (h = 0) or an intermediate token. Whatever
        // is left of them goes to the recipient; nothing stays here for the next caller.
        for (uint256 h; h < hops.length; ++h) {
            address token = hops[h].tokenIn;
            uint256 left = token.balanceOf(address(this));
            if (left != 0) token.safeTransfer(endpoints.recipient, left);
        }
    }

    /// @dev V4 `unlock` re-enters here, once, during our own `execute`.
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        uint256 armed;
        assembly ("memory-safe") {
            armed := tload(_V4_UNLOCK_SLOT)
            tstore(_V4_UNLOCK_SLOT, 0)
        }
        if (msg.sender != POOL_MANAGER || armed == 0) revert NotPool();
        _run(abi.decode(data, (Hop[])));
        return "";
    }

    /// @dev Pays a V3 leg's input; only the pool `_swapV3` is calling right now.
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data)
        external
    {
        address expected;
        assembly ("memory-safe") {
            expected := tload(_V3_POOL_SLOT)
        }
        if (msg.sender != expected || expected == address(0)) revert NotPool();
        address tokenIn = abi.decode(data, (address));
        uint256 owed = uint256(amount0Delta > 0 ? amount0Delta : amount1Delta);
        tokenIn.safeTransfer(msg.sender, owed);
    }

    // ── Token table ──────────────────────────────────────────────────────────

    /// @notice Entry `index` of the token table (published with the universe).
    function tokenAt(uint256 index) public pure returns (address token) {
        if (index >= TOKEN_COUNT) revert UnknownToken(index);
        // Pairs (2k, 2k + 1) resolve branch-free on the index's low bit.
        assembly ("memory-safe") {
            function pick(i, even, odd) -> t {
                t := xor(even, mul(xor(even, odd), and(i, 1)))
            }
            switch lt(index, 16)
            case 0 { token := T16_XAUT }
            default {
                switch lt(index, 8)
                case 1 {
                    switch lt(index, 4)
                    case 1 {
                        switch lt(index, 2)
                        case 1 { token := pick(index, T0_WETH, T1_USDC) }
                        default { token := pick(index, T2_USDT, T3_DAI) }
                    }
                    default {
                        switch lt(index, 6)
                        case 1 { token := pick(index, T4_WBTC, T5_USDE) }
                        default { token := pick(index, T6_SUSDE, T7_USDS) }
                    }
                }
                default {
                    switch lt(index, 12)
                    case 1 {
                        switch lt(index, 10)
                        case 1 { token := pick(index, T8_SUSDS, T9_PYUSD) }
                        default { token := pick(index, T10_CBBTC, T11_WSTETH) }
                    }
                    default {
                        switch lt(index, 14)
                        case 1 { token := pick(index, T12_STETH, T13_WEETH) }
                        default { token := pick(index, T14_RLUSD, T15_USDG) }
                    }
                }
            }
        }
    }

    // ── Decode + check + bind (no external calls) ────────────────────────────

    function _decode(uint256[] calldata route, Endpoints calldata endpoints)
        private
        pure
        returns (Hop[] memory hops, bool usesV4)
    {
        uint256[] memory s = route;
        if (s.length < RouteCodec.HEADER_WORDS) revert BadVersion();
        if (RouteCodec.read(s, RouteCodec.STREAM_START, 8) != RouteCodec.VERSION) {
            revert BadVersion();
        }
        uint256 hopCount = RouteCodec.read(s, RouteCodec.STREAM_START + 8, 4);
        if (hopCount == 0) revert BadVersion();
        uint256 p = RouteCodec.HOPS_START;

        hops = new Hop[](hopCount);
        address tokenIn = endpoints.tokenIn;

        for (uint256 h; h < hopCount; ++h) {
            uint256 tokenInIndex = RouteCodec.read(s, p, 4);
            uint256 legCount = RouteCodec.read(s, p + 4, 4);
            p += 8;
            // Q22: the input is the previous hop's output (index 0 = the route's tokenIn).
            if (tokenInIndex != h) revert BadTokenIndex(h, tokenInIndex);
            Hop memory hop = hops[h];
            hop.tokenIn = tokenIn;
            if (h + 1 == hopCount) {
                hop.tokenOut = endpoints.tokenOut;
            } else {
                uint256 tokenOutIndex = RouteCodec.read(s, p, RouteCodec.TOKEN_INDEX_BITS);
                p += RouteCodec.TOKEN_INDEX_BITS;
                if (tokenOutIndex == RouteCodec.TOKEN_ESCAPE) {
                    hop.tokenOut = address(uint160(RouteCodec.read(s, p, 160)));
                    p += 160;
                } else {
                    hop.tokenOut = tokenAt(tokenOutIndex);
                }
            }
            if (hop.tokenIn == hop.tokenOut) revert SameToken();
            tokenIn = hop.tokenOut;

            hop.legs = new Leg[](legCount);
            for (uint256 l; l < legCount; ++l) {
                Leg memory leg = hop.legs[l];
                leg.protocolId = uint8(RouteCodec.read(s, p, 8));
                leg.share = uint24(RouteCodec.read(s, p + 8, 24));
                leg.flags = uint8(RouteCodec.read(s, p + 32, 8));
                p += 40;
                (uint256 bits, bool carries) = _shape(leg.protocolId);
                if (bits != 0) {
                    leg.params = RouteCodec.read(s, p, bits);
                    p += bits;
                }
                if (carries) {
                    // Bound by nothing on chain: jit-router keeps it inside the universe.
                    leg.pool = address(uint160(RouteCodec.read(s, p, 160)));
                    p += 160;
                } else {
                    leg.pool = _bind(leg.protocolId, hop.tokenIn, hop.tokenOut, leg.params);
                }
                if (leg.protocolId == UNI_V4 || leg.protocolId == UNI_V4_STABLE_PAIR) {
                    usesV4 = true;
                }
            }
        }
    }

    /// @dev What a leg of `protocolId` carries after its 40 fixed bits: `bits` of params and
    ///      whether a 160-bit pool / venue follows. Reverts on an id this Router does not know.
    function _shape(uint8 protocolId) private pure returns (uint256 bits, bool carries) {
        if (protocolId == UNI_V2 || protocolId == SUSHI_V2) return (0, false);
        if (protocolId == UNI_V3) return (24, false);
        if (protocolId == UNI_V4 || protocolId == UNI_V4_STABLE_PAIR) return (48, false);
        if (protocolId == CURVE_NG || protocolId == CURVE_LEGACY || protocolId == FLUID) {
            return (0, true);
        }
        if (protocolId == EKUBO_V3 || protocolId == EKUBO_V1) return (256, false);
        if (protocolId >= FERMI && protocolId <= BEBOP) return (0, true);
        revert UnknownProtocol(protocolId);
    }

    /// @dev The pool a non-carrying leg touches: CREATE2 from code constants (V2, V3), the
    ///      `PoolManager` (V4: the pool is the key `_v4Key` rebuilds), or 0 (Ekubo: the adapter
    ///      holds its cores and gets the config as `params`).
    function _bind(uint8 protocolId, address tokenIn, address tokenOut, uint256 params)
        private
        pure
        returns (address)
    {
        (address t0, address t1) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
        if (protocolId == UNI_V2) {
            return _create2(UNI_V2_FACTORY, keccak256(abi.encodePacked(t0, t1)), UNI_V2_HASH);
        }
        if (protocolId == SUSHI_V2) {
            return _create2(SUSHI_V2_FACTORY, keccak256(abi.encodePacked(t0, t1)), SUSHI_V2_HASH);
        }
        if (protocolId == UNI_V3) {
            uint24 fee = uint24(params);
            return _create2(UNI_V3_FACTORY, keccak256(abi.encode(t0, t1, fee)), UNI_V3_HASH);
        }
        if (protocolId == UNI_V4 || protocolId == UNI_V4_STABLE_PAIR) return POOL_MANAGER;
        return address(0);
    }

    function _create2(address deployer, bytes32 salt, bytes32 initHash)
        private
        pure
        returns (address)
    {
        return address(
            uint160(uint256(keccak256(abi.encodePacked(hex"ff", deployer, salt, initHash))))
        );
    }

    // ── Run ──────────────────────────────────────────────────────────────────

    function _run(Hop[] memory hops) private {
        for (uint256 h; h < hops.length; ++h) {
            Hop memory hop = hops[h];
            // The whole balance of the hop's input: this contract holds nothing else.
            uint256 amount = hop.tokenIn.balanceOf(address(this));
            uint256 remaining = amount;
            uint256 legCount = hop.legs.length;
            for (uint256 l; l < legCount; ++l) {
                Leg memory leg = hop.legs[l];
                uint256 legIn = l + 1 == legCount ? remaining : (amount * leg.share) >> 24;
                remaining -= legIn;
                if (legIn != 0) _swapLeg(leg, hop.tokenIn, hop.tokenOut, legIn, h, l);
            }
        }
    }

    function _swapLeg(
        Leg memory leg,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 h,
        uint256 l
    ) private {
        uint8 protocolId = leg.protocolId;
        if (protocolId == UNI_V2 || protocolId == SUSHI_V2) {
            return _swapV2(leg.pool, tokenIn, tokenOut, amountIn);
        }
        if (protocolId == UNI_V3) return _swapV3(leg.pool, tokenIn, tokenOut, amountIn);
        if (protocolId == UNI_V4 || protocolId == UNI_V4_STABLE_PAIR) {
            return _swapV4(leg, tokenIn, tokenOut, amountIn);
        }
        // Adapter leg: fund it, call it, measure what came back.
        address adapter = _adapterOf(protocolId);
        uint256 before = tokenOut.balanceOf(address(this));
        tokenIn.safeTransfer(adapter, amountIn);
        IAdapter(adapter)
            .swap(leg.pool, protocolId, tokenIn, tokenOut, amountIn, leg.params, leg.flags);
        if (tokenOut.balanceOf(address(this)) <= before) revert NoOutput(h, l);
    }

    /// @dev Only ids `_shape` accepted reach here.
    function _adapterOf(uint8 protocolId) private view returns (address) {
        if (protocolId == CURVE_NG || protocolId == CURVE_LEGACY) return ADAPTER_CURVE;
        if (protocolId == FLUID) return ADAPTER_FLUID;
        if (protocolId == EKUBO_V3 || protocolId == EKUBO_V1) return ADAPTER_EKUBO;
        return ADAPTER_PAMM;
    }

    /// @dev Exact-in on a constant-product pair. The input is measured at the pair, so a
    ///      fee-on-transfer token is priced on what arrived.
    function _swapV2(address pool, address tokenIn, address tokenOut, uint256 amountIn) private {
        tokenIn.safeTransfer(pool, amountIn);
        (uint112 r0, uint112 r1,) = IUniswapV2Pair(pool).getReserves();
        bool zeroForOne = tokenIn < tokenOut;
        (uint256 rIn, uint256 rOut) =
            zeroForOne ? (uint256(r0), uint256(r1)) : (uint256(r1), uint256(r0));
        uint256 inWithFee = (tokenIn.balanceOf(pool) - rIn) * (10_000 - V2_FEE_BPS);
        uint256 amountOut = inWithFee * rOut / (rIn * 10_000 + inWithFee);
        (uint256 a0, uint256 a1) = zeroForOne ? (uint256(0), amountOut) : (amountOut, uint256(0));
        IUniswapV2Pair(pool).swap(a0, a1, address(this), "");
    }

    function _swapV3(address pool, address tokenIn, address tokenOut, uint256 amountIn) private {
        bool zeroForOne = tokenIn < tokenOut;
        assembly ("memory-safe") {
            tstore(_V3_POOL_SLOT, pool)
        }
        IUniswapV3Pool(pool)
            .swap(
                address(this),
                zeroForOne,
                int256(amountIn),
                zeroForOne ? MIN_SQRT_PRICE_PLUS_ONE : MAX_SQRT_PRICE_MINUS_ONE,
                abi.encode(tokenIn)
            );
        assembly ("memory-safe") {
            tstore(_V3_POOL_SLOT, 0)
        }
    }

    /// @dev The leg's `PoolKey`: the hop's tokens (WETH as native `address(0)` when flags bit 0
    ///      is set), fee and tick spacing from `params`, the id's hook. The pool id the
    ///      PoolManager keys state on is `keccak256(abi.encode(key))`.
    function _v4Key(uint8 protocolId, address currencyIn, address currencyOut, uint256 params)
        private
        pure
        returns (IPoolManager.PoolKey memory key)
    {
        (key.currency0, key.currency1) =
            currencyIn < currencyOut ? (currencyIn, currencyOut) : (currencyOut, currencyIn);
        key.fee = uint24(params >> 24);
        key.tickSpacing = int24(uint24(params));
        key.hooks = protocolId == UNI_V4_STABLE_PAIR ? STABLE_PAIR_HOOK : address(0);
    }

    /// @dev Inside the route's single unlock. Pays first and swaps what settled:
    ///      `settle` credits the manager's OBSERVED balance change, so a token that delivers
    ///      `n ± 1` still nets to zero. Then takes whatever the swap delta owes this contract: the
    ///      output, and any input left unspent. The swap's returned delta is the caller's, already
    ///      net of hook deltas (StablePair's dynamic fee included), so nothing here depends on
    ///      the hook. Native ETH is unwrapped before `settle` and wrapped after `take`.
    function _swapV4(Leg memory leg, address tokenIn, address tokenOut, uint256 amountIn) private {
        address currencyIn = tokenIn;
        address currencyOut = tokenOut;
        if (leg.flags & 1 != 0) {
            if (tokenIn == WETH) currencyIn = address(0);
            else if (tokenOut == WETH) currencyOut = address(0);
        }
        IPoolManager.PoolKey memory key =
            _v4Key(leg.protocolId, currencyIn, currencyOut, leg.params);
        bool zeroForOne = currencyIn == key.currency0;
        IPoolManager pm = IPoolManager(POOL_MANAGER);

        uint256 paid;
        if (currencyIn == address(0)) {
            IWETH9(WETH).withdraw(amountIn);
            paid = pm.settle{ value: amountIn }();
        } else {
            pm.sync(currencyIn);
            tokenIn.safeTransfer(POOL_MANAGER, amountIn);
            paid = pm.settle();
        }

        int256 delta = pm.swap(
            key,
            IPoolManager.SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(paid), // negative = exact input
                sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_PRICE_PLUS_ONE : MAX_SQRT_PRICE_MINUS_ONE
            }),
            ""
        );
        int256 d0 = int256(int128(delta >> 128));
        int256 d1 = int256(int128(delta));
        (int256 dIn, int256 dOut) = zeroForOne ? (d0, d1) : (d1, d0);
        // `paid + dIn` is input the swap did not spend (a price limit); a negative value is
        // left for `unlock` to refuse (`CurrencyNotSettled`).
        int256 unspent = int256(paid) + dIn;
        if (unspent > 0) _take(currencyIn, uint256(unspent));
        if (dOut > 0) _take(currencyOut, uint256(dOut));
    }

    function _take(address currency, uint256 amount) private {
        IPoolManager(POOL_MANAGER).take(currency, address(this), amount);
        if (currency == address(0)) IWETH9(WETH).deposit{ value: amount }();
    }
}

src/interfaces/IAdapter.sol

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

/// @notice A non-core leg's executor (RFC "Router": adapter families and the pAMM adapter). The
///         `Router` reaches it by `call`, never `delegatecall`, at an address that is immutable
///         in the `Router`'s code.
///
///         Funding: the `Router` transfers `amountIn` of `tokenIn` to the adapter before the call.
///         The adapter pays the whole output to `msg.sender` within the call and holds nothing
///         after it. The `Router` measures its own `tokenOut` balance across the call and uses
///         that, not the return value.
interface IAdapter {
    /// @param pool       The pool or venue the leg carries (Curve, Fluid, pAMM ids), or
    ///                   `address(0)` for ids whose adapter holds its own cores (Ekubo).
    /// @param protocolId The leg's 8-bit id, so one adapter can serve several ids of one family.
    /// @param params     The leg's right-aligned params field: Ekubo's raw 256-bit pool config,
    ///                   0 for ids that carry none.
    /// @param flags      The leg's 8 flag bits; their meaning is per family (Curve: i 4 | j 4).
    function swap(
        address pool,
        uint8 protocolId,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 params,
        uint8 flags
    ) external returns (uint256 amountOut);
}

src/interfaces/IRouter.sol

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

/// @notice The executor `JITSettler` holds as an immutable (RFC "Router").
interface IRouter {
    /// @dev The route's endpoints, and the recipient of any leftovers. The codec omits them from
    ///      the hops (the first hop's input is index 0, the last hop's output is implicit), so
    ///      they travel next to the words.
    struct Endpoints {
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        address recipient;
    }

    /// @notice The only caller of `execute`: this pair's `JITSettler` (Q20).
    function SETTLER() external view returns (address);

    /// @notice RFC: `execute(endpoints, route)`. `route` is the lane exactly as PUR returned it
    ///         (header included; the `Router` skips the fixed-width header). `amountIn` of
    ///         `tokenIn` is already held by the `Router`. Pays its whole `tokenOut` balance to
    ///         `msg.sender` and returns nothing: `JITSettler` measures its own balance change
    ///         (`routedGrossOut`).
    function execute(Endpoints calldata endpoints, uint256[] calldata route) external;
}

src/interfaces/venues/IPoolManager.sol

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

/// @notice Uniswap V4 `PoolManager`, the calls one exact-in leg needs. Currencies are addresses
///         (`address(0)` = native ETH); `BalanceDelta` is an `int256` packing amount0 in the high
///         128 bits and amount1 in the low 128, from the caller's side (positive = owed to it).
interface IPoolManager {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

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

    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (int256 swapDelta);
    function sync(address currency) external;
    function settle() external payable returns (uint256 paid);
    function take(address currency, address to, uint256 amount) external;
}

src/interfaces/venues/IUniswapV2Pair.sol

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

/// @notice The two Uniswap V2 pair calls an exact-in leg needs (also SushiSwap V2).
interface IUniswapV2Pair {
    function getReserves() external view returns (uint112, uint112, uint32);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

src/interfaces/venues/IUniswapV3Pool.sol

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

/// @notice The Uniswap V3 pool call an exact-in leg needs. The pool calls back
///         `uniswapV3SwapCallback(amount0Delta, amount1Delta, data)` on `msg.sender`.
interface IUniswapV3Pool {
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

src/interfaces/venues/IWETH9.sol

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

/// @notice Canonical WETH: wrap and unwrap, for V4 pools whose WETH side is native ETH.
interface IWETH9 {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
}

src/libraries/RouteCodec.sol

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

/// @notice The route encoding, version 5 (RFC "Lane key and encoding"): one big-endian bit stream
///         over the lane's words, fixed-width fields, no ABI. Bit 0 is the MSB of `slots[0]`;
///         the stream starts at bit 40 because PUR keeps the top 40 bits of slot 0 (timestamp 32,
///         slot count 8) and returns `slots[0]` with them zeroed. 1 word holds 216 bits, 2 hold
///         472, 3 hold 728.
///
///         Header (156 bits, fits word 0):
///           version 8 | hopCount 4 | routedEstOut 40 | simOriginalOut 40 | postingChargeOut 40 |
///           routedEstGas 24
///         Amounts are 40-bit floats (`decodeAmount`): mantissa 32 | exponent 8, value =
///         mantissa << exponent. jit-router rounds `simOriginalOut` up (the floor only tightens),
///         `postingChargeOut` down (the treasury only gets less) and `routedEstOut` down (`peek`
///         never overstates). The two estimates feed only `peek`, the `maxGas` refusal and
///         `Settled`, never the floor or the treasury's share. Nothing price-like is posted.
///         No `feeBps` field: `JITSettler`'s `FEE_BPS` is a constructor-fixed immutable (0 in v1).
///         No `Router` field: `JITSettler`'s `Router` is immutable and PUR lanes are per target.
///         No fingerprint: a request reads whatever route its lane holds this block.
///         Per hop:  tokenInIndex 4 | legCount 4 | tokenOutIndex 16 (omitted on the last hop):
///                   an index into the `Router`'s token table, or `TOKEN_ESCAPE` followed by
///                   tokenOut 160 for a token outside it.
///         Per leg:  protocolId 8 | share 24 | flags 8, then what the id carries (the `Router`'s
///                   code, not a bit), params first (read into `Leg.params`, right-aligned),
///                   then a carried address (`Leg.pool`):
///                   - V3 (16): fee 24
///                   - V4 (32, 33): fee << 24 | tickSpacing, 48 in all
///                   - Ekubo (104, 105): the raw PoolConfig word, 256
///                   - Curve (96, 97) and Fluid (101): carried pool address, 160
///                   - pAMM venues (224-226): carried venue address, 160 (Q26)
///                   - nothing for any other id; the V2 ids (1, 2) are compiled in but outside
///                     the published universe. An unknown id reverts.
///         Example (RFC): 2 hops, legs V3 + V4 then V2, tabled intermediate token:
///         156 + 32 + 192 = 380 bits, 2 words.
///
///         The writer is jit-router (`crates/jit-router`), header included; the fixtures in
///         `test/fixtures/routes_v5.json` pin the writer.
library RouteCodec {
    /// @dev The format version in the header's first 8 bits; any other value is "no route".
    uint8 internal constant VERSION = 5;

    uint256 internal constant STREAM_START = 40;
    uint256 internal constant HEADER_BITS = 156;
    uint256 internal constant HOPS_START = STREAM_START + HEADER_BITS; // 196
    /// @dev Words the header needs: ceil(196 / 256).
    uint256 internal constant HEADER_WORDS = 1;

    /// @dev A 40-bit float: mantissa 32 | exponent 8. Exponents above 224 would overflow 256 bits
    ///      and make the header invalid.
    uint256 internal constant AMOUNT_BITS = 40;
    uint256 internal constant MAX_EXPONENT = 224;

    /// @dev `tokenOutIndex` value meaning "a full 160-bit address follows".
    uint256 internal constant TOKEN_INDEX_BITS = 16;
    uint256 internal constant TOKEN_ESCAPE = 0xFFFF;

    uint256 internal constant LANES = 256;

    struct Header {
        uint8 version;
        uint8 hopCount;
        /// @dev Decoded from 40-bit floats to full width.
        /// @dev jit-router's estimate of `routedOut`, net of `postingChargeOut` and `feeOut`.
        ///      0 = no route. Never rewritten after sim 2.
        uint256 routedEstOut;
        /// @dev Builder sim 1: tokenOut `Transfer` logs into `recipient` in the order's tx.
        uint256 simOriginalOut;
        /// @dev postingGas * basefee * outPerEth / 1e18, computed off chain by jit-router: the
        ///      order's own update tx, priced at basefee, in tokenOut.
        uint256 postingChargeOut;
        /// @dev jit-router's estimate of the gas `swap` spends with the route.
        uint24 routedEstGas;
    }

    // ── Lane key ─────────────────────────────────────────────────────────────

    /// @notice RFC: key = keccak(msg.sender, tokenIn, tokenOut, amountIn, minOut, recipient).
    ///         `maxGas` is deliberately not in it: jit-router fits the route under `maxGas`.
    function laneKey(
        address caller,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minOut,
        address recipient
    ) internal pure returns (bytes32) {
        return keccak256(abi.encode(caller, tokenIn, tokenOut, amountIn, minOut, recipient));
    }

    /// @notice Lane = key % 256.
    function laneIndex(bytes32 key) internal pure returns (uint256) {
        return uint256(key) % LANES;
    }

    // ── Bit reader ───────────────────────────────────────────────────────────

    /// @notice `n` bits (1..256) at stream position `p`, as an integer. Reverts (array index)
    ///         past the last word, which in `execute` is a failed route.
    function read(uint256[] memory slots, uint256 p, uint256 n) internal pure returns (uint256) {
        uint256 w = p >> 8;
        uint256 off = p & 255;
        uint256 hi = slots[w] << off;
        if (off + n > 256) hi |= slots[w + 1] >> (256 - off);
        return hi >> (256 - n);
    }

    // ── Amounts ──────────────────────────────────────────────────────────────

    /// @notice A 40-bit float `mantissa 32 | exponent 8` as `mantissa << exponent`, or
    ///         `ok == false` when the exponent exceeds `MAX_EXPONENT`. Exact: the rounding is the
    ///         encoder's (jit-router), with the smallest exponent whose mantissa fits 32 bits, per
    ///         field: `simOriginalOut` up, `routedEstOut` and `postingChargeOut` down.
    function decodeAmount(uint256 raw) internal pure returns (bool ok, uint256 value) {
        uint256 e = raw & 0xFF;
        if (e > MAX_EXPONENT) return (false, 0);
        return (true, (raw >> 8) << e);
    }

    // ── Header ───────────────────────────────────────────────────────────────

    /// @notice Header fields, or `ok == false` when the lane is too short, not this version, or
    ///         an amount's exponent exceeds `MAX_EXPONENT`.
    ///         Never reverts: `peek` is a view that must answer 0, not throw.
    function tryDecodeHeader(uint256[] memory slots)
        internal
        pure
        returns (bool ok, Header memory h)
    {
        if (slots.length < HEADER_WORDS) return (false, h);
        uint256 p = STREAM_START;
        h.version = uint8(read(slots, p, 8));
        p += 8;
        if (h.version != VERSION) return (false, h);
        h.hopCount = uint8(read(slots, p, 4));
        p += 4;
        bool okEst;
        bool okOriginal;
        bool okPosting;
        (okEst, h.routedEstOut) = decodeAmount(read(slots, p, AMOUNT_BITS));
        p += AMOUNT_BITS;
        (okOriginal, h.simOriginalOut) = decodeAmount(read(slots, p, AMOUNT_BITS));
        p += AMOUNT_BITS;
        (okPosting, h.postingChargeOut) = decodeAmount(read(slots, p, AMOUNT_BITS));
        p += AMOUNT_BITS;
        h.routedEstGas = uint24(read(slots, p, 24));
        ok = h.hopCount != 0 && okEst && okOriginal && okPosting;
    }
}

src/libraries/SafeERC20Min.sol

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

/// @notice Minimal ERC20 surface for `SafeERC20Min`: empty returndata is success (USDT), a
///         returned word is the bool it claims.
interface IERC20Min {
    function balanceOf(address) external view returns (uint256);
    function transferFrom(address, address, uint256) external returns (bool);
    function transfer(address, uint256) external returns (bool);
}

library SafeERC20Min {
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        _call(token, abi.encodeWithSelector(IERC20Min.transferFrom.selector, from, to, amount));
    }

    function safeTransfer(address token, address to, uint256 amount) internal {
        _call(token, abi.encodeWithSelector(IERC20Min.transfer.selector, to, amount));
    }

    function balanceOf(address token, address who) internal view returns (uint256) {
        return IERC20Min(token).balanceOf(who);
    }

    function _call(address token, bytes memory data) private {
        (bool ok, bytes memory ret) = token.call(data);
        require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "erc20 call failed");
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "priority-update-registry/=vendor/priority-update-registry/src/",
    "solady/=lib/priority-update-registry/lib/solady/src/",
    "@openzeppelin/=lib/priority-update-registry/lib/openzeppelin-contracts/",
    "erc4626-tests/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/priority-update-registry/lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.