Skip to content
Verified contractExactMIT

UniswapV4EscrowFactoryV4

Address0xeadfd738c602f79fb191f4bee297f944979829d4
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
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,393,079
Creation transaction
0xee326e0d77…ad61c31c21

contracts/UniswapV4EscrowFactoryV4.sol

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

import { FactoryGovernance } from "./FactoryGovernance.sol";
import { Clones1167 } from "./Clones1167.sol";
import { PoolKey, PathKey, SwapParams, IPoolManager } from "./UniswapV4EscrowFactory.sol";

/// @title IUniswapV4EscrowFactoryV4: the minimal surface the escrow needs.
interface IUniswapV4EscrowFactoryV4 {
    function operator() external view returns (address);
    function treasury() external view returns (address);
    function refundTimeout() external view returns (uint256);
    function creationUnlockAt() external view returns (uint256);
    function requireApprovals(
        bytes4 action, address token, address target, uint256 amount,
        bytes32 dataHash, uint256 nonce, uint256 deadline, bytes[] calldata approvals
    ) external view;
}

/// @title  UniswapV4SwapEscrowV4: UniswapV4SwapEscrowV3 with the Hashlock findings fixed.
/// @notice Swap / settlement logic unchanged (this escrow already had PartialFill, BadAmount, maxFee and
///         _settleRemainder). Changes vs V3, by finding:
///         L-03 / Q-10: `initialize` rejects sentinel userRefund / recipient (address(1), address(2)).
///         L-04 / Q-13: for an ERC20 `tokenOut`, `minOut` is enforced on what the recipient actually RECEIVES
///           (balance delta around `take`), so a fee-on-transfer output cannot under-deliver. Native output
///           keeps the gross check (no transfer tax exists for native; a receiver that forwards ETH inside
///           `receive()` would otherwise fail a legitimate swap).
///         Q-11: `_trySendEth` / `_tryTransfer` never copy or decode return data, so the best-effort refund
///           leg of `_settleRemainder` can never revert the swap.
///         Fix review Q-08: the PoolManager, the factory, the implementation and the escrow itself are refused as
///           recipient or refund address. Q-25: `swapHold` restarts the refund clock. Q-32 / Q-35 / Q-40 / Q-41:
///           zero amounts and empty sweeps revert before an approval is consumed, a refund of nothing emits
///           nothing, `swapped()` / `heldActive()` expose the lifecycle, `NativeNotEnabled` is the one error for
///           a native leg on a chain without native support.
///         Gen-10 (external researcher, 2026-10-28; the Q-16 treatment SwapEscrowV7 already had): `deferredRefund`
///           records failed best-effort refunds (never fee, never swept, delivered by `refund*`); `heldAmount`
///           tracks the parked native output (excluded from `sweepEth` and native fee settlement); `forwardEth`
///           carries a signed `maxFee` (dataHash = keccak256(abi.encode(maxFee)), capped at the amount) and settles
///           what is left of the held output right after the push.
///         Gen-11 (external researcher 0xkonde, 2026-11-05): `sweep` / `sweepEth` take an explicit `amount` that the
///           approvers sign, at most the sweepable balance (deferred refund and held output still excluded), instead
///           of binding the balance read at execution, so a 1-unit donation between signing and broadcast no longer
///           voids the signatures; the surplus stays sweepable later. `AmountExceedsSweepable` guards the cap before
///           any approval is consumed.
///         Gen-11 (external researcher H. A. Yulian, 2026-11-08): `_preSwap` sizes the swap against the available
///           balance (deferred refund and held output excluded) instead of the raw balance, so a reserved refund is
///           never swap inventory (this venue latches after its one swap; the check keeps the two families identical).
///         Gen-11 (third audit): L-02 `redirectDeferred` (approval-gated exit for a deferred refund whose address cannot
///           receive it), Q-02 best-effort fee leg (`FeeWaived`), Q-04 `forwardEth` caps `maxFee` at the held rest,
///           Q-05 the escrow itself is refused as forward target, Q-06 the held output is forwarded once (a second
///           call reverts `NothingHeld`), Q-07 a zero-output swap reverts `TooLittleOut` (one hold per escrow here,
///           so the refund clock restarts once by construction).
contract UniswapV4SwapEscrowV4 {
    address public immutable factory;
    address public immutable poolManager;
    bool    public immutable nativeAllowed;

    // slot 0: written once by initialize()
    address public userRefund;
    uint64 private _refundUnlockAt;
    bool private _initialized;
    bool private _swapped;
    bool private _holdSwap; // set for the duration of swapHold's unlock: the callback takes the output HERE

    address public recipient;
    address public tokenIn;
    address public tokenOut;
    uint256 public approvalNonce;
    uint256 private _entered;
    /// @notice Native output parked by `swapHold` and not yet pushed by `forwardEth`: never fee, never swept.
    uint256 public heldAmount;
    /// @notice Refund amounts whose best-effort delivery failed, per token (address(0) = native). Never counted
    ///         as fee, never swept; `refundToUser` / `refundEthToUser` deliver and clear them.
    mapping(address => uint256) public deferredRefund;

    uint160 private constant MIN_SQRT_PRICE = 4295128739;
    uint160 private constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    uint24  private constant DYNAMIC_FEE_FLAG = 0x800000;
    uint24  private constant MAX_LP_FEE = 1_000_000;
    int24   private constant MAX_TICK_SPACING = 32767;
    /// @dev Gas given to the best-effort refund leg (user-controlled receiver); the claim paths have no cap.
    uint256 private constant REFUND_GAS_NATIVE = 150_000;
    uint256 private constant REFUND_GAS_TOKEN = 200_000;

    event SwapForwarded(address indexed effTokenIn, address indexed effTokenOut, uint256 amountIn, uint256 amountOut, address recipient);
    event SwapHeld(address indexed effTokenIn, address indexed effTokenOut, uint256 amountIn, uint256 amountOut);
    event EthForwarded(address indexed to, uint256 amount);
    event RefundedToUser(address indexed token, uint256 amount);
    event Swept(address indexed token, address indexed treasury, uint256 amount);
    event RefundDeferred(address indexed token, uint256 amount);
    event RefundRedirected(address indexed token, address indexed to, uint256 amount);
    event FeeWaived(address indexed token, uint256 amount);

    error NotOperator();
    error NotFactory();
    error AlreadyInitialized();
    error NotPoolManager();
    error RefundLocked();
    error ZeroAddress();
    error SentinelAddress();
    error Reentrancy();
    error SameAsset();
    error Expired();
    error BadPath();
    error BadHook();
    error BadFee();
    error BadAmount();
    error PartialFill();
    error InsufficientDeposit();
    error TooLittleOut();
    error NativeNotEnabled();
    error AlreadySwapped();
    error FeeTooLarge();
    error NativeOutOnly();
    error NothingHeld();
    error ZeroAmount();
    error InvalidRecipient();
    error TokenHasNoCode();
    error AmountExceedsSweepable();

    modifier nonReentrant() {
        if (_entered == 1) revert Reentrancy();
        _entered = 1;
        _;
        _entered = 0;
    }

    /// @dev Deployed by the factory inside its constructor (the factory has no code yet, so the
    ///      chain-wide parameters arrive as arguments instead of being read back from it).
    constructor(address _poolManager, bool _nativeEnabled) {
        if (_poolManager == address(0)) revert ZeroAddress();
        factory = msg.sender;
        poolManager = _poolManager;
        nativeAllowed = _nativeEnabled;
        _initialized = true;
    }

    function initialize(address _userRefund, address _recipient, address _tokenIn, address _tokenOut) external {
        if (msg.sender != factory) revert NotFactory();
        if (_initialized) revert AlreadyInitialized();
        if (_userRefund == address(0) || _recipient == address(0)) revert ZeroAddress();
        if (uint160(_userRefund) <= 2 || uint160(_recipient) <= 2) revert SentinelAddress();
        if (_recipient == address(this) || _userRefund == address(this)) revert InvalidRecipient();
        if (_tokenIn == _tokenOut) revert SameAsset();
        if (!nativeAllowed && (_tokenIn == address(0) || _tokenOut == address(0))) revert NativeNotEnabled();
        _initialized = true;
        userRefund = _userRefund;
        recipient = _recipient;
        tokenIn = _tokenIn;
        tokenOut = _tokenOut;
        _refundUnlockAt = uint64(IUniswapV4EscrowFactoryV4(factory).creationUnlockAt());
    }

    function refundUnlockAt() external view returns (uint256) {
        return _refundUnlockAt;
    }

    /// @notice True once the one-shot swap ran (a second `swapForward` / `swapHold` reverts `AlreadySwapped`).
    function swapped() external view returns (bool) {
        return _swapped;
    }

    /// @notice True while `swapHold` output is parked here (until then `forwardEth` reverts `NothingHeld`).
    function heldActive() external view returns (bool) {
        return heldAmount > 0;
    }

    function _operator() internal view returns (address) {
        return IUniswapV4EscrowFactoryV4(factory).operator();
    }

    modifier onlyOperator() {
        if (msg.sender != _operator()) revert NotOperator();
        _;
    }

    function _approved(
        bytes4 action, address token, address target, uint256 amount, bytes32 dataHash,
        uint256 deadline, bytes[] calldata approvals
    ) internal {
        IUniswapV4EscrowFactoryV4(factory).requireApprovals(action, token, target, amount, dataHash, approvalNonce, deadline, approvals);
        approvalNonce++;
    }

    /// @param path abi.encode(PathKey[] hops, uint256 maxFee), see V1.
    function swapForward(
        uint256 amountIn,
        uint256 minOut,
        uint256 deadline,
        bytes calldata path,
        bytes[] calldata approvals
    ) external onlyOperator nonReentrant returns (uint256 amountOut) {
        _preSwap(amountIn, deadline, path);
        _approved(this.swapForward.selector, tokenIn, recipient, amountIn, keccak256(abi.encode(minOut, path)), deadline, approvals);
        uint256 maxFee;
        (amountOut, maxFee) = _unlockSwap(amountIn, minOut, path);
        if (amountOut == 0) revert TooLittleOut(); // Q-07
        emit SwapForwarded(tokenIn, tokenOut, amountIn, amountOut, recipient);
        _settleRemainder(maxFee);
    }

    /// @notice COMBO-OUT step 1 (D9): swap tokenIn -> NATIVE and HOLD the output here; the bridge leg is
    ///         created afterwards with the exact amount and pushed with `forwardEth`. The input remainder
    ///         settles like swapForward (capped fee to the treasury, rest back to the user).
    function swapHold(
        uint256 amountIn,
        uint256 minOut,
        uint256 deadline,
        bytes calldata path,
        bytes[] calldata approvals
    ) external onlyOperator nonReentrant returns (uint256 amountOut) {
        if (tokenOut != address(0)) revert NativeOutOnly();
        _preSwap(amountIn, deadline, path);
        _approved(this.swapHold.selector, tokenIn, address(this), amountIn, keccak256(abi.encode(minOut, path)), deadline, approvals);
        _holdSwap = true; // read by unlockCallback: take the output HERE; a reverting swap rolls it back
        uint256 maxFee;
        (amountOut, maxFee) = _unlockSwap(amountIn, minOut, path);
        _holdSwap = false;
        if (amountOut == 0) revert TooLittleOut(); // Q-07
        heldAmount += amountOut;
        // the held output waits for the bridge leg; the permissionless refund clock restarts with it (once: this
        // venue latches after the swap)
        _refundUnlockAt = uint64(IUniswapV4EscrowFactoryV4(factory).creationUnlockAt());
        emit SwapHeld(tokenIn, address(0), amountIn, amountOut);
        _settleRemainder(maxFee); // tokenIn is an ERC20 here (tokenOut is native), so the held native is untouched
    }

    /// @notice COMBO-OUT step 2: push `amount` of the HELD native balance to `to` (bridge deposit / recipient), then
    ///         settle what is left of the held output (min(rest, maxFee) to the treasury, the remainder back to the
    ///         user). Nothing held survives the call; the held output is forwarded ONCE (Q-06).
    /// @dev dataHash = keccak256(abi.encode(maxFee)); maxFee is capped at the held rest `held - amount` (Q-04).
    function forwardEth(address to, uint256 amount, uint256 maxFee, uint256 deadline, bytes[] calldata approvals)
        external onlyOperator nonReentrant
    {
        uint256 held = heldAmount;
        if (held == 0) revert NothingHeld();
        if (to == address(0)) revert ZeroAddress();
        if (to == address(this)) revert InvalidRecipient(); // Q-05
        if (amount == 0) revert ZeroAmount();
        if (amount > held) revert InsufficientDeposit();
        if (maxFee > held - amount) revert FeeTooLarge();
        _approved(this.forwardEth.selector, address(0), to, amount, keccak256(abi.encode(maxFee)), deadline, approvals);
        heldAmount = 0;
        _sendEth(to, amount);
        emit EthForwarded(to, amount);
        _settleNative(_sweepableNative(), maxFee);
    }

    /// @notice L-02: a deferred refund whose address cannot receive it leaves through here, to a destination the
    ///         approvers sign; the record is cleared. The amount is the whole record (`token == address(0)` = native).
    function redirectDeferred(address token, address to, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        if (uint160(to) <= 2) revert SentinelAddress();
        if (to == address(this)) revert InvalidRecipient();
        uint256 amount = deferredRefund[token];
        if (amount == 0) revert ZeroAmount();
        _approved(this.redirectDeferred.selector, token, to, amount, bytes32(0), deadline, approvals);
        delete deferredRefund[token];
        if (token == address(0)) _sendEth(to, amount); else _safeTransfer(token, to, amount);
        emit RefundRedirected(token, to, amount);
    }

    function _preSwap(uint256 amountIn, uint256 deadline, bytes calldata path) internal view {
        if (_swapped) revert AlreadySwapped();
        if (block.timestamp > deadline) revert Expired();
        if (amountIn == 0 || amountIn > uint256(uint128(type(int128).max))) revert BadAmount();
        if (path.length < 64) revert BadPath();
        address tIn = tokenIn;
        // only the available balance (deferred refund and held output excluded) is swap inventory
        if (tIn == address(0)) {
            if (_sweepableNative() < amountIn) revert InsufficientDeposit();
        } else {
            if (_sweepable(tIn, _balanceOf(tIn)) < amountIn) revert InsufficientDeposit();
        }
    }

    /// @dev One PoolManager unlock; the callback swaps the hops and takes the output to the recipient
    ///      (or to this escrow when `_holdSwap`). Latches the one-shot.
    function _unlockSwap(uint256 amountIn, uint256 minOut, bytes calldata path)
        internal returns (uint256 amountOut, uint256 maxFee)
    {
        bytes memory out = IPoolManager(poolManager).unlock(abi.encode(path, amountIn, minOut));
        (amountOut, maxFee) = abi.decode(out, (uint256, uint256));
        _swapped = true;
    }

    /// @dev The part of a token balance that is not a deferred refund.
    function _sweepable(address token, uint256 bal) internal view returns (uint256) {
        uint256 d = deferredRefund[token];
        return bal > d ? bal - d : 0;
    }

    /// @dev The part of the native balance that is neither held output nor a deferred refund.
    function _sweepableNative() internal view returns (uint256) {
        uint256 reserved = heldAmount + deferredRefund[address(0)];
        uint256 bal = address(this).balance;
        return bal > reserved ? bal - reserved : 0;
    }

    /// @dev Capped fee to the treasury (best effort, Q-02: a failed fee leg joins the user leg), rest back to the
    ///      user (best effort, recorded in `deferredRefund` when it fails).
    function _settleRemainder(uint256 maxFee) internal {
        address tIn = tokenIn;
        if (tIn == address(0)) {
            _settleNative(_sweepableNative(), maxFee);
        } else {
            address t = IUniswapV4EscrowFactoryV4(factory).treasury();
            uint256 rem = _sweepable(tIn, _balanceOf(tIn));
            uint256 fee = rem > maxFee ? maxFee : rem;
            uint256 back = rem - fee;
            if (fee > 0) {
                if (_tryTransfer(tIn, t, fee)) emit Swept(tIn, t, fee);
                else { back += fee; emit FeeWaived(tIn, fee); }
            }
            if (back > 0) {
                if (_tryTransfer(tIn, userRefund, back)) emit RefundedToUser(tIn, back);
                else { deferredRefund[tIn] += back; emit RefundDeferred(tIn, back); }
            }
        }
    }

    /// @dev Native settlement of `rem`: capped fee to the treasury (best effort, Q-02), the rest to the user or deferred.
    function _settleNative(uint256 rem, uint256 maxFee) internal {
        if (rem == 0) return;
        address t = IUniswapV4EscrowFactoryV4(factory).treasury();
        uint256 fee = rem > maxFee ? maxFee : rem;
        uint256 back = rem - fee;
        if (fee > 0) {
            if (_trySendEth(t, fee)) emit Swept(address(0), t, fee);
            else { back += fee; emit FeeWaived(address(0), fee); }
        }
        if (back > 0) {
            if (_trySendEth(userRefund, back)) emit RefundedToUser(address(0), back);
            else { deferredRefund[address(0)] += back; emit RefundDeferred(address(0), back); }
        }
    }

    /// @dev MUST NOT carry nonReentrant (PoolManager re-enters us). Asserts the latch instead.
    function unlockCallback(bytes calldata raw) external returns (bytes memory) {
        IPoolManager pm = IPoolManager(poolManager);
        if (msg.sender != address(pm)) revert NotPoolManager();
        if (_entered != 1) revert Reentrancy();

        (bytes memory rawPath, uint256 amountIn, uint256 minOut) = abi.decode(raw, (bytes, uint256, uint256));
        (PathKey[] memory hops, uint256 maxFee) = abi.decode(rawPath, (PathKey[], uint256));
        if (hops.length == 0) revert BadPath();
        if (maxFee > amountIn) revert FeeTooLarge();

        address cIn = tokenIn;
        uint256 amt = amountIn;

        for (uint256 i = 0; i < hops.length; ++i) {
            PathKey memory h = hops[i];
            if (h.hooks != address(0)) revert BadHook();
            if (h.hookData.length != 0) revert BadPath();
            if (h.fee == DYNAMIC_FEE_FLAG || h.fee > MAX_LP_FEE) revert BadFee();
            if (h.tickSpacing <= 0 || h.tickSpacing > MAX_TICK_SPACING) revert BadPath();

            address cOut = h.intermediateCurrency;
            if (!nativeAllowed && cOut == address(0)) revert NativeNotEnabled();
            if (cOut == cIn) revert BadPath();
            bool zeroForOne = cIn < cOut;

            PoolKey memory key = PoolKey({
                currency0: zeroForOne ? cIn : cOut,
                currency1: zeroForOne ? cOut : cIn,
                fee: h.fee,
                tickSpacing: h.tickSpacing,
                hooks: address(0)
            });

            int256 delta = pm.swap(
                key,
                SwapParams({
                    zeroForOne: zeroForOne,
                    amountSpecified: -int256(amt),
                    sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_PRICE + 1 : MAX_SQRT_PRICE - 1
                }),
                bytes("")
            );

            int128 a0 = int128(delta >> 128);
            int128 a1 = int128(delta);
            int128 dIn = zeroForOne ? a0 : a1;
            int128 dOut = zeroForOne ? a1 : a0;
            if (dOut <= 0 || dIn >= 0) revert BadPath();
            if (i == 0 && uint256(uint128(-dIn)) != amountIn) revert PartialFill();

            amt = uint256(uint128(dOut));
            if (amt == 0) revert BadPath();
            cIn = cOut;
        }

        address tOut = tokenOut;
        if (cIn != tOut) revert BadPath();
        if (amt < minOut) revert TooLittleOut();

        address tIn = tokenIn;
        if (tIn == address(0)) {
            pm.sync(address(0));
            pm.settle{ value: amountIn }();
        } else {
            pm.sync(tIn);
            _safeTransfer(tIn, address(pm), amountIn);
            pm.settle();
        }
        address to = _holdSwap ? address(this) : recipient;
        if (tOut == address(0)) {
            pm.take(tOut, to, amt);
            return abi.encode(amt, maxFee);
        }
        // L-04: enforce minOut on what the recipient actually receives (fee-on-transfer tokenOut).
        uint256 before = _balanceOfAt(tOut, to);
        pm.take(tOut, to, amt);
        uint256 received = _balanceOfAt(tOut, to) - before;
        if (received < minOut) revert TooLittleOut();
        return abi.encode(received, maxFee);
    }

    function refundToUser(address token) external nonReentrant {
        if (userRefund == address(0)) revert ZeroAddress(); // the locked implementation itself
        if (msg.sender != _operator() && block.timestamp < _refundUnlockAt) revert RefundLocked();
        uint256 bal = _balanceOf(token);
        delete deferredRefund[token];
        if (bal == 0) return;
        _safeTransfer(token, userRefund, bal);
        emit RefundedToUser(token, bal);
    }

    function refundEthToUser() external nonReentrant {
        if (userRefund == address(0)) revert ZeroAddress();
        if (msg.sender != _operator() && block.timestamp < _refundUnlockAt) revert RefundLocked();
        uint256 bal = address(this).balance;
        delete deferredRefund[address(0)];
        heldAmount = 0; // the customer takes the held output back after the unlock
        if (bal == 0) return;
        _sendEth(userRefund, bal);
        emit RefundedToUser(address(0), bal);
    }

    /// @notice Fee remainder to the treasury, approval-gated. The approvers sign `amount`; it may not exceed the
    ///         sweepable balance (on-chain balance minus any deferred refund, which stays the customer's). Anything
    ///         above `amount` (a donation that landed after signing) stays in the escrow, sweepable later.
    function sweep(address token, uint256 amount, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
        address t = IUniswapV4EscrowFactoryV4(factory).treasury();
        if (amount == 0) revert ZeroAmount();
        if (amount > _sweepable(token, _balanceOf(token))) revert AmountExceedsSweepable();
        _approved(this.sweep.selector, token, t, amount, bytes32(0), deadline, approvals);
        _safeTransfer(token, t, amount);
        emit Swept(token, t, amount);
    }

    /// @notice Native fee remainder to the treasury; held output and deferred refunds are not sweepable.
    function sweepEth(uint256 amount, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
        address t = IUniswapV4EscrowFactoryV4(factory).treasury();
        if (amount == 0) revert ZeroAmount();
        if (amount > _sweepableNative()) revert AmountExceedsSweepable();
        _approved(this.sweepEth.selector, address(0), t, amount, bytes32(0), deadline, approvals);
        _sendEth(t, amount);
        emit Swept(address(0), t, amount);
    }

    receive() external payable {}

    function _safeTransfer(address token, address to, uint256 amount) internal {
        if (token.code.length == 0) revert TokenHasNoCode(); // Q-07 parity with SwapEscrowV7 / SplitEscrowV4
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
    }

    function _balanceOf(address token) internal view returns (uint256) {
        return _balanceOfAt(token, address(this));
    }

    function _balanceOfAt(address token, address who) internal view returns (uint256) {
        (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, who));
        require(ok && data.length >= 32, "BALANCE_FAILED");
        return abi.decode(data, (uint256));
    }

    function _sendEth(address to, uint256 amount) internal {
        if (amount == 0) return;
        (bool ok, ) = payable(to).call{ value: amount }("");
        require(ok, "ETH_SEND_FAILED");
    }

    /// @dev Q-11: never reverts, never copies return data; gas capped at REFUND_GAS_NATIVE (user-controlled receiver).
    function _trySendEth(address to, uint256 amount) internal returns (bool ok) {
        uint256 g = REFUND_GAS_NATIVE;
        assembly ("memory-safe") {
            ok := call(g, to, amount, 0, 0, 0, 0)
        }
    }

    /// @dev Q-11: success = call ok AND (no return data OR first word non-zero); nothing decoded that can revert.
    ///      Gas capped at REFUND_GAS_TOKEN.
    function _tryTransfer(address token, address to, uint256 amount) internal returns (bool ok) {
        bytes memory payload = abi.encodeWithSelector(0xa9059cbb, to, amount);
        uint256 g = REFUND_GAS_TOKEN;
        assembly ("memory-safe") {
            let success := call(g, token, 0, add(payload, 0x20), mload(payload), 0, 0)
            let size := returndatasize()
            switch success
            case 0 { ok := 0 }
            default {
                switch size
                case 0 { ok := iszero(iszero(extcodesize(token))) } // no return data is fine only from real code
                default {
                    switch lt(size, 0x20)
                    case 1 { ok := 0 } // short return data is not a bool: failure, never a revert
                    default {
                        returndatacopy(0, 0, 0x20)
                        ok := iszero(iszero(mload(0)))
                    }
                }
            }
        }
    }
}

/// @title  UniswapV4EscrowFactoryV4: UniswapV4EscrowFactoryV3 with FactoryGovernance and the Hashlock fixes.
/// @notice M-03 / Q-14: `treasury != operator` enforced by FactoryGovernance (immutable treasury in gen-10). M-05:
///         `predictEscrow` already mirrored `initialize` in V3; the sentinel check (L-03) is added to both.
///         Gen-11 (third audit M-01 / Q-10): `createEscrow` is approval-gated again (the predicted address binds
///         userRefund, recipient and both tokens) and returns an escrow that already exists (see EscrowFactoryV7).
contract UniswapV4EscrowFactoryV4 is FactoryGovernance {
    address public immutable poolManager;
    bool    public immutable nativeEnabled;
    address public immutable implementation;

    event EscrowCreated(bytes32 indexed salt, address indexed escrow, address indexed userRefund, address recipient, address tokenIn, address tokenOut);

    error SentinelAddress();
    error SameAsset();
    error NativeNotEnabled();
    error PredictionMismatch();
    error InvalidRecipient();

    constructor(
        address _owner, address _operator, address _treasury, address _guardian, uint256 _refundTimeout,
        address _poolManager, bool _nativeEnabled,
        address[] memory initialApprovers, uint256 _required, uint256 _minRequired
    ) FactoryGovernance(_owner, _operator, _treasury, _guardian, _refundTimeout, initialApprovers, _required, _minRequired) {
        if (_poolManager == address(0)) revert ZeroAddress();
        poolManager = _poolManager;
        nativeEnabled = _nativeEnabled;
        implementation = address(new UniswapV4SwapEscrowV4(_poolManager, _nativeEnabled));
    }

    function _eip712Name() internal pure override returns (string memory) { return "InstaswapUniswapV4EscrowFactory"; }
    function _eip712Version() internal pure override returns (string memory) { return "11"; }

    /// @notice Approval subject: escrow = predictEscrow(...), action = this selector, token 0, target = userRefund,
    ///         amount 0, dataHash 0, nonce 0 (the address commits to recipient, tokenIn and tokenOut as well).
    function createEscrow(
        bytes32 salt, address userRefund, address recipient, address tokenIn, address tokenOut,
        uint256 deadline, bytes[] calldata approvals
    ) external returns (address escrow) {
        bytes32 s = _salt(salt, userRefund, recipient, tokenIn, tokenOut);
        address predicted = Clones1167.predict(implementation, s, address(this));
        if (predicted.code.length != 0) return predicted; // Q-10
        _validateParams(userRefund, recipient, tokenIn, tokenOut);
        _checkApprovals(predicted, this.createEscrow.selector, address(0), userRefund, 0, bytes32(0), 0, deadline, approvals);
        escrow = Clones1167.clone(implementation, s);
        if (escrow != predicted) revert PredictionMismatch();
        UniswapV4SwapEscrowV4(payable(escrow)).initialize(userRefund, recipient, tokenIn, tokenOut);
        emit EscrowCreated(salt, escrow, userRefund, recipient, tokenIn, tokenOut);
    }

    function predictEscrow(bytes32 salt, address userRefund, address recipient, address tokenIn, address tokenOut)
        external view returns (address)
    {
        _validateParams(userRefund, recipient, tokenIn, tokenOut);
        return Clones1167.predict(implementation, _salt(salt, userRefund, recipient, tokenIn, tokenOut), address(this));
    }

    function _validateParams(address userRefund, address recipient, address tokenIn, address tokenOut) internal view {
        if (userRefund == address(0) || recipient == address(0)) revert ZeroAddress();
        if (uint160(userRefund) <= 2 || uint160(recipient) <= 2) revert SentinelAddress();
        if (_reserved(recipient) || _reserved(userRefund)) revert InvalidRecipient();
        if (tokenIn == tokenOut) revert SameAsset();
        if (!nativeEnabled && (tokenIn == address(0) || tokenOut == address(0))) revert NativeNotEnabled();
        creationUnlockAt(); // LooseningImminent in the last CREATION_CUTOFF before a pending loosening executes
    }

    /// @dev Fix review Q-08: output taken to the PoolManager, the factory or the implementation is lost or sweepable.
    function _reserved(address a) internal view returns (bool) {
        return a == poolManager || a == address(this) || a == implementation;
    }

    function _salt(bytes32 salt, address userRefund, address recipient, address tokenIn, address tokenOut)
        internal pure returns (bytes32)
    {
        return keccak256(abi.encode(salt, userRefund, recipient, tokenIn, tokenOut));
    }
}

contracts/ApproverRegistry.sol

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

/// @title  ApproverRegistry: owner-set approver set + EIP-712 M-of-N approval check.
/// @notice Inherited by every V5-generation factory (near-bridge V5, split V2, Uniswap V2/V4V2).
///         An APPROVAL is an EIP-712 signature by an independent policy signer over one specific
///         fund-moving call of one specific escrow:
///
///           Approval(address escrow, bytes4 action, address token, address target,
///                    uint256 amount, bytes32 dataHash, uint256 nonce, uint256 deadline)
///
///         The escrow (msg.sender of `requireApprovals`) supplies action/token/target/amount/
///         dataHash from ITS OWN calldata and its own monotonic `approvalNonce`, so a signature
///         can never be replayed on another escrow, another call, another amount or after the
///         escrow's nonce moved. `approvalsRequired` distinct approvers must sign (signatures
///         sorted by ascending signer address). `approvalsRequired == 0` disables the check
///         (staged rollout: deploy -> setApprovers([A],1) -> setApprovers([A,B],2)).
///
///         ESCROW CREATION is guarded too (the factory calls `_checkApprovals` with escrow = the
///         CREATE2 address it is about to deploy, action = its createEscrow selector, target =
///         userRefund, nonce 0): the approver re-derives `predictEscrow(...)` from the parameters
///         the CUSTOMER asked for, so a poisoned deposit address (attacker-chosen userRefund /
///         recipient baked into the escrow) is never deployed and its unguarded refund path never
///         exists. Replay is impossible: the same salt + parameters cannot be deployed twice.
///
///         An approver may never be the operator (`ApproverIsOperator`): the two signatures must
///         come from two different keys on two different machines.
///
///         Verification lives HERE (one copy per factory) and not in the per-swap escrows, so the
///         escrow creation bytecode stays small; escrows read the live set via the factory exactly
///         like they read `operator()`: changing approvers protects in-flight escrows instantly.
abstract contract ApproverRegistry {
    bytes32 public constant APPROVAL_TYPEHASH = keccak256(
        "Approval(address escrow,bytes4 action,address token,address target,uint256 amount,bytes32 dataHash,uint256 nonce,uint256 deadline)"
    );
    bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(
        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
    );
    uint256 private constant SECP256K1_HALF_N = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    address[] internal _approvers;
    mapping(address => bool) public isApprover;
    uint256 public approvalsRequired;

    event ApproversChanged(address[] approvers, uint256 approvalsRequired);

    error ApproverZero();
    error ApproverDuplicate();
    error ApproverIsOperator();
    error ThresholdTooHigh();
    error ApprovalExpired();
    error ApprovalsInsufficient();
    error ApprovalBadSignature();
    error ApprovalSignerUnknown();
    error ApprovalSignersUnsorted();

    function approvers() external view returns (address[] memory) {
        return _approvers;
    }

    /// @dev name/version are per-factory (see `_eip712Name`), chainId + this factory bind the domain.
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(
            EIP712_DOMAIN_TYPEHASH,
            keccak256(bytes(_eip712Name())),
            keccak256(bytes(_eip712Version())),
            block.chainid,
            address(this)
        ));
    }

    function _eip712Name() internal pure virtual returns (string memory);
    function _eip712Version() internal pure virtual returns (string memory);
    /// @dev The inheriting factory's current operator (approvers must never equal it).
    function _currentOperator() internal view virtual returns (address);

    /// @notice The digest an approver signs for a call of `escrow`. Exposed so signers/tests build
    ///         exactly what the chain verifies. Virtual so a later registry can bind more fields
    ///         (ApproverRegistryV2 adds the approver epoch); the keyword changes no bytecode here.
    function approvalDigest(
        address escrow,
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline
    ) public view virtual returns (bytes32) {
        bytes32 structHash = keccak256(abi.encode(
            APPROVAL_TYPEHASH, escrow, action, token, target, amount, dataHash, nonce, deadline
        ));
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
    }

    /// @notice Called by an escrow (msg.sender) before a guarded call. Reverts unless
    ///         `approvalsRequired` distinct approvers signed this exact call. `deadline` is the
    ///         common expiry the approvers signed; `approvals` are 65-byte r||s||v signatures
    ///         sorted by ascending signer address.
    function requireApprovals(
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline,
        bytes[] calldata approvals
    ) external view {
        _checkApprovals(msg.sender, action, token, target, amount, dataHash, nonce, deadline, approvals);
    }

    /// @dev Same check with the escrow passed explicitly; the factory uses it for createEscrow
    ///      (escrow = predicted CREATE2 address).
    function _checkApprovals(
        address escrow,
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline,
        bytes[] calldata approvals
    ) internal view virtual {
        uint256 need = approvalsRequired;
        if (need == 0) return;
        if (block.timestamp > deadline) revert ApprovalExpired();
        if (approvals.length < need) revert ApprovalsInsufficient();
        bytes32 digest = approvalDigest(escrow, action, token, target, amount, dataHash, nonce, deadline);
        address last = address(0);
        uint256 valid = 0;
        for (uint256 i = 0; i < approvals.length; i++) {
            address signer = _recover(digest, approvals[i]);
            if (signer <= last) revert ApprovalSignersUnsorted(); // also rejects duplicates + zero
            if (!isApprover[signer]) revert ApprovalSignerUnknown();
            last = signer;
            valid++;
        }
        if (valid < need) revert ApprovalsInsufficient();
    }

    function _recover(bytes32 digest, bytes calldata sig) internal pure returns (address) {
        if (sig.length != 65) revert ApprovalBadSignature();
        bytes32 r = bytes32(sig[0:32]);
        bytes32 s = bytes32(sig[32:64]);
        uint8 v = uint8(sig[64]);
        if (v < 27) v += 27;
        if (v != 27 && v != 28) revert ApprovalBadSignature();
        if (uint256(s) > SECP256K1_HALF_N) revert ApprovalBadSignature(); // low-s only
        address signer = ecrecover(digest, v, r, s);
        if (signer == address(0)) revert ApprovalBadSignature();
        return signer;
    }

    /// @dev Owner-only in the inheriting factory. Replaces the whole set atomically.
    function _setApprovers(address[] calldata newApprovers, uint256 newRequired) internal {
        if (newRequired > newApprovers.length) revert ThresholdTooHigh();
        address op = _currentOperator();
        for (uint256 i = 0; i < _approvers.length; i++) isApprover[_approvers[i]] = false;
        delete _approvers;
        for (uint256 i = 0; i < newApprovers.length; i++) {
            address a = newApprovers[i];
            if (a == address(0)) revert ApproverZero();
            if (a == op) revert ApproverIsOperator();
            if (isApprover[a]) revert ApproverDuplicate();
            isApprover[a] = true;
            _approvers.push(a);
        }
        approvalsRequired = newRequired;
        emit ApproversChanged(newApprovers, newRequired);
    }
}

contracts/ApproverRegistryV2.sol

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

import { ApproverRegistry } from "./ApproverRegistry.sol";

/// @title  ApproverRegistryV2: ApproverRegistry with the approval deadline always enforced, a ceiling on how far
///         ahead a deadline may lie, the approver epoch bound into every approval, an on-chain build identity,
///         and (gen-10) no gate-off path at all.
/// @notice Hashlock Q-03: in ApproverRegistry, `approvalsRequired == 0` returned before the deadline check, so
///         a factory running with approvals disabled also lost expiry on every guarded call. Here the deadline
///         is checked FIRST, unconditionally, then the signatures.
///         Fix review Q-27 / governance audit Q-03: `deadline` may not lie more than `MAX_APPROVAL_TTL` ahead,
///         so a signer mistake cannot produce an approval that stays valid for years (the signers use 15 min).
///         Governance audit Q-03 (second pass): the signed struct carries `approverEpoch`, a counter the
///         governance layer advances on EVERY change of the approver set or threshold. An approval signed under
///         one set is worthless under the next one, so a bundle that was short of signatures can never become
///         sufficient because a threshold cut executed while it was still inside its deadline.
///         Fix review Q-26: `version()` and ERC-5267 `eip712Domain()` expose the build on-chain, so indexers and
///         signer services can tell factory generations apart without an off-chain address list.
///         Gen-10 (centralisation re-assessment, item 1): the `approvalsRequired == 0` return of the base
///         registry is gone. `_checkApprovals` is implemented here in full: a threshold of zero reverts, every
///         guarded call needs `approvalsRequired` distinct approver signatures, no exception, no gate-off mode.
abstract contract ApproverRegistryV2 is ApproverRegistry {
    uint256 public constant MAX_APPROVAL_TTL = 1 hours;

    bytes32 public constant APPROVAL_TYPEHASH_V2 = keccak256(
        "Approval(address escrow,bytes4 action,address token,address target,uint256 amount,bytes32 dataHash,uint256 nonce,uint256 deadline,uint256 approverEpoch)"
    );

    /// @notice Advances on every approver set or threshold change (genesis sets it to 1). Signers read it
    ///         right before signing; the factory binds the live value, so stale approvals fail to recover.
    uint256 public approverEpoch;

    event ApproverEpochAdvanced(uint256 indexed approverEpoch);

    error ApprovalDeadlineTooFar();
    error ApprovalsRequiredZero();

    /// @notice The EIP-712 version string doubles as the generation tag of this factory build.
    function version() external pure returns (string memory) {
        return _eip712Version();
    }

    /// @notice ERC-5267: the domain this factory verifies approvals against.
    function eip712Domain()
        external view
        returns (bytes1 fields, string memory name, string memory ver, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions)
    {
        return (hex"0f", _eip712Name(), _eip712Version(), block.chainid, address(this), bytes32(0), new uint256[](0));
    }

    /// @notice Same arguments as the base: the live `approverEpoch` is read from storage, so signers only have
    ///         to fetch it and put it in the struct they sign.
    function approvalDigest(
        address escrow,
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline
    ) public view override returns (bytes32) {
        bytes32 structHash = keccak256(abi.encode(
            APPROVAL_TYPEHASH_V2, escrow, action, token, target, amount, dataHash, nonce, deadline, approverEpoch
        ));
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
    }

    function _advanceApproverEpoch() internal {
        approverEpoch += 1;
        emit ApproverEpochAdvanced(approverEpoch);
    }

    /// @dev Full check, without the base's early return: deadline window first, then `approvalsRequired`
    ///      distinct known signers in ascending order over the epoch-bound digest.
    function _checkApprovals(
        address escrow,
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline,
        bytes[] calldata approvals
    ) internal view virtual override {
        if (block.timestamp > deadline) revert ApprovalExpired();
        if (deadline > block.timestamp + MAX_APPROVAL_TTL) revert ApprovalDeadlineTooFar();
        uint256 need = approvalsRequired;
        if (need == 0) revert ApprovalsRequiredZero();
        if (approvals.length < need) revert ApprovalsInsufficient();
        bytes32 digest = approvalDigest(escrow, action, token, target, amount, dataHash, nonce, deadline);
        address last = address(0);
        uint256 valid = 0;
        for (uint256 i = 0; i < approvals.length; i++) {
            address signer = _recover(digest, approvals[i]);
            if (signer <= last) revert ApprovalSignersUnsorted(); // also rejects duplicates + zero
            if (!isApprover[signer]) revert ApprovalSignerUnknown();
            last = signer;
            valid++;
        }
        if (valid < need) revert ApprovalsInsufficient();
    }
}

contracts/Clones1167.sol

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

/// @title  Clones1167 — deterministic EIP-1167 minimal proxies (CREATE2).
/// @notice A clone is a 45-byte contract that DELEGATECALLs one fixed implementation: it has its own
///         address, balance and storage but runs the implementation's code. Deploying one costs ~45k
///         gas instead of writing the whole escrow bytecode per swap. Plain-Solidity twin of the
///         OpenZeppelin `Clones` library: identical bytecode, and the address formula is reproducible
///         off-chain as keccak256(0xff ++ deployer ++ salt ++ keccak256(initcode(implementation))).
library Clones1167 {
    error CloneFailed();

    /// @dev 10-byte creation prefix ++ 10-byte runtime prefix ++ implementation ++ 15-byte runtime suffix (55 bytes).
    function initcode(address implementation) internal pure returns (bytes memory) {
        return abi.encodePacked(
            hex"3d602d80600a3d3981f3363d3d373d3d3d363d73",
            implementation,
            hex"5af43d82803e903d91602b57fd5bf3"
        );
    }

    function predict(address implementation, bytes32 salt, address deployer) internal pure returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(hex"ff", deployer, salt, keccak256(initcode(implementation)))))));
    }

    function clone(address implementation, bytes32 salt) internal returns (address instance) {
        bytes memory code = initcode(implementation);
        assembly ("memory-safe") {
            instance := create2(0, add(code, 0x20), mload(code), salt)
        }
        if (instance == address(0)) revert CloneFailed();
    }
}

contracts/FactoryGovernance.sol

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

import { ApproverRegistryV2 } from "./ApproverRegistryV2.sol";

/// @title  FactoryGovernance: the owner / operator / treasury / guardian block shared by every approver-gated
///         factory of this generation, with a timelock on every change that LOOSENS security.
/// @notice One copy for the four factory families (near-bridge V7, split V4, Uniswap V4, UniswapV4 V4). Rules:
///
///         ROLES: `owner` decides, `operator` moves funds only with approvals, `treasury` receives fees,
///         `guardian` can only STOP things (cancel a pending change, pause the gate) and never loosen anything.
///         The five roles are pairwise distinct where it matters: owner / operator / treasury are three keys,
///         the guardian is none of owner, operator, treasury or an approver (current or pending), approvers are
///         none of owner, operator, treasury, guardian (governance audit L-02, fix review Q-43, gen-11 Q-08).
///         A key that is both owner and approver, treasury and approver, or guardian and approver, would collapse
///         the separation the approval gate is built on.
///
///         GEN-10 (centralisation re-assessment, items 1 and 2):
///           - `minApprovalsRequired` is an immutable floor under the threshold. Genesis, `scheduleApprovers`
///             and `executeApprovers` all reject a threshold below it, so the owner can never schedule the gate
///             down or off; the registry has no `approvalsRequired == 0` path left (ApproverRegistryV2). The floor
///             itself is at least `ABSOLUTE_MIN_APPROVALS` (2): a single key is never enough to move funds.
///           - `treasury` is immutable. There is no schedule, cancel or execute for it; the only way to a new
///             fee address is a new factory generation. Fees from every escrow of this factory land there and
///             nowhere else.
///
///         INSTANT (tightening or incident response; a captured owner key gains nothing from them):
///           - `raiseThreshold(n)`, `removeApprover(a)`: both DROP a pending approver schedule, so an old
///             snapshot can never put a removed key back or lower a raised threshold (governance audit M-01).
///             Removing a key below the threshold pauses the gate instead of reverting, so a leaked key can
///             always be cut immediately (governance audit L-03). Both advance `approverEpoch`.
///           - `pause()`: owner or guardian; every approval-gated call of a DEPLOYED escrow reverts `GatePaused()`.
///             Creation stays open while paused (it moves no funds and is the only way a counterfactual deposit
///             reaches its refund path) as long as the live approver set can still sign it; after a removal that
///             left the threshold unreachable it waits for the new set like everything else. Refunds are never
///             gated. `unpause()` is the owner's, once the live set can meet the threshold again.
///
///         GEN-11 (third audit, M-01): `createEscrow` is approval-gated again on every factory. The approvers
///         bind the predicted address and `userRefund` (the address commits to every parameter) before the
///         unguarded refund path can exist, so a poisoned quote (attacker-chosen refund address or recipient)
///         is never deployed. Third parties still deploy with approvals obtained from the public recovery
///         listeners, as in gen-9; an escrow that already exists is returned instead of reverting (Q-10).
///         Q-03: an owner nominee may not sit in the pending approver set. Q-08: the guardian is never an approver
///         or the treasury, an approver is never the guardian. Q-09: `cancelGuardian` is the owner's alone, so a
///         guardian can no longer veto its own replacement (a leaked guardian key is replaced after the 48 h delay
///         instead of holding the factory hostage); every other cancel stays owner-or-guardian.
///
///         DELAYED by `GOVERNANCE_DELAY` (48 h), announced on-chain, cancellable by the owner OR the guardian
///         (the guardian change by the owner alone, Q-09), executable by anyone once due and only inside
///         `EXECUTION_WINDOW` after that (a forgotten change lapses instead of staying live forever, governance
///         audit L-04):
///           - `scheduleApprovers(set, required)`: adding or replacing approvers, lowering the threshold down to
///             the floor. Executing advances `approverEpoch`.
///           - `scheduleOperator(o)`: EVERY operator change (governance audit M-02, second pass: an instant
///             rotation let a captured owner key install its operator first and schedule its approvers after,
///             so the order of the two calls decided whether the "loosening pending" guard applied). The new
///             operator may not be any other role, pending ones included (Q-01); the incident response for a
///             leaked operator key is `pause()` plus the schedule.
///           - `scheduleGuardian(g)`: the guardian is the brake, so replacing it is a loosening.
///           - `transferOwnership(new)` + `acceptOwnership()`: the new owner can accept only after the delay
///             and only inside the window, the transfer can be cancelled meanwhile, and accepting clears every
///             pending change of the previous owner (governance audit M-02 and L-04, Q-02).
///
///         WHY THE DELAY PROTECTS DEPOSITS (governance audit M-02): `refundTimeout` is capped at
///         `GOVERNANCE_DELAY - 1 hours`, so every escrow deposited BEFORE a loosening is scheduled unlocks its
///         permissionless refund before the loosening can execute. Escrows created WHILE an approver or
///         operator change is pending (second pass) get `creationUnlockAt()`: their refund unlocks no later
///         than `UNLOCK_MARGIN` before the change can execute, and in the last `CREATION_CUTOFF` before it no
///         escrow can be created or predicted at all (`LooseningImminent`), so no deployed escrow can ever be
///         locked past the moment a new approver set or operator takes over. The guardian cancel stays as the
///         brake for the one case the chain cannot cover: funds sent to an address that was never deployed.
///         A captured owner cannot remove that brake quickly: the guardian only changes through the delayed
///         path, announced 48 h ahead on-chain, and an approver or operator change scheduled after it waits
///         another 48 h, all of it visible to the public watcher.
///
///         IMMUTABLE: `refundTimeout`, `treasury` and `minApprovalsRequired` are constructor arguments without
///         a setter. A quoted deposit address can only ever be deployed with the timeout the customer was quoted.
///
///         GENESIS: the initial approver set and threshold are constructor arguments and the threshold must
///         be at least the floor, so approvals are on from block 1. The initial owner, operator, treasury and
///         guardian are announced in events so monitoring can rebuild the state from the first block.
abstract contract FactoryGovernance is ApproverRegistryV2 {
    address public owner;
    address public pendingOwner;
    uint64 public ownershipEffectiveAt; // 0 = no transfer pending
    address public operator;
    address public immutable treasury;
    address public guardian;
    bool public paused;
    uint256 public immutable refundTimeout;
    /// @notice The threshold can never be scheduled below this (gen-10, item 1). At least ABSOLUTE_MIN_APPROVALS.
    uint256 public immutable minApprovalsRequired;

    uint256 public constant GOVERNANCE_DELAY = 48 hours;
    uint256 public constant EXECUTION_WINDOW = 7 days;
    uint256 public constant MIN_REFUND_TIMEOUT = 1 hours;
    uint256 public constant MAX_REFUND_TIMEOUT = GOVERNANCE_DELAY - 1 hours;
    uint256 public constant MAX_APPROVERS = 16;
    /// @notice Lowest floor a factory can be built with: one signature alone never moves funds.
    uint256 public constant ABSOLUTE_MIN_APPROVALS = 2;
    /// @notice An escrow created while a loosening is pending unlocks at least this long before it executes.
    uint256 public constant UNLOCK_MARGIN = 1 hours;
    /// @notice No escrow is created or predicted when a loosening executes sooner than this.
    uint256 public constant CREATION_CUTOFF = MIN_REFUND_TIMEOUT + UNLOCK_MARGIN;

    struct PendingApprovers {
        address[] approvers;
        uint256 required;
        uint64 effectiveAt; // 0 = nothing pending
    }
    struct PendingOperator {
        address operator;
        uint64 effectiveAt;
    }
    struct PendingGuardian {
        address guardian;
        uint64 effectiveAt;
    }
    PendingApprovers internal _pendingApprovers;
    PendingOperator public pendingOperator;
    PendingGuardian public pendingGuardian;

    event OperatorChanged(address indexed oldOperator, address indexed newOperator);
    event OperatorScheduled(address indexed operator, uint256 effectiveAt);
    event OperatorCancelled();
    event TreasuryChanged(address indexed oldTreasury, address indexed newTreasury);
    event GuardianChanged(address indexed oldGuardian, address indexed newGuardian);
    event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner, uint256 effectiveAt);
    event OwnershipTransferCancelled(address indexed pendingOwner);
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
    event ApproversScheduled(address[] approvers, uint256 approvalsRequired, uint256 effectiveAt);
    event ApproversCancelled();
    event GuardianScheduled(address indexed guardian, uint256 effectiveAt);
    event GuardianCancelled();
    event Paused(address indexed by);
    event Unpaused(address indexed by);

    error NotOwner();
    error NotOwnerOrGuardian();
    error NotOperator();
    error NotPendingOwner();
    error ZeroAddress();
    error TimeoutOutOfRange();
    error TreasuryIsOperator();
    error TreasuryIsApprover();
    error OwnerIsOperator();
    error OwnerIsTreasury();
    error ApproverIsOwner();
    error GuardianConflict();
    error NothingPending();
    error NotYetEffective();
    error ChangeExpired();
    error LooseningImminent();
    error NotAnApprover();
    error ThresholdUnreachable();
    error NotATightening();
    error ThresholdBelowFloor();
    error FloorTooLow();
    error TooManyApprovers();
    error ApproversUnsorted();
    error GatePaused();
    error NotPaused();

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyOwnerOrGuardian() {
        if (msg.sender != owner && msg.sender != guardian) revert NotOwnerOrGuardian();
        _;
    }

    /// @param initialApprovers initial approver set, strictly ascending (approvals on from block 1)
    /// @param _required        initial threshold, at least `_minRequired`
    /// @param _minRequired     the floor under every future threshold, at least ABSOLUTE_MIN_APPROVALS
    constructor(
        address _owner,
        address _operator,
        address _treasury,
        address _guardian,
        uint256 _refundTimeout,
        address[] memory initialApprovers,
        uint256 _required,
        uint256 _minRequired
    ) {
        if (_owner == address(0) || _operator == address(0) || _treasury == address(0) || _guardian == address(0)) revert ZeroAddress();
        if (_treasury == _operator) revert TreasuryIsOperator();
        if (_owner == _operator) revert OwnerIsOperator();
        if (_owner == _treasury) revert OwnerIsTreasury();
        if (_guardian == _owner || _guardian == _operator || _guardian == _treasury) revert GuardianConflict();
        if (_refundTimeout < MIN_REFUND_TIMEOUT || _refundTimeout > MAX_REFUND_TIMEOUT) revert TimeoutOutOfRange();
        if (_minRequired < ABSOLUTE_MIN_APPROVALS) revert FloorTooLow();
        owner = _owner;
        operator = _operator;
        treasury = _treasury;
        guardian = _guardian;
        refundTimeout = _refundTimeout;
        minApprovalsRequired = _minRequired;
        emit OwnershipTransferred(address(0), _owner);
        emit OperatorChanged(address(0), _operator);
        emit TreasuryChanged(address(0), _treasury);
        emit GuardianChanged(address(0), _guardian);
        _setApproversMemory(initialApprovers, _required);
    }

    function _currentOperator() internal view override returns (address) { return operator; }

    /// @dev The pause sits in front of every approval check of a deployed escrow. Creation targets an address
    ///      without code and is let through: deploying moves nothing and opens the customer's refund path.
    function _checkApprovals(
        address escrow,
        bytes4 action,
        address token,
        address target,
        uint256 amount,
        bytes32 dataHash,
        uint256 nonce,
        uint256 deadline,
        bytes[] calldata approvals
    ) internal view override {
        if (paused && escrow.code.length != 0) revert GatePaused();
        super._checkApprovals(escrow, action, token, target, amount, dataHash, nonce, deadline, approvals);
    }

    // ─── instant: tightening / incident response ─────────────────────────────

    /// @notice Raise the threshold on the current set. Lowering goes through `scheduleApprovers`.
    function raiseThreshold(uint256 newRequired) external onlyOwner {
        if (newRequired <= approvalsRequired) revert NotATightening();
        if (newRequired > _approvers.length) revert ThresholdTooHigh();
        _dropPendingApprovers();
        approvalsRequired = newRequired;
        _advanceApproverEpoch();
        emit ApproversChanged(_approvers, newRequired);
    }

    /// @notice Drop one approver immediately. If the remaining set can no longer meet the threshold the gate is
    ///         paused in the same transaction: nothing moves until the owner schedules a new set and unpauses.
    function removeApprover(address a) external onlyOwner {
        if (!isApprover[a]) revert NotAnApprover();
        _dropPendingApprovers();
        isApprover[a] = false;
        uint256 n = _approvers.length;
        for (uint256 i = 0; i < n; i++) {
            if (_approvers[i] == a) {
                _approvers[i] = _approvers[n - 1];
                _approvers.pop();
                break;
            }
        }
        _advanceApproverEpoch();
        emit ApproversChanged(_approvers, approvalsRequired);
        if (approvalsRequired > n - 1) _pause();
    }

    /// @notice Stop every approval-gated call of the deployed escrows (forwards, swaps, sweeps). Creation and
    ///         refunds are unaffected.
    function pause() external onlyOwnerOrGuardian {
        _pause();
    }

    function unpause() external onlyOwner {
        if (!paused) revert NotPaused();
        if (approvalsRequired > _approvers.length) revert ThresholdUnreachable();
        paused = false;
        emit Unpaused(msg.sender);
    }

    // ─── delayed: loosening ───────────────────────────────────────────────────

    /// @notice Schedule a full replacement of the approver set and threshold (the only way to add or
    ///         replace approvers, or to lower the threshold, never below `minApprovalsRequired`). Effective
    ///         after GOVERNANCE_DELAY, executable for EXECUTION_WINDOW after that.
    function scheduleApprovers(address[] calldata newApprovers, uint256 newRequired) external onlyOwner {
        _validateApprovers(newApprovers, newRequired);
        uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
        delete _pendingApprovers.approvers;
        for (uint256 i = 0; i < newApprovers.length; i++) _pendingApprovers.approvers.push(newApprovers[i]);
        _pendingApprovers.required = newRequired;
        _pendingApprovers.effectiveAt = at;
        emit ApproversScheduled(newApprovers, newRequired, at);
    }

    function cancelApprovers() external onlyOwnerOrGuardian {
        if (_pendingApprovers.effectiveAt == 0) revert NothingPending();
        delete _pendingApprovers;
        emit ApproversCancelled();
    }

    /// @notice Anyone may execute a due change; the owner decided it 48 h ago and nobody cancelled it.
    function executeApprovers() external {
        uint64 at = _pendingApprovers.effectiveAt;
        if (at == 0) revert NothingPending();
        _requireDue(at);
        address[] memory set = _pendingApprovers.approvers;
        uint256 req = _pendingApprovers.required;
        delete _pendingApprovers;
        _setApproversMemory(set, req);
    }

    function pendingApprovers() external view returns (address[] memory approversList, uint256 required, uint256 effectiveAt) {
        return (_pendingApprovers.approvers, _pendingApprovers.required, _pendingApprovers.effectiveAt);
    }

    /// @notice Every operator change waits the delay (governance audit M-02, second pass). Role-checked now and
    ///         again at execution.
    function scheduleOperator(address _operator) external onlyOwner {
        _checkOperatorRole(_operator);
        uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
        pendingOperator = PendingOperator({ operator: _operator, effectiveAt: at });
        emit OperatorScheduled(_operator, at);
    }

    function cancelOperator() external onlyOwnerOrGuardian {
        if (pendingOperator.effectiveAt == 0) revert NothingPending();
        delete pendingOperator;
        emit OperatorCancelled();
    }

    function executeOperator() external {
        PendingOperator memory p = pendingOperator;
        if (p.effectiveAt == 0) revert NothingPending();
        _requireDue(p.effectiveAt);
        _checkOperatorRole(p.operator);
        delete pendingOperator;
        emit OperatorChanged(operator, p.operator);
        operator = p.operator;
    }

    /// @notice When the earliest pending approver or operator change can execute, 0 when none is pending.
    ///         These two are the changes that decide who can move escrowed funds. A change that is due counts
    ///         until it is executed or cancelled (anyone may execute it at any moment); a change that has lapsed
    ///         can never execute and no longer counts.
    function looseningEffectiveAt() public view returns (uint256) {
        uint256 a = _liveOrZero(_pendingApprovers.effectiveAt);
        uint256 o = _liveOrZero(pendingOperator.effectiveAt);
        if (a == 0) return o;
        if (o == 0) return a;
        return a < o ? a : o;
    }

    function _liveOrZero(uint64 at) internal view returns (uint256) {
        if (at == 0 || block.timestamp > uint256(at) + EXECUTION_WINDOW) return 0;
        return at;
    }

    /// @notice The refund unlock an escrow created now receives: `refundTimeout` ahead, capped so that it falls
    ///         at least `UNLOCK_MARGIN` before any pending loosening can execute. Reverts `LooseningImminent`
    ///         when that cap would leave less than `MIN_REFUND_TIMEOUT`: no escrow is created, predicted or
    ///         re-locked (swapHold) in the last `CREATION_CUTOFF` before a loosening runs, nor while a due
    ///         change waits to be executed.
    function creationUnlockAt() public view returns (uint256) {
        uint256 unlock = block.timestamp + refundTimeout;
        uint256 at = looseningEffectiveAt();
        if (at != 0) {
            if (at < block.timestamp + CREATION_CUTOFF) revert LooseningImminent();
            uint256 cap = at - UNLOCK_MARGIN;
            if (cap < unlock) unlock = cap;
        }
        return unlock;
    }

    function scheduleGuardian(address _guardian) external onlyOwner {
        _checkGuardianRole(_guardian);
        uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
        pendingGuardian = PendingGuardian({ guardian: _guardian, effectiveAt: at });
        emit GuardianScheduled(_guardian, at);
    }

    /// @notice Q-09: only the owner cancels a guardian change, so the guardian cannot block its own replacement.
    function cancelGuardian() external onlyOwner {
        if (pendingGuardian.effectiveAt == 0) revert NothingPending();
        delete pendingGuardian;
        emit GuardianCancelled();
    }

    function executeGuardian() external {
        PendingGuardian memory p = pendingGuardian;
        if (p.effectiveAt == 0) revert NothingPending();
        _requireDue(p.effectiveAt);
        _checkGuardianRole(p.guardian);
        delete pendingGuardian;
        emit GuardianChanged(guardian, p.guardian);
        guardian = p.guardian;
    }

    // ─── ownership (2-step, delayed) ──────────────────────────────────────────

    function transferOwnership(address _pendingOwner) external onlyOwner {
        if (_pendingOwner == address(0)) revert ZeroAddress();
        if (_pendingOwner == operator || _pendingOwner == pendingOperator.operator) revert OwnerIsOperator();
        if (_pendingOwner == treasury) revert OwnerIsTreasury();
        if (_pendingOwner == guardian || _pendingOwner == pendingGuardian.guardian) revert GuardianConflict();
        if (isApprover[_pendingOwner] || _inPendingApprovers(_pendingOwner)) revert ApproverIsOwner();
        uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
        pendingOwner = _pendingOwner;
        ownershipEffectiveAt = at;
        emit OwnershipTransferStarted(owner, _pendingOwner, at);
    }

    function cancelOwnershipTransfer() external onlyOwnerOrGuardian {
        address p = pendingOwner;
        if (p == address(0)) revert NothingPending();
        pendingOwner = address(0);
        ownershipEffectiveAt = 0;
        emit OwnershipTransferCancelled(p);
    }

    /// @notice The nominee accepts inside the window. Every change queued by the previous owner is dropped.
    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        _requireDue(ownershipEffectiveAt);
        _dropPendingApprovers();
        if (pendingOperator.effectiveAt != 0) { delete pendingOperator; emit OperatorCancelled(); }
        if (pendingGuardian.effectiveAt != 0) { delete pendingGuardian; emit GuardianCancelled(); }
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
        ownershipEffectiveAt = 0;
    }

    // ─── internals ────────────────────────────────────────────────────────────

    function _pause() internal {
        if (paused) return;
        paused = true;
        emit Paused(msg.sender);
    }

    function _dropPendingApprovers() internal {
        if (_pendingApprovers.effectiveAt == 0) return;
        delete _pendingApprovers;
        emit ApproversCancelled();
    }

    function _requireDue(uint64 at) internal view {
        if (block.timestamp < at) revert NotYetEffective();
        if (block.timestamp > uint256(at) + EXECUTION_WINDOW) revert ChangeExpired();
    }

    /// @dev A guardian is none of the other roles, pending ones included (gen-11 Q-08: nor an approver, nor the
    ///      immutable treasury, which no later governance call could undo).
    function _checkGuardianRole(address g) internal view {
        if (g == address(0)) revert ZeroAddress();
        if (g == owner || g == pendingOwner || g == operator || g == pendingOperator.operator) revert GuardianConflict();
        if (g == treasury || isApprover[g] || _inPendingApprovers(g)) revert GuardianConflict();
    }

    /// @dev An operator is none of the other roles, pending ones included (the treasury is immutable, so a
    ///      pending treasury no longer exists to check against).
    function _checkOperatorRole(address o) internal view {
        if (o == address(0)) revert ZeroAddress();
        if (o == treasury) revert TreasuryIsOperator();
        if (o == owner || o == pendingOwner) revert OwnerIsOperator();
        if (o == guardian || o == pendingGuardian.guardian) revert GuardianConflict();
        if (isApprover[o] || _inPendingApprovers(o)) revert ApproverIsOperator();
    }

    function _inPendingApprovers(address a) internal view returns (bool) {
        uint256 n = _pendingApprovers.approvers.length;
        for (uint256 i = 0; i < n; i++) {
            if (_pendingApprovers.approvers[i] == a) return true;
        }
        return false;
    }

    /// @dev An approver is none of the other roles, pending ones included.
    function _checkApproverRole(address a) internal view {
        if (a == address(0)) revert ApproverZero();
        if (a == operator || a == pendingOperator.operator) revert ApproverIsOperator();
        if (a == owner || a == pendingOwner) revert ApproverIsOwner();
        if (a == treasury) revert TreasuryIsApprover();
        if (a == guardian || a == pendingGuardian.guardian) revert GuardianConflict();
    }

    /// @dev Strictly ascending input: duplicates are impossible and the check is linear (fix review Q-42).
    ///      The threshold must sit between the floor and the set size.
    function _validateApprovers(address[] calldata set, uint256 required) internal view {
        if (required < minApprovalsRequired) revert ThresholdBelowFloor();
        if (required > set.length) revert ThresholdTooHigh();
        if (set.length > MAX_APPROVERS) revert TooManyApprovers();
        address prev = address(0);
        for (uint256 i = 0; i < set.length; i++) {
            address a = set[i];
            if (a <= prev) revert ApproversUnsorted();
            _checkApproverRole(a);
            prev = a;
        }
    }

    /// @dev Memory twin of `_validateApprovers` that also writes the set (constructor, executeApprovers).
    function _setApproversMemory(address[] memory set, uint256 required) internal {
        if (required < minApprovalsRequired) revert ThresholdBelowFloor();
        if (required > set.length) revert ThresholdTooHigh();
        if (set.length > MAX_APPROVERS) revert TooManyApprovers();
        for (uint256 i = 0; i < _approvers.length; i++) isApprover[_approvers[i]] = false;
        delete _approvers;
        address prev = address(0);
        for (uint256 i = 0; i < set.length; i++) {
            address a = set[i];
            if (a <= prev) revert ApproversUnsorted();
            _checkApproverRole(a);
            isApprover[a] = true;
            _approvers.push(a);
            prev = a;
        }
        approvalsRequired = required;
        _advanceApproverEpoch();
        emit ApproversChanged(set, required);
    }
}

contracts/UniswapV4EscrowFactory.sol

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

// ─────────────────────────────────────────────────────────────────────────────
//  UniswapV4EscrowFactory — the v4 sibling of UniswapEscrowFactory.sol.
//
//  THIS IS THE ONLY NEW CONTRACT. Everything else in contracts/contracts/ stays
//  exactly as it is:
//    EscrowFactory.sol / V2 / V3 / V4   → the near-bridge escrows (untouched)
//    SplitEscrowFactory.sol             → the split/railgun escrow (untouched)
//    UniswapEscrowFactory.sol           → the Uniswap **v3** escrow (untouched)
//  (Note: "EscrowFactoryV4.sol" is OUR v4 of the near-bridge escrow. It has
//   nothing to do with Uniswap v4. Do not confuse the two.)
//
//  Deliberately NO evmVersion change: this file compiles on the repo's existing
//  settings — solc 0.8.24 with evmVersion unset, which under Hardhat resolves to
//  `paris` (Hardhat pins paris for 0.8.20+ so PUSH0 never reaches an L2 that
//  lacks it; solc's own default would be shanghai). Confirmed by the compile
//  line: "evm target: paris". It never uses transient storage — TSTORE /
//  TLOAD live inside PoolManager's own deployed bytecode, not ours. All v4
//  interfaces are declared inline, exactly as UniswapEscrowFactory.sol declares
//  IV3SwapRouter/IWETH9 inline, so there is no @uniswap dependency to add.
//
//  WHAT CHANGED vs the v3 escrow, and nothing else:
//    • router + weth immutables      → poolManager + nativeEnabled immutables
//    • router.exactInput(path)       → poolManager.unlock → swap → settle → take
//    • packed v3 bytes path          → abi.encode(PathKey[], uint256 maxFee) in
//                                      the SAME `bytes path` argument (D6 holds)
//    • WETH9 wrap/unwrap             → deleted (v4 native is Currency(address(0)))
//    • swapHold / forwardEth         → OMITTED in this first release, see below
//    • unbounded fee sweep           → sweep capped at the blob's maxFee
//  Ownership, CREATE2 surface, refunds and the SwapForwarded signature are
//  copied verbatim so the backend needs no ABI change.
//
//  OMITTED ON PURPOSE — swapHold / forwardEth:
//    swapHold is native-out only, and on Arc native is disabled (nativeEnabled
//    = false), so it could never execute there. Shipping it would also mean
//    shipping forwardToken(), widening operator discretion from "one native
//    amount to a bridge address" to "any token, any destination". The backend
//    MUST therefore exclude a univ4 venue whenever it would call swapHold
//    (combo-OUT and stock fee-on-output). Without that guard those rows hit a
//    missing selector and burn their retry budget into REFUNDING.
// ─────────────────────────────────────────────────────────────────────────────

/// @title IUniswapV4EscrowFactory — the minimal surface the escrow needs.
interface IUniswapV4EscrowFactory {
    function operator() external view returns (address);
    function treasury() external view returns (address);
    function refundTimeout() external view returns (uint256);
    function poolManager() external view returns (address);
    function nativeEnabled() external view returns (bool);
}

/// @dev Uniswap v4 pool identity. `currency0 < currency1` by raw address, so
///      native (address(0)) is ALWAYS currency0. hooks == address(0) means the
///      pool has no hook contract and behaves exactly like a v3 pool.
struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

/// @dev One hop of a v4 route. This is the v4 replacement for the packed
///      token(20)+fee(3)+token(20) path — `intermediateCurrency` is the hop's
///      OUTPUT currency.
struct PathKey {
    address intermediateCurrency;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
    bytes hookData;
}

/// @dev NOTE the sign convention: amountSpecified NEGATIVE = exact input.
///      This is inverted versus Uniswap v3.
struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

interface IPoolManager {
    function unlock(bytes calldata data) external returns (bytes memory);
    /// @return swapDelta packed BalanceDelta: amount0 in the high 128 bits,
    ///         amount1 in the low 128. Negative = we owe, positive = we are owed.
    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);
    function take(address currency, address to, uint256 amount) external;
}

/// @title  UniswapV4SwapEscrow — per-swap fund container for the univ4 venue.
/// @notice userRefund, recipient, tokenIn and tokenOut are all committed into
///         the CREATE2 address, so value can only ever reach one of three
///         addresses: `recipient`, `userRefund`, or the factory's `treasury`.
///
///         TRUST MODEL, stated precisely (the v3 header's "worst case is a bad
///         minOut" understates it, and this file will not repeat that):
///         a compromised operator key can degrade a swap three ways —
///           1. choose a bad `minOut`;
///           2. choose a small `amountIn`, leaving the rest as "fee";
///           3. choose `recipient` at createEscrow time, before the user has
///              deposited anything.
///         All three end with funds at `recipient`, `userRefund` or `treasury`,
///         never at an attacker-chosen address. (2) is bounded per swap by the
///         `maxFee` committed in the path blob — see swapForward.
///
///         GAS NOTE: `sqrtPriceLimitX96` is hardcoded to the tick extremes (the
///         same choice V4Router makes). On a thin or empty pool, Pool.swap's
///         loop only terminates at that extreme, walking every initialised tick
///         word on the way — with tickSpacing 1 that can exceed the block gas
///         limit and the tx runs out of gas rather than under-filling. The
///         operator pays. Off-chain liquidity checks are what prevent it.
contract UniswapV4SwapEscrow {
    address public immutable factory;
    address public immutable userRefund;
    address public immutable recipient;
    address public immutable tokenIn;   // address(0) = native
    address public immutable tokenOut;  // address(0) = native
    uint256 public immutable refundUnlockAt;
    /// Snapshotted from the factory at construction. Both are `immutable` on the
    /// factory too, so this is identical in value and two STATICCALLs cheaper
    /// per swap — and it lets the per-hop native check below be a plain read.
    address public immutable poolManager;
    bool    public immutable nativeAllowed;

    uint256 private _entered; // simple non-reentrancy latch
    bool private _swapped;    // ONE-SHOT: see swapForward

    // v4 constants, inlined rather than imported (see header).
    uint160 private constant MIN_SQRT_PRICE = 4295128739;
    uint160 private constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    uint24  private constant DYNAMIC_FEE_FLAG = 0x800000;
    uint24  private constant MAX_LP_FEE = 1_000_000;
    int24   private constant MAX_TICK_SPACING = 32767;

    /// @dev Same SIGNATURE (therefore same topic0) as
    ///      UniswapSwapEscrow.SwapForwarded, so the backend's
    ///      finalizeFromReceipt (which matches on parsed.name) and the resume
    ///      scan (filters.SwapForwarded() with no indexed args) work unchanged.
    ///      One value differs deliberately: for a native leg v3 logged WETH
    ///      here, v4 logs address(0). Cosmetic — it reaches indexers, not
    ///      filters.
    event SwapForwarded(
        address indexed effTokenIn,
        address indexed effTokenOut,
        uint256 amountIn,
        uint256 amountOut,
        address recipient
    );
    event RefundedToUser(address indexed token, uint256 amount);
    event Swept(address indexed token, address indexed treasury, uint256 amount);
    /// Emitted when the post-swap remainder could NOT be delivered to userRefund
    /// (a contract with no receive(), or a blocklisted address — Arc's USDC
    /// blocklist reverts at runtime). The amount stays in this escrow, where
    /// refundToUser / refundEthToUser can retry it. The swap itself succeeded.
    event RefundDeferred(address indexed token, uint256 amount);

    error NotOperator();
    error NotPoolManager();
    error RefundLocked();
    error ZeroAddress();
    error Reentrancy();
    error SameAsset();
    error Expired();
    error BadPath();
    error BadHook();
    error BadFee();
    error BadAmount();
    error PartialFill();
    error InsufficientDeposit();
    error TooLittleOut();
    error NativeDisabled();
    error AlreadySwapped();
    error FeeTooLarge();

    modifier nonReentrant() {
        if (_entered == 1) revert Reentrancy();
        _entered = 1;
        _;
        _entered = 0;
    }

    constructor(address _userRefund, address _recipient, address _tokenIn, address _tokenOut) {
        if (_userRefund == address(0) || _recipient == address(0)) revert ZeroAddress();
        factory = msg.sender;
        poolManager = IUniswapV4EscrowFactory(msg.sender).poolManager();
        nativeAllowed = IUniswapV4EscrowFactory(msg.sender).nativeEnabled();
        // v4 has no wrapped native, so the pair check is direct — there is no
        // "native is WETH under the hood" normalisation to do.
        if (_tokenIn == _tokenOut) revert SameAsset();
        if (!nativeAllowed) {
            // Arc: USDC is the native gas asset at 18 decimals AND an ERC-20 at
            // 6 decimals. Allowing the native leg would mix the two precisions
            // by a factor of 1e12. Reject it at construction.
            if (_tokenIn == address(0) || _tokenOut == address(0)) revert NativeDisabled();
        }
        userRefund = _userRefund;
        recipient = _recipient;
        tokenIn = _tokenIn;
        tokenOut = _tokenOut;
        refundUnlockAt = block.timestamp + IUniswapV4EscrowFactory(msg.sender).refundTimeout();
    }

    function _operator() internal view returns (address) {
        return IUniswapV4EscrowFactory(factory).operator();
    }

    modifier onlyOperator() {
        if (msg.sender != _operator()) revert NotOperator();
        _;
    }

    /// @notice Execute the swap: `amountIn` of tokenIn → tokenOut through the
    ///         v4 PoolManager along `path`; output goes DIRECTLY to `recipient`;
    ///         the remaining input asset (our withheld fee) auto-sweeps to the
    ///         treasury in the SAME transaction.
    /// @param path abi.encode(PathKey[] hops, uint256 maxFee)
    ///        `hops` — one entry per hop, each naming that hop's OUTPUT
    ///        currency. Every hop must have hooks == address(0) and no hookData.
    ///        `maxFee` — the most of `tokenIn` that may reach the treasury.
    ///        The backend sets it to the fee it actually withheld. It must be
    ///        <= amountIn (a fee larger than the trade is never legitimate), so
    ///        passing type(uint256).max reverts rather than silently restoring
    ///        an uncapped sweep.
    ///
    ///        SETTLEMENT AT THE END OF THE SWAP:
    ///          min(remaining, maxFee)  → treasury          (must succeed)
    ///          everything else          → userRefund         (best effort)
    ///        Normally nothing is left behind. That matters because the escrow
    ///        address is public and users re-send: an uncapped sweep would put a
    ///        duplicate deposit in the fee sink, and merely capping it would
    ///        strand the excess at a per-swap address the user does not know
    ///        exists — while `sweep()` would hand it to the treasury anyway.
    ///        The refund leg is BEST EFFORT on purpose: if userRefund cannot
    ///        receive (no receive(), or blocklisted — on Arc that reverts at
    ///        runtime) the swap must still deliver tokenOut to recipient. The
    ///        remainder then stays here, RefundDeferred is emitted, and the
    ///        ordinary refund path retries it. `_swapped` is what makes a
    ///        retained balance safe.
    ///
    /// @dev ONE-SHOT. A successful swapForward can never run twice on the same
    ///      escrow. In the v3 escrow that was emergent — the balance check
    ///      happened to fail on a second call — and it would have been lost the
    ///      moment a balance was deliberately left behind. Here it is explicit,
    ///      so a duplicate deposit plus a backend retry cannot execute a second
    ///      real swap. A REVERTED attempt changes no state and can be retried.
    function swapForward(
        uint256 amountIn,
        uint256 minOut,
        uint256 deadline,
        bytes calldata path
    ) external onlyOperator nonReentrant returns (uint256 amountOut) {
        if (_swapped) revert AlreadySwapped();
        if (block.timestamp > deadline) revert Expired();
        if (amountIn == 0 || amountIn > uint256(uint128(type(int128).max))) revert BadAmount();
        // cheap, distinguishable pre-flight: a malformed blob otherwise reverts
        // inside abi.decode with EMPTY return data, indistinguishable from OOG.
        if (path.length < 64) revert BadPath();

        if (tokenIn == address(0)) {
            if (address(this).balance < amountIn) revert InsufficientDeposit();
        } else {
            if (_balanceOf(tokenIn) < amountIn) revert InsufficientDeposit();
        }

        // ONE decode, in the callback; maxFee comes back with the output so the
        // blob is never decoded twice (an N-hop path would otherwise be
        // materialised twice concurrently, and memory pricing turns quadratic).
        bytes memory out = IPoolManager(poolManager).unlock(abi.encode(path, amountIn, minOut));
        uint256 maxFee;
        (amountOut, maxFee) = abi.decode(out, (uint256, uint256));
        _swapped = true;

        emit SwapForwarded(tokenIn, tokenOut, amountIn, amountOut, recipient);

        // Settle what is left: capped fee to the treasury (must succeed — it is
        // ours), everything else back to the user (best effort — it is theirs).
        // Normally the escrow ends at zero. If userRefund cannot receive, the
        // remainder stays here behind the _swapped latch and RefundDeferred
        // says so; refundToUser / refundEthToUser retry it later.
        address t = IUniswapV4EscrowFactory(factory).treasury();
        if (tokenIn == address(0)) {
            uint256 remEth = address(this).balance;
            uint256 feeEth = remEth > maxFee ? maxFee : remEth;
            if (feeEth > 0) { _sendEth(t, feeEth); emit Swept(address(0), t, feeEth); }
            uint256 backEth = remEth - feeEth;
            if (backEth > 0) {
                if (_trySendEth(userRefund, backEth)) emit RefundedToUser(address(0), backEth);
                else emit RefundDeferred(address(0), backEth);
            }
        } else {
            uint256 rem = _balanceOf(tokenIn);
            uint256 fee = rem > maxFee ? maxFee : rem;
            if (fee > 0) { _safeTransfer(tokenIn, t, fee); emit Swept(tokenIn, t, fee); }
            uint256 back = rem - fee;
            if (back > 0) {
                if (_tryTransfer(tokenIn, userRefund, back)) emit RefundedToUser(tokenIn, back);
                else emit RefundDeferred(tokenIn, back);
            }
        }
    }

    /// @notice PoolManager flash-accounting callback.
    /// @dev    *** THIS FUNCTION MUST NOT CARRY `nonReentrant`. ***
    ///         PoolManager.unlock re-enters this contract while swapForward's
    ///         latch is held, so a nonReentrant modifier here would revert 100%
    ///         of swaps, deterministically. Instead we assert the latch IS held:
    ///         that is simultaneously the reentrancy guard and the proof that we
    ///         are inside our own swapForward rather than someone else's unlock.
    ///         `returns (bytes memory)` is mandatory — unlock abi-decodes it.
    function unlockCallback(bytes calldata raw) external returns (bytes memory) {
        IPoolManager pm = IPoolManager(poolManager);
        if (msg.sender != address(pm)) revert NotPoolManager();
        if (_entered != 1) revert Reentrancy();

        (bytes memory rawPath, uint256 amountIn, uint256 minOut) =
            abi.decode(raw, (bytes, uint256, uint256));
        (PathKey[] memory hops, uint256 maxFee) = abi.decode(rawPath, (PathKey[], uint256));
        if (hops.length == 0) revert BadPath();
        // A fee larger than the traded amount is never legitimate. Without this,
        // maxFee = type(uint256).max silently restores an uncapped sweep.
        if (maxFee > amountIn) revert FeeTooLarge();

        address cIn = tokenIn;
        uint256 amt = amountIn;

        for (uint256 i = 0; i < hops.length; ++i) {
            PathKey memory h = hops[i];

            // ── validation. `hooks == address(0)` is the load-bearing check:
            // a hook is arbitrary code that can block the swap, skim value, set
            // a 100% fee or re-enter us. A zero hook also cannot be a
            // dynamic-fee pool, because PoolManager rejects that combination.
            if (h.hooks != address(0)) revert BadHook();
            // hooks == 0 means hookData can never be read by anything. Reject it
            // rather than carry unbounded calldata we decode and discard.
            if (h.hookData.length != 0) revert BadPath();
            if (h.fee == DYNAMIC_FEE_FLAG || h.fee > MAX_LP_FEE) revert BadFee();
            if (h.tickSpacing <= 0 || h.tickSpacing > MAX_TICK_SPACING) revert BadPath();

            address cOut = h.intermediateCurrency;
            // On a nativeEnabled=false chain (Arc) the endpoints are rejected at
            // construction, but an INTERMEDIATE is not — and D5's invariant is
            // "native is for gas only, never a swap asset". Enforce it per hop.
            if (!nativeAllowed && cOut == address(0)) revert NativeDisabled();
            if (cOut == cIn) revert BadPath();
            bool zeroForOne = cIn < cOut;

            PoolKey memory key = PoolKey({
                currency0: zeroForOne ? cIn : cOut,
                currency1: zeroForOne ? cOut : cIn,
                fee: h.fee,
                tickSpacing: h.tickSpacing,
                hooks: address(0)
            });

            // amountSpecified NEGATIVE == exact input (inverted vs v3).
            // sqrtPriceLimit is hardcoded to the extremes on purpose: a "real"
            // limit is not computable from an aggregate minOut, is strictly
            // weaker than the minOut check, and turns a loud failure into a
            // silent partial fill. V4Router itself does exactly this.
            int256 delta = pm.swap(
                key,
                SwapParams({
                    zeroForOne: zeroForOne,
                    amountSpecified: -int256(amt),
                    sqrtPriceLimitX96: zeroForOne ? MIN_SQRT_PRICE + 1 : MAX_SQRT_PRICE - 1
                }),
                bytes("")
            );

            int128 a0 = int128(delta >> 128);
            int128 a1 = int128(delta);
            int128 dIn = zeroForOne ? a0 : a1;   // negative = we owe
            int128 dOut = zeroForOne ? a1 : a0;  // positive = we are owed

            // sign-check BEFORE any cast: uint256(int256(negative)) is an
            // astronomically large number, and -int256(huge) silently flips
            // exact-in to exact-out.
            if (dOut <= 0 || dIn >= 0) revert BadPath();

            // Hop 0's input is the only debt we settle by hand, so it is the
            // only leg whose partial fill would NOT be caught by
            // CurrencyNotSettled. v4 pools UNDER-FILL rather than revert when
            // liquidity runs out, and tolerating that would let the treasury
            // sweep take part of the user's principal. Fail loudly instead.
            if (i == 0 && uint256(uint128(-dIn)) != amountIn) revert PartialFill();

            amt = uint256(uint128(dOut)); // ← the next hop's input, MEASURED
            // Unreachable given `dOut > 0` above. Kept as belt-and-braces, NOT
            // counted as a protection.
            if (amt == 0) revert BadPath();
            cIn = cOut;
        }

        if (cIn != tokenOut) revert BadPath();
        if (amt < minOut) revert TooLittleOut();

        // ONE settle for the single input debt. Every intermediate currency has
        // already netted to zero inside this unlock — settling or taking them
        // per hop would be pure waste and is broken for native intermediates.
        if (tokenIn == address(0)) {
            pm.sync(address(0));
            pm.settle{ value: amountIn }();
        } else {
            pm.sync(tokenIn);                              // MUST precede the transfer
            _safeTransfer(tokenIn, address(pm), amountIn); // USDT-safe, not IERC20.transfer
            pm.settle();                                   // msg.value MUST be 0 here
        }

        // settle BEFORE take, so the recipient's reentrancy window never
        // coincides with an outstanding input debt. take goes straight to the
        // baked recipient — one transfer, and the output never sits in a
        // contract whose sweep could push it to the treasury.
        pm.take(tokenOut, recipient, amt);

        // NEVER call PoolManager.mint / burn / clear here. mint zeroes the delta
        // exactly like take does, so unlock would succeed — but the value would
        // stay inside PoolManager as an ERC-6909 claim owned by an immutable
        // per-swap escrow that has no burn surface. Those funds are
        // unrecoverable, permanently.
        return abi.encode(amt, maxFee);
    }

    /// @notice Refund full `token` balance to the immutable user refund address.
    ///         Operator: any time. Anyone else: only after `refundUnlockAt`.
    function refundToUser(address token) external nonReentrant {
        if (msg.sender != _operator() && block.timestamp < refundUnlockAt) revert RefundLocked();
        uint256 bal = _balanceOf(token);
        if (bal > 0) _safeTransfer(token, userRefund, bal);
        emit RefundedToUser(token, bal);
    }

    /// @notice Refund full native balance to the user (same rules).
    function refundEthToUser() external nonReentrant {
        if (msg.sender != _operator() && block.timestamp < refundUnlockAt) revert RefundLocked();
        uint256 bal = address(this).balance;
        _sendEth(userRefund, bal);
        emit RefundedToUser(address(0), bal);
    }

    /// @notice Sweep remaining `token` balance (stray funds) to the treasury.
    function sweep(address token) external onlyOperator nonReentrant {
        address t = IUniswapV4EscrowFactory(factory).treasury();
        uint256 bal = _balanceOf(token);
        if (bal > 0) _safeTransfer(token, t, bal);
        emit Swept(token, t, bal);
    }

    /// @notice Sweep stray native coin to the treasury.
    function sweepEth() external onlyOperator nonReentrant {
        address t = IUniswapV4EscrowFactory(factory).treasury();
        uint256 bal = address(this).balance;
        _sendEth(t, bal);
        emit Swept(address(0), t, bal);
    }

    receive() external payable {}

    // ─── internal (copied verbatim from UniswapEscrowFactory.sol) ─────────────

    /// @dev USDT-safe ERC20 transfer (no return value required).
    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSelector(0xa9059cbb, to, amount) // transfer(address,uint256)
        );
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
    }

    function _balanceOf(address token) internal view returns (uint256) {
        (bool ok, bytes memory data) = token.staticcall(
            abi.encodeWithSelector(0x70a08231, address(this)) // balanceOf(address)
        );
        require(ok && data.length >= 32, "BALANCE_FAILED");
        return abi.decode(data, (uint256));
    }

    function _sendEth(address to, uint256 amount) internal {
        if (amount == 0) return;
        (bool ok, ) = payable(to).call{ value: amount }("");
        require(ok, "ETH_SEND_FAILED");
    }

    // ─── best-effort variants — used ONLY for the post-swap remainder ─────────
    // Never revert. A refund address the user controls must not be able to
    // block delivery of tokenOut to recipient. Reentrancy from `to` is blocked
    // by the latch on every entrypoint except unlockCallback, which requires
    // msg.sender == poolManager.

    function _trySendEth(address to, uint256 amount) internal returns (bool ok) {
        (ok, ) = payable(to).call{ value: amount }("");
    }

    function _tryTransfer(address token, address to, uint256 amount) internal returns (bool) {
        (bool ok, bytes memory data) = token.call(
            abi.encodeWithSelector(0xa9059cbb, to, amount) // transfer(address,uint256)
        );
        return ok && (data.length == 0 || (data.length >= 32 && abi.decode(data, (bool))));
    }
}

/// @title  UniswapV4EscrowFactory — operator-gated CREATE2 factory for the
///         univ4 venue of the uni_escrow route. One deploy PER CHAIN.
/// @notice Same admin model as UniswapEscrowFactory (owner = cold wallet,
///         2-step transfer; operator = backend hot wallet; treasury = fee sink)
///         and the SAME 5-arg createEscrow/predictEscrow surface, so the
///         backend's FACTORY_ABI and every call site are unchanged.
///         `poolManager` and `nativeEnabled` are IMMUTABLE per chain.
contract UniswapV4EscrowFactory {
    address public owner;          // cold wallet
    address public pendingOwner;   // 2-step ownership transfer
    address public operator;       // backend hot wallet
    address public treasury;       // fee destination
    uint256 public refundTimeout;  // seconds until permissionless user refund

    address public immutable poolManager;  // Uniswap v4 PoolManager on this chain
    bool    public immutable nativeEnabled; // false on chains whose native is an ERC-20 (Arc)

    event EscrowCreated(
        bytes32 indexed salt,
        address indexed escrow,
        address indexed userRefund,
        address recipient,
        address tokenIn,
        address tokenOut
    );
    event OperatorChanged(address indexed oldOperator, address indexed newOperator);
    event TreasuryChanged(address indexed oldTreasury, address indexed newTreasury);
    event RefundTimeoutChanged(uint256 oldTimeout, uint256 newTimeout);
    event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner);
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    error NotOwner();
    error NotOperator();
    error NotPendingOwner();
    error ZeroAddress();
    error TimeoutOutOfRange();
    error SameAsset();
    error NativeNotEnabled();

    uint256 public constant MIN_REFUND_TIMEOUT = 1 hours;
    uint256 public constant MAX_REFUND_TIMEOUT = 30 days;

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyOperator() {
        if (msg.sender != operator) revert NotOperator();
        _;
    }

    constructor(
        address _owner,
        address _operator,
        address _treasury,
        uint256 _refundTimeout,
        address _poolManager,
        bool _nativeEnabled
    ) {
        if (
            _owner == address(0) || _operator == address(0) || _treasury == address(0) ||
            _poolManager == address(0)
        ) revert ZeroAddress();
        if (_refundTimeout < MIN_REFUND_TIMEOUT || _refundTimeout > MAX_REFUND_TIMEOUT) revert TimeoutOutOfRange();
        owner = _owner;
        operator = _operator;
        treasury = _treasury;
        refundTimeout = _refundTimeout;
        poolManager = _poolManager;
        nativeEnabled = _nativeEnabled;
    }

    /// @notice Deploy the escrow for `salt` (= keccak256 of our swap UUID).
    function createEscrow(
        bytes32 salt,
        address userRefund,
        address recipient,
        address tokenIn,
        address tokenOut
    ) external onlyOperator returns (address escrow) {
        escrow = address(new UniswapV4SwapEscrow{ salt: salt }(userRefund, recipient, tokenIn, tokenOut));
        emit EscrowCreated(salt, escrow, userRefund, recipient, tokenIn, tokenOut);
    }

    /// @notice Predict the escrow address WITHOUT deploying (counterfactual).
    function predictEscrow(
        bytes32 salt,
        address userRefund,
        address recipient,
        address tokenIn,
        address tokenOut
    ) external view returns (address) {
        // Mirror the escrow constructor, so the backend can never be handed a
        // deposit address for a swap that createEscrow will then refuse.
        if (userRefund == address(0) || recipient == address(0)) revert ZeroAddress();
        if (tokenIn == tokenOut) revert SameAsset();
        if (!nativeEnabled && (tokenIn == address(0) || tokenOut == address(0))) revert NativeNotEnabled();
        bytes32 initCodeHash = keccak256(
            abi.encodePacked(
                type(UniswapV4SwapEscrow).creationCode,
                abi.encode(userRefund, recipient, tokenIn, tokenOut)
            )
        );
        return address(uint160(uint256(
            keccak256(abi.encodePacked(hex"ff", address(this), salt, initCodeHash))
        )));
    }

    // ─── owner (cold wallet) admin ────────────────────────────────────────────
    function setOperator(address _operator) external onlyOwner {
        if (_operator == address(0)) revert ZeroAddress();
        emit OperatorChanged(operator, _operator);
        operator = _operator;
    }

    function setTreasury(address _treasury) external onlyOwner {
        if (_treasury == address(0)) revert ZeroAddress();
        emit TreasuryChanged(treasury, _treasury);
        treasury = _treasury;
    }

    function setRefundTimeout(uint256 _refundTimeout) external onlyOwner {
        if (_refundTimeout < MIN_REFUND_TIMEOUT || _refundTimeout > MAX_REFUND_TIMEOUT) revert TimeoutOutOfRange();
        emit RefundTimeoutChanged(refundTimeout, _refundTimeout);
        refundTimeout = _refundTimeout;
    }

    function transferOwnership(address _pendingOwner) external onlyOwner {
        if (_pendingOwner == address(0)) revert ZeroAddress();
        pendingOwner = _pendingOwner;
        emit OwnershipTransferStarted(owner, _pendingOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, pendingOwner);
        owner = pendingOwner;
        pendingOwner = address(0);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.