Skip to content
Verified contractExactGPL-2.0-or-later

UniV4SwapHandlerV2

Address0x9520e4bb81f3c71ef8f6665aaf023c47deca8db1
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,087,929
Creation transaction
0xc44316561c…c38f9c3964

contracts/router/modules/UniV4SwapHandlerV2.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.24; // transient storage (EIP-1153) — compiled with 0.8.28/cancun (see hardhat.config overrides)
pragma abicoder v2;

/// @title UniV4SwapHandlerV2 — PoolManager-direct Uniswap V4 swap handler
///
/// @notice Replaces the UniV4SwapHandler -> AkkaV4Router pair. The handler
/// unlocks the PoolManager ITSELF, swaps, and settles from its OWN balance —
/// no intermediary router, no token approval, no transferFrom.
///
/// WHY (2026-09, MetaMask/Blockaid): the previous shape was
///     handler:  approve(AkkaV4Router, amountIn)
///     router:   PoolManager.unlock -> callback -> transferFrom(handler -> PoolManager)
/// i.e. "approve an unknown contract, which then pulls the tokens" — the same
/// drainer-shaped pattern UniV3SwapHandlerV2 removed for V3 (896635f). Every
/// Ethereum swap with a uni_v4 leg surfaced a "High-risk approval" warning
/// while uni_v3-only swaps (already pool-direct) did not. Settling from the
/// handler's own balance leaves nothing to flag: no Approval event, no
/// third-party spender, no allowance-based pull.
///
/// WHAT IS PRESERVED FROM AkkaV4Router (verbatim where it matters):
///   - Swap math: exact-input, amountSpecified = -(amountIn * 10000 / feeSrc).
///   - The 4x sqrt-price band around the CURRENT price (read via extsload), so
///     an unfillable exact-input swap partial-fills at the band edge instead of
///     walking the whole tick range (~18.7M gas on fragmented pools).
///   - Native-ETH pools: WETH is unwrapped to settle native input, native
///     output is taken, wrapped and sent as WETH — the module only ever sees
///     WETH, exactly as before.
///   - path.data decoding (64-byte legacy / 128-byte extended PoolKey form)
///     and the WETH -> address(0) mapping from UniV4SwapHandler.
///   - The repo-wide handler convention `amount == 0 => own balance`.
///
/// WHAT IS TIGHTER THAN BEFORE:
///   - The PoolManager is an immutable: `path.pairAddr` must equal it.
///   - One-shot transient guard: unlockCallback runs only while THIS handler's
///     own unlock() is in flight, only from the PoolManager, only once.
///   - ETH is accepted only from WETH (unwrap) and the PoolManager (take).
///   - No owner, no setters.
///
/// WHAT CHANGES FOR THE MODULE: nothing. Same ISwapHandler.executeSwap
/// signature; wired via setUniV4SwapHandler. AkkaV4Router stays deployed and
/// inert (the flashloan path, if any, is unaffected).

interface ISwapHandlerV4 {
    struct PathDescription {
        address srcToken;
        address dstToken;
        address pairAddr;
        uint256 fee;
        uint256 srcAmount;
        uint256 dstMinAmount;
        uint256 feeSrc;
        uint256 feeDst;
        uint256 liquidityType;
        bytes data;
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address from,
        address to
    ) external returns (uint256 amountOut);
}

interface IPoolManagerV4Min {
    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);
    function settle() external payable returns (uint256);
    function take(address currency, address to, uint256 amount) external;
    function sync(address currency) external;
    function extsload(bytes32 slot) external view returns (bytes32);
}

interface IWETH9Min {
    function deposit() external payable;
    function withdraw(uint256) external;
}

interface IERC20Min {
    function balanceOf(address) external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
}

contract UniV4SwapHandlerV2 is ISwapHandlerV4 {
    address public immutable poolManager;
    address public immutable weth;

    // keccak256("akka.univ4handlerv2.armed") - 1. Inline assembly requires a
    // number constant.
    uint256 private constant ARMED_SLOT = 0xf3d441fc81cfedab7d2ecb177666ff838106f82f8abac1c7e9478c94c3c7459b;

    uint160 private constant MIN_SQRT_PRICE_PLUS_1 = 4295128740; // TickMath.MIN_SQRT_RATIO + 1
    uint160 private constant MAX_SQRT_PRICE_MINUS_1 = 1461446703485210103287273052203988822378723970341; // TickMath.MAX_SQRT_RATIO - 1
    /// @dev PoolManager._pools mapping slot (v4-periphery StateLibrary.POOLS_SLOT)
    uint256 private constant POOLS_SLOT = 6;

    struct SwapData {
        address tokenIn;   // address(0) for native
        address tokenOut;  // address(0) for native
        uint24 fee;
        int24 tickSpacing;
        address hooks;
        uint256 amountIn;
        address recipient;
        uint256 feeSrc;
    }

    constructor(address _poolManager, address _weth) {
        require(_poolManager.code.length > 0, "V4H: bad pool manager");
        require(_weth.code.length > 0, "V4H: bad weth");
        poolManager = _poolManager;
        weth = _weth;
    }

    /// @dev ETH arrives only from WETH.withdraw (native input) and
    ///      PoolManager.take (native output).
    receive() external payable {
        require(msg.sender == weth || msg.sender == poolManager, "V4H: unexpected ETH");
    }

    // ── transient one-shot guard ────────────────────────────────────────────

    function _arm() private {
        assembly { tstore(ARMED_SLOT, 1) }
    }

    function _disarm() private {
        assembly { tstore(ARMED_SLOT, 0) }
    }

    function _consumeArmed() private returns (bool armed) {
        assembly {
            armed := tload(ARMED_SLOT)
            tstore(ARMED_SLOT, 0)
        }
    }

    // ── helpers ─────────────────────────────────────────────────────────────

    /// safeTransfer that tolerates non-standard (no-return) ERC20s (USDT).
    function _safeTransfer(address token, address to, uint256 value) private {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20Min.transfer.selector, to, value)
        );
        require(success && (data.length == 0 || abi.decode(data, (bool))), "V4H: transfer failed");
    }

    function _amount0(int256 balanceDelta) private pure returns (int128 a0) {
        assembly { a0 := sar(128, balanceDelta) }
    }

    function _amount1(int256 balanceDelta) private pure returns (int128 a1) {
        assembly { a1 := signextend(15, balanceDelta) }
    }

    /// @dev 4x band around the current sqrt price; absolute limits if the
    ///      pool is uninitialized (the PoolManager then reverts on its own).
    function _sqrtLimit(IPoolManagerV4Min.PoolKey memory key, bool zeroForOne) private view returns (uint160) {
        bytes32 poolId = keccak256(abi.encode(key));
        bytes32 stateSlot = keccak256(abi.encode(poolId, POOLS_SLOT));
        uint160 current = uint160(uint256(IPoolManagerV4Min(poolManager).extsload(stateSlot)));
        if (current == 0) {
            return zeroForOne ? MIN_SQRT_PRICE_PLUS_1 : MAX_SQRT_PRICE_MINUS_1;
        }
        if (zeroForOne) {
            uint256 limit = uint256(current) / 2;
            return limit <= MIN_SQRT_PRICE_PLUS_1 ? MIN_SQRT_PRICE_PLUS_1 : uint160(limit);
        }
        uint256 raised = uint256(current) * 2;
        return raised >= MAX_SQRT_PRICE_MINUS_1 ? MAX_SQRT_PRICE_MINUS_1 : uint160(raised);
    }

    // ── entry point (called by the swap module) ─────────────────────────────

    /// @dev `from` is unused (the module has already moved the input into this
    ///      contract, as for every other handler).
    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address /* from */,
        address to
    ) external override returns (uint256 amountOut) {
        require(path.pairAddr == poolManager, "V4H: unknown pool manager");
        require(path.feeSrc > 0, "V4H: zero feeSrc");
        uint256 amountIn = amount == 0 ? IERC20Min(path.srcToken).balanceOf(address(this)) : amount;
        require(amountIn > 0, "V4H: zero input");

        // path.data: extended (int24 tickSpacing, address hooks, address currency0, address currency1)
        //            or legacy (int24 tickSpacing, address hooks)
        int24 tickSpacing;
        address hooks;
        address currency0;
        address currency1;
        if (path.data.length >= 128) {
            (tickSpacing, hooks, currency0, currency1) = abi.decode(path.data, (int24, address, address, address));
        } else {
            (tickSpacing, hooks) = abi.decode(path.data, (int24, address));
            currency0 = path.srcToken < path.dstToken ? path.srcToken : path.dstToken;
            currency1 = path.srcToken < path.dstToken ? path.dstToken : path.srcToken;
        }

        // Map normalized WETH back to native for the PoolKey (as UniV4SwapHandler).
        address tokenIn = path.srcToken;
        if (currency0 == address(0) && path.srcToken == weth) tokenIn = address(0);
        if (currency1 == address(0) && path.srcToken == weth) tokenIn = address(0);
        address tokenOut = path.dstToken;
        if (currency0 == address(0) && path.dstToken == weth) tokenOut = address(0);
        if (currency1 == address(0) && path.dstToken == weth) tokenOut = address(0);

        _arm();
        bytes memory result = IPoolManagerV4Min(poolManager).unlock(
            abi.encode(
                SwapData({
                    tokenIn: tokenIn,
                    tokenOut: tokenOut,
                    fee: uint24(path.fee),
                    tickSpacing: tickSpacing,
                    hooks: hooks,
                    amountIn: amountIn,
                    recipient: to,
                    feeSrc: path.feeSrc
                })
            )
        );
        _disarm(); // already consumed by the callback; belt and braces
        amountOut = abi.decode(result, (uint256));
    }

    // ── PoolManager callback ────────────────────────────────────────────────

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        require(msg.sender == poolManager && _consumeArmed(), "V4H: bad callback");
        SwapData memory p = abi.decode(data, (SwapData));

        bool inputIsNative = p.tokenIn == address(0);
        bool outputIsNative = p.tokenOut == address(0);
        bool zeroForOne = p.tokenIn < p.tokenOut;

        IPoolManagerV4Min.PoolKey memory key = IPoolManagerV4Min.PoolKey({
            currency0: zeroForOne ? p.tokenIn : p.tokenOut,
            currency1: zeroForOne ? p.tokenOut : p.tokenIn,
            fee: p.fee,
            tickSpacing: p.tickSpacing,
            hooks: p.hooks
        });

        uint256 adjustedAmount = (p.amountIn * 10000) / p.feeSrc;
        require(adjustedAmount <= uint256(type(int256).max), "V4H: int256 overflow");

        int256 balanceDelta = IPoolManagerV4Min(poolManager).swap(
            key,
            IPoolManagerV4Min.SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(adjustedAmount),
                sqrtPriceLimitX96: _sqrtLimit(key, zeroForOne)
            }),
            ""
        );

        // negative = we owe the PoolManager, positive = it owes us
        int128 a0 = _amount0(balanceDelta);
        int128 a1 = _amount1(balanceDelta);
        uint256 inputAmount;
        uint256 amountOut;
        if (zeroForOne) {
            inputAmount = uint256(int256(-a0));
            amountOut = uint256(int256(a1));
        } else {
            inputAmount = uint256(int256(-a1));
            amountOut = uint256(int256(a0));
        }

        // Settle the input from OUR OWN balance — a push, never a pull.
        if (inputIsNative) {
            IWETH9Min(weth).withdraw(inputAmount);
            IPoolManagerV4Min(poolManager).sync(address(0));
            IPoolManagerV4Min(poolManager).settle{value: inputAmount}();
        } else {
            IPoolManagerV4Min(poolManager).sync(p.tokenIn);
            _safeTransfer(p.tokenIn, poolManager, inputAmount);
            IPoolManagerV4Min(poolManager).settle();
        }

        // Take the output to the recipient (native is wrapped: the module sees WETH).
        if (outputIsNative) {
            IPoolManagerV4Min(poolManager).take(address(0), address(this), amountOut);
            IWETH9Min(weth).deposit{value: amountOut}();
            _safeTransfer(weth, p.recipient, amountOut);
        } else {
            IPoolManagerV4Min(poolManager).take(p.tokenOut, p.recipient, amountOut);
        }

        return abi.encode(amountOut);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.