Skip to content
Verified contractExactMIT

V2ToV3Adapter

Address0x0a1abba22c2e52636ada3da47b01cec3a0219205
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.38

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.38+commit.1835d247
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,457,135
Creation transaction
0x47f8559573…02c12ed932

V2ToV3Adapter.sol

// SPDX-License-Identifier: MIT
// V2ToV3Adapter.sol — Uniswap V2 router interface, Uniswap V3 execution
// --------------------------------------------------------------------------------
// Exposes the Uniswap V2 router interface our flash contracts already call
// (swapExactTokensForTokens + getAmountsOut) for ONE Uniswap V3 pool — a
// fixed token pair at a fixed fee tier — and executes each swap through
// Uniswap V3 SwapRouter02.exactInputSingle.
//
// Deploy ONE instance per fee tier (e.g. one pinned to the 0.3% pool, one
// to the 1% pool) and pass the two instances as the two "routers" the
// flash contracts already expect. ZERO changes to Tech v4, DollarV3, or
// SmartWalletV3.
//
// Why this exists: on the L2 testnets the only real DEX liquidity is
// Uniswap V3, and V3 routers speak exactInputSingle, not the V2
// swapExactTokensForTokens(path) our contracts call. See
// FLASH_TESTNET_RESEARCH.md — no testnet has real V2 liquidity + Aave
// together, so the adapter is the one new piece of code a real round
// trip needs.
//
// DESIGN:
//  - Immutable config, no owner, no setters, no funds held: the adapter
//    is a dumb pipe. It pulls exactly amountIn from the caller, approves
//    the V3 router for exactly amountIn, and the V3 router sends the
//    output straight to `to`. It never holds a balance between calls, so
//    there is nothing to steal and no admin key to lose.
//  - Only 2-hop paths on the configured pair, either direction. Any other
//    path reverts (BadPath) — the adapter never silently routes somewhere
//    the caller did not intend.
//  - SafeERC20-style token calls throughout (accept a bool `true` return
//    OR empty returndata), same as the flash contracts — real USDT
//    returns nothing, and the adapter must not be the thing that breaks
//    on it.
//  - getAmountsOut is a REAL view function: it reads the pool's
//    slot0 sqrt price and converts at the CURRENT price, with a 5%
//    haircut (returns 95% of the at-price output). It does NOT use
//    the V3 Quoter — and that is deliberate, not a shortcut:
//      * The V2 router interface declares getAmountsOut as `view`,
//        so every V2 caller (Tech v4's spot engine included) invokes
//        it via STATICCALL. The static context propagates down the
//        whole call chain.
//      * The V3 Quoter simulates the swap by calling pool.swap,
//        which WRITES state during the simulation (the Quoter relies
//        on its own callback reverting to roll the simulation back).
//        Under STATICCALL that write is forbidden: the pool reverts
//        with "write protection", the Quoter turns it into
//        "Unexpected error", and Tech's autoTrade reverts.
//        PROVEN on an Arbitrum Sepolia fork with a call trace
//        (2026-11-17): STATICCALL Tech -> adapter -> Quoter ->
//        pool.swap reverts "write protection".
//      * The slot0 quote is STATICCALL-safe (pure reads) and is all
//        the spot engine needs: it only uses the quote to derive
//        minOut (99% of the quote), and the swap itself enforces
//        minOut on-chain. The 5% haircut covers the pool fee
//        (0.3%/1%) plus price impact on small trades — verified
//        against the live 0.3% pool: the haircut quote is 95-99% of
//        the true Quoter value for 1-10 USDC trades, so minOut sits
//        safely below the actual output.
//      * SIZE LIMIT: the haircut does NOT cover price impact on
//        LARGE trades (a 100 USDC trade on the thin test pool moves
//        the price ~35%, and the haircut quote then OVERSTATES the
//        output). A too-large spot trade simply reverts on minOut
//        ("Too little received") — clean, no funds at risk — but it
//        will not execute. Spot trades through this adapter must
//        stay small relative to the pool. The flash path never calls
//        getAmountsOut (it uses off-chain Quoter values for its
//        minOuts), so it is unaffected by this limit.
//  - UNAUDITED, like everything in this rebuild. A professional audit is
//    REQUIRED before any mainnet use with real money.
// --------------------------------------------------------------------------------
pragma solidity ^0.8.20;

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface ISwapRouter02 {
    // NOTE: the deployed SwapRouter02 on Arbitrum Sepolia (and on
    // mainnet — byte-identical) uses the ORIGINAL 7-field
    // ExactInputSingleParams with NO deadline (selector 0x04e45aaf).
    // The 8-field version WITH a deadline (selector 0x414bf389) does
    // NOT exist on this router — proven by dispatcher analysis and a
    // live eth_call (8-field reverts empty; 7-field reaches the swap
    // and reverts 'STF' as expected without an approval). The V2
    // deadline is enforced by THIS adapter instead (see below), so
    // callers still get deadline protection.
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    function exactInputSingle(ExactInputSingleParams calldata params)
        external
        payable
        returns (uint256 amountOut);
}

/// @dev Minimal V3 pool interface — only slot0, for the quote.
interface IUniswapV3Pool {
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );
}

contract V2ToV3Adapter {
    address public immutable swapRouter;
    address public immutable pool;
    address public immutable tokenA;
    address public immutable tokenB;
    uint24 public immutable fee;

    /// @dev getAmountsOut returns 95% of the at-current-price output.
    ///      See the header note for why.
    uint256 internal constant QUOTE_HAIRCUT_BPS = 9500;
    uint256 internal constant Q96 = 2 ** 96;

    error BadPath();
    error Expired();
    error ZeroAddress();
    error TokenCallFailed();
    error TokenCallReturnedFalse();

    constructor(
        address _swapRouter,
        address _pool,
        address _tokenA,
        address _tokenB,
        uint24 _fee
    ) {
        if (
            _swapRouter == address(0) ||
            _pool == address(0) ||
            _tokenA == address(0) ||
            _tokenB == address(0) ||
            _tokenA == _tokenB
        ) revert ZeroAddress();
        swapRouter = _swapRouter;
        pool = _pool;
        tokenA = _tokenA;
        tokenB = _tokenB;
        fee = _fee;
    }

    /// @notice V2-interface swap: pull exactly amountIn from the caller,
    ///         execute one V3 exactInputSingle on the pinned pool, send
    ///         the output straight to `to`. Reverts if the output is
    ///         below amountOutMin (enforced by the V3 router) or the
    ///         deadline has passed.
    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts) {
        if (block.timestamp > deadline) revert Expired();
        (address tokenIn, address tokenOut) = _parsePath(path);
        _safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
        _safeApprove(tokenIn, swapRouter, amountIn);
        uint256 amountOut = ISwapRouter02(swapRouter).exactInputSingle(
            ISwapRouter02.ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: fee,
                recipient: to,
                amountIn: amountIn,
                amountOutMinimum: amountOutMin,
                sqrtPriceLimitX96: 0
            })
        );
        amounts = new uint256[](2);
        amounts[0] = amountIn;
        amounts[1] = amountOut;
    }

    /// @notice V2-interface quote for Tech v4's spot engine. A REAL
    ///         view function: reads the pool's slot0 sqrt price and
    ///         converts at the current price, with a 5% haircut. The
    ///         quote is only used to derive minOut (the spot engine
    ///         takes 99% of it); the swap itself enforces minOut
    ///         on-chain. See the header note for why the Quoter is
    ///         NOT used here (STATICCALL) and for the size limit.
    function getAmountsOut(uint256 amountIn, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts)
    {
        (address tokenIn, ) = _parsePath(path);
        (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
        uint256 sqrtP = uint256(sqrtPriceX96);
        // V3 price = (sqrtP / 2^96)^2 = token1 per token0, in RAW
        // token units (decimals already baked into the raw ratio).
        address token0 = tokenA < tokenB ? tokenA : tokenB;
        uint256 atPrice;
        if (tokenIn == token0) {
            // tokenIn is token0: out = in * price.
            atPrice = ((amountIn * sqrtP) / Q96 * sqrtP) / Q96;
        } else {
            // tokenIn is token1: out = in / price.
            atPrice = ((amountIn * Q96) / sqrtP * Q96) / sqrtP;
        }
        uint256 amountOut = (atPrice * QUOTE_HAIRCUT_BPS) / 10000;
        amounts = new uint256[](2);
        amounts[0] = amountIn;
        amounts[1] = amountOut;
    }

    /// @dev Only the configured pair, either direction, exactly 2 hops.
    function _parsePath(address[] calldata path)
        internal
        view
        returns (address tokenIn, address tokenOut)
    {
        if (path.length != 2) revert BadPath();
        if (
            (path[0] == tokenA && path[1] == tokenB) ||
            (path[0] == tokenB && path[1] == tokenA)
        ) {
            return (path[0], path[1]);
        }
        revert BadPath();
    }

    // --- SafeERC20-style token calls (no imports, self-contained) ---
    /// @dev Low-level ERC20 call that accepts EITHER a bool `true` return
    ///      OR empty returndata. Real USDT returns NOTHING from transfer /
    ///      transferFrom / approve — proven on a mainnet fork — which
    ///      reverts a standard `returns (bool)` ABI decode.
    function _callOptionalReturn(address token, bytes memory data) internal {
        (bool success, bytes memory ret) = token.call(data);
        if (!success) revert TokenCallFailed();
        if (ret.length > 0) {
            if (!abi.decode(ret, (bool))) revert TokenCallReturnedFalse();
        }
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        _callOptionalReturn(token, abi.encodeCall(IERC20.transferFrom, (from, to, amount)));
    }

    function _safeApprove(address token, address spender, uint256 amount) internal {
        _callOptionalReturn(token, abi.encodeCall(IERC20.approve, (spender, amount)));
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.