Skip to content
Verified contractExactMIT

UniswapSwapEscrowV4

Address0x5ef984f69ad13b97337ca7a4faf2f83aea64e065
Balance

0 ETH

 

Transactions

0

 

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,078
Creation transaction
0x884a447066…2564954873

contracts/UniswapEscrowFactoryV4.sol

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

import { FactoryGovernance } from "./FactoryGovernance.sol";
import { Clones1167 } from "./Clones1167.sol";

interface IUniswapEscrowFactoryV4 {
    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 router() external view returns (address);
    function weth() external view returns (address);
    function requireApprovals(
        bytes4 action, address token, address target, uint256 amount,
        bytes32 dataHash, uint256 nonce, uint256 deadline, bytes[] calldata approvals
    ) external view;
}

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

/// @dev Uniswap SwapRouter02 exactInput (NO deadline in struct: 02 semantics).
interface IV3SwapRouterV4 {
    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}

/// @title  UniswapSwapEscrowV4: UniswapSwapEscrowV3 with the Hashlock findings fixed.
/// @notice Changes vs V3, by finding:
///         M-02 / L-08: `_swap` measures the input actually pulled by the router and reverts `PartialFill()`
///           unless it equals `amountIn` (SwapRouter02 does not require full consumption on thin pools).
///           The signed `path` blob is now `abi.encode(bytes uniPath, uint256 maxFee)` exactly like the v4
///           venue escrow: the input remainder settles as min(remainder, maxFee) -> treasury, rest -> user
///           (`_settleRemainder`), instead of the whole remainder being treated as fee. `MAX_HOPS` bounds
///           the path on-chain. Multihop: a partial fill on a LATER hop leaves the intermediate
///           token inside the router, where anyone can take it with the public `sweepToken()`; `_swap`
///           snapshots the router's balance of every intermediate token of the signed path and reverts
///           `PartialFill()` if the swap changed it, so no hop can leave value behind.
///         L-04 / Q-13: `minOut` is enforced on what the output recipient actually RECEIVES
///           (balance delta of the recipient for an ERC20 output, of this escrow for a native output or a
///           held output), not on the router's return value; the reported `amountOut` is the received amount.
///         L-02: `amountIn == 0` reverts (SwapRouter02 reads 0 as "swap the router's own balance").
///         L-03 / Q-10: `initialize` rejects the router sentinel recipients address(1) / address(2).
///         Fix review L-05: SwapRouter02 pays any WETH leg from its own native balance when it has one, so value
///           parked in the router by a stranger made the input check (or the intermediate digest) fail on demand.
///           `_swap` now calls the router's `refundETH()` first: whatever was parked lands in this escrow and is
///           settled or refunded here, the stranger forfeits it, and the swap sees the router empty.
///           Input under-consumption reverts `PartialFill()`, a later-hop residue reverts `IntermediateResidue()`.
///         Fix review Q-08: the router, the wrapped native token, the factory, the implementation and the escrow
///           itself are refused as recipient or refund address (output sent there is lost or sweepable by anyone).
///         Fix review Q-25: `swapHold` restarts the refund clock, so a held native output cannot become
///           permissionlessly refundable before the bridge leg is pushed.
///         Fix review Q-32 / Q-35 / Q-40: zero amounts and empty sweeps revert before an approval is consumed, a
///           refund of nothing emits nothing, `heldActive()` exposes the lifecycle.
///         Selectors and approval fields were unchanged by the fix review (the maxFee travels inside the signed
///           dataHash); gen-10 then changed `forwardEth` (new `maxFee` argument, dataHash = keccak256(abi.encode(maxFee))).
///         Gen-10 (external researcher, 2026-10-28; the Q-16 treatment SwapEscrowV7 already had):
///           - `deferredRefund[token]` records a customer refund whose best-effort delivery failed; it is never
///             counted as fee, never swept, and `refundToUser` / `refundEthToUser` deliver and clear it.
///           - `heldAmount` replaces the `_heldActive` flag: the native output parked by `swapHold` is tracked as
///             an amount, excluded from `sweepEth` and from every native fee settlement, consumed by `forwardEth`
///             and returned whole by `refundEthToUser`.
///           - `forwardEth` carries a signed `maxFee` (dataHash = keccak256(abi.encode(maxFee)), capped at the
///             forwarded amount): after the push, min(remaining held, maxFee) goes to the treasury and the rest to
///             `userRefund`, so no held output is ever left for a later sweep.
///         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): the swap input was checked against the raw balance,
///           so a later approved swap covering the whole balance could spend a deferred refund as inventory and
///           leave the mapping stale. `_pullIn` now sizes the swap against the available balance (deferred refund
///           and held output excluded), the same quantity the sweeps and fee settlements already use.
///         Gen-11 (third audit): L-02 `redirectDeferred` is the approval-gated exit for a deferred refund whose address
///           cannot receive it. Q-02 the fee leg of a settlement is best effort (`FeeWaived`: the fee joins the user
///           leg instead of blocking the customer). Q-04 `forwardEth` caps `maxFee` at the held rest, the base the
///           settlement applies it to. Q-05 the escrow itself is refused as forward target. Q-06 `forwardEth` forwards
///           the held output ONCE and settles the rest in the same call; partial forwards are not a supported flow
///           (a second call reverts `NothingHeld`). Q-07 a swap with zero output reverts `TooLittleOut`, and only the
///           first `swapHold` restarts the refund clock.
contract UniswapSwapEscrowV4 {
    address public immutable factory;

    // slot 0: written once by initialize()
    address public userRefund;
    uint64 private _refundUnlockAt;
    bool private _initialized;

    address public recipient;
    address public tokenIn;   // address(0) = native coin
    address public tokenOut;  // address(0) = native coin
    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;

    /// @dev Hard ceiling on signed routes. Off-chain routing goes further (depth-gated, single hop on thin pools).
    uint256 public constant MAX_HOPS = 2;
    /// @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 RefundDeferred(address indexed token, uint256 amount);
    event RefundRedirected(address indexed token, address indexed to, uint256 amount);
    event Swept(address indexed token, address indexed treasury, uint256 amount);
    event FeeWaived(address indexed token, uint256 amount);

    error NotOperator();
    error NotFactory();
    error AlreadyInitialized();
    error RefundLocked();
    error ZeroAddress();
    error SentinelAddress();
    error Reentrancy();
    error SameAsset();
    error Expired();
    error BadPath();
    error TooManyHops();
    error InsufficientDeposit();
    error TooLittleOut();
    error PartialFill();
    error IntermediateResidue();
    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;
    }

    constructor() {
        factory = msg.sender;
        _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();
        address w = IUniswapEscrowFactoryV4(factory).weth();
        if ((_tokenIn == address(0) ? w : _tokenIn) == (_tokenOut == address(0) ? w : _tokenOut)) revert SameAsset();
        _initialized = true;
        userRefund = _userRefund;
        recipient = _recipient;
        tokenIn = _tokenIn;
        tokenOut = _tokenOut;
        _refundUnlockAt = uint64(IUniswapEscrowFactoryV4(factory).creationUnlockAt());
    }

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

    /// @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 IUniswapEscrowFactoryV4(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 {
        IUniswapEscrowFactoryV4(factory).requireApprovals(action, token, target, amount, dataHash, approvalNonce, deadline, approvals);
        approvalNonce++;
    }

    /// @param path abi.encode(bytes uniPath, uint256 maxFee); uniPath = SwapRouter02 packed path.
    function swapForward(
        uint256 amountIn, uint256 minOut, uint256 deadline, bytes calldata path, bytes[] calldata approvals
    ) external onlyOperator nonReentrant returns (uint256 amountOut) {
        if (block.timestamp > deadline) revert Expired();
        if (amountIn == 0) revert InsufficientDeposit();
        address w = IUniswapEscrowFactoryV4(factory).weth();
        address effIn = tokenIn == address(0) ? w : tokenIn;
        (bytes memory uniPath, uint256 maxFee) = _decodePath(path, amountIn, effIn, tokenOut == address(0) ? w : tokenOut);
        _approved(this.swapForward.selector, tokenIn, recipient, amountIn, keccak256(abi.encode(minOut, path)), deadline, approvals);
        _pullIn(w, amountIn);
        amountOut = _swap(effIn, w, uniPath, amountIn, minOut);
        if (amountOut == 0) revert TooLittleOut(); // Q-07: an approval is never spent on a swap that delivers nothing
        _deliver(w, effIn, amountIn, amountOut);
        _settleRemainder(maxFee, true);
    }

    /// @dev Native output: unwrap the WETH the router left here and pay the recipient; ERC20 output was paid by the router.
    function _deliver(address w, address effIn, uint256 amountIn, uint256 amountOut) internal {
        address tOut = tokenOut;
        if (tOut == address(0)) {
            IWETH9V4(w).withdraw(amountOut);
            _sendEth(recipient, amountOut);
        }
        emit SwapForwarded(effIn, tOut == address(0) ? w : tOut, amountIn, amountOut, recipient);
    }

    /// @notice COMBO-OUT step 1: swap tokenIn -> native and HOLD the output.
    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();
        if (block.timestamp > deadline) revert Expired();
        if (amountIn == 0) revert InsufficientDeposit();
        address w = IUniswapEscrowFactoryV4(factory).weth();
        address effIn = tokenIn == address(0) ? w : tokenIn;
        (bytes memory uniPath, uint256 maxFee) = _decodePath(path, amountIn, effIn, w);
        _approved(this.swapHold.selector, tokenIn, address(this), amountIn, keccak256(abi.encode(minOut, path)), deadline, approvals);
        _pullIn(w, amountIn);
        amountOut = _swap(effIn, w, uniPath, amountIn, minOut);
        if (amountOut == 0) revert TooLittleOut(); // Q-07
        IWETH9V4(w).withdraw(amountOut);
        bool firstHold = heldAmount == 0;
        heldAmount += amountOut;
        // the held output waits for the bridge leg; the permissionless refund clock restarts with the FIRST hold only
        // (Q-07), capped like a creation while a loosening is pending, and refused in the cutoff
        if (firstHold) _refundUnlockAt = uint64(IUniswapEscrowFactoryV4(factory).creationUnlockAt());
        emit SwapHeld(effIn, w, amountIn, amountOut);
        _settleRemainder(maxFee, false); // held native output must stay: only an ERC20 input remainder settles
    }

    /// @dev Balance check + WETH wrap of a native deposit. Only the available balance (deferred refund and held
    ///      output excluded) may be swapped: a reserved refund is never inventory for a later swap.
    function _pullIn(address w, uint256 amountIn) internal {
        address tIn = tokenIn;
        if (tIn == address(0)) {
            if (_sweepableNative() < amountIn) revert InsufficientDeposit();
            IWETH9V4(w).deposit{ value: amountIn }();
        } else if (_sweepable(tIn, _balanceOf(tIn)) < amountIn) {
            revert InsufficientDeposit();
        }
    }

    /// @dev Decode the signed blob, bound the fee and validate the packed path (ends, shape, hop count).
    function _decodePath(bytes calldata path, uint256 amountIn, address effIn, address effOut)
        internal pure returns (bytes memory uniPath, uint256 maxFee)
    {
        (uniPath, maxFee) = abi.decode(path, (bytes, uint256));
        if (maxFee > amountIn) revert FeeTooLarge();
        uint256 len = uniPath.length;
        if (len < 43 || (len - 20) % 23 != 0) revert BadPath();
        if ((len - 20) / 23 > MAX_HOPS) revert TooManyHops();
        address first; address last;
        assembly ("memory-safe") {
            first := shr(96, mload(add(uniPath, 0x20)))
            last := shr(96, mload(add(add(uniPath, 0x20), sub(len, 20))))
        }
        if (first != effIn || last != effOut) revert BadPath();
    }

    /// @dev Digest of the router's balances of the tokens strictly between the two ends of the packed path
    ///      (one per extra hop; bytes32(0) for a single hop). Compared before/after the swap: a later-hop partial
    ///      fill is only visible as a change here.
    function _intermediateBalances(bytes memory uniPath, address routerAddr) internal view returns (bytes32 h) {
        uint256 n = (uniPath.length - 20) / 23 - 1;
        for (uint256 i = 0; i < n; i++) {
            uint256 off = 23 * (i + 1);
            address mid;
            assembly ("memory-safe") {
                mid := shr(96, mload(add(add(uniPath, 0x20), off)))
            }
            h = keccak256(abi.encodePacked(h, _balanceOfAt(mid, routerAddr)));
        }
    }

    /// @dev Output side of a swap plus the balances the post-swap checks compare against. A native output (and so
    ///      every swapHold) is paid in WETH to this escrow; an ERC20 output goes straight to the recipient.
    struct SwapSnap { address effOut; address to; uint256 inBefore; uint256 outBefore; bytes32 mids; }

    function _snapshot(address effIn, address w, bytes memory uniPath, address routerAddr)
        internal view returns (SwapSnap memory s)
    {
        address tOut = tokenOut;
        s.effOut = tOut == address(0) ? w : tOut;
        s.to = tOut == address(0) ? address(this) : recipient;
        s.inBefore = _balanceOf(effIn);
        s.outBefore = _balanceOfAt(s.effOut, s.to);
        s.mids = _intermediateBalances(uniPath, routerAddr);
    }

    /// @dev Approve hygiene with the Q-01 token class in mind: a reset to 0 only when an allowance is standing.
    ///      M-02: the input must be fully consumed AND no intermediate token may be left in the router (a later-hop
    ///      partial fill is only visible there). L-04: minOut is checked on what the output side received, which is
    ///      also what is reported. L-05: the router is emptied of parked native value first (see the notice).
    function _swap(address effIn, address w, bytes memory uniPath, uint256 amountIn, uint256 minOut)
        internal returns (uint256 amountOut)
    {
        address routerAddr = IUniswapEscrowFactoryV4(factory).router();
        _drainRouterNative(routerAddr);
        _resetApproveIfNeeded(effIn, routerAddr);
        _approve(effIn, routerAddr, amountIn);
        SwapSnap memory s = _snapshot(effIn, w, uniPath, routerAddr);
        IV3SwapRouterV4(routerAddr).exactInput(
            IV3SwapRouterV4.ExactInputParams({ path: uniPath, recipient: s.to, amountIn: amountIn, amountOutMinimum: minOut })
        );
        if (_balanceOf(effIn) + amountIn != s.inBefore) revert PartialFill(); // also catches input pushed back
        if (_intermediateBalances(uniPath, routerAddr) != s.mids) revert IntermediateResidue(); // later-hop residue in the router
        amountOut = _balanceOfAt(s.effOut, s.to) - s.outBefore;
        if (amountOut < minOut) revert TooLittleOut();
        _resetApproveIfNeeded(effIn, routerAddr); // a full pull leaves 0: nothing to reset
    }

    /// @dev SwapRouter02 `refundETH()` sends the router's whole native balance to the caller. Called before every
    ///      swap so a stranger's parked value cannot make the router pay a WETH leg from its own balance (which
    ///      would leave our input unpulled or an intermediate token behind). Routers without the function, or
    ///      with nothing parked, simply return; the result is deliberately ignored.
    function _drainRouterNative(address routerAddr) internal {
        (bool ok, ) = routerAddr.call(abi.encodeWithSignature("refundETH()"));
        ok; // a failed drain never blocks the swap; the checks below still hold
    }

    /// @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 Input remainder: min(remainder, maxFee) -> treasury (best effort, Q-02: a failed fee leg joins the user
    ///      leg instead of blocking the settlement), rest -> userRefund (best effort, recorded in `deferredRefund`
    ///      when it fails). Native input is settled only when `nativeToo` (swapHold keeps its held native output).
    function _settleRemainder(uint256 maxFee, bool nativeToo) internal {
        address tIn = tokenIn;
        if (tIn == address(0)) {
            if (!nativeToo) return;
            _settleNative(_sweepableNative(), maxFee);
        } else {
            address t = IUniswapEscrowFactoryV4(factory).treasury();
            uint256 rem = _sweepable(tIn, _balanceOf(tIn));
            if (rem == 0) return;
            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 = IUniswapEscrowFactoryV4(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); }
        }
    }

    /// @notice COMBO-OUT step 2: push `amount` of the HELD native balance to `to`, 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, so a later `sweepEth` can only ever take fee the approvers signed. The held output
    ///         is forwarded ONCE (Q-06): the bridge leg is a single push, a second call reverts `NothingHeld`.
    /// @dev dataHash = keccak256(abi.encode(maxFee)); maxFee is capped at the held rest `held - amount` (Q-04), the
    ///      base the settlement applies it to; stray native above the held rest always goes back to the user.
    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: a push to itself would turn held output into fee
        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 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 = IUniswapEscrowFactoryV4(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 = IUniswapEscrowFactoryV4(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 _approve(address token, address spender, uint256 amount) internal {
        if (token.code.length == 0) revert TokenHasNoCode();
        (bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, spender, amount));
        require(ok && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
    }

    /// @dev Q-01: tokens such as legacy BNB revert on approve(0); skip the reset when nothing is approved.
    function _resetApproveIfNeeded(address token, address spender) internal {
        (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0xdd62ed3e, address(this), spender));
        if (ok && data.length >= 32 && abi.decode(data, (uint256)) == 0) return;
        _approve(token, spender, 0);
    }

    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  UniswapEscrowFactoryV4: UniswapEscrowFactoryV3 with FactoryGovernance and the Hashlock fixes.
///         One per chain (Uniswap v3-style SwapRouter02 venues, incl. PancakeSwap on BNB).
/// @notice M-03 / Q-14: `treasury != operator` is enforced by FactoryGovernance (constructor; the treasury is
///         immutable in gen-10). M-05: `predictEscrow` applies the `initialize` preconditions.
///         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 UniswapEscrowFactoryV4 is FactoryGovernance {
    address public immutable router;
    address public immutable weth;
    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 PredictionMismatch();
    error InvalidRecipient();

    constructor(
        address _owner, address _operator, address _treasury, address _guardian, uint256 _refundTimeout,
        address _router, address _weth,
        address[] memory initialApprovers, uint256 _required, uint256 _minRequired
    ) FactoryGovernance(_owner, _operator, _treasury, _guardian, _refundTimeout, initialApprovers, _required, _minRequired) {
        if (_router == address(0) || _weth == address(0)) revert ZeroAddress();
        router = _router;
        weth = _weth;
        implementation = address(new UniswapSwapEscrowV4());
    }

    function _eip712Name() internal pure override returns (string memory) { return "InstaswapUniswapEscrowFactory"; }
    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();
        UniswapSwapEscrowV4(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));
    }

    /// @dev Exactly the `initialize` preconditions, so a predicted address is always deployable (M-05), plus the
    ///      contracts an output or a refund can never be meant for (fix review Q-08: the router keeps nothing
    ///      for anyone, a stranger sweeps it).
    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();
        address w = weth;
        if (_reserved(recipient, w) || _reserved(userRefund, w)) revert InvalidRecipient();
        if ((tokenIn == address(0) ? w : tokenIn) == (tokenOut == address(0) ? w : tokenOut)) revert SameAsset();
        creationUnlockAt(); // LooseningImminent in the last CREATION_CUTOFF before a pending loosening executes
    }

    function _reserved(address a, address w) internal view returns (bool) {
        return a == router || a == w || 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);
    }
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.