Skip to content
Verified contractPartialMIT

UniV4SwapFacet

Address0xb28691b7a093dd7879cc40187b4e468a54798edc
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,458,685
Creation transaction
0xb533f551ab…8ff3fee728

contracts/UniV4SwapFacet.sol

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

/// @title UniV4SwapFacet
/// @notice Uniswap V4 adapter logic, extracted verbatim from BullBearSettlement's
///         _swapUniV4/unlockCallback/_univ4Key/_univ4Pay/_univ4Take (2026-10-02, second
///         facet split -- see docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md, which named
///         Uniswap V4 as "the next-largest self-contained block" after Ekubo, specifically
///         because the live routing graph almost never reaches it: V4 pools are absent from
///         the main pathfinding graph entirely (only a narrow, often-empty per-pair bridge
///         hook touches them) -- unlike V2/V3/Stable/Hashflow, which the same design doc
///         explicitly keeps inline because they carry the router's actual live volume.
///         Moving a LOW-volume venue to a facet trades a one-time bytecode saving for a
///         small ongoing gas cost on the FEW trades that use it -- the opposite trade would
///         be wrong for V2/V3.
///
/// Triggered by a real, concrete need, not speculation: the same-day re-attack of commit
/// c9f5e1c (2026-10-02, the FoT custody-recipient-delivery floor) found a second, sibling
/// gap in `_distribute`'s fee-fallback transfer that is worth closing for bookkeeping
/// accuracy, but costs 178 bytes against only 100 bytes of EIP-170 headroom. This facet
/// recovers real room so that fix (and future ones) are not blocked by bytecode size.
///
/// DELEGATECALL-ONLY. This contract is never meant to be called directly -- it is deployed
/// once and its address wired into BullBearSettlement's immutable UNIV4_FACET, which
/// delegatecalls into univ4Swap()/univ4UnlockCallback() from _swapUniV4()/unlockCallback().
/// Under delegatecall, `address(this)`, `msg.sender`, and all STORAGE resolve to the CALLER
/// (BullBearSettlement), not this contract -- exactly what every function below relies on
/// (they read/write BullBearSettlement's own token balances and the two storage slots its
/// own receive()/_swapV3Direct/_swapUniV4 family already use).
///
/// unlockCallback() ITSELF cannot move here: the Uniswap V4 PoolManager calls back the
/// EXACT address that called unlock() -- which, under delegatecall, is BullBearSettlement's
/// own address, not this facet's. BullBearSettlement therefore keeps a thin `unlockCallback`
/// entry point (real, dispatchable code at its own address) that itself delegatecalls into
/// this facet's `univ4UnlockCallback`, mirroring exactly how `_swapEkubo` on the main
/// contract is itself a thin wrapper around EkuboSwapFacet.ekuboSwap. Because delegatecall
/// preserves `msg.sender` from the calling frame (here, the PoolManager calling
/// BullBearSettlement.unlockCallback), the `msg.sender == manager` check below is still
/// correct even though it executes inside this facet's own code.
///
/// SAFETY INVARIANT THIS FILE MUST NEVER VIOLATE: zero state variables of its own (see
/// EkuboSwapFacet.sol's own doc comment for the full reasoning -- a facet's own declared
/// state variable would silently collide with BullBearSettlement's slot 0/1, corrupting
/// unrelated contract state the instant this is delegatecalled). Every piece of state this
/// file touches (NATIVE_UNWRAP_SLOT, UNIV4_UNLOCK_SLOT) uses the SAME explicit, hardcoded
/// assembly sstore/sload pattern BullBearSettlement itself already uses for exactly this
/// reason, with the IDENTICAL literal keccak256 input as the main contract's own copies --
/// must never drift from them.
///
/// UNIV4_POOL_MANAGER and WRAPPED_NATIVE are passed in as plain function arguments, NOT
/// declared as this contract's own `immutable`s, for the same reason EkuboSwapFacet does
/// this for EKUBO_ROUTER/EKUBO_CORE: a delegatecall executes THIS contract's code but reads
/// THIS contract's own immutables (baked into ITS OWN bytecode at ITS OWN construction),
/// never the delegatecalling contract's -- sourcing both from BullBearSettlement's own
/// immutables at the call site avoids two separately-configured values that must always
/// agree, a drift-prone footgun this design avoids entirely.
///
/// _ekuboOrientation and MIN_SQRT_RATIO/MAX_SQRT_RATIO/UNIV4_HOOK_AMOUNT_CHANGING are
/// duplicated here verbatim rather than imported, matching EkuboSwapFacet.sol's own
/// documented precedent ("NOT a relocation -- a COPY") for pure/constant values a facet
/// needs but that also still live on the main contract for a DIFFERENT caller
/// (_ekuboOrientation was shared between _swapEkubo and _swapUniV4 on the main contract;
/// now that _swapUniV4's own logic lives here, the main contract's copy of
/// _ekuboOrientation has no remaining caller and is deleted there -- this facet's copy is
/// the only one UniV4 needs; EkuboSwapFacet.sol keeps its own, independent copy for Ekubo).
/// MIN_SQRT_RATIO/MAX_SQRT_RATIO stay on the main contract too (still used by the hot-path
/// _swapV3Direct, which is NOT moving) -- duplicating two uint160 constants costs nothing
/// (they compile to inline literals, not storage) and avoids a cross-contract dependency.
interface IUniV4PoolManagerF {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }
    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;   // NEGATIVE = exact input (v4 sign convention)
        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;
}

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

interface IERC20F2 {
    function balanceOf(address) external view returns (uint256);
}

contract UniV4SwapFacet {
    uint8 internal constant PROTO_UNIV4 = 5;

    /// @dev IDENTICAL to BullBearSettlement's own NATIVE_UNWRAP_SLOT -- same literal
    ///      keccak256 input, so this facet reads/writes the exact same storage slot on the
    ///      delegatecalling contract. Must never drift from the main contract's copy.
    bytes32 private constant NATIVE_UNWRAP_SLOT =
        keccak256("bullbearswap.settlement.nativeunwrap.v1");
    /// @dev IDENTICAL to BullBearSettlement's own UNIV4_UNLOCK_SLOT, same reasoning.
    bytes32 private constant UNIV4_UNLOCK_SLOT =
        keccak256("bullbearswap.settlement.univ4unlock.v1");

    // Full V3/V4 tick range: a swap consumes the whole exact-input (moving price to the
    // limit) rather than reverting, matching each DEX's own quoter -- same values as the
    // main contract's own copy (used there by _swapV3Direct, which stays inline).
    uint160 private constant MIN_SQRT_RATIO = 4295128739;
    uint160 private constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
    uint160 private constant UNIV4_HOOK_AMOUNT_CHANGING = (1 << 3) | (1 << 2);

    /// @dev Same three-field shape as BullBearSettlement's own EdgeSwapFailed -- identical
    ///      name+param types compile to the identical 4-byte selector, so a revert here
    ///      decodes exactly the same way whether raised directly or bubbled through the
    ///      delegatecall wrapper in _swapUniV4.
    error EdgeSwapFailed(uint256 index, address pool, uint8 protocol);
    /// @dev Identical name+shape to BullBearSettlement's own UnexpectedV4Unlock/
    ///      UniV4HookNotSupported/WrongNativeWrapper -- same selector either way.
    error UnexpectedV4Unlock();
    error UniV4HookNotSupported(address hooks);
    error WrongNativeWrapper();

    function _setNativeUnwrap(address wrapper) private {
        bytes32 slot = NATIVE_UNWRAP_SLOT;
        assembly { sstore(slot, wrapper) }
    }

    function _setUniV4Unlock(uint256 v) private {
        bytes32 slot = UNIV4_UNLOCK_SLOT;
        assembly { sstore(slot, v) }
    }

    function _univ4Unlock() private view returns (uint256 v) {
        bytes32 slot = UNIV4_UNLOCK_SLOT;
        assembly { v := sload(slot) }
    }

    function _balanceOfSelf(address token) private view returns (uint256) {
        return IERC20F2(token).balanceOf(address(this));
    }

    function _safeTransfer(address token, address to, uint256 amount) private {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(ptr, 4), to)
            mstore(add(ptr, 36), amount)
            let success := call(gas(), token, 0, ptr, 68, ptr, 32)
            let ok := and(success, or(iszero(returndatasize()), and(gt(returndatasize(), 31), eq(mload(ptr), 1))))
            if iszero(ok) { revert(0, 0) }
        }
    }

    /// @notice Verbatim relocation of BullBearSettlement._swapUniV4's body.
    ///         `manager` is the caller's own UNIV4_POOL_MANAGER immutable, passed through
    ///         rather than duplicated here (see file-level doc comment).
    function univ4Swap(
        address manager,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) external {
        if (manager == address(0)) revert EdgeSwapFailed(index, address(0), PROTO_UNIV4);
        uint256 balBefore = _balanceOfSelf(tokenOut);
        // Bind the unlock re-entry to THIS call, mirror of _setV3ExpectedPool.
        _setUniV4Unlock(1);
        IUniV4PoolManagerF(manager).unlock(abi.encode(tokenIn, tokenOut, extraData, amountIn));
        _setUniV4Unlock(0);
        uint256 amountOut = _balanceOfSelf(tokenOut) - balBefore;
        if (amountOut < minAmountOut) {
            revert EdgeSwapFailed(index, manager, PROTO_UNIV4);
        }
    }

    /// @notice Verbatim relocation of BullBearSettlement.unlockCallback's body.
    ///         `manager`/`wrappedNative` are the caller's own immutables, passed through.
    ///         See file-level doc comment for why this is safe to call via delegatecall
    ///         even though the REAL PoolManager callback lands on the main contract's own
    ///         thin `unlockCallback` wrapper, not directly here.
    function univ4UnlockCallback(address manager, address wrappedNative, bytes calldata data)
        external
        returns (bytes memory)
    {
        if (msg.sender != manager || _univ4Unlock() == 0) revert UnexpectedV4Unlock();
        (address tokenIn, address tokenOut, bytes memory extra, uint256 amountIn) =
            abi.decode(data, (address, address, bytes, uint256));
        IUniV4PoolManagerF.PoolKey memory key = _univ4Key(extra, tokenIn, tokenOut);
        (uint8 mode, bool isToken1) =
            _ekuboOrientation(tokenIn, tokenOut, key.currency0, key.currency1);
        if (mode == 3) revert UnexpectedV4Unlock();
        bool zeroForOne = !isToken1;
        int256 delta = IUniV4PoolManagerF(manager).swap(
            key,
            IUniV4PoolManagerF.SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn),
                sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1
            }),
            ""
        );
        (int128 dIn, int128 dOut) = zeroForOne
            ? (int128(delta >> 128), int128(delta))
            : (int128(delta), int128(delta >> 128));
        _univ4Pay(manager, wrappedNative, tokenIn, mode, uint256(uint128(-dIn)));
        if (dOut > 0) {
            _univ4Take(manager, wrappedNative, tokenOut, mode, uint256(uint128(dOut)));
        }
        return abi.encode(uint256(uint128(dOut)));
    }

    /// @dev Verbatim relocation of BullBearSettlement._univ4Key.
    function _univ4Key(bytes memory extra, address tokenIn, address tokenOut)
        private
        pure
        returns (IUniV4PoolManagerF.PoolKey memory key)
    {
        if (extra.length >= 160) {
            (uint24 fee, int24 tickSpacing, address c0, address c1, address hooks) =
                abi.decode(extra, (uint24, int24, address, address, address));
            if (uint160(hooks) & UNIV4_HOOK_AMOUNT_CHANGING != 0) {
                revert UniV4HookNotSupported(hooks);
            }
            key = IUniV4PoolManagerF.PoolKey({
                currency0: c0, currency1: c1, fee: fee,
                tickSpacing: tickSpacing, hooks: hooks});
        } else if (extra.length >= 128) {
            (uint24 fee, int24 tickSpacing, address c0, address c1) =
                abi.decode(extra, (uint24, int24, address, address));
            key = IUniV4PoolManagerF.PoolKey({
                currency0: c0, currency1: c1, fee: fee,
                tickSpacing: tickSpacing, hooks: address(0)});
        } else {
            (uint24 fee, int24 tickSpacing) = abi.decode(extra, (uint24, int24));
            (address c0, address c1) =
                tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
            key = IUniV4PoolManagerF.PoolKey({
                currency0: c0, currency1: c1, fee: fee,
                tickSpacing: tickSpacing, hooks: address(0)});
        }
    }

    /// @dev NOT a relocation -- a COPY, identical to EkuboSwapFacet.sol's own copy and to
    ///      BullBearSettlement's (now-deleted) copy. See file-level doc comment.
    function _ekuboOrientation(address tokenIn, address tokenOut, address k0, address k1)
        private pure returns (uint8 mode, bool isToken1)
    {
        if (k0 == address(0)) {
            if (tokenIn == k1 && tokenOut != k1 && tokenOut != address(0)) {
                return (2, true);
            }
            if (tokenOut == k1 && tokenIn != k1 && tokenIn != address(0)) {
                return (1, false);
            }
            return (3, false);
        }
        if (tokenIn == k0 && tokenOut == k1) return (0, false);
        if (tokenIn == k1 && tokenOut == k0) return (0, true);
        return (3, false);
    }

    /// @dev Relocation of BullBearSettlement._univ4Pay. RT35 (2026-10-01, f8b6548)
    ///      fixed this exact gap on feat/helper-coverage-pack BEFORE this facet split
    ///      (2026-10-02) ever happened on this branch, but the fix never landed here --
    ///      this branch's own _univ4Pay was still unguarded at split time, so the
    ///      "verbatim relocation" silently carried the unfixed version into this facet.
    ///      Found and closed during RT44's cross-branch port to feat/helper-coverage-pack
    ///      (see .intoiq/evidence/redteam44_trackC_contracts_2026_10_02/REPORT.md),
    ///      ported back here immediately given UNIV4_POOL_MANAGER is this branch's own
    ///      live, non-zero deploy config -- mode==1 (native INPUT) never checked
    ///      tokenIn == wrappedNative before withdraw(pay) + settle{value: pay}, and mode
    ///      is selected purely by the real V4 pool's own currency orientation, never by
    ///      what tokenIn actually is -- a route-chosen fake-wrapper token could drain
    ///      this contract's own stranded ETH through a plain execute() call. The sibling
    ///      output side, _univ4Take mode==2 below, already carries this pin (BB-02,
    ///      2026-09-19, pre-fork shared ancestry).
    function _univ4Pay(address manager, address wrappedNative, address tokenIn, uint8 mode, uint256 pay) private {
        if (mode == 1) {
            if (tokenIn != wrappedNative) revert WrongNativeWrapper();
            _setNativeUnwrap(tokenIn);
            IWrappedNativeF2(tokenIn).withdraw(pay);
            _setNativeUnwrap(address(0));
            IUniV4PoolManagerF(manager).settle{value: pay}();
        } else {
            IUniV4PoolManagerF(manager).sync(tokenIn);
            _safeTransfer(tokenIn, manager, pay);
            IUniV4PoolManagerF(manager).settle();
        }
    }

    /// @dev Verbatim relocation of BullBearSettlement._univ4Take. `wrappedNative` is the
    ///      caller's own WRAPPED_NATIVE immutable, passed through (see file-level comment).
    function _univ4Take(address manager, address wrappedNative, address tokenOut, uint8 mode, uint256 amt) private {
        if (mode == 2) {
            if (tokenOut != wrappedNative) revert WrongNativeWrapper();
            _setNativeUnwrap(manager);
            IUniV4PoolManagerF(manager).take(address(0), address(this), amt);
            _setNativeUnwrap(address(0));
            IWrappedNativeF2(tokenOut).deposit{value: amt}();
        } else {
            IUniV4PoolManagerF(manager).take(tokenOut, address(this), amt);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.