Skip to content
Verified contractPartialMIT

BullBearSettlement

Address0xe6869444b8201fc646eee5e918b5715ea116e900
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

Only this contract

 

Details

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

contracts/BullBearSettlement.sol

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

/// @title BullBearSettlement
/// @notice Atomic multi-edge swap settlement with a surplus-based fee. Not upgradeable.
/// @dev Privileged roles (all fixed at deployment, none can be changed afterwards):
///        - No owner and no upgrade path. All configuration is immutable.
///        - GUARDIAN (may be address(0), which removes it): can pause()/unpause() every fund-moving
///          entry point, switch executeWithPermit2 off and on, and call rescue(), which pays ONLY to
///          FEE_RECIPIENT and ONLY the balance no trader is owed. It cannot move user funds.
///        - BENCHMARK_ATTESTOR (a hot signing key): its signature sets the benchmark and quote the fee
///          is computed from, and co-signs the route of a relayed order. A leaked key can raise a fee up
///          to MAX_FEE_BPS_OF_GROSS of the output (and, on a relayed order, only up to the maxFee the
///          user signed); it cannot redirect funds or lower a user's signed minimum.
///        - The AdapterRegistry (a separate contract, see facets) lists the venue adapters the
///          adapter legs may call; its owner changes that list.
///
///      Fee model: the fee is half of the edge BBS showed over the benchmark (the best competing
///      aggregator's output), charged only on the part of that edge the fill itself delivers:
///        fee = min( quote-time edge x SURPLUS_FEE_BPS scaled by the delivery ratio,
///                   (gross - benchmark) x SURPLUS_FEE_BPS,
///                   MAX_FEE_BPS_OF_GROSS of the output ).
///      The fee is ZERO when there is no attestation, when quoted <= benchmark, when the fill
///      does not beat the benchmark, or when the fill came in more than MAX_FEE_DRIFT_BPS under the
///      quote. Whenever a fee is charged the user keeps at least the benchmark output. This is a
///      statement about the fee, not a price guarantee: the user's protection against a bad fill
///      is params.minBuyAmount, enforced on-chain.
///
///      Known limits (documented in docs/ETH_SETTLEMENT_KNOWN_LIMITS_AND_TRUSTED_VENUES_2026_11_03.md):
///        - A missing, expired or invalid attestation means fee 0, never a revert, so a hand-built
///          call can skip the BBS fee; a plan with a maker leg still needs an attestation.
///        - Slippage protection is the caller's floor (minBuyAmount); legs accept the pool price.
///        - Pools are authenticated against trusted factories or an allowlist, but those factories
///          are permissionless: a genuine pool can still quote poor value.
///        - A transfer-taxed token is supported as the buy token (executeFot); as a sell token on
///          V2/V3 legs only if the route supplies a fee factor adjusted for the tax.
///        - Guardian, fee recipient and attestor are fixed at deployment: no rotation, no timelock.
///
///      Protocol adapters (the PROTO_* constants and _executeEdge are the authoritative list):
///        0 = Uniswap V2 direct pool swap (PulseX V1/V2, any V2 fork)
///        1 = Uniswap V3 direct pool swap (9mm / LibertySwap / Uniswap V3)
///        2 = Balancer V2 Vault.swap (PHUX)
///        3 = Curve-style StableSwap pool.exchange (PulseX Stable)
///        4 = Balancer V3 BatchRouter.swapExactIn (TIDE) — via Permit2
///        5 = Uniswap V4 PoolManager swap (canonical V4; a hook is admitted only
///            when its permission bits cannot move the swap amount)
///        6 = Maker (Lite)PSM sellGem/buyGem (fixed-rate gem<->DAI)
///        7 = Balancer V1 standalone BPool swapExactAmountIn
///        8 = DODO V2 DVM/DPP sellBase/sellQuote (prepay pattern)

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
    function approve(address, uint256) external returns (bool);
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
}

// WETH9-style wrapped-native token (WPLS on PulseChain, WETH on Ethereum).
// deposit() credits msg.value 1:1 and sends nothing back. withdraw() PUSHES
// native back to the caller, which is why executeToNative needs the guarded
// receive() below — the only native this contract ever accepts is that push,
// mid-flight, from the wrapper params.buyToken names.
interface IWrappedNative {
    function deposit() external payable;
    function withdraw(uint256 wad) external;
}

interface IUniswapV2Pair {
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
    function token0() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
}

// Registry check, not CREATE2: ask the REAL factory "do you recognize this
// pair as yours" instead of recomputing an address from an init-code hash.
// Works identically across every V2 fork regardless of tiny bytecode/init-
// hash differences between forks, and self-verifies against the live chain
// state rather than a value baked in at compile time.
interface IUniswapV2Factory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

// Direct pool interface for ANY Uniswap-V3-style DEX. The swap() + token0/1
// signatures are identical across 9mm (Pancake fork), LibertySwap, and Uniswap
// V3 on PulseChain (verified on-chain); only the swap-callback NAME differs,
// which is why the adapter implements all three (see uniswap/pancake/liberty
// V3SwapCallback below). This replaces the single per-DEX router.
interface IUniswapV3Pool {
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);
}

// Registry check for V3-shaped pools, same reasoning as IUniswapV2Factory:
// ask the real factory whether it deployed this exact (token0, token1, fee)
// combination, rather than trusting the pool address from calldata.
interface IUniswapV3Factory {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

interface IBalancerVault {
    enum SwapKind { GIVEN_IN, GIVEN_OUT }
    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        address assetIn;
        address assetOut;
        uint256 amount;
        bytes userData;
    }
    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }
    function swap(
        SingleSwap memory singleSwap,
        FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256);
}

interface IStableSwap {
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);
}

// Maker (Lite)PSM — fixed-rate USDC<->DAI. Chain-verified 2026-08-16 on the
// live LitePSM 0xf6e72Db5 (gem=USDC, tin=tout=0, to18ConversionFactor=1e12,
// sellGem 0x95991276 / buyGem 0x8d7ef9bb present). sellGem pulls the gem and
// mints DAI to usr; buyGem pulls DAI and sends gemAmt of gem — NOTE buyGem's
// argument is the OUTPUT amount, so the adapter solves gemAmt from the DAI
// input using the contract's own tout/conversion factor.
interface IMakerPsm {
    function gem() external view returns (address);
    function tout() external view returns (uint256);
    function to18ConversionFactor() external view returns (uint256);
    function sellGem(address usr, uint256 gemAmt) external returns (uint256 daiOutWad);
    function buyGem(address usr, uint256 gemAmt) external returns (uint256 daiInWad);
}

// Balancer V1 — STANDALONE weighted pools (no vault). Chain-verified:
// swapExactAmountIn 0x8201aa3f present on the live pools. The pool pulls
// tokenIn via allowance; maxPrice at uint-max defers the user's protection
// to the final net floor (single-final-floor design).
interface IBalancerV1Pool {
    function swapExactAmountIn(
        address tokenIn, uint256 tokenAmountIn, address tokenOut,
        uint256 minAmountOut, uint256 maxPrice
    ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
}

// DODO V2 (DVM/DPP) — prepay pattern like a V2 pair: transfer the input to
// the pool, THEN call sellBase/sellQuote(to). Pools are clone proxies, so
// selector presence was verified by DISPATCH (eth_call answers), not
// bytecode grep.
interface IDodoV2Pool {
    function sellBase(address to) external returns (uint256 receiveQuoteAmount);
    function sellQuote(address to) external returns (uint256 receiveBaseAmount);
}

// Balancer V3 (TIDE on PulseChain) does NOT let a caller approve the router
// and have it pull directly — it pulls tokenIn through a Permit2 intermediary.
// On PulseChain that Permit2 is deployed at a NON-canonical address (from the
// BatchRouter's own getPermit2()), so it is an immutable, never taken from
// calldata. approve() OVERWRITES (does not increment) and its transferFrom
// decrements the allowance, so an exact per-leg approval is self-clearing.
interface IPermit2 {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
}

// Permit2 SignatureTransfer (canonical 0x000000000022D473030F116dDEE9F6B43aC78BA3 on
// Ethereum and Sepolia). The relayed path pulls the sell token with ONE user
// signature whose witness is the RelayedOrder, so the same signature that moves
// the tokens binds every order field. Interface shape = Permit2's own.
interface IPermit2SignatureTransfer {
    struct TokenPermissions { address token; uint256 amount; }
    struct PermitTransferFrom { TokenPermissions permitted; uint256 nonce; uint256 deadline; }
    struct SignatureTransferDetails { address to; uint256 requestedAmount; }
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;
    /// @dev The plain (non-witness) SignatureTransfer variant — used by
    ///      executeWithPermit2 below, where no separate witness/route
    ///      attestation is needed (the signer submits their own transaction,
    ///      so there is no third party to attest a route against).
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;
}

// Balancer V3 BatchRouter (verified source on PulseChain). Interface is the
// canonical V3 shape; the ONLY PulseChain deviation is the Permit2 address
// above. Each BBS edge is ONE pool swap = a one-step path. isBuffer is NOT
// hardcoded false: it is computed per-call from `pool == tokenIn || pool ==
// tokenOut` (see the call site below) so boosted-pool routes can move the raw
// underlying through an ERC4626 buffer step — a deliberate, later change from
// this interface's original hardcoded-false posture; see the call site's own
// comment for why the detection has no false positives. Output is delivered
// to msg.sender (this contract) and measured by balanceOf delta, so a thin
// fill is caught by the final params.minBuyAmount, never trusted from the
// return value.
interface IBalancerV3BatchRouter {
    struct SwapPathStep {
        address pool;
        address tokenOut;
        bool isBuffer;
    }
    struct SwapPathExactAmountIn {
        address tokenIn;
        SwapPathStep[] steps;
        uint256 exactAmountIn;
        uint256 minAmountOut;
    }
    function swapExactIn(
        SwapPathExactAmountIn[] calldata paths,
        uint256 deadline,
        bool wethIsEth,
        bytes calldata userData
    ) external payable returns (uint256[] memory pathAmountsOut, address[] memory tokensOut, uint256[] memory amountsOut);
}

// Fluid DEX Lite (Instadapp) — singleton at 0xBbcb9144…6e00; pools keyed by
// DexKey{token0,token1,salt} (token0 < token1 numerically). Chain-verified
// 2026-08-17: resolver estimateSwapSingle matches Kyber's live hop to
// −0.003%. Non-callback swapSingle pulls tokenIn via allowance; positive
// amountSpecified = exact input; returns the output amount.
interface IFluidDexLite {
    struct DexKey {
        address token0;
        address token1;
        bytes32 salt;
    }
    function swapSingle(
        DexKey calldata dexKey, bool swap0To1, int256 amountSpecified,
        uint256 amountLimit, address to, bool isCallback,
        bytes calldata callbackData, bytes calldata extraData
    ) external payable returns (uint256 amountUnspecified);
}

// Uniswap V4 PoolManager (canonical singleton; Ethereum mainnet
// 0x000000000004444c5dc75cB358380D2e3dE08A90). Every V4 pool lives INSIDE
// this one contract, addressed by its PoolKey — there is no per-pool address.
// Exact-input flow: unlock() -> the manager calls unlockCallback() back on
// this contract -> swap() returns a packed BalanceDelta (int128 amount0 in
// the upper bits, int128 amount1 in the lower; positive = this contract is
// owed) -> the input is paid via sync()+transfer+settle(), the output
// withdrawn via take(). BalanceDelta and Currency are user-defined value
// types in v4-core; their ABI IS the underlying type (int256 / address),
// which is how they are declared here.
interface IUniV4PoolManager {
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }
    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;   // NEGATIVE = exact input (v4 sign convention)
        uint160 sqrtPriceLimitX96;
    }
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external returns (int256 swapDelta);
    function sync(address currency) external;
    function settle() external payable returns (uint256 paid);
    function take(address currency, address to, uint256 amount) external;
}

// Ekubo V3 router periphery (Ethereum mainnet MEVCaptureRouter
// 0xd26f20001a72a18C002b00e6710000d68700ce00). Pools live inside the Ekubo
// Core singleton, addressed by PoolKey{token0, token1, config} where config
// is a packed bytes32 (extension | fee | tick config) and native ETH is
// address(0), always token0. SwapParameters and PoolBalanceUpdate are
// user-defined value types over bytes32 — declared as bytes32 here so the
// selector matches swap((address,address,bytes32),bytes32,int256,address).
// The router pulls ERC20 input via transferFrom(swapper -> Core), so the
// allowance is granted TO THE ROUTER; output is delivered from Core.
// Hashflow RFQ-T (2026-09-16): a market maker's SIGNED quote settled through
// Hashflow's router. The router pulls baseToken via transferFrom(trader) and
// pays quoteToken to trader; it checks the maker's signature over every
// field, the expiry, the nonce, and that msg.sender == trader. Pro-rata:
// effectiveBaseTokenAmount <= baseTokenAmount fills proportionally.
// Mainnet router 0x55084eE0fEf03f14a305cd24286359A35D735151 (selector
// c52ac720 verified in its bytecode). ERC20 legs only (native is not used).

// Delegatecall target for the Ekubo adapter (contracts/EkuboSwapFacet.sol,
// docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md). Only the selector/shape
// needed to encode the delegatecall — the real implementation lives in the
// facet's own file, never imported (this codebase never uses `import`;
// every interface is declared inline, matching every interface above).
interface IEkuboSwapFacet {
    function ekuboSwap(
        address ekuboRouter,
        address ekuboCore,
        address wrappedNative,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) external;
}

interface IUniV4SwapFacet {
    function univ4Swap(
        address manager,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) external;
    function univ4UnlockCallback(address manager, address wrappedNative, bytes calldata data)
        external returns (bytes memory);
}

// Delegatecall target for EVERY external venue leg (contracts/VenueHubFacet.sol, 2026-10-17):
// Hashflow RFQ-T (12), Bebop RFQ (13), PropAMM Router (14). Only the selectors needed to encode the
// delegatecall, as for the two facets above.
interface IAdapterRegistry {
    function kindOf(address adapter) external view returns (uint8);
}

interface IVenueHubFacet {
    function hashflowSwap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, bytes calldata extraData, uint256 index) external payable;
    function bebopSwap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, bytes calldata extraData, uint256 index) external payable;
    function propAmmSwap(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, bytes calldata extraData, uint256 index) external payable;
    function venueCall(address tokenIn, address tokenOut, uint256 amountIn, uint256 minAmountOut, bytes calldata extraData, uint256 index) external payable;
    function HASHFLOW_ROUTER() external view returns (address);
}

// Ringswap fw-wrapper token (FEG's exploit-era V2 fork). Pairs hold
// fw-WRAPPED tokens, 1:1 with the underlying numerically (chain-verified
// 2026-08-13). Interface extracted from the deployed fwWETH bytecode
// dispatcher (0xa250cc72...): wrap(uint256) 0xea598cb0 pulls the
// underlying via transferFrom (allowance to the fw contract) and mints fw
// 1:1; unwrap(uint256) 0xde0e9a3e burns fw and sends the underlying —
// REVERTING when the fw contract's underlying balance cannot cover it,
// which IS the venue's real capacity domain (fw tokens are massively
// unbacked: fwSNX 22%, fwWETH 1.2% — the quote side refuses beyond
// capacity and execution fail-closes on the same boundary here).
// token() names the underlying, used to cross-check calldata on-chain.
interface IFwToken {
    function wrap(uint256 amount) external;
    function unwrap(uint256 amount) external;
    function token() external view returns (address);
}

contract BullBearSettlement {
    // --- Protocol identifiers ---
    uint8 public constant PROTO_V2_DIRECT   = 0;
    uint8 public constant PROTO_V3_ROUTER   = 1;
    uint8 public constant PROTO_BALANCER    = 2;
    uint8 public constant PROTO_STABLE      = 3;
    uint8 public constant PROTO_BALANCER_V3 = 4;
    uint8 public constant PROTO_UNIV4      = 5;
    uint8 internal constant PROTO_PSM        = 6;
    uint8 public constant PROTO_EKUBO      = 10;
    uint8 public constant PROTO_HASHFLOW   = 12;
    // Bebop RFQ as a settlement leg (2026-10-12): delegatecalled into contracts/
    // BebopSwapFacet.sol (facets_ slot 2). The whole-trade path keeps the standalone
    // BebopHelper; this id is the maker leg beside AMM legs in one plan.
    uint8 public constant PROTO_BEBOP      = 13;
    // PropAMM Router as a settlement leg (2026-10-17): delegatecalled into contracts/VenueHubFacet.sol
    // (facets_ slot 2) with PROTO 12 and 13. No signed order: the router prices at execution.
    uint8 public constant PROTO_PROPAMM    = 14;
    // Registry-gated generic venue call (2026-10-21, hub V2): delegatecalled into VenueHubFacetV2.venueCall (the same facets_ slot 2).
    // Treated as a MAKER-CLASS leg (RT70-M1): a venue listed later may be stateful, so on the wallet path it runs only under the same
    // v2 benchmark attestation as Hashflow/Bebop, and executeFot / executeHopFromHelper refuse it by name.
    uint8 public constant PROTO_VENUE_CALL = 15;
    // Hub V3 (2026-10-22, Kyber's shape): a leg executed by an ADAPTER the owner listed in the AdapterRegistry (usable at once, no delay). 16 = PLAIN adapter
    // (an AMM-like venue priced on chain), 17 = MAKER adapter (priced per user; runs only under the route attestation, exactly like 12/13/15).
    // The registry's kind and the protocol number must agree. Per leg: listed? -> hand over the input (transfer to the adapter, or approve) -> call -> output floor
    // -> revoke the approval (Kyber's swapGeneric flow). The adapter's own checks decide which pools it accepts.
    uint8 public constant PROTO_ADAPTER = 16;
    uint8 public constant PROTO_ADAPTER_MAKER = 17;
    // Bebop RFQ (PMM) is NOT settled in this contract. It executes through the
    // standalone BebopHelper (contracts/BebopHelper.sol) which the server routes a
    // whole-trade Bebop win to directly -- so no Bebop adapter logic lives here
    // (RT17-A1: keeps the settlement under the EIP-170 24,576-byte limit).

    // --- Fee configuration ---
    /// @notice Fee in basis points charged on surplus above benchmark.
    ///         5000 = 50% of surplus. Immutable.
    uint256 public immutable SURPLUS_FEE_BPS;

    /// @notice Fee denominator (10000 = 100%).
    uint256 public constant FEE_BPS_DENOMINATOR = 10000;

    /// @notice Hard ceiling on the fee as a fraction of GROSS output, bps.
    ///         The surplus formula alone is only as honest as the caller's
    ///         `benchmarkOutput`: an audit proved a server passing
    ///         benchmarkOutput = 0 could take 50% of the user's output as
    ///         "surplus". This ceiling is the layer that survives a
    ///         compromised or buggy quoting key — no signature, no config,
    ///         no upgrade path can lift it, because the check is against
    ///         gross output, not against anything the caller supplies.
    ///         SIZED FROM MEASUREMENT, not intuition. Campaign data, 1,837
    ///         honestly-scored wins (guard-flagged rows excluded): BBS's
    ///         surplus over the best rival is p50 0.50%, p95 8.41%, p99
    ///         9.68%, max 9.97% — so a legitimate 50%-of-surplus fee is
    ///         p50 25 bps, p99 441 bps, max 453 bps of gross. A first draft
    ///         set this to 30 bps and the EVM gate caught it capping an
    ///         HONEST fee (an 8x under-charge): the ceiling must sit above
    ///         the legitimate distribution or it silently rewrites the fee
    ///         model. The figures above are the PulseChain campaign. On
    ///         Ethereum the 36 fees actually paid (41 settlements, two
    ///         deployments) were median 3.6 bps, p90 16 bps, max 21.4 bps of
    ///         gross; 50 bps is ~2.3x that maximum: room for corridors better
    ///         than anything yet observed, while bounding the audit's exploit
    ///         (benchmarkOutput = 0 => 50% of the user's output) to <= 0.5%.
    ///         Immutable, unconditional, and
    ///         checked against GROSS — a number the caller cannot inflate
    ///         because it is measured by balanceOf after the swaps.
    ///         Re-derive if the surplus distribution ever shifts up.
    uint256 public constant MAX_FEE_BPS_OF_GROSS = 50;

    /// @notice How far the DELIVERED amount may fall short of the quoted one
    ///         and still be charged a fee. 100 bps = 1%.
    /// @dev    The fee is the quote-time edge applied to the delivered amount,
    ///         so it survives ordinary quote-to-execution drift — which is the
    ///         point. But "ordinary" has a limit: measured on live swaps, drift
    ///         is a few bps on liquid pairs and reached -5% to -9.8% on thin
    ///         PulseChain tokens (swaps 50, 56, 104). Charging a fee on a trade
    ///         that delivered a tenth less than the screen promised is
    ///         indefensible however good the routing was, so outside this
    ///         window the fee is zero. Deliberately a CONSTANT, not a
    ///         constructor argument: it is a user protection, and a deployment
    ///         must not be able to widen it.
    uint256 public constant MAX_FEE_DRIFT_BPS = 100;

    /// @notice Uniswap V4 hook permissions live in the LOW 14 BITS OF THE HOOK
    ///         ADDRESS (v4-core Hooks.sol, ALL_HOOK_MASK = (1 << 14) - 1). Of
    ///         the fourteen, exactly two let a hook change the swap AMOUNT:
    ///             BEFORE_SWAP_RETURNS_DELTA = 1 << 3
    ///             AFTER_SWAP_RETURNS_DELTA  = 1 << 2
    ///         Every other bit observes, gates or reverts, but cannot move the
    ///         number tick math produced - so a quote priced off tick math is
    ///         still honest for those pools. This mirrors the router's own
    ///         V4_HOOK_AMOUNT_CHANGING, and the two must never drift: the
    ///         pricer admitting a pool this contract then refuses is exactly
    ///         the split that made 3,646 provably-safe hooked pools
    ///         unreachable (measured over 123,799 V4 pools: 29,798 hooked,
    ///         26,152 amount-changing, 2.5% of swap flow excluded for nothing).
    uint160 public constant UNIV4_HOOK_AMOUNT_CHANGING = (1 << 3) | (1 << 2);

    // --- Benchmark attestation (EIP-712) ---
    /// @notice Signer whose attestation authorises a non-zero fee.
    ///         address(0) = attestation disabled (fee then relies solely on
    ///         the MAX_FEE_BPS_OF_GROSS ceiling). Immutable.
    address public immutable BENCHMARK_ATTESTOR;

    /// @notice Longest the contract will honour a benchmark attestation ahead
    ///         of the current block, in seconds. The attestation carries no
    ///         nonce, so one signature is otherwise replayable across every
    ///         identical-size trade of the same pair until its signed deadline.
    ///         This cap bounds that replay to at most MAX_ATTESTATION_WINDOW:
    ///         an attestation is honoured only while
    ///           deadline - MAX_ATTESTATION_WINDOW <= block.timestamp <= deadline,
    ///         so a signature with a far-future (buggy or malicious) deadline is
    ///         NOT usable now — only in the short window just before that
    ///         deadline. SIZED from the design's own horizon: the swap deadline
    ///         is 2-3 blocks (~20-30s on PulseChain) because "a longer deadline
    ///         is pure attacker option value" (execution_pillar_design 1b). The
    ///         attestation must additionally tolerate the human quote->sign->land
    ///         gap a submit-time swap deadline does not, so it is set an order of
    ///         magnitude looser at 300s — still short, and FAIL-SAFE: exceeding
    ///         it only drops the fee to ZERO (pro-user), it never reverts a
    ///         swap. A stale/replayed benchmark is in any case bounded by the
    ///         MAX_FEE_BPS_OF_GROSS ceiling; this window is defence in depth on
    ///         top of that. Hardcoded like the fee ceiling: no config lifts it.
    uint256 public constant MAX_ATTESTATION_WINDOW = 300;

    /// @dev RECIPIENT-DELIVERY FLOOR TOLERANCE (2026-10-02 follow-up). The floor
    ///      in `_distribute` compares what the recipient actually received
    ///      against `netOutput` to catch a buy token that taxes the custody ->
    ///      user transfer. Some tokens are not a tax, just unavoidable wei-level
    ///      rounding from internal share accounting: a fresh fork measurement
    ///      against REAL stETH (`0xae7ab96...`, 10 amounts from 0.001 to 10,000
    ///      ETH-equivalent, see MeasureStethTransferRounding_2026_10_02.t.sol)
    ///      found a single `transfer()` call rounds down by at most 2 wei. This
    ///      constant is set to 4x that measured maximum, and applies to EVERY
    ///      buy token uniformly -- not a stETH-specific carve-out, because any
    ///      other share-based/rebasing token would hit the exact same shape.
    ///      It cannot mask a real fee-on-transfer attack: those cost basis
    ///      points of the output at any trade size large enough to matter,
    ///      which dwarfs a single-digit-wei tolerance by many orders of
    ///      magnitude. The worst case this constant can ever hide is bounded
    ///      by its own value -- economically negligible at any real size.
    uint256 public constant RECIPIENT_DELIVERY_WEI_TOLERANCE = 8;

    bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(
        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    /// @dev v2 (RT48-F1, 2026-10-12): the attestation also binds `edgesHash` (keccak256 of the edges
    ///      being executed) and `owner` (who funds the trade: msg.sender on the wallet paths, the
    ///      RelayedOrder owner on the relayed path). A maker-signed order (Hashflow PROTO 12, Bebop
    ///      PROTO 13) is bound to THIS contract as taker and execute() is permissionless, so without
    ///      this anyone who saw the order bytes in the mempool could run them through their own
    ///      execute() with dust of their own and burn the user's nonce. A plan with a maker leg now
    ///      executes on a wallet path only under an attestation the server signed for THESE edges and
    ///      THIS sender (_settle, MakerLegNotAttested); the fee rule is unchanged (a zero-fee plan is
    ///      signed with quotedOutput <= benchmarkOutput, which _calculateSurplusFee answers 0).
    ///      v4 (SolidProof L2, 2026-11; "v3" is the referral program's typehash on another branch): also binds `recipient`, so an attestation made for one
    ///      destination cannot be reused for another inside its window (the window itself, the owner and
    ///      the edges were already bound; a nonce was left out on purpose, see _benchmarkAttested).
    bytes32 public constant BENCHMARK_TYPEHASH = keccak256(
        "Benchmark(address sellToken,address buyToken,uint256 sellAmount,uint256 benchmarkOutput,uint256 quotedOutput,uint256 deadline,bytes32 edgesHash,address owner,address recipient)");

    /// @notice Address that receives surplus fees. Immutable.
    ///         Set once at deployment, never changed.
    address public immutable FEE_RECIPIENT;

    // POOL AUTHENTICATION (2026-09-14, bounty report). edge.pool used to be
    // trusted as given for every V2-shaped leg — a caller-supplied contract
    // that keeps whatever _safeTransfer pushes to it and returns nothing.
    // Set ONCE in the constructor from the same factory addresses the
    // off-chain routing engine already treats as trusted (config/mainnet_
    // amm_provider_registry.*.json), never writable again — same immutable-
    // by-design posture as everything else here, just as a storage array
    // since Solidity's `immutable` keyword doesn't support arrays.
    address[] public trustedV2Factories;
    address[] public trustedV3Factories;
    // STABLE pools have no universal permissionless-deployment factory to
    // check against (Curve forks span multiple factory types, and many
    // PulseChain-era stable pools are hand-deployed) — a direct allowlist
    // of the exact, already on-chain-verified pool addresses the off-chain
    // routing engine trusts (config/mainnet_amm_provider_registry.*.json,
    // each with source_proof.status "pool_verified_on_chain") is the
    // practical anchor here, same conclusion an earlier audit reached.
    address[] public trustedStablePools;
    /// @dev O(1) form of trustedStablePools for the per-leg check: with the
    ///      widened Ethereum list (every Curve pool whose exchange() was
    ///      fork-proven to deliver its get_dy, 2026-09-16) a linear scan
    ///      would cost ~2.1k gas per entry per stable leg.
    mapping(address => bool) private _isTrustedStablePool;

    // COMPOSED-HOP CALLERS (2026-10-07, draft -- see
    // docs/PROPAMM_COMPOSED_HOP_DESIGN_2026_10_07.md). PropAmmHelper/
    // BebopHelper/HashflowHelper are STANDALONE contracts (kept out of this
    // file's own bytecode to stay under EIP-170, same reason as their own
    // doc comments) that each do ONE whole-trade venue call and deliver
    // straight to the user -- there was previously no way for any of them
    // to be hop 1 of a multi-hop route, because composing hop 2 needs this
    // contract's own trusted-pool-authenticated PROTO dispatch, and nothing
    // exposed that to an external caller. executeHopFromHelper (below) is
    // that exposure: a narrow, allowlisted entrypoint that pulls a caller's
    // own tokens, runs ONE edge through the exact same _executeEdge every
    // other entry point already uses, and hands the result back to the
    // caller -- no recipient, no fee, no end-user floor logic here, so the
    // calling helper's EXISTING relayer-refund/floor/delivery logic is
    // completely unchanged in shape, just operating on a hop-2 amount
    // instead of hop 1's. Same immutable-after-construction posture as
    // trustedV2Factories/trustedV3Factories/trustedStablePools above -- this
    // allowlist is PRIVILEGE (access to authenticated-pool dispatch), not a
    // fund-safety boundary by itself, but it is set once and never writable,
    // matching this contract's whole ownerless/immutable trust model.
    address[] public trustedHopCallers;
    mapping(address => bool) private _isTrustedHopCaller;

    // EMERGENCY PAUSE (2026-09-14). The single biggest operational lesson of
    // tonight: three live-fund-theft bugs were found and NOTHING could stop
    // real traffic from reaching them while a fix was being built and
    // reviewed — the contract was fully ownerless and immutable, by design,
    // with no way to react. GUARDIAN's power is deliberately narrow and
    // exhaustively enumerated: it can flip `paused`, and NOTHING else. It
    // cannot move funds, change FEE_RECIPIENT, change the trusted pool
    // lists, upgrade anything, or touch a single line of routing logic —
    // every other function in this file is completely unaffected by who
    // GUARDIAN is. Set to address(0) at deploy for a deployment that wants
    // to stay exactly as ownerless/immutable as before this commit; pause()
    // and unpause() both revert unconditionally in that case, forever.
    address public immutable GUARDIAN;
    bool public paused;

    // SCOPED KILL SWITCH for executeWithPermit2 ONLY (round-10 red team,
    // RT10-A-1, 2026-09-17). Before this, executeWithPermit2 and
    // executeRelayed/executeRelayedToNative shared exactly one gate --
    // RELAY_PERMIT2 == address(0) -- despite having different trust models
    // (self-directed vs. third-party-submitted/attestor-gated), so an
    // operator could not disable the self-directed path alone without also
    // killing the relayer's Permit2 pull. Same GUARDIAN-only,
    // no-op-forever-at-address(0) pattern as pause()/unpause(); does NOT
    // touch RELAY_PERMIT2 or executeRelayed's own gates.
    bool public permit2DirectPaused;

    modifier whenNotPaused() {
        if (paused) revert ContractPaused();
        _;
    }

    /// @dev The GUARDIAN-only, no-op-forever-at-address(0) access check
    ///      pause()/unpause()/setPermit2DirectPaused() all share verbatim.
    ///      Was three copies of the same `if` (RT10 EIP-170 trim pass,
    ///      2026-09-17) -- one modifier so the check exists in the runtime
    ///      bytecode once, not three times.
    modifier onlyGuardian() {
        if (msg.sender != GUARDIAN || GUARDIAN == address(0)) revert NotGuardian();
        _;
    }

    // --- Router configuration ---
    // V3 legs swap directly against edge.pool (any V3 DEX); no per-DEX router exists.
    // The first constructor argument is a retained, ignored placeholder (SolidProof I8):
    // it keeps the constructor ABI, and so every deploy path, unchanged. Pass address(0).
    address public immutable BALANCER_VAULT;

    // Balancer V3 (TIDE). The BatchRouter that executes swapExactIn, and the
    // Permit2 it pulls tokenIn through. BOTH are immutable — a Balancer-V3 leg
    // never calls an address supplied in calldata; only edge.pool comes from
    // calldata, and the Vault validates it (an unregistered pool reverts
    // atomically). address(0) on either disables the Balancer-V3 path (a leg
    // with protocol 4 then reverts, with empty revert data — the builder never
    // emits protocol 4 for a chain without TIDE, so this only bites
    // misconfiguration).
    address public immutable BALANCER_V3_ROUTER;
    address public immutable BALANCER_V3_PERMIT2;

    // Uniswap V4 PoolManager singleton. address(0) on chains without
    // canonical V4 (PulseChain) — a PROTO_UNIV4 leg then reverts rather than
    // calling the zero address; the calldata builder never emits protocol 5
    // unless the deployment carries the manager, so this only bites
    // misconfiguration.
    address public immutable UNIV4_POOL_MANAGER;

    // Ekubo V3: the deployed router periphery this contract swaps through,
    // and the Core singleton behind it. CORE is stored because a native-out
    // Ekubo swap is a raw ETH push FROM CORE (its accountant withdraw), and
    // the guarded receive() only accepts native from the address armed in
    // NATIVE_UNWRAP_SLOT. address(0) disables the Ekubo path entirely.
    address public immutable EKUBO_ROUTER;

    // --- Relayed execution (design: docs/RELAYED_EXECUTION_DESIGN.md) ---
    /// @notice Permit2 the relayed path (and executeWithPermit2) pulls the
    ///         sell token through. address(0) = BOTH relayed execution AND
    ///         executeWithPermit2 disabled on this deployment -- this one
    ///         immutable is a shared prerequisite for both entry points, not
    ///         a per-path switch. To disable executeWithPermit2 ALONE while
    ///         keeping executeRelayed live, use the separate
    ///         permit2DirectPaused / setPermit2DirectPaused() switch below
    ///         instead (RT10-A-1, 2026-09-17); RELAY_PERMIT2==0 remains the
    ///         only way to kill both paths at once (or executeRelayed alone,
    ///         via BENCHMARK_ATTESTOR==0).
    address public immutable RELAY_PERMIT2;
    /// @dev The order the user signs as the Permit2 witness. No nonce and no
    ///      deadline of its own: Permit2's unordered nonce bitmap makes the
    ///      signature single-use and Permit2's deadline bounds it in time.
    struct RelayedOrder {
        address owner;            // signer; tokens leave this account
        address recipient;        // who receives the buy output (may be a contract, e.g. a smart-account owner)
        address sellToken;
        address buyToken;
        uint256 sellAmount;
        uint256 minBuyAmount;     // NET to the user after fee AND relayer refund
        uint256 maxRelayerRefund; // cap on what the relayer may take, in buyToken
        address relayer;          // who may submit (and take the refund); address(0) = anyone
        uint256 maxFee;           // SolidProof L2: cap on the BBS fee, in buyToken; the signed benchmark numbers must not be able to exceed it
        bool nativeOut;           // SolidProof L5: the user signed for native (true) or wrapped (false) delivery
    }
    // `relayer` is SIGNED: the first mainnet fill (2026-09-06) was submitted by a
    // searcher who copied the order out of a private-relay hint and took the
    // refund, because the entry was open to any caller. A bound submitter makes
    // a copied signature worthless to anyone else.
    bytes32 private constant RELAYED_ORDER_TYPEHASH = keccak256(
        "RelayedOrder(address owner,address recipient,address sellToken,address buyToken,uint256 sellAmount,uint256 minBuyAmount,uint256 maxRelayerRefund,address relayer,uint256 maxFee,bool nativeOut)");
    /// @dev Permit2 witness type string: the tail of the PermitWitnessTransferFrom
    ///      type, "<Witness> witness)" + the witness struct + TokenPermissions.
    ///      Off-chain signers hardcode this exact string (src/iq_defi/relayer.py);
    ///      it is not read on-chain, so no public getter is emitted.
    string private constant RELAYED_WITNESS_TYPE =
        "RelayedOrder witness)RelayedOrder(address owner,address recipient,address sellToken,address buyToken,uint256 sellAmount,uint256 minBuyAmount,uint256 maxRelayerRefund,address relayer,uint256 maxFee,bool nativeOut)TokenPermissions(address token,uint256 amount)";
    /// @dev The route (the `edges` array) is NOT part of what the user signs —
    ///      the user signs the ORDER (what goes in, the floor, where it lands),
    ///      not the venues. The relayer is trusted to submit but MUST NOT be
    ///      trusted to choose the route: a compromised relayer could otherwise
    ///      substitute an edge set that drains the whole slippage budget through
    ///      a pool it controls (2026-09-09, HIGH). So the route is
    ///      co-signed by BENCHMARK_ATTESTOR — the same off-chain key that
    ///      attests the fee benchmark, but a DIFFERENT key from the hot relayer
    ///      wallet that broadcasts. Route substitution now needs BOTH keys.
    ///      Bound: the order hash (this exact order), the edges hash (this exact
    ///      route), and the Permit2 nonce + deadline (single-use, time-bounded —
    ///      the nonce Permit2 consumes makes the attestation single-use too).
    bytes32 private constant RELAYED_ROUTE_TYPEHASH = keccak256(
        "RelayedRoute(bytes32 orderHash,bytes32 edgesHash,uint256 permitNonce,uint256 deadline)");
    /// @dev Set for the duration of one relayed settlement: who funded it and
    ///      what the relayer takes. Read by _distribute / _refundLeftover so the
    ///      shared body stays byte-identical for the wallet-sent paths.
    address private _relayOwner;
    uint256 private _relayRefund;
    /// @dev token => the trader a FAILED residue refund is owed to. Set only when
    ///      `_refundLeftover`'s best-effort transfer back to the funder is blocked
    ///      (a token that reverts/false-returns on transfer to that trader, e.g. an
    ///      admin blacklist). `sweep()` then pays this recorded owner instead of an
    ///      arbitrary caller, so a permissionless sweep can never hand a specific
    ///      user's stranded positive-slippage residue to a third party (M-01).
    ///      A sweep to a still-blocked owner reverts — griefed, never
    ///      stolen; it clears once the transfer can land.
    ///      RT3-01 (red team round 3, 2026-09-16): keyed by token AND trader,
    ///      with the amount, so a later blocked refund can never overwrite an
    ///      earlier trader's record and a claim pays only the claimant's own.
    mapping(address => mapping(address => uint256)) private _residueOwed;
    /// @dev hub V3: the SUM of `_residueOwed[token][*]` (written beside every write of `_residueOwed`). `rescue` pays out only the balance above it.
    mapping(address => uint256) private _residueTotal;
    event RelayedSettlement(address indexed relayer, address indexed owner, uint256 relayerRefund);
    error RelayDisabled();
    error RelayOrderMismatch();
    error RelayFeeExceedsCap();
    error RelayRefundExceedsCap(uint256 refund, uint256 cap);
    error RelayFloorTooLow(uint256 paramsMin, uint256 required);
    error RelayNotAuthorised(address caller, address relayer);
    error RouteNotAttested();
    /// @dev RT48-F1: a maker leg (PROTO 12/13) reached a path whose route is not bound to its submitter.
    error MakerLegNotAttested();
    event Rescued(address indexed token, uint256 amount);
    // SolidProof L3/L4: every guardian switch and every residue entitlement is observable.
    event Paused(address indexed guardian);
    event Unpaused(address indexed guardian);
    event Permit2DirectPausedSet(address indexed guardian, bool paused);
    event ResidueRecorded(address indexed token, address indexed owner, uint256 amount);
    event ResidueSwept(address indexed token, address indexed owner, address to, uint256 amount);
    // SolidProof I10/I11: named reverts instead of empty ones, and a sweep that pays nothing says so.
    error WrapFailed();
    error TokenCallFailed();
    error NothingToSweep();
    /// @notice Native-output mode (V4/Ekubo leg pushes raw ETH/PLS back)
    ///         requires the leg's declared `tokenOut` to equal this pinned
    ///         address before the contract wraps it — the fix for BB-02
    ///         (2026-09-17; same class independently flagged
    ///         2026-09-11). Before this, mode was decided purely by
    ///         `tokenOut != poolKeyCurrency && tokenOut != address(0)`, with
    ///         no check that `tokenOut` was actually the real wrapper — a
    ///         route naming a hostile contract as `tokenOut` would receive
    ///         real native value via that contract's own `deposit()`, and
    ///         only the balance-delta floor on the NAMED (attacker) token
    ///         stood between the trader and a bad fill. VERIFIED 2026-09-19
    ///         this is the same pattern the majors use: Uniswap Universal
    ///         Router pins WETH9 as a `RouterImmutables` immutable, 1inch's
    ///         router hardcodes WETH as a bytecode constant, Kyber's
    ///         MetaAggregationRouter has `address public immutable WETH` —
    ///         none of them trust a caller/route-supplied token for this.
    ///         Derived from `block.chainid` rather than a new constructor
    ///         parameter so this fix touches zero deploy scripts and zero
    ///         of the 54 existing test call sites that construct this
    ///         contract directly.
    error WrongNativeWrapper();
    /// @dev SolidProof I3: an amount or deadline that does not fit the narrower type a venue takes reverts by name instead of wrapping to a different number.
    error AmountOutOfRange();
    address public immutable WRAPPED_NATIVE;
    address public immutable EKUBO_CORE;

    /// @notice EkuboSwapFacet (contracts/EkuboSwapFacet.sol), delegatecalled
    ///         from _swapEkubo — see docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md.
    ///         address(0) disables the Ekubo path exactly like EKUBO_ROUTER==0
    ///         does today (both are checked; either alone is enough to fail
    ///         closed). Deliberately a delegatecall target, NOT an
    ///         upgradeable proxy facet: this address is set once, here, at
    ///         construction and can never change — no diamondCut, no owner
    ///         who can swap what a signed order settles against. The facet
    ///         has ZERO storage of its own; every byte it touches lives in
    ///         THIS contract's own storage (delegatecall shares address(this),
    ///         msg.sender and storage with the caller). Set from the
    ///         constructor's `facets_` array, slot 0 — see the FACET SLOTS
    ///         comment at the constructor for how a slot 1+ gets added later
    ///         without ever changing the constructor's own signature again.
    address public immutable EKUBO_FACET;

    /// @notice UniV4SwapFacet (contracts/UniV4SwapFacet.sol), delegatecalled from
    ///         _swapUniV4/unlockCallback -- see docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md
    ///         and UniV4SwapFacet.sol's own doc comment (2026-10-02, second facet split,
    ///         slot 1 per the design doc's own documented extension path). address(0)
    ///         disables the UniV4 path exactly like UNIV4_POOL_MANAGER==0 does today (both
    ///         are checked; either alone is enough to fail closed). Same trust model as
    ///         EKUBO_FACET above: set once at construction, never an upgradeable proxy
    ///         facet, zero storage of its own. Set from the constructor's `facets_` array,
    ///         slot 1.
    address public immutable UNIV4_FACET;

    /// @notice VenueHubFacet (contracts/VenueHubFacet.sol), delegatecalled from _swapVenue for every
    ///         EXTERNAL venue leg: Hashflow (12), Bebop (13), PropAMM Router (14) (2026-10-17; this slot
    ///         held the Bebop-only facet 2026-10-12). Same shape and reasoning as EKUBO_FACET /
    ///         UNIV4_FACET above: set once at construction from `facets_` slot 2; identity pinned by
    ///         EXPECTED_VENUE_FACET_CODEHASH; zero storage of its own; address(0) on a chain without
    ///         those venues (PulseChain), where _swapVenue fails closed. The facet carries the routers'
    ///         addresses as constants; the constructor checks its Hashflow router == HASHFLOW_ROUTER.
    address public immutable VENUE_FACET;

    /// @notice hub V3: the AdapterRegistry (contracts/AdapterRegistry.sol), from `facets_` slot 3. It is CALLED (a view), never delegatecalled. address(0) = no adapters.
    address public immutable ADAPTER_REGISTRY;

    /// @notice keccak256(EXTCODEHASH) of contracts/EkuboSwapFacet.sol's own
    ///         compiled runtime bytecode (RT11-A-1 fix, 2026-09-17). Every
    ///         byte a facet touches under delegatecall lives in THIS
    ///         contract's own storage — the constructor previously checked
    ///         EKUBO_FACET for emptiness only, never identity, so a wrong or
    ///         malicious non-zero facet address got unrestricted storage
    ///         read/write the instant any trader routed a PROTO_EKUBO leg
    ///         (round-11 red team, live-proven: flips `paused` without
    ///         GUARDIAN, forges a `_residueOwed` entitlement drained through
    ///         the real sweepTo()). This constant pins the ONLY facet
    ///         bytecode the constructor will accept at a non-zero slot.
    /// @dev    RT12-A-1 fix (2026-09-17): the prior value here
    ///         (0x300a9d1e...) was captured via `forge inspect ...
    ///         deployedBytecode`, which uses Foundry's default
    ///         `bytecode_hash="ipfs"` metadata trailer. The REAL deploy
    ///         scripts (deploy_settlement_ethereum.py / _mainnet.py /
    ///         _testnet.py) never use that toolchain to build or check this
    ///         facet — they go through `scripts/_bytecode_scan.py`'s
    ///         `compile_deployed_bytecode()` / `verify_facet_bytecode()`,
    ///         which compile with `metadata.bytecodeHash: "none"` (the exact
    ///         setting `scripts/compile_contracts.js` and
    ///         `docs/REDEPLOY_V2_BUILD.md`'s own documented reproduce command
    ///         use). Those two toolchains produce DIFFERENT runtime bytecode
    ///         for byte-identical source (2120B w/ ipfs metadata vs 2079B
    ///         w/ metadata stripped) — so the old constant made every
    ///         real, documented build of this facet permanently rejected by
    ///         this constructor. Recomputed live via the SAME path the real
    ///         deploy/verify scripts use: `IQ_SOLC=<solc-0.8.36>
    ///         node scripts/compile_contracts.js` (equivalently,
    ///         `compile_deployed_bytecode()` against
    ///         contracts/EkuboSwapFacet.sol), keccak256 of the resulting
    ///         `evm.deployedBytecode.object` — 2079 bytes, cross-checked
    ///         against a real live deploy+EXTCODEHASH readback on a local
    ///         chain. EkuboSwapFacet.sol declares no immutables and no
    ///         constructor, so its deployed bytecode never varies with
    ///         constructor arguments; recompiling under the SAME pinned
    ///         settings is therefore always reproducible. MUST be recomputed
    ///         and updated (both here and in the deploy scripts' own
    ///         facet-bytecode check) if EkuboSwapFacet.sol's source,
    ///         compiler version, optimizer setting, or evm_version ever
    ///         changes — run `scripts/check_ekubo_facet_codehash.py` after
    ///         any such change; it recomputes this exact value via the real
    ///         deploy toolchain and fails loudly on drift instead of relying
    ///         on someone remembering to update this comment.
    bytes32 public constant EXPECTED_EKUBO_FACET_CODEHASH =
        0x79f94d5088f19270fbc9a195abe153413736a1241ddfd6feb814d461b900a4a5;
    // ^ Recomputed 2026-10-02 (RT44 cross-branch port): added the RT35 sibling fix
    //   (mode==1 WrongNativeWrapper pin, matching _univ4Pay's own RT35 fix -- see
    //   EXPECTED_UNIV4_FACET_CODEHASH's own comment below for the full trace) that
    //   this branch's EkuboSwapFacet.sol never received, dormant today only because
    //   EKUBO_ROUTER/EKUBO_FACET are zero on every live deployment of this branch,
    //   closed anyway per this lineage's practice. Recomputed via
    //   scripts/check_ekubo_facet_codehash.py against the real deploy toolchain
    //   (IQ_SOLC=solc-0.8.36) -- matches feat/helper-coverage-pack's own
    //   independently-recomputed value exactly, confirming the two branches'
    //   EkuboSwapFacet.sol source is now byte-identical again.
    // Prior history: Recomputed 2026-09-19 (BB-02 fix changed EkuboSwapFacet.sol's
    //   source -- wrappedNative param + WrongNativeWrapper check -- which changes
    //   its compiled bytecode/codehash). Recomputed via
    //   scripts/check_ekubo_facet_codehash.py against the real deploy
    //   toolchain (IQ_SOLC=solc-0.8.36), the same method RT12-A-1 established
    //   specifically to avoid a wrong-toolchain drift like RT13-A-1 found.

    /// @notice keccak256(EXTCODEHASH) of contracts/UniV4SwapFacet.sol's own compiled
    ///         runtime bytecode (2026-10-02, second facet split). Same purpose/mechanism
    ///         as EXPECTED_EKUBO_FACET_CODEHASH above -- rejects a wrong or malicious
    ///         UNIV4_FACET at construction instead of trusting any non-zero address.
    ///         Recomputed via `node scripts/compile_contracts.js` (the real deploy/verify
    ///         toolchain) + `keccak256(deployedBytecode)` -- re-run after ANY change to
    ///         contracts/UniV4SwapFacet.sol's source, compiler version, optimizer
    ///         setting, or evm_version.
    bytes32 public constant EXPECTED_UNIV4_FACET_CODEHASH =
        0x95049fa0d40f3d71c06784d7d938390264bf54eb2feea71f151e9501903eb487;

    /// @notice keccak256(EXTCODEHASH) of contracts/VenueHubFacet.sol's compiled runtime bytecode
    ///         (2026-10-17). Same purpose/mechanism as the two pins above: a non-zero VENUE_FACET whose
    ///         code is not that bytecode is refused at construction. Computed with the deploy toolchain
    ///         (solc 0.8.36 native, viaIR, runs 200, shanghai, metadata.bytecodeHash none) -- re-run
    ///         after ANY change to the facet's source, compiler version, optimizer setting or evm_version.
    bytes32 public constant EXPECTED_VENUE_FACET_CODEHASH =
        0x031e9e75ae5c646d595080ce03bc57254dd5380d86f4fc7dfa8030e7d39d907a;
    // ^ Recomputed 2026-10-02 (RT44 cross-branch port, same session as the
    //   EXPECTED_EKUBO_FACET_CODEHASH update above): this branch's own facet split
    //   (earlier the same day) relocated _univ4Pay as a "verbatim relocation" of
    //   this branch's then-current source -- which never received RT35 (f8b6548,
    //   feat/helper-coverage-pack, 2026-10-01: mode==1 native-input never checked
    //   tokenIn == wrappedNative before withdraw()+settle{value}, letting a
    //   route-chosen fake-wrapper token drain this contract's own stranded ETH --
    //   live risk here since UNIV4_POOL_MANAGER is this branch's own real, non-zero
    //   deploy config, not dormant). Found while porting this facet split onto
    //   feat/helper-coverage-pack for RT44 (see
    //   .intoiq/evidence/redteam44_trackC_contracts_2026_10_02/REPORT.md) and ported
    //   back here immediately. _univ4Pay gained a wrappedNative parameter + the same
    //   check _univ4Take's mode==2 already has. Computed via a real solc 0.8.36
    //   native binary (Foundry's own svm cache:
    //   ~/AppData/Roaming/svm/0.8.36/solc-0.8.36 on Windows) -- matches
    //   feat/helper-coverage-pack's own independently-recomputed value exactly,
    //   confirming both branches' UniV4SwapFacet.sol source is now byte-identical.
    // Prior history: computed from Foundry's own compile (tests/foundry_h1_redeploy/
    //   out/UniV4SwapFacet.sol/UniV4SwapFacet.json, keccak256(deployedBytecode)), NOT
    //   via `node scripts/compile_contracts.js`'s bundled solc-js default --
    //   empirically confirmed that path does NOT reproduce EXPECTED_EKUBO_FACET_
    //   CODEHASH either (solc-js and this machine's native solc 0.8.30 agree with
    //   each other, both diverge from the real 0.8.36 toolchain). A working 0.8.36
    //   binary was later found at the path above (RT44) -- re-verify via it before
    //   any further change to contracts/UniV4SwapFacet.sol's source, compiler
    //   version, optimizer setting, or evm_version.

    // Hashflow RFQ-T router (address(0) disables the path; PulseChain has none).
    address public immutable HASHFLOW_ROUTER;

    /// @dev Reentrancy guard slot, held in REGULAR storage (SSTORE/SLOAD).
    ///      Transient storage (EIP-1153 TSTORE/TLOAD) would be ~200 gas
    ///      cheaper, but PulseChain — mainnet AND testnet v4 — is PRE-CANCUN
    ///      (proven live 2026-08-12: `invalid opcode: TLOAD` on both). The
    ///      transient version would deploy and then revert on EVERY execute().
    ///      A keccak-derived fixed slot (ERC-7201 style) is collision-safe.
    ///      Semantics unchanged: 0 = not entered, 1 = entered; the SSTORE
    ///      back to 0 at exit costs ~5k/tx more than transient — negligible
    ///      at PulseChain's ~$0.01 gas, and correctness beats the saving.
    bytes32 private constant REENTRANCY_SLOT =
        keccak256("bullbearswap.settlement.reentrancy.v1");

    /// @dev V3 direct-swap callback binding. During a V3 pool.swap this slot
    ///      holds the pool being swapped, so ONLY that pool's callback is
    ///      honoured; outside a swap it is 0, so any direct call to a
    ///      *V3SwapCallback reverts (msg.sender != 0 == the slot). Pre-Cancun:
    ///      a regular keccak-derived storage slot (sstore/sload), NOT transient.
    bytes32 private constant V3_EXPECTED_POOL_SLOT =
        keccak256("bullbearswap.settlement.v3expectedpool.v1");

    /// @dev Native-unwrap binding: holds the WRAPPER address (params.buyToken)
    ///      ONLY while executeToNative is unwrapping the user's net output, so
    ///      receive() accepts native exclusively as that wrapper's withdraw()
    ///      push — any other send (forced, stray, or hostile) reverts and the
    ///      holds-nothing-between-trades invariant survives the new entry.
    bytes32 private constant NATIVE_UNWRAP_SLOT =
        keccak256("bullbearswap.settlement.nativeunwrap.v1");

    // UNIV4_UNLOCK_SLOT deleted here (2026-10-02 UniV4 facet split) -- same literal
    // keccak256("bullbearswap.settlement.univ4unlock.v1") now lives only in
    // UniV4SwapFacet.sol, the sole remaining reader/writer of that storage slot.
    // Full V3 tick range: swap consumes the whole exact-input (moving price to
    // the limit) rather than reverting, matching each DEX's own quoter.
    uint160 private constant MIN_SQRT_RATIO = 4295128739;
    uint160 private constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice One edge in the flow optimizer's solution.
    struct EdgeSwap {
        address pool;
        address tokenIn;
        address tokenOut;
        uint256 amountIn;
        uint256 minAmountOut;
        uint8   protocol;
        bytes   extraData;
    }

    /// @notice Packed execution parameters.
    struct ExecuteParams {
        address sellToken;
        uint256 sellAmount;
        address buyToken;
        uint256 minBuyAmount;     // absolute minimum — reverts below this
        uint256 benchmarkOutput;  // best competing aggregator output (for fee calc)
        // BBS's OWN best-rate output at quote time. It locks the fee as a
        // CEILING: execution can only shrink it, so favorable slippage between
        // quote and fill goes 100% to the user, never to BBS (fee model rule:
        // every ambiguity in the user's favour). Signed by the attestor exactly
        // like benchmarkOutput; a lying-HIGH value can only make the ceiling
        // non-binding (min falls back to the gross cap), never raise the fee.
        uint256 quotedOutput;
        address recipient;
        uint256 deadline;
        // EIP-712 attestation over (sellToken, buyToken, sellAmount,
        // benchmarkOutput, quotedOutput, attestationDeadline) signed by
        // BENCHMARK_ATTESTOR. Absent/invalid/expired => fee is ZERO (pro-user
        // default), never a revert: a signing outage must cost BBS its fee,
        // never the user their swap.
        uint256 attestationDeadline;
        bytes   benchmarkSignature;
    }

    event SettlementExecuted(
        address indexed sender,
        address indexed recipient,
        address sellToken,
        address buyToken,
        uint256 sellAmount,
        uint256 grossBuyAmount,
        uint256 surplusFee,
        uint256 netBuyAmount,
        uint256 benchmarkOutput,
        uint256 edgeCount
    );

    error InsufficientOutput(uint256 actual, uint256 minimum);
    error NativeValueMismatch(uint256 sent, uint256 expected);
    error EdgeSwapFailed(uint256 index, address pool, uint8 protocol);
    error TrackedTokenBelowBaseline(address token, uint256 baseline, uint256 current);
    error UntrustedPool(address pool, uint8 protocol, uint256 index);
    error ContractPaused();
    error NotGuardian();
    error UnknownProtocol(uint256 index, uint8 protocol);
    error DeadlinePassed();
    error Reentrancy();
    error InvalidFeeConfig();
    /// @dev RT11-A-1 fix (2026-09-17): a non-zero EKUBO_FACET whose deployed
    ///      codehash does not match EXPECTED_EKUBO_FACET_CODEHASH.
    error BadFacetCodehash(address facet, bytes32 actual, bytes32 expected);
    error InvalidRecipient();
    error SellBuyTokensSame();
    error ZeroFloor();
    error UnexpectedV3Callback();
    error UnexpectedV4Unlock();
    /// @dev A Uniswap V4 hook whose permission bits let it CHANGE the swap
    ///      amount. Such a pool cannot be settled against a quote priced from
    ///      tick math alone, so the leg fails closed rather than paying out an
    ///      amount nobody quoted.
    error UniV4HookNotSupported(address hooks);
    error UnexpectedNative();
    error NativeSendFailed();
    /// @dev executeHopFromHelper (draft, 2026-10-07): msg.sender is not in
    ///      trustedHopCallers.
    error UntrustedHopCaller(address caller);

    /// @notice Emitted by executeHopFromHelper -- the composed-hop twin of
    ///         SettlementExecuted, scoped to one caller-supplied edge with no
    ///         recipient/fee fields (those stay the calling helper's own
    ///         concern; see the field's storage-declaration comment above).
    event HopExecutedForHelper(
        address indexed caller,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 delivered
    );

    modifier nonReentrant() {
        _enter();
        _;
        _exit();
    }

    /// @dev Guard body lives in internal functions, not inline in the
    ///      modifier: a modifier's code is COPIED into every function that
    ///      uses it, so inlining it grows the deployed bytecode once per
    ///      call site for no benefit.
    function _enter() private {
        bytes32 slot = REENTRANCY_SLOT;
        uint256 entered;
        assembly { entered := sload(slot) }
        if (entered != 0) revert Reentrancy();
        assembly { sstore(slot, 1) }
    }

    function _exit() private {
        bytes32 slot = REENTRANCY_SLOT;
        assembly { sstore(slot, 0) }
    }

    function _entered() private view returns (bool flag) {
        bytes32 slot = REENTRANCY_SLOT;
        uint256 v;
        assembly { v := sload(slot) }
        flag = v != 0;
    }

    function _setV3ExpectedPool(address pool) private {
        bytes32 slot = V3_EXPECTED_POOL_SLOT;
        assembly { sstore(slot, pool) }
    }

    function _v3ExpectedPool() private view returns (address pool) {
        bytes32 slot = V3_EXPECTED_POOL_SLOT;
        assembly { pool := sload(slot) }
    }

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

    function _nativeUnwrapWrapper() private view returns (address wrapper) {
        bytes32 slot = NATIVE_UNWRAP_SLOT;
        assembly { wrapper := sload(slot) }
    }

    /// @dev The ONLY native this contract accepts: the wrapper's withdraw()
    ///      push during an in-flight executeToNative unwrap. Everything else
    ///      reverts — the slot is zero outside the unwrap, so a cold send can
    ///      never match. (selfdestruct-forced native remains theoretically
    ///      possible on any contract; it strands rather than routes, and the
    ///      accounting below never reads address(this).balance.)
    receive() external payable {
        if (msg.sender != _nativeUnwrapWrapper()) revert UnexpectedNative();
    }

    // _setUniV4Unlock/_univ4Unlock deleted here (2026-10-02 UniV4 facet split) -- the
    // unlock-guard they implemented now lives in UniV4SwapFacet.sol, which reads/writes
    // the identical UNIV4_UNLOCK_SLOT literal on this contract's own storage via
    // delegatecall. See UniV4SwapFacet.sol's file-level doc comment.

    /// @dev The first argument is ignored (see "Router configuration"); pass address(0).
    /// @param balancerVault   Balancer V2 Vault address
    /// @param feeRecipient    Address that receives surplus fees (immutable)
    /// @param surplusFeeBps   Fee in bps on surplus above benchmark (e.g. 5000 = 50%)
    /// @param benchmarkAttestor Signer of EIP-712 benchmark attestations;
    ///                          address(0) disables attestation checking.
    /// @param balancerV3Router  Balancer V3 (TIDE) BatchRouter; address(0) disables.
    /// @param balancerV3Permit2 Permit2 the BatchRouter pulls through (from its
    ///                          getPermit2()); address(0) disables the V3 path.
    /// @param univ4PoolManager  Uniswap V4 PoolManager singleton; address(0)
    ///                          disables the V4 path (PulseChain deployments).
    /// @param ekuboRouter      Ekubo V3 router periphery; address(0) disables.
    /// @param ekuboCore        Ekubo Core singleton (native-out push sender);
    ///                          both must be set or both zero — a router with
    ///                          no core would leave native output unreceivable.
    /// @param facets_          Delegatecall facet addresses, by fixed slot
    ///                          index — see the "FACET SLOTS" block below for
    ///                          what each index means and how to add one.
    constructor(
        address,
        address balancerVault,
        address feeRecipient,
        uint256 surplusFeeBps,
        address benchmarkAttestor,
        address balancerV3Router,
        address balancerV3Permit2,
        address univ4PoolManager,
        address ekuboRouter,
        address ekuboCore,
        address relayPermit2,
        address[] memory trustedV2Factories_,
        address[] memory trustedV3Factories_,
        address[] memory trustedStablePools_,
        address guardian,
        address hashflowRouter,
        address[] memory facets_,
        // Draft (2026-10-07): standalone helper contracts allowed to call
        // executeHopFromHelper. Deliberately its OWN trailing array param
        // (not folded into facets_, which is delegatecall targets with a
        // totally different trust shape) -- an empty array disables the
        // composed-hop path entirely, same fail-closed posture as every
        // other optional feature in this constructor.
        address[] memory trustedHopCallers_
    ) {
        HASHFLOW_ROUTER = hashflowRouter;
        // FACET SLOTS (2026-09-17, docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md
        // + the follow-up generalization after the Ekubo split needed a 44-file
        // constructor-arg ripple to land). ONE array parameter instead of one
        // named `address` parameter per facet, so adding facet #2 later never
        // changes this constructor's SIGNATURE again — only what a caller
        // passes IN it. A caller that doesn't care about facets keeps passing
        // `new address[](0)` forever, unmodified, no matter how many slots
        // exist by then; Solidity treats a missing trailing index as simply
        // not supplied, which this constructor reads as address(0) below —
        // there is no way to positionally "get the wrong facet" by a caller
        // passing a shorter array than the constructor now expects.
        //
        // Slot 0 = EKUBO_FACET (the only one that exists today).
        // TO ADD SLOT 1 FOR A NEW FACET LATER: (a) declare
        // `address public immutable YOUR_FACET;` next to EKUBO_FACET's own
        // declaration, (b) add ONE line here —
        // `address _facet1 = facets_.length > 1 ? facets_[1] : address(0);
        // YOUR_FACET = _facet1;` — (c) wire its own delegatecall call site the
        // same way `_swapEkubo` does. That is the ENTIRE diff. No constructor
        // parameter changes, so no existing `new BullBearSettlement(...)` call
        // site anywhere (tests, deploy scripts) needs to change unless it
        // specifically wants to wire up the new facet.
        //
        // These are true `immutable`s, not a storage mapping with "no setter"
        // as the only protection — deliberately: this contract's whole trust
        // model is that nothing can EVER redirect what a signed order settles
        // against, and an immutable is a compiler/EVM-structural guarantee of
        // that, not a promise kept only by omitting a setter function.
        address _facet0 = facets_.length > 0 ? facets_[0] : address(0);
        EKUBO_FACET = _facet0;
        // Slot 1 = UNIV4_FACET (2026-10-02, second facet split) -- added via the EXACT
        // extension path the FACET SLOTS comment above already documents: one new
        // immutable, one line here, one delegatecall call site wired the same way
        // _swapEkubo already does it. No change to this constructor's own signature.
        address _facet1 = facets_.length > 1 ? facets_[1] : address(0);
        UNIV4_FACET = _facet1;
        // Slot 2 = VENUE_FACET (2026-10-12 Bebop-only; 2026-10-17 every external venue) -- the same extension path.
        address _facet2 = facets_.length > 2 ? facets_[2] : address(0);
        VENUE_FACET = _facet2;
        // Slot 3 = ADAPTER_REGISTRY (hub V3): read through kindOf(), never delegatecalled.
        ADAPTER_REGISTRY = facets_.length > 3 ? facets_[3] : address(0);
        RELAY_PERMIT2 = relayPermit2;
        GUARDIAN = guardian;
        // WRAPPED_NATIVE (BB-02 fix, 2026-09-19): chain-keyed, not a new
        // constructor parameter — see the field's own doc comment above for
        // why. Fails closed on an unrecognised chain: WRAPPED_NATIVE stays
        // address(0), so _univ4Take's tokenOut==WRAPPED_NATIVE check can
        // never pass and every native-output leg reverts WrongNativeWrapper
        // there instead of silently trusting an unverified address — the
        // ERC20-output path is unaffected on any chain.
        if (block.chainid == 1) {
            WRAPPED_NATIVE = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH, Ethereum mainnet
        } else if (block.chainid == 369) {
            WRAPPED_NATIVE = 0xA1077a294dDE1B09bB078844df40758a5D0f9a27; // WPLS, PulseChain mainnet
        } else {
            WRAPPED_NATIVE = address(0); // unrecognised chain: native-output mode fails closed
        }
        if (surplusFeeBps > FEE_BPS_DENOMINATOR) revert InvalidFeeConfig();
        if ((ekuboRouter == address(0)) != (ekuboCore == address(0))) revert InvalidFeeConfig();
        // RT10 facet split (2026-09-17): EKUBO_ROUTER set but EKUBO_FACET
        // forgotten (or vice versa) would silently disable a path the
        // deployer believed was live -- fail at construction, not at the
        // first user's swap.
        if ((ekuboRouter == address(0)) != (_facet0 == address(0))) revert InvalidFeeConfig();
        // RT11-A-1 (round-11 red team, 2026-09-17): the checks above only
        // ever confirmed EKUBO_FACET is non-empty, never that it IS
        // EkuboSwapFacet.sol's own bytecode -- a wrong or malicious non-zero
        // facet address got full delegatecall storage read/write with no
        // identity check at all. codehash is EXTCODEHASH under the hood, so
        // this also rejects an address with no code the same way the
        // constructor already rejects an empty EKUBO_ROUTER/EKUBO_FACET pair
        // above, just against the correct bytecode instead of just "any".
        // hub V3: slot 0 (EKUBO_FACET) is no longer delegatecalled, so it is no longer identity-checked either; wire address(0).
        if (_facet0 != address(0)) revert BadFacetCodehash(_facet0, _facet0.codehash, bytes32(0));
        // Same two checks as EKUBO_ROUTER/EKUBO_FACET above, for UNIV4_POOL_MANAGER/
        // UNIV4_FACET: a deployer who forgets to wire the facet after this split lands
        // would otherwise silently lose the whole UniV4 path (the thin wrapper below
        // fails closed on facet==address(0), exactly like the Ekubo one already does --
        // this just catches the misconfiguration at construction instead of at a
        // user's first UniV4 swap), and a wrong/malicious non-zero facet address must
        // never get delegatecall storage access without an identity check.
        if ((univ4PoolManager == address(0)) != (_facet1 == address(0))) revert InvalidFeeConfig();
        if (_facet1 != address(0) && _facet1.codehash != EXPECTED_UNIV4_FACET_CODEHASH) {
            revert BadFacetCodehash(_facet1, _facet1.codehash, EXPECTED_UNIV4_FACET_CODEHASH);
        }
        // VENUE_FACET: zero on a chain without the external venues, but a non-zero address must be
        // VenueHubFacet.sol's own bytecode (RT11-A-1's rule). The Hashflow leg now lives in the facet (its
        // router is the facet's constant), so two deployments are refused here instead of at the first fill:
        // a Hashflow router configured with no facet to execute it, and a configured router that is not the
        // facet's. hashflowRouter == 0 beside a facet is allowed: HASHFLOW_ROUTER() then reads 0 and the
        // server keeps Hashflow off (the safe direction); Bebop and PropAMM legs still run.
        if (_facet2 == address(0)) {
            if (hashflowRouter != address(0)) revert InvalidFeeConfig();
        } else {
            if (_facet2.codehash != EXPECTED_VENUE_FACET_CODEHASH) {
                revert BadFacetCodehash(_facet2, _facet2.codehash, EXPECTED_VENUE_FACET_CODEHASH);
            }
            if (hashflowRouter != address(0) && IVenueHubFacet(_facet2).HASHFLOW_ROUTER() != hashflowRouter) {
                revert InvalidFeeConfig();
            }
        }
        BALANCER_VAULT = balancerVault;
        FEE_RECIPIENT = feeRecipient;
        SURPLUS_FEE_BPS = surplusFeeBps;
        BENCHMARK_ATTESTOR = benchmarkAttestor;
        BALANCER_V3_ROUTER = balancerV3Router;
        BALANCER_V3_PERMIT2 = balancerV3Permit2;
        UNIV4_POOL_MANAGER = univ4PoolManager;
        EKUBO_ROUTER = ekuboRouter;
        EKUBO_CORE = ekuboCore;
        for (uint256 i = 0; i < trustedV2Factories_.length; ) {
            trustedV2Factories.push(trustedV2Factories_[i]);
            unchecked { ++i; }
        }
        for (uint256 i = 0; i < trustedV3Factories_.length; ) {
            trustedV3Factories.push(trustedV3Factories_[i]);
            unchecked { ++i; }
        }
        for (uint256 i = 0; i < trustedStablePools_.length; ) {
            trustedStablePools.push(trustedStablePools_[i]);
            _isTrustedStablePool[trustedStablePools_[i]] = true;
            unchecked { ++i; }
        }
        for (uint256 i = 0; i < trustedHopCallers_.length; ) {
            trustedHopCallers.push(trustedHopCallers_[i]);
            _isTrustedHopCaller[trustedHopCallers_[i]] = true;
            unchecked { ++i; }
        }
    }

    /// @notice Freeze every fund-moving entry point. GUARDIAN-only, and a
    ///         no-op-forever if GUARDIAN is address(0). sweep() is
    ///         deliberately NOT gated — it only ever pays a recorded
    ///         _residueOwed trader or nobody, never an arbitrary caller
    ///         (see sweep()'s own comments), so it stays safe and available
    ///         to return stuck funds even while paused.
    function pause() external onlyGuardian {
        paused = true;
        emit Paused(msg.sender);
    }

    /// @notice Resume. Same GUARDIAN-only, same permanent no-op at
    ///         address(0) — an operator who wants the old fully-immutable,
    ///         nobody-can-ever-touch-it posture gets exactly that by
    ///         deploying with guardian = address(0).
    function unpause() external onlyGuardian {
        paused = false;
        emit Unpaused(msg.sender);
    }

    /// @notice Scoped counterpart to pause()/unpause(): freezes or resumes
    ///         ONLY executeWithPermit2, leaving executeRelayed/
    ///         executeRelayedToNative (and every other entry point)
    ///         untouched. GUARDIAN-only, and a no-op-forever if GUARDIAN is
    ///         address(0) -- identical gating to pause(). Exists because
    ///         RELAY_PERMIT2==0 is the only other lever that disables
    ///         executeWithPermit2, and that same flag also disables
    ///         executeRelayed's Permit2 pull, so it cannot isolate one path
    ///         from the other (RT10-A-1, 2026-09-17). One function taking
    ///         the target state, not a pausePermit2Direct()/
    ///         unpausePermit2Direct() pair like pause()/unpause() above --
    ///         those two have DIFFERENT gates (paused affects every
    ///         entry point, so its own name matters at every call site);
    ///         this one has exactly one caller to gate either way, so a
    ///         second near-duplicate function is pure runtime-bytecode
    ///         cost (RT10 EIP-170 trim pass, 2026-09-17) with no
    ///         readability gained.
    function setPermit2DirectPaused(bool paused_) external onlyGuardian {
        permit2DirectPaused = paused_;
        emit Permit2DirectPausedSet(msg.sender, paused_);
    }

    /// @dev EIP-712 domain separator, shared by every attestation this contract
    ///      verifies (benchmark fee AND relayed route). One definition, so the
    ///      two digest builders cannot drift apart.
    function _domainSeparator() internal view returns (bytes32) {
        return keccak256(abi.encode(
            EIP712_DOMAIN_TYPEHASH,
            keccak256(bytes("BullBearSettlement")),
            keccak256(bytes("1")),
            block.chainid,
            address(this)
        ));
    }

    /// @notice EIP-712 digest of a benchmark attestation.
    /// @dev internal: the off-chain attestor mirrors this in Python
    ///      (src/iq_defi/execution_calldata.py) and never reads it on-chain, so
    ///      no external getter is emitted; still called by _benchmarkAttested.
    function benchmarkDigest(
        address sellToken,
        address buyToken,
        uint256 sellAmount,
        uint256 benchmarkOutput,
        uint256 quotedOutput,
        uint256 deadline,
        bytes32 edgesHash,
        address owner,
        address recipient
    ) internal view returns (bytes32) {
        bytes32 structHash = keccak256(abi.encode(
            BENCHMARK_TYPEHASH, sellToken, buyToken, sellAmount, benchmarkOutput, quotedOutput, deadline,
            edgesHash, owner, recipient));
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparator(), structHash));
    }

    /// @notice EIP-712 digest of a relayed-route attestation. `orderHash` is the
    ///         Permit2 witness (the RelayedOrder the user signed); `edgesHash` is
    ///         keccak256(abi.encode(edges)). BENCHMARK_ATTESTOR signs this so the
    ///         relayer cannot swap in a route the solver never chose.
    function relayedRouteDigest(
        bytes32 orderHash,
        bytes32 edgesHash,
        uint256 permitNonce,
        uint256 deadline
    ) internal view returns (bytes32) {
        bytes32 structHash = keccak256(abi.encode(
            RELAYED_ROUTE_TYPEHASH, orderHash, edgesHash, permitNonce, deadline));
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparator(), structHash));
    }

    /// @dev Signature recovery with EIP-2 low-s enforcement. Malleable
    ///      signatures are rejected rather than normalised: an attestation
    ///      is an authorisation, and two valid encodings of one
    ///      authorisation is a replay surface, not a convenience.
    function _recoverAttestor(bytes32 digest, bytes calldata signature)
        internal pure returns (address)
    {
        if (signature.length != 65) return address(0);
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := calldataload(signature.offset)
            s := calldataload(add(signature.offset, 32))
            v := byte(0, calldataload(add(signature.offset, 64)))
        }
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return address(0);
        }
        if (v < 27) v += 27;
        if (v != 27 && v != 28) return address(0);
        return ecrecover(digest, v, r, s);
    }

    /// @notice Execute settlement with surplus-based fee.
    ///
    ///  Fee logic (CHANGED 2026-09-02 — see _calculateSurplusFee):
    ///    grossOutput   = actual output from all edge swaps  (EXECUTION time)
    ///    quoteSurplus  = quotedOutput - benchmarkOutput     (both QUOTE time)
    ///    feeAtQuote    = quoteSurplus * SURPLUS_FEE_BPS / 10000
    ///    fee           = feeAtQuote * min(gross/quoted, 1)
    ///    userReceives  = grossOutput - fee
    ///
    ///  Guarantees:
    ///    - fee = 0 when quotedOutput <= benchmarkOutput (no edge, no charge)
    ///    - fee = 0 when grossOutput drifted more than MAX_FEE_DRIFT_BPS below
    ///      quotedOutput (never charge on a trade that went badly for the user)
    ///    - fee <= the edge BBS demonstrated at quote time, and <= 0.5% of gross
    ///    - positive slippage accrues to the USER: the delivery ratio is capped
    ///      at 1.0, so a better-than-quoted fill never raises the fee
    ///    - userReceives >= minBuyAmount (hard safety floor, reverts if not met)
    ///
    ///  DELIBERATELY NO LONGER GUARANTEED: `userReceives >= benchmarkOutput`.
    ///  That read well but compared two different moments — the user's
    ///  EXECUTION-time receipt against a rival's QUOTE-time number — so
    ///  ordinary drift erased fees BBS had genuinely earned (6 of the first 24
    ///  swaps). The rival's number is equally stale; had the user taken it they
    ///  would have drifted too. What is guaranteed instead is that the fee
    ///  never exceeds the routing edge actually demonstrated, and is never
    ///  charged at all once the trade has moved more than 1% against the user.
    function execute(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params
    ) external nonReentrant whenNotPaused {
        _checkParams(params);
        uint256 sellTokenBefore = _balanceOfSelf(params.sellToken);
        // Pull sell token from user
        _safeTransferFrom(params.sellToken, msg.sender, address(this), params.sellAmount);
        _settle(edges, params, false, sellTokenBefore);
    }

    /// @notice execute() variant that pulls the sell token through a
    ///         single-use Permit2 signature instead of a standing ERC-20
    ///         approval to this contract. Self-directed only: `owner` is
    ///         hardcoded to msg.sender below (not taken from calldata), so
    ///         Permit2 reverts unless the CALLER is the signer — there is no
    ///         third-party-submission mode here, unlike executeRelayed. That
    ///         is deliberate: because the signer is also the one choosing and
    ///         submitting `edges` in this same transaction, there is no
    ///         separate route to attest against (the relayed path's
    ///         BENCHMARK_ATTESTOR co-signature exists ONLY because a relayer,
    ///         not the signer, picks the route there). No witness is needed
    ///         for the same reason: nothing about this call is decided by
    ///         anyone other than the permit signer.
    ///         Gated by RELAY_PERMIT2==0 (shared prerequisite with
    ///         executeRelayed) AND, independently, by permit2DirectPaused
    ///         (scoped to this function alone -- see setPermit2DirectPaused()),
    ///         so an operator can pull this path without touching
    ///         executeRelayed's own Permit2 pull (RT10-A-1, 2026-09-17).
    function executeWithPermit2(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params,
        uint256 permitNonce,
        bytes calldata permitSignature
    ) external nonReentrant whenNotPaused {
        if (RELAY_PERMIT2 == address(0)) revert RelayDisabled();
        if (permit2DirectPaused) revert RelayDisabled();
        _checkParams(params);
        uint256 sellTokenBefore = _balanceOfSelf(params.sellToken);
        IPermit2SignatureTransfer(RELAY_PERMIT2).permitTransferFrom(
            IPermit2SignatureTransfer.PermitTransferFrom({
                permitted: IPermit2SignatureTransfer.TokenPermissions({ token: params.sellToken, amount: params.sellAmount }),
                nonce: permitNonce,
                deadline: params.deadline
            }),
            IPermit2SignatureTransfer.SignatureTransferDetails({ to: address(this), requestedAmount: params.sellAmount }),
            msg.sender, permitSignature);
        _settle(edges, params, false, sellTokenBefore);
    }

    /// @notice execute() sent by a RELAYER on behalf of `order.owner`, who signed
    ///         ONE Permit2 witness signature. The relayer pays gas and takes
    ///         `relayerRefund` (<= order.maxRelayerRefund) from the output; the
    ///         user's floor is on what the USER nets. ERC-20 sell only (a
    ///         signature cannot move native value); ERC-20 buy here, native buy
    ///         via executeRelayedToNative; fee-on-transfer buys keep the
    ///         wallet-sent path (their own floor semantics).
    ///         `_settle` is untouched: the floor it enforces is params.minBuyAmount,
    ///         which this entry requires to be >= order.minBuyAmount + refund, so
    ///         netOutput - refund >= order.minBuyAmount holds by construction.
    function executeRelayed(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params,
        RelayedOrder calldata order,
        uint256 permitNonce,
        uint256 relayerRefund,
        bytes calldata permitSignature,
        bytes calldata routeSignature
    ) external nonReentrant {
        _executeRelayed(edges, params, order, permitNonce, relayerRefund, permitSignature, routeSignature, false);
    }

    /// @notice executeRelayed() for a NATIVE buy (ETH/PLS out): the identical
    ///         one-signature pull, checks and settlement on the WRAPPED buy
    ///         token (params.buyToken = order.buyToken = the WETH9-style
    ///         wrapper the pools trade), then the user's NET output is unwrapped
    ///         and pushed as native, exactly as executeToNative does for a
    ///         wallet-sent swap. The relayer's refund is paid in the WRAPPED
    ///         token before the unwrap (the relayer wants gas money, not a
    ///         native push it must then re-wrap); the fee stays wrapped too.
    ///         Deployed 2026-09-07 so the default Ethereum swap (buy ETH)
    ///         gets BBS-paid gas and private submission instead of the wallet
    ///         path (fill 0x4602cf4a: $4.07 of wallet gas on a $4.47 trade).
    function executeRelayedToNative(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params,
        RelayedOrder calldata order,
        uint256 permitNonce,
        uint256 relayerRefund,
        bytes calldata permitSignature,
        bytes calldata routeSignature
    ) external nonReentrant {
        _executeRelayed(edges, params, order, permitNonce, relayerRefund, permitSignature, routeSignature, true);
    }

    function _executeRelayed(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params,
        RelayedOrder calldata order,
        uint256 permitNonce,
        uint256 relayerRefund,
        bytes calldata permitSignature,
        bytes calldata routeSignature,
        bool nativeOut
    ) private whenNotPaused {
        if (RELAY_PERMIT2 == address(0)) revert RelayDisabled();
        // A relayed fill is ONLY as safe as the route attestation below, which
        // needs the attestor key. A deployment without an attestor cannot secure
        // the relayed path, so it must not offer one.
        if (BENCHMARK_ATTESTOR == address(0)) revert RelayDisabled();
        _checkParams(params);
        uint256 sellTokenBefore = _balanceOfSelf(params.sellToken);
        // recipient is now SIGNED by the user (order.recipient), so the output
        // may land at a smart-account or a third party the user chose — not only
        // back at the signer. params must match that signed recipient exactly.
        if (params.sellToken != order.sellToken || params.buyToken != order.buyToken
                || params.sellAmount != order.sellAmount || params.recipient != order.recipient
                || order.owner == address(0) || order.nativeOut != nativeOut) revert RelayOrderMismatch();
        // SolidProof L2: the largest fee the signed benchmark numbers can ever produce must sit inside the
        // cap the USER signed. A relayer that presents another valid attestation for these edges cannot
        // raise what the user pays.
        if (_maxFeeBound(params.quotedOutput, params.benchmarkOutput) > order.maxFee) revert RelayFeeExceedsCap();
        if (order.relayer != address(0) && msg.sender != order.relayer) revert RelayNotAuthorised(msg.sender, order.relayer);
        if (relayerRefund > order.maxRelayerRefund) revert RelayRefundExceedsCap(relayerRefund, order.maxRelayerRefund);
        if (params.minBuyAmount < order.minBuyAmount + relayerRefund)
            revert RelayFloorTooLow(params.minBuyAmount, order.minBuyAmount + relayerRefund);
        // Pull the sell token with the user's Permit2 witness signature. Permit2
        // verifies the signature over (permitted, spender=this, nonce, deadline,
        // witness) and marks the nonce used; the witness is the order itself.
        bytes32 witness = keccak256(abi.encode(
            RELAYED_ORDER_TYPEHASH, order.owner, order.recipient, order.sellToken, order.buyToken,
            order.sellAmount, order.minBuyAmount, order.maxRelayerRefund, order.relayer, order.maxFee, order.nativeOut));
        // The user signed the ORDER (witness) but NOT the route. Require the
        // attestor to have co-signed THIS route for THIS order at THIS nonce, so
        // a relayer — even a compromised one — cannot substitute a skimming edge
        // set (HIGH). Bound to permitNonce, which Permit2 consumes below,
        // so the attestation is single-use for free. Malleable/low-s rejected by
        // _recoverAttestor; BENCHMARK_ATTESTOR != 0 guaranteed above, so a bad
        // signature recovers to a different address (or 0) and reverts here.
        if (_recoverAttestor(
                relayedRouteDigest(witness, keccak256(abi.encode(edges)), permitNonce, params.deadline),
                routeSignature) != BENCHMARK_ATTESTOR) revert RouteNotAttested();
        IPermit2SignatureTransfer(RELAY_PERMIT2).permitWitnessTransferFrom(
            IPermit2SignatureTransfer.PermitTransferFrom({
                permitted: IPermit2SignatureTransfer.TokenPermissions({ token: order.sellToken, amount: order.sellAmount }),
                nonce: permitNonce,
                deadline: params.deadline
            }),
            IPermit2SignatureTransfer.SignatureTransferDetails({ to: address(this), requestedAmount: order.sellAmount }),
            order.owner, witness, RELAYED_WITNESS_TYPE, permitSignature);
        _relayOwner = order.owner;
        _relayRefund = relayerRefund;
        _settle(edges, params, nativeOut, sellTokenBefore);
        emit RelayedSettlement(msg.sender, order.owner, relayerRefund);
        _relayOwner = address(0);
        _relayRefund = 0;
    }

    /// @notice execute() for a NATIVE sell (PLS/ETH): the user attaches the
    ///         sell amount as msg.value and the contract wraps it into
    ///         params.sellToken (the chain's canonical WETH9-style wrapper)
    ///         before running the identical settlement path. One transaction —
    ///         no separate wrap, no approval (native needs none).
    ///
    ///         SAFETY: params.sellToken must be the chain's WRAPPED_NATIVE (checked
    ///         below, SolidProof L1), so the value is only ever wrapped by the
    ///         real wrapper. A deposit() that mints nothing is still caught by the
    ///         balance-increase check below (L-01, WrapFailed). deposit() sends
    ///         nothing back. The contract does have a receive(), but it accepts
    ///         native ONLY as the wrapper's withdraw() push while an executeToNative
    ///         unwrap is in flight (see receive()); any other send reverts, so
    ///         nothing is held between trades.
    function executeNative(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params
    ) external payable nonReentrant whenNotPaused {
        _checkParams(params);
        if (msg.value != params.sellAmount) revert NativeValueMismatch(msg.value, params.sellAmount);
        // SolidProof L1: the wrap target is the chain's real wrapper, never a caller-named contract (the buy side is pinned in _distributeNative, RT34).
        if (params.sellToken != WRAPPED_NATIVE) revert WrongNativeWrapper();
        uint256 wrappedBefore = _balanceOfSelf(params.sellToken);
        IWrappedNative(params.sellToken).deposit{value: msg.value}();
        // The wrap MUST have minted the wrapper to this contract; a wrapper that
        // takes the native value and mints nothing is rejected here rather than
        // relying on a (possibly waived) downstream floor.
        if (_balanceOfSelf(params.sellToken) <= wrappedBefore) revert WrapFailed();
        _settle(edges, params, false, wrappedBefore);
    }

    /// @notice execute() for a NATIVE buy (ETH/PLS out): identical settlement
    ///         on the WRAPPED buy token (params.buyToken = the WETH9-style
    ///         wrapper every pool actually trades), then the user's NET output
    ///         is unwrapped and sent as native in the SAME transaction — the
    ///         two-step swap-then-unwrap flow collapsed to one signature. The
    ///         fee stays in the wrapped token (ledger unchanged). Guarded by
    ///         the NATIVE_UNWRAP_SLOT receive() above; a recipient that
    ///         rejects native reverts the whole settlement atomically.
    function executeToNative(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params
    ) external nonReentrant whenNotPaused {
        _checkParams(params);
        uint256 sellTokenBefore = _balanceOfSelf(params.sellToken);
        _safeTransferFrom(params.sellToken, msg.sender, address(this), params.sellAmount);
        _settle(edges, params, true, sellTokenBefore);
    }


    /// @notice execute() for a fee-on-transfer BUY whose buy token is taxed on
    ///         EVERY transfer (pTGC / SURF / GAGA class). The custody path
    ///         (execute) round-trips the buy token pool -> settlement -> user,
    ///         so an every-transfer token is taxed TWICE; a direct-delivery
    ///         router (e.g. PulseX's FoT swap) taxes it ONCE. This entry
    ///         delivers every buy-token-producing leg pool -> USER directly (one
    ///         taxed transfer) and enforces the floor on the USER's measured
    ///         balance delta — a STRONGER guarantee than the custody path, which
    ///         floors the settlement's pre-final-transfer balance. BBS then
    ///         matches a rival router's 1x delivery and competes on routing.
    ///
    ///         Charges NO fee: every-transfer buys have benchmarkOutput forced
    ///         to 0 upstream (post-tax gross vs pre-tax rival benchmarks are
    ///         unlike units), so there is no surplus to take and nothing for the
    ///         contract to hold — the buy token never rests here. EVERY
    ///         buy-token-producing leg MUST be V2 (the only venue that targets
    ///         an arbitrary recipient in this contract); a non-V2 buy-token leg
    ///         reverts, and the off-chain builder only routes here when that
    ///         holds and the buy token is a known every-transfer token.
    function executeFot(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params
    ) external nonReentrant whenNotPaused {
        _checkParams(params);
        uint256 sellTokenBefore = _balanceOfSelf(params.sellToken);
        _safeTransferFrom(params.sellToken, msg.sender, address(this), params.sellAmount);
        uint256 recvBefore = IERC20(params.buyToken).balanceOf(params.recipient);
        // Same residue-snapshot fix as _settle (2026-09-14): this path also
        // calls _refundResiduals directly, so it needs its own pre-edge
        // snapshot rather than inheriting one.
        (uint256[] memory tokenInBefore, uint256[] memory tokenOutBefore, bool hasMakerLeg) = _snapshotEdgeTokens(edges);
        if (hasMakerLeg) revert MakerLegNotAttested();   // RT49-R1: this entry carries no route attestation
        uint256 buyTokenBeforeFot = _balanceOfSelf(params.buyToken);
        uint256 edgeCount = edges.length;
        for (uint256 i = 0; i < edgeCount;) {
            _executeEdgeTo(edges[i], i, params.deadline, params.recipient, params.buyToken,
                edges[i].tokenIn == params.sellToken ? sellTokenBefore : tokenInBefore[i]);
            unchecked { ++i; }
        }
        // Floor on what the USER actually received, net of the single transfer
        // tax — the buy token was delivered straight to them.
        uint256 delivered = IERC20(params.buyToken).balanceOf(params.recipient) - recvBefore;
        if (delivered < params.minBuyAmount) {
            revert InsufficientOutput(delivered, params.minBuyAmount);
        }
        // Return any non-buy token the route touched (sell dust, stranded
        // intermediates) to the trader — the buy token is already with the user.
        _refundResiduals(edges, params.sellToken, params.buyToken, sellTokenBefore, tokenInBefore, tokenOutBefore);
        // Same experimental post-condition invariant as _settle (see its
        // comment for the known, still-open gap it does NOT cover).
        _assertBaselinesHeld(params.sellToken, sellTokenBefore, params.buyToken, buyTokenBeforeFot, edges, tokenInBefore, tokenOutBefore);
        emit SettlementExecuted(
            msg.sender, params.recipient, params.sellToken, params.buyToken,
            params.sellAmount, delivered, 0, delivered, params.benchmarkOutput, edges.length
        );
    }

    /// @dev _executeEdge's direct-delivery twin: a leg whose output IS the buy
    ///      token swaps straight to `recipient` (one transfer, one tax); every
    ///      intermediate leg still lands in this contract to feed the next hop
    ///      via the unchanged _executeEdge. Only V2 can target the recipient
    ///      here — a non-V2 buy-token leg reverts rather than silently routing
    ///      to this contract (which would make the recipient-delta floor
    ///      under-count and revert a good swap).
    function _executeEdgeTo(
        EdgeSwap calldata edge,
        uint256 index,
        uint256 deadline,
        address recipient,
        address buyToken,
        uint256 baseline
    ) internal {
        if (edge.tokenOut == buyToken) {
            uint256 actualIn = _ownBalance(edge.tokenIn, baseline);   // RT-30: own balance only
            if (actualIn > edge.amountIn) actualIn = edge.amountIn;
            if (actualIn == 0) return;
            if (edge.protocol != PROTO_V2_DIRECT) revert UnknownProtocol(index, edge.protocol);
            _swapV2Direct(edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index, recipient);
        } else {
            _executeEdge(edge, index, deadline, baseline);
        }
    }

    // hub V3 (2026-10-22): executeHopFromHelper (the composed-hop draft of 2026-10-07) is REMOVED. It was disabled on every deployment (trustedHopCallers_ empty), a composed
    // hop measured negative against the solver's own plan, and its 1,083 B are needed for the adapter leg and the restricted rescue. `trustedHopCallers_` stays a
    // constructor parameter (signature and deploy tooling unchanged); nothing reads it.

    function _checkParams(ExecuteParams calldata params) private view {
        if (block.timestamp > params.deadline) revert DeadlinePassed();
        if (params.recipient == address(this) || params.recipient == address(0)) revert InvalidRecipient();
        if (params.sellToken == params.buyToken) revert SellBuyTokensSame();
        // MG_C1 (2026-09-14, 3-session red-team). Pool-auth and
        // the produce guard close the fund-LOSS versions of a zero floor,
        // but minBuyAmount=0 is still calldata-controlled and still means
        // "accept literally any output" through an otherwise-legitimate,
        // authenticated pool — a thin/manipulated (sandwiched) real pool can
        // still return a near-worthless amount and this settles it as
        // success. Requiring a nonzero floor costs the caller nothing
        // (their own quote already implies a real expected amount) and
        // removes the one remaining way to represent "I don't care what I
        // get" in calldata. Residual: a NONZERO-but-loose floor is still
        // exploitable by a sandwich/MEV attack against a thin pool - this
        // closes the always-zero case, not the "floor set too low" case,
        // which is an off-chain quote-quality problem, not a contract one.
        if (params.minBuyAmount == 0) revert ZeroFloor();
    }

    /// @dev The shared settlement body: edges -> fee -> floor -> distribute ->
    ///      refund. Callers have already placed params.sellAmount of
    ///      params.sellToken in this contract (transferFrom or native wrap).
    function _settle(
        EdgeSwap[] calldata edges,
        ExecuteParams calldata params,
        bool nativeOut,
        uint256 sellTokenBalanceBefore
    ) private {
        // FEE-BASIS SNAPSHOT (H1 fix, 2026-09-13). Taken
        // BEFORE this swap's own edges run, so it captures whatever the
        // buy-token balance already was for any reason unrelated to this
        // trade — the buy token is deliberately never swept as residue (see
        // _refundLeftover), so a plain donation sent to this contract at any
        // earlier, unrelated moment sits here until whichever swap next
        // settles this exact token inherits it. That balance never touched a
        // pool, so it cannot legitimately answer "did THIS swap's own
        // routing beat or miss the drift guard" — only the DELTA this swap's
        // own edges produce can. Verified live against the deployed contract
        // (0x128716Ea...) via a direct computeFee() call and a fork-free
        // Foundry reproduction (tests/foundry_h1/): an honest -1.5% drift
        // correctly charges 0 both before and after this fix; adding a
        // 6-token donation on top made the unfixed contract charge a fee
        // exceeding the donation (trader net LOWER than the honest
        // no-donation case) while the fixed contract still charges 0 and the
        // donation passes through to the trader as a harmless windfall.
        uint256 buyBalanceBeforeEdges = _balanceOfSelf(params.buyToken);

        // RESIDUE-SNAPSHOT FIX (2026-09-14, independent repro).
        // _refundResiduals used to hand each non-buy token's FULL current
        // balance to msg.sender — the identical bug class as the buy-token
        // distribution issue fixed above, just on the sell/intermediate
        // side, and it predates that fix entirely (introduced in 18085d8,
        // long before H1). execute([], {sellToken: STRANDED, sellAmount: 0,
        // buyToken: ANY, recipient: attacker}) ran zero edges and walked
        // away with any token's entire stranded balance — confirmed on the
        // deployed bytecode of BOTH the un-cutover redeploy and current
        // live production, zero capital required. Snapshot every edge
        // token's balance HERE, before any edge runs (a mid-loop snapshot
        // would catch a multi-hop token mid-swap and refund the wrong
        // amount); the sell token's own pre-pull balance is snapshotted by
        // the caller (sellTokenBalanceBefore) since by the time _settle
        // runs the sell token has already been pulled in.
        (uint256[] memory tokenInBefore, uint256[] memory tokenOutBefore, bool hasMakerLeg) = _snapshotEdgeTokens(edges);

        // Execute each edge in order
        // `i` is bounded by edges.length, so ++i cannot overflow; skipping
        // the compiler's check saves ~30-40 gas per leg. The bound is the
        // proof — this is not a blanket unchecked block.
        uint256 edgeCount = edges.length;
        // RT48-F1: the attestation is judged ONCE, over these edges and this trade's funding owner.
        // On a wallet path a maker leg (PROTO 12/13) executes only under a valid one (and only when an
        // attestor is configured); the relayed path is already bound to its order by RelayedRoute, so
        // there the verdict only decides the fee. executeFot / executeHopFromHelper never run one (RT49-R1).
        bool attested = _benchmarkAttested(params, keccak256(abi.encode(edges)),
            _relayOwner != address(0) ? _relayOwner : msg.sender);
        if (hasMakerLeg && _relayOwner == address(0) && (!attested || BENCHMARK_ATTESTOR == address(0))) revert MakerLegNotAttested();
        for (uint256 i = 0; i < edgeCount;) {
            // the sell token was pulled BEFORE _snapshotEdgeTokens ran, so its
            // baseline is the caller's pre-pull snapshot (RT-30)
            _executeEdge(edges[i], i, params.deadline,
                edges[i].tokenIn == params.sellToken ? sellTokenBalanceBefore : tokenInBefore[i]);
            unchecked { ++i; }
        }

        // Calculate fee from surplus.
        // The benchmark is only trusted when an attestation from
        // BENCHMARK_ATTESTOR covers this exact trade; otherwise the
        // benchmark is treated as +infinity (fee = 0). Combined with the
        // gross-output ceiling this is defense in depth: attestation stops
        // a lying CLIENT, the ceiling bounds a compromised SIGNER.
        uint256 grossOutput = _balanceOfSelf(params.buyToken);
        // FEE BASIS FIX (H1). grossOutput above is the TOTAL contract balance
        // — it can include tokens that arrived from OUTSIDE this swap's own
        // edges (a donation, or leftover dust). Feed the fee math the DELTA
        // this swap's own edges actually produced instead: any pre-existing
        // balance still passes through to the trader below via netOutput/
        // distribution exactly as before (a harmless windfall, same as
        // today), so this changes ONLY what the fee is computed from, never
        // who receives funds.
        uint256 producedByThisSwap = grossOutput > buyBalanceBeforeEdges
            ? grossOutput - buyBalanceBeforeEdges
            : 0;
        uint256 surplusFee = 0;
        if (attested) {
            surplusFee = _calculateSurplusFee(producedByThisSwap, params.benchmarkOutput, params.quotedOutput);
        }
        // DISTRIBUTION BASIS FIX (2026-09-14). netOutput used to
        // be grossOutput - surplusFee, i.e. the FULL balance including any
        // pre-existing stranded buy-token balance - only the FEE was scoped
        // to producedByThisSwap by the H1 fix, never the payout. That let
        // whoever next executed a swap in the stranded token choose
        // params.recipient = themselves and walk away with the full donation:
        // an active theft, not a "harmless windfall" as this file's own H1
        // comment above wrongly called it. Distribute only what THIS swap's
        // own edges produced; any pre-existing balance stays in the contract
        // untouched, protected from a permissionless payout by the sweep()
        // fix below (no _residueOwed record -> sweep() cannot move it either).
        uint256 netOutput = producedByThisSwap - surplusFee;

        // Enforce minimum output (hard floor)
        if (netOutput < params.minBuyAmount) {
            revert InsufficientOutput(netOutput, params.minBuyAmount);
        }

        // Distribute output and emit event. producedByThisSwap, not
        // grossOutput, is what actually moves now - see the netOutput
        // comment above. The event's "grossOutput" field reports the same
        // value for consistency with what surplusFee/netOutput are both
        // actually computed from.
        if (nativeOut) {
            _distributeNative(params, producedByThisSwap, surplusFee, netOutput, edges.length);
        } else {
            _distribute(params, producedByThisSwap, surplusFee, netOutput, edges.length);
        }

        // Refund ANY token the route touched other than the buy token, back to
        // the trader. The buy token's whole balance is the gross that was just
        // distributed; everything else (the sell token's rounding dust AND any
        // intermediate hop token left behind when a downstream leg consumed
        // less than an upstream leg produced) must return to msg.sender.
        // Without this, positive slippage on an intermediate leg stranded value
        // in the contract that a permissionless sweep() then handed to an
        // arbitrary caller — a leak of the user's own funds and a violation of
        // the "holds nothing between trades" invariant.
        _refundResiduals(edges, params.sellToken, params.buyToken, sellTokenBalanceBefore, tokenInBefore, tokenOutBefore);

        // POST-CONDITION INVARIANT (2026-09-14, experimental — testing this
        // independently before trusting it, see the test suite). Every
        // token this swap touched must end at or above where it started.
        // This is a by-construction backstop, not a replacement for the
        // per-path baseline clamps above: it catches ANY future path that
        // leaks a tracked token below its pre-swap balance, known or not.
        // NOTE: this check does NOT catch a trader's OWN fresh pull being
        // paid to an unauthenticated pool that returns nothing, because a
        // legitimate swap and that attack are identical from this contract's
        // own balance-sheet view — both pull sellAmount in and fully consume
        // it, ending back at baseline. That gap is closed by pool
        // authentication (_requireTrustedV2Pool / _requireTrustedV3Pool and the
        // trustedStablePools allowlist, bounty fix 2026-09-14), not by this
        // check.
        _assertBaselinesHeld(params.sellToken, sellTokenBalanceBefore, params.buyToken, buyBalanceBeforeEdges, edges, tokenInBefore, tokenOutBefore);
    }

    function _assertBaselinesHeld(
        address sellToken,
        uint256 sellTokenBefore,
        address buyToken,
        uint256 buyTokenBefore,
        EdgeSwap[] calldata edges,
        uint256[] memory tokenInBefore,
        uint256[] memory tokenOutBefore
    ) private view {
        uint256 sellCur = _balanceOfSelf(sellToken);
        if (sellCur < sellTokenBefore) revert TrackedTokenBelowBaseline(sellToken, sellTokenBefore, sellCur);
        uint256 buyCur = _balanceOfSelf(buyToken);
        if (buyCur < buyTokenBefore) revert TrackedTokenBelowBaseline(buyToken, buyTokenBefore, buyCur);
        uint256 n = edges.length;
        for (uint256 i = 0; i < n;) {
            // sellToken/buyToken are checked above against their own TRUE
            // earliest baseline (pre-pull / pre-edge-loop). tokenInBefore/
            // tokenOutBefore were snapshotted inside _settle, AFTER the
            // sell token was already pulled in — using that snapshot for an
            // edge whose tokenIn/tokenOut happens to BE the sell token
            // would wrongly treat the just-pulled sellAmount as a "pre-
            // existing" balance, tripping on every ordinary swap that fully
            // consumes it. Skip the edge-level check for those two tokens
            // entirely; they're already covered, correctly, above.
            address tIn = edges[i].tokenIn;
            if (tIn != sellToken && tIn != buyToken) {
                uint256 curIn = _balanceOfSelf(tIn);
                if (curIn < tokenInBefore[i]) revert TrackedTokenBelowBaseline(tIn, tokenInBefore[i], curIn);
            }
            address tOut = edges[i].tokenOut;
            if (tOut != sellToken && tOut != buyToken) {
                uint256 curOut = _balanceOfSelf(tOut);
                if (curOut < tokenOutBefore[i]) revert TrackedTokenBelowBaseline(tOut, tokenOutBefore[i], curOut);
            }
            unchecked { ++i; }
        }
    }

    /// @dev Snapshot every edge token's balance ONCE, before any edge in the
    ///      route has moved anything. A multi-hop route reuses a token as
    ///      both tokenOut of leg i and tokenIn of leg i+1; taking this here
    ///      (not inside the edge-execution loop) is what makes every later
    ///      refund delta measure against this swap's true starting point,
    ///      not a mid-route value. Shared by _settle and executeFot (its
    ///      direct-delivery twin, which also calls _refundResiduals).
    function _snapshotEdgeTokens(EdgeSwap[] calldata edges)
        private
        view
        returns (uint256[] memory tokenInBefore, uint256[] memory tokenOutBefore, bool hasMakerLeg)
    {
        uint256 n = edges.length;
        tokenInBefore = new uint256[](n);
        tokenOutBefore = new uint256[](n);
        for (uint256 i = 0; i < n;) {
            tokenInBefore[i] = _balanceOfSelf(edges[i].tokenIn);
            tokenOutBefore[i] = _balanceOfSelf(edges[i].tokenOut);
            // RT48-F1 / RT49-R1: a maker-signed leg (Hashflow 12, Bebop 13) is reported to the caller, which
            // decides whether its path may run one (_settle: only under the v2 attestation; executeFot: never)
            if (edges[i].protocol == PROTO_HASHFLOW || edges[i].protocol == PROTO_BEBOP || edges[i].protocol == PROTO_VENUE_CALL || edges[i].protocol == PROTO_ADAPTER_MAKER) hasMakerLeg = true;
            unchecked { ++i; }
        }
    }

    /// @dev Return every non-buy token the route touched to the trader.
    ///      Idempotent per token: once a token's balance is swept the next
    ///      balanceOf reads 0, so duplicate token addresses across edges cost
    ///      only a view call. The buy token is skipped — its balance is the
    ///      distributed gross.
    ///
    ///      RECIPIENT NOTE: residue is refunded to `msg.sender`, correct for
    ///      the current DIRECT wallet flow where the caller IS the trader (and
    ///      typically the `recipient`). This intentionally mirrors how the sell
    ///      token is pulled — `_safeTransferFrom(sellToken, msg.sender, ...)`.
    ///      If BBS ever relays execution (a router or gasless meta-tx where
    ///      `msg.sender` is a relayer, not the user), this dust would go to the
    ///      relayer. Any such path must first switch the funds source off
    ///      `msg.sender` (Permit2/signature) AND retarget this refund to the
    ///      order's owner. See docs/execution_pillar_design.md §1d.
    function _refundResiduals(
        EdgeSwap[] calldata edges,
        address sellToken,
        address buyToken,
        uint256 sellTokenBefore,
        uint256[] memory tokenInBefore,
        uint256[] memory tokenOutBefore
    ) internal {
        _refundLeftover(sellToken, buyToken, sellTokenBefore);
        uint256 n = edges.length;
        for (uint256 i = 0; i < n;) {
            // Each token ONCE (RT3-01 follow-through): an intermediate is edge
            // i's tokenOut and edge i+1's tokenIn, so the loop used to visit
            // it twice. Harmless while a refund landed (the first visit empties
            // the delta), but a BLOCKED refund left the delta in place and the
            // second visit recorded the same residue again.
            if (!_refundedEarlier(edges, i, edges[i].tokenIn, sellToken, true)) {
                _refundLeftover(edges[i].tokenIn, buyToken, tokenInBefore[i]);
            }
            if (!_refundedEarlier(edges, i, edges[i].tokenOut, sellToken, false)) {
                _refundLeftover(edges[i].tokenOut, buyToken, tokenOutBefore[i]);
            }
            unchecked { ++i; }
        }
    }

    /// @dev Was `token` already visited by the refund loop: the sell token, a
    ///      token of an earlier edge, or (for a tokenOut) this edge's tokenIn.
    function _refundedEarlier(
        EdgeSwap[] calldata edges,
        uint256 i,
        address token,
        address sellToken,
        bool isTokenIn
    ) private pure returns (bool) {
        if (token == sellToken) return true;
        for (uint256 j = 0; j < i;) {
            if (edges[j].tokenIn == token || edges[j].tokenOut == token) return true;
            unchecked { ++j; }
        }
        return !isTokenIn && edges[i].tokenIn == token;
    }

    /// @param before This token's balance before THIS swap touched it at
    ///      all (pre-pull for the sell token, pre-edge-loop for every
    ///      intermediate — see _snapshotEdgeTokens). Only the balance ABOVE
    ///      that baseline is this swap's own dust; a pre-existing stranded
    ///      balance (donation, earlier mis-send) is never this swap's to
    ///      give away, and stays in the contract exactly like sweep()'s
    ///      no-owner branch already leaves it (2026-09-14).
    function _refundLeftover(address token, address buyToken, uint256 before) internal {
        if (token == buyToken) return;
        uint256 current = _balanceOfSelf(token);
        if (current <= before) return;
        uint256 bal = current - before;
        // Best-effort (try-pattern), NOT _safeTransfer: a refund is a
        // courtesy return of residue, so it must never brick an otherwise
        // valid settlement. Normal ERC20s (WPLS/USDC/DAI/...) transfer fine,
        // so the common path returns every wei of intermediate residue.
        // Residue belongs to whoever funded the sell: the caller on the
        // wallet-sent paths, the ORDER OWNER on the relayed path (a relayer
        // must never keep the user's dust).
        address owed = _relayOwner != address(0) ? _relayOwner : msg.sender;
        if (!_tryTransfer(token, owed, bal)) {
            // The refund was blocked (token reverts/false-returns on transfer
            // to this trader — an admin blacklist, or a token engineered to
            // block a victim). Record whom it is owed so a later sweep() can
            // only pay THIS trader, never an arbitrary caller (M-01). The
            // dust stays put until the transfer can land; it is never stolen.
            _residueOwed[token][owed] += bal;
            _residueTotal[token] += bal;
            emit ResidueRecorded(token, owed, bal);
        }
    }

    /// @notice Is this trade's benchmark authorised by the attestor?
    /// @dev Returns TRUE when attestation is disabled (attestor unset) —
    ///      that deployment mode leans on MAX_FEE_BPS_OF_GROSS alone.
    function _benchmarkAttested(ExecuteParams calldata params, bytes32 edgesHash, address owner) internal view returns (bool) {
        if (BENCHMARK_ATTESTOR == address(0)) return true;
        if (block.timestamp > params.attestationDeadline) return false;
        // Reject a deadline further ahead than the replay window. Without a
        // nonce this is what bounds one signature's reuse: a far-future
        // deadline is honoured only in the short window just before it, never
        // now. Fail-safe — an over-far deadline yields fee 0, never a revert.
        if (params.attestationDeadline > block.timestamp + MAX_ATTESTATION_WINDOW) return false;
        if (params.benchmarkSignature.length != 65) return false;
        bytes32 digest = benchmarkDigest(
            params.sellToken, params.buyToken, params.sellAmount,
            params.benchmarkOutput, params.quotedOutput, params.attestationDeadline, edgesHash, owner, params.recipient);
        address rec = _recoverAttestor(digest, params.benchmarkSignature);
        return rec != address(0) && rec == BENCHMARK_ATTESTOR;
    }

    /// @dev The largest fee _calculateSurplusFee can return for these signed numbers, whatever the fill: the quote-time edge
    ///      share, bounded by the gross ceiling taken on the quote (the fill only lowers both). Zero where the fee path waives
    ///      the fee (no edge, or a quote so large the multiply would overflow: RT101-A3, which used to revert the order instead).
    function _maxFeeBound(uint256 quoted, uint256 benchmark) private view returns (uint256 b) {
        if (quoted <= benchmark || quoted > type(uint256).max / FEE_BPS_DENOMINATOR) return 0;
        b = (quoted - benchmark) * SURPLUS_FEE_BPS / FEE_BPS_DENOMINATOR;
        uint256 c = quoted * MAX_FEE_BPS_OF_GROSS / FEE_BPS_DENOMINATOR;
        if (c < b) b = c;
    }

    /// @notice Calculate surplus fee — the quote-time EDGE, applied to what was
    ///         actually delivered.
    ///         feeAtQuote = (quoted - benchmark) * SURPLUS_FEE_BPS / 10000
    ///         ratio      = min(gross / quoted, 1)      // slippage is the user's
    ///         fee        = min(feeAtQuote * ratio, (gross - benchmark) * SURPLUS_FEE_BPS / 10000,
    ///                          min(gross, quoted) * MAX_FEE_BPS_OF_GROSS / 10000)
    ///         Returns 0 if quoted <= benchmark (no edge was demonstrated), if
    ///         gross <= benchmark (the fill did not beat the benchmark), or
    ///         if gross fell more than MAX_FEE_DRIFT_BPS below quoted.
    ///         `gross` no longer gates the fee by itself: it scales it.
    /// @dev THE QUOTE LOCK. The exec fee alone FLOATS with `gross`: a favorable
    ///      block move between quote and fill raises gross, which would raise
    ///      the fee — BBS pocketing ~50% of the user's lucky slippage. That
    ///      violates the fee doctrine (every ambiguity in the user's favour).
    ///      `quotedOutput` is BBS's own best-rate output signed at quote time,
    ///      so `(quoted - benchmark) * bps` is the fee BBS committed to then.
    ///      Adding it to the `min` means execution can only ever LOWER the fee:
    ///      favorable drift (gross > quoted) is kept whole by the user;
    ///      unfavorable drift (gross < quoted) shrinks the fee exactly as
    ///      before. It is `min`-only, so it is NON-WEAPONIZABLE — a compromised
    ///      attestor signing an absurdly HIGH quotedOutput merely makes this
    ///      ceiling non-binding; the gross cap still bounds the fee to <= 0.5%,
    ///      and the multiply is overflow-guarded so an absurd value can never
    ///      revert the swap either.
    function _calculateSurplusFee(
        uint256 grossOutput,
        uint256 benchmarkOutput,
        uint256 quotedOutput
    ) internal view returns (uint256) {
        if (FEE_RECIPIENT == address(0)) return 0;
        // RT3-02 (red team round 3): magnitudes no real token reaches. The
        // checked multiplies below would revert the swap where this function
        // promises fee 0; waive the fee instead of the swap.
        if (quotedOutput > type(uint256).max / FEE_BPS_DENOMINATOR
                || grossOutput > type(uint256).max / FEE_BPS_DENOMINATOR) return 0;
        // NO EDGE AT QUOTE TIME, NO FEE. Both of these are quote-time numbers
        // and both are covered by the attestation, so this is the one honest
        // comparison available: it asks whether BBS ROUTED BETTER, at a single
        // moment, against a rival number from that same moment.
        if (quotedOutput <= benchmarkOutput) return 0;
        uint256 quoteSurplus = quotedOutput - benchmarkOutput; // >= 1

        // WHY NOT (grossOutput - benchmarkOutput). That subtracted an
        // EXECUTION-time amount from a QUOTE-time one — two different moments —
        // so ordinary drift between quoting and settling erased a fee that had
        // genuinely been earned. Measured over the first 24 BBS swaps, 6 of
        // them (25%) showed a real quote-time edge and charged nothing: swap
        // 168 quoted +0.1151% ahead, drifted -0.390%, and paid 0.00bp where the
        // edge was worth 5.75bp; swap 104 quoted +0.3855% ahead and paid
        // nothing after a -9.744% drift. ops.html already states the principle
        // for its own "saved vs rival %" column — "a quantity would shrink with
        // ordinary quote-to-execution drift even when the edge did not move; a
        // ratio does not" — and this makes the contract agree with it.
        //
        // The fee is therefore the quote-time EDGE, applied to what was
        // actually delivered.
        uint256 feeAtQuote;
        unchecked {
            // Overflow-safe: divide back by quoteSurplus (>= 1, never zero) so
            // a lying-HIGH quotedOutput saturates instead of reverting. When
            // SURPLUS_FEE_BPS == 0 this yields 0, matching a fee-disabled
            // deployment.
            uint256 scaled = quoteSurplus * SURPLUS_FEE_BPS;
            feeAtQuote = scaled / quoteSurplus == SURPLUS_FEE_BPS
                ? scaled / FEE_BPS_DENOMINATOR
                : type(uint256).max;
        }

        // DRIFT GUARD, and it is the reason this change is safe to make. A fee
        // must never be charged on a trade that went materially against the
        // user, however good the routing was: swaps 50/56/104 drifted -5% to
        // -9.8%, and charging there would be indefensible to the person who
        // received a tenth less than the screen promised. Inside the window the
        // edge is real and is charged; outside it, nothing is.
        if (grossOutput < quotedOutput
                - (quotedOutput * MAX_FEE_DRIFT_BPS) / FEE_BPS_DENOMINATOR) {
            return 0;
        }

        // Scale the quote-time fee by the delivery ratio, in bps, and never
        // ABOVE 1.0 — positive slippage belongs to the user, not to the fee.
        // Bounded on purpose: grossOutput * 10000 and feeAtQuote * 10000 both
        // stay far inside uint256 for any real amount, so this needs no 512-bit
        // mulDiv and cannot revert a swap on an exotic token's magnitude.
        uint256 ratioBps = (grossOutput * FEE_BPS_DENOMINATOR) / quotedOutput;
        if (ratioBps > FEE_BPS_DENOMINATOR) ratioBps = FEE_BPS_DENOMINATOR;
        uint256 fee = (feeAtQuote * ratioBps) / FEE_BPS_DENOMINATOR;

        // SolidProof M1, FILL-TIME RULE. Everything above is a QUOTE-time number;
        // the benchmark is a rival's price at that moment and the market moves
        // between quote and fill. So the fee is also bounded by the edge the
        // FILL itself shows: SURPLUS_FEE_BPS of (gross - benchmark), and zero
        // when the fill does not beat the benchmark at all. SURPLUS_FEE_BPS is
        // at most 10000, so whenever a fee is charged the user keeps at least
        // the benchmark (gross - fee >= benchmark). `min`-only, so
        // it can only lower the fee. gross <= type(uint256).max / 10000 here,
        // so the multiply cannot overflow.
        if (grossOutput <= benchmarkOutput) return 0;
        uint256 fillEdgeFee = ((grossOutput - benchmarkOutput) * SURPLUS_FEE_BPS) / FEE_BPS_DENOMINATOR;
        if (fee > fillEdgeFee) fee = fillEdgeFee;

        // Gross cap, unconditional: bounded by min(gross, quoted), neither of
        // which the caller can inflate (gross is measured by balanceOf after the
        // swaps; quoted is signed at quote time). Capping at the SMALLER keeps
        // the doctrine exact in EVERY regime — a better-than-quoted fill can
        // never lift this ceiling above its quote-time value, so favorable
        // slippage stays wholly with the user even when the ceiling binds. With
        // a bare gross ceiling, a fill above the quote raised the fee up to
        // feeAtQuote in the >13.636%-surplus regime (reported 2026-09-10,
        // verified on the deployed computeFee); min(gross, quoted) closes that
        // while keeping fee <= 0.5% of gross (quoted <= gross on that path).
        uint256 ceilBase = grossOutput < quotedOutput ? grossOutput : quotedOutput;
        uint256 grossCeiling = (ceilBase * MAX_FEE_BPS_OF_GROSS) / FEE_BPS_DENOMINATOR;
        return fee < grossCeiling ? fee : grossCeiling;
    }

    /// @notice Read-only: compute fee for a gross output, benchmark, and the
    ///         quote-time output that locks the ceiling.
    /// @return fee The fee _calculateSurplusFee charges (see its NatSpec).
    /// @return netOutput grossOutput - fee.
    /// @return fillEdge grossOutput - benchmarkOutput, floored at 0: the edge the FILL shows.
    ///         It bounds the fee (fee <= fillEdge x SURPLUS_FEE_BPS / 10000) but is NOT
    ///         what the fee is computed from, which is the quote-time edge scaled by the delivery ratio.
    function computeFee(
        uint256 grossOutput,
        uint256 benchmarkOutput,
        uint256 quotedOutput
    ) external view returns (uint256 fee, uint256 netOutput, uint256 fillEdge) {
        fee = _calculateSurplusFee(grossOutput, benchmarkOutput, quotedOutput);
        netOutput = grossOutput - fee;
        fillEdge = grossOutput > benchmarkOutput ? grossOutput - benchmarkOutput : 0;
    }

    /// @notice Pay the caller their OWN blocked-refund residue (see
    ///         _refundLeftover / _residueOwed) — never a mis-send or any other
    ///         trader's balance; those stay permanently inert by design (the
    ///         2026-09-14 fix this function's regression tests guard).
    /// @dev Protected by reentrancy check — cannot be called during execute().
    ///      Prevents read-only reentrancy where a malicious token's balanceOf
    ///      callback calls sweep() to steal intermediate tokens.
    ///      Thin wrapper over sweepTo(token, minAmount, msg.sender) — see it
    ///      for the shared entitlement check and payout logic.
    function sweep(address token, uint256 minAmount) external {
        sweepTo(token, minAmount, msg.sender);
    }

    /// @notice Same entitlement as sweep() — pays out ONLY msg.sender's own
    ///         recorded _residueOwed balance — but to a caller-chosen `to`
    ///         instead of hardcoding msg.sender as the destination.
    /// @dev Exists because a blocking/blacklisting token targets a specific
    ///      ADDRESS, not a person: if that address is the trader's own
    ///      msg.sender, sweep() can never land for them, ever — the residue
    ///      is correctly attributed but permanently stuck (see
    ///      RedTeam_StrandedBalance.t.sol's "unrecoverable, by design" case,
    ///      which is about a genuine mis-send with no owner at all; this is
    ///      the sibling case where an owner IS recorded but their one
    ///      allowed payout address is the very address that's blocked).
    ///      `to` only ever changes WHERE msg.sender's own already-owed
    ///      balance goes, never WHO is authorised — the authorisation check
    ///      is identical to sweep()'s, so this opens no new claim on anyone
    ///      else's residue. Guards against address(0)/address(this) the same
    ///      way _checkParams does for a normal recipient.
    function sweepTo(address token, uint256 minAmount, address to) public {
        // Reads the SAME storage slot the reentrancy guard writes (REENTRANCY_SLOT,
        // a regular keccak-derived slot, not transient). This check is the
        // read-only-reentrancy defence (a malicious token's balanceOf
        // callback calling sweep() mid-execute to steal intermediate
        // tokens), so it has to move with the guard.
        if (_entered()) revert Reentrancy();
        if (to == address(0) || to == address(this)) revert InvalidRecipient();
        // RT3-01 (red team round 3, 2026-09-16): the record is per token AND
        // per trader, with the amount. A blocked trader claims their OWN
        // residue once the token lets a transfer land somewhere they can
        // receive it; nobody else's, and never a balance no trade recorded
        // (a mis-send stays inert, as before, 2026-09-14). One slot per
        // token let a later blocked refund overwrite an earlier trader's
        // record and then sweep the whole balance, theirs and everyone
        // else's.
        uint256 owedAmt = _residueOwed[token][msg.sender];
        if (owedAmt == 0) revert NothingToSweep();
        uint256 balance = _balanceOfSelf(token);
        uint256 pay = owedAmt < balance ? owedAmt : balance;
        if (pay == 0 || pay < minAmount) revert NothingToSweep();
        _residueOwed[token][msg.sender] = owedAmt - pay;
        _residueTotal[token] -= pay;
        _safeTransfer(token, to, pay);
        emit ResidueSwept(token, msg.sender, to, pay);
    }

    /// @notice What `owner` can still claim with sweep()/sweepTo() for `token` (blocked-refund residue; 0 if none).
    function residueOf(address token, address owner) external view returns (uint256) {
        return _residueOwed[token][owner];
    }

    /// @notice hub V3 (2026-10-22, operator decision): a RESTRICTED rescue, not an owner's `rescueFunds`. Only the GUARDIAN; never during a swap (the same reentrancy
    ///         read as sweepTo); pays ONLY to the FEE_RECIPIENT fixed at deploy; and only the part of the balance no trader is owed (`_residueTotal`), so a trader's
    ///         recorded residue is never touched. It recovers what nobody can claim: dust an adapter or venue left, or a token sent here by mistake.
    function rescue(address token) external onlyGuardian {
        if (_entered()) revert Reentrancy();
        uint256 bal = _balanceOfSelf(token);
        uint256 owedTotal = _residueTotal[token];
        if (bal <= owedTotal) return;
        unchecked { bal -= owedTotal; }
        _safeTransfer(token, FEE_RECIPIENT, bal);
        emit Rescued(token, bal);
    }

    function _distribute(
        ExecuteParams calldata params,
        uint256 grossOutput,
        uint256 surplusFee,
        uint256 netOutput,
        uint256 edgeCount
    ) internal {
        // Send net output to user
        // Relayed settlement: the relayer's refund comes out of the user's net
        // (the floor already covered it: params.minBuyAmount >= order.min + refund).
        uint256 refund = _relayRefund;
        if (refund > 0) {
            _safeTransfer(params.buyToken, msg.sender, refund);
            netOutput -= refund;
        }
        // RECIPIENT-DELIVERY FLOOR (2026-10-02). Everything above this line prices
        // and floors `netOutput` against what the CONTRACT received (the H1 +
        // 2026-09-14 fixes above already made that delta-correct) — but this single
        // transfer is the first point this settlement ever asks what the RECIPIENT
        // actually received. A buy token that taxes THIS specific transfer (custody
        // -> user, as opposed to pool -> custody, which the balance delta above
        // already prices correctly) would otherwise hand the user less than
        // `netOutput` with nothing here to notice or stop it — exactly the
        // "nets owner below signed min" class hunters keep reporting on untracked
        // fee-on-transfer tokens the off-chain router failed to classify in advance
        // (see tax-tokens-out-of-scope). `executeFot` already measures and floors
        // the recipient's own balance delta for every-transfer tokens it knows
        // about; this applies that SAME, already-proven pattern as a backstop on
        // the ordinary custody path too, so protection no longer depends entirely
        // on correct advance classification. Reverting (not silently shorting) a
        // trade this path cannot price correctly is strictly better for the user:
        // they keep their original funds and can retry via executeFot/a route that
        // handles this token, instead of silently receiving less than they signed.
        uint256 recipientBefore = IERC20(params.buyToken).balanceOf(params.recipient);
        _safeTransfer(params.buyToken, params.recipient, netOutput);
        uint256 delivered = IERC20(params.buyToken).balanceOf(params.recipient) - recipientBefore;
        if (delivered + RECIPIENT_DELIVERY_WEI_TOLERANCE < netOutput) {
            revert InsufficientOutput(delivered, netOutput);
        }

        // Send fee to fee recipient (if any).
        // Use try-pattern: if fee transfer fails (e.g. FEE_RECIPIENT is a
        // reverting contract), send the fee to the user instead of bricking
        // the entire settlement. User always gets their output.
        if (surplusFee > 0 && FEE_RECIPIENT != address(0)) {
            if (!_tryTransfer(params.buyToken, FEE_RECIPIENT, surplusFee)) {
                // RT-FOT-1 Track A fix (2026-10-02, found same-day re-attack of the
                // recipient-delivery floor above): this fallback pays `params.recipient`
                // a BONUS on top of the `netOutput` they already received, floor-verified,
                // a few lines above -- their signed `minBuyAmount` is already satisfied by
                // that earlier transfer, regardless of what happens here. Unlike the main
                // payout, a shortfall on THIS transfer must NOT revert the whole
                // settlement -- that would brick an already-fully-satisfied trade over an
                // incidental bonus, exactly the bricking this fallback exists to prevent
                // (see the comment above). The gap this round found: the old code still
                // blindly set `surplusFee = 0` regardless of what the recipient actually
                // received, so a buyToken that taxes THIS specific transfer made the
                // emitted event (and this variable) silently overstate the bonus the user
                // got -- cosmetic (surplusFee is read only by the event below), but
                // measuring it properly is free now that the UniV4 facet split recovered
                // the headroom this fix needs.
                uint256 recipientFeeBefore = IERC20(params.buyToken).balanceOf(params.recipient);
                _safeTransfer(params.buyToken, params.recipient, surplusFee);
                // SolidProof I6: the redirected fee is part of what the recipient got, so it joins
                // netOutput in the event and surplusFee reads 0 (no fee was taken).
                netOutput += IERC20(params.buyToken).balanceOf(params.recipient) - recipientFeeBefore;
                surplusFee = 0;
            }
        }

        // Leftover sell-token dust AND any stranded intermediate hop token are
        // returned to the trader by _refundResiduals() after this call — see
        // execute(). Keeping the refund in one place stops an intermediate
        // token from being left behind for a permissionless sweep().

        emit SettlementExecuted(
            msg.sender, params.recipient, params.sellToken, params.buyToken,
            params.sellAmount, grossOutput, surplusFee, netOutput,
            params.benchmarkOutput, edgeCount
        );
    }

    /// @dev _distribute's native twin: fee stays in the WRAPPED token (the
    ///      ledger and fee wallet are unchanged); the user's NET is unwrapped
    ///      via the wrapper's own withdraw() — accepted by the guarded
    ///      receive() — and pushed as native. A failing native send REVERTS
    ///      the settlement (the user chose the recipient; a silent WETH
    ///      fallback here would be a bait-and-switch on the asset kind).
    function _distributeNative(
        ExecuteParams calldata params,
        uint256 grossOutput,
        uint256 surplusFee,
        uint256 netOutput,
        uint256 edgeCount
    ) internal {
        // RT34 fix (2026-10-01): pin buyToken to the real wrapper before
        // treating its reported balance/withdraw() as native-backed — the
        // same guard _univ4Take already has on this exact immutable
        // constant. Without it, nativeOut (an independent calldata flag on
        // executeToNative/executeRelayedToNative) let a caller pick any
        // buyToken; an attacker-deployed fake wrapper with a fabricated
        // balanceOf and a no-op withdraw() could push ETH already stranded
        // on this contract to params.recipient as real unwrap proceeds.
        if (params.buyToken != WRAPPED_NATIVE) revert WrongNativeWrapper();
        if (surplusFee > 0 && FEE_RECIPIENT != address(0)) {
            if (!_tryTransfer(params.buyToken, FEE_RECIPIENT, surplusFee)) {
                netOutput += surplusFee;   // failed fee goes to the user, as native
                surplusFee = 0;
            }
        }
        // Relayed settlement (executeRelayedToNative): the relayer's refund is
        // paid in the WRAPPED token before the unwrap; the floor already covered
        // it (params.minBuyAmount >= order.min + refund, and netOutput passed
        // that floor), so netOutput - refund >= order.min holds here too.
        uint256 refund = _relayRefund;
        if (refund > 0) {
            _safeTransfer(params.buyToken, msg.sender, refund);
            netOutput -= refund;
        }
        _setNativeUnwrap(params.buyToken);
        IWrappedNative(params.buyToken).withdraw(netOutput);
        _setNativeUnwrap(address(0));
        (bool ok, ) = params.recipient.call{value: netOutput}("");
        if (!ok) revert NativeSendFailed();
        emit SettlementExecuted(
            msg.sender, params.recipient, params.sellToken, params.buyToken,
            params.sellAmount, grossOutput, surplusFee, netOutput,
            params.benchmarkOutput, edgeCount
        );
    }

    function _ownBalance(address token, uint256 baseline) private view returns (uint256) {
        uint256 balance = _balanceOfSelf(token);
        return balance > baseline ? balance - baseline : 0;
    }

    /// @param baseline the token's balance BEFORE this trade added anything
    ///        (pre-pull for the sell token, pre-edge-loop for every other):
    ///        a leg may spend only what this trade itself brought in.
    function _executeEdge(EdgeSwap calldata edge, uint256 index, uint256 deadline, uint256 baseline) internal {
        // Use min(planned, OWN balance) for the input amount. "Own" = the
        // balance above the pre-trade baseline. For intermediate tokens the
        // amount prior edges produced may differ from the planned amount;
        // min() never spends more than this trade holds, and the surplus is
        // captured by later edges consuming the same token. Spending the
        // WHOLE balance (red-team RT-30, 2026-09-16) let one stranded wei of
        // any token be consumed by a MAX-sentinel leg, after which
        // _assertBaselinesHeld saw the token below its baseline and reverted
        // every such swap of that token, permanently, on the live contract.
        uint256 actualIn = _ownBalance(edge.tokenIn, baseline);
        if (actualIn > edge.amountIn) actualIn = edge.amountIn;
        if (actualIn == 0) return;

        // PER-LEG PRODUCE GUARD (2026-09-14, independently
        // verified). Every _swap* below floors its OWN reported amountOut
        // against edge.minAmountOut — vacuous at minAmountOut=0, which the
        // calldata controls. Worse: some protocols (STABLE's coin indices,
        // most concretely) let a caller-supplied parameter make a REAL,
        // TRUSTED, allowlisted pool actually deliver a DIFFERENT token than
        // edge.tokenOut declares. That leg then "succeeds" at amountOut=0
        // for the declared tokenOut while real value lands in the contract
        // as a token nothing tracks - not stolen, but a real trader's real
        // funds evaporate into an untracked, permanently stuck balance.
        // Checking tokenOut's balance ONCE at the end of the whole swap
        // (the existing invariant) cannot catch this: tokenOut legitimately
        // never moves, so it never drops below its baseline either. This
        // must be checked per-leg, immediately, against the declared
        // tokenOut specifically - not deferred to the aggregate invariant.
        uint256 __outBefore = _balanceOfSelf(edge.tokenOut);

        if (edge.protocol == PROTO_V2_DIRECT) {
            _swapV2Direct(edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index, address(this));
        } else if (edge.protocol == PROTO_V3_ROUTER) {
            _swapV3Direct(edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, index);
        } else if (edge.protocol == PROTO_BALANCER) {
            _swapBalancer(edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index, deadline);
        } else if (edge.protocol == PROTO_STABLE) {
            _swapStable(edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index);
        } else if (edge.protocol == PROTO_BALANCER_V3) {
            _swapBalancerV3(edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, index, deadline);
        } else if (edge.protocol == PROTO_UNIV4) {
            _swapUniV4(edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index);
        } else if (edge.protocol == PROTO_HASHFLOW || edge.protocol == PROTO_BEBOP || edge.protocol == PROTO_PROPAMM
                || edge.protocol == PROTO_VENUE_CALL) {
            _swapVenue(edge.protocol, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index);
        } else if (edge.protocol == PROTO_ADAPTER || edge.protocol == PROTO_ADAPTER_MAKER) {
            _swapAdapter(edge.protocol, edge.pool, edge.tokenIn, edge.tokenOut, actualIn, edge.minAmountOut, edge.extraData, index);
        } else {
            revert UnknownProtocol(index, edge.protocol);
        }

        if (_balanceOfSelf(edge.tokenOut) <= __outBefore) {
            _edgeFail(index, edge.pool, edge.protocol);
        }
    }

    // --- External venue legs (2026-10-17): Hashflow (12), Bebop (13), PropAMM Router (14) ---
    /// @dev ONE delegatecall into VENUE_FACET (contracts/VenueHubFacet.sol) for every external venue.
    ///      The facet pins what each venue may not choose (Hashflow: trader = this contract, the leg's
    ///      tokens, input <= the signed maximum; Bebop: the RT17/RT48 order pins; PropAMM: empty
    ///      extraData), approves exactly the leg input, resets the allowance to 0 and judges the
    ///      tokenOut delta against the leg floor. Fails closed when no facet is wired (PulseChain).
    function _swapVenue(
        uint8 proto,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) internal {
        address facet = VENUE_FACET;
        // RTVH-F1: HASHFLOW_ROUTER == 0 still means "Hashflow off" on this settlement, exactly as the inline leg it
        // replaced refused it -- the hub's own router constant must not switch Hashflow on behind the deployer's back.
        if (facet == address(0) || (proto == PROTO_HASHFLOW && HASHFLOW_ROUTER == address(0))) _edgeFail(index, address(0), proto);
        bytes4 sel = proto == PROTO_HASHFLOW ? IVenueHubFacet.hashflowSwap.selector
            : (proto == PROTO_BEBOP ? IVenueHubFacet.bebopSwap.selector
                : (proto == PROTO_VENUE_CALL ? IVenueHubFacet.venueCall.selector : IVenueHubFacet.propAmmSwap.selector));
        (bool ok, bytes memory ret) = facet.delegatecall(
            abi.encodeWithSelector(sel, tokenIn, tokenOut, amountIn, minAmountOut, extraData, index));
        if (!ok) {
            // Bubble the facet's own revert data verbatim (EdgeSwapFailed with the same args).
            assembly { revert(add(ret, 32), mload(ret)) }
        }
    }

    /// @dev Kyber's per-swap flow for ONE adapter leg. `extraData = abi.encodePacked(uint8 mode, address approveTarget, bytes callData)` (1 + 20 + n bytes): mode 0 transfers exactly `amountIn`
    ///      to the adapter, mode 1 approves `approveTarget` (0 = the adapter) for exactly `amountIn`. The adapter (and a distinct approveTarget) must be listed with the
    ///      kind this protocol number requires; the call is `adapter.call(callData)` with no value; the tokenOut balance must rise by at least `minAmountOut`; the approval is
    ///      reset to 0. A bad adapter can deliver less than expected, never less than the leg's floor.
    function _swapAdapter(
        uint8 proto,
        address adapter,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) internal {
        address reg = ADAPTER_REGISTRY;
        if (reg == address(0)) _edgeFail(index, adapter, proto);
        if (extraData.length < 22) _edgeFail(index, adapter, proto);
        uint256 mode;
        address approveTarget;
        assembly { mode := shr(248, calldataload(extraData.offset)) approveTarget := shr(96, calldataload(add(extraData.offset, 1))) }
        if (IAdapterRegistry(reg).kindOf(adapter) != (proto == PROTO_ADAPTER ? 1 : 2)) _edgeFail(index, adapter, proto);
        if (mode > 1 || adapter == address(this) || adapter == tokenIn || adapter == tokenOut) _edgeFail(index, adapter, proto);
        address spender = approveTarget == address(0) ? adapter : approveTarget;
        uint256 outBefore = _balanceOfSelf(tokenOut);
        if (mode == 0) {
            _safeTransfer(tokenIn, adapter, amountIn);
        } else {
            if (spender != adapter && IAdapterRegistry(reg).kindOf(spender) == 0) _edgeFail(index, spender, proto);
            if (spender == address(this) || spender == tokenIn || spender == tokenOut) _edgeFail(index, spender, proto);
            _safeApprove(tokenIn, spender, amountIn);
        }
        bool ok;
        assembly {
            let n := sub(extraData.length, 21)
            let ptr := mload(0x40)
            calldatacopy(ptr, add(extraData.offset, 21), n)
            ok := call(gas(), adapter, 0, ptr, n, 0, 0)
        }
        if (mode == 1) _safeApprove(tokenIn, spender, 0);
        if (!ok || _balanceOfSelf(tokenOut) < outBefore + minAmountOut) _edgeFail(index, adapter, proto);
    }

    // --- V2 Direct Pool Swap ---
    function _swapV2Direct(
        address pool,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index,
        address to
    ) internal {
        // POOL AUTHENTICATION (bounty report). `pool` is caller-supplied calldata;
        // without this, a contract that merely implements swap()/token0()/
        // getReserves() and keeps whatever gets pushed to it passes every
        // downstream check (amountOut < minAmountOut is vacuous at
        // minAmountOut=0). Require it to be a REAL pair some trusted
        // factory itself recognizes, checked BEFORE any funds move.
        _requireTrustedV2Pool(pool, tokenIn, tokenOut, index);

        uint256 feeFactor = extraData.length >= 32
            ? abi.decode(extraData, (uint256))
            : 9971;

        _safeTransfer(tokenIn, pool, amountIn);

        address token0 = IUniswapV2Pair(pool).token0();
        // Reserve reads and the intermediate products are scoped so they free
        // their stack slots before the swap call below (the added `to` param
        // pushed this function past the 16-slot EVM stack limit otherwise).
        uint256 amountOut;
        {
            (uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(pool).getReserves();
            (uint256 reserveIn, uint256 reserveOut) = tokenIn == token0
                ? (uint256(reserve0), uint256(reserve1))
                : (uint256(reserve1), uint256(reserve0));
            uint256 amountInWithFee = amountIn * feeFactor;
            amountOut = (amountInWithFee * reserveOut) / (reserveIn * 10000 + amountInWithFee);
        }

        if (amountOut < minAmountOut) {
            _edgeFail(index, pool, PROTO_V2_DIRECT);
        }

        if (tokenIn == token0) {
            IUniswapV2Pair(pool).swap(0, amountOut, to, "");
        } else {
            IUniswapV2Pair(pool).swap(amountOut, 0, to, "");
        }
    }

    /// @dev Reverts unless SOME trusted factory's own getPair(tokenIn,
    ///      tokenOut) returns exactly `pool` — a registry check against the
    ///      real, live DEX factory, not a value this contract computes or
    ///      trusts from calldata. An empty trustedV2Factories (unconfigured
    ///      deployment) fails closed: every V2 leg reverts, same posture as
    ///      every other optional-protocol zero-address disable in this file.
    function _requireTrustedV2Pool(address pool, address tokenIn, address tokenOut, uint256 index) private view {
        if (pool == address(0)) revert UntrustedPool(pool, PROTO_V2_DIRECT, index);        // SolidProof I4: getPair returns 0 for a pair that does not exist
        uint256 n = trustedV2Factories.length;
        for (uint256 i = 0; i < n; ) {
            if (IUniswapV2Factory(trustedV2Factories[i]).getPair(tokenIn, tokenOut) == pool) return;
            unchecked { ++i; }
        }
        revert UntrustedPool(pool, PROTO_V2_DIRECT, index);
    }

    // --- V3 Direct Pool Swap (any V3 DEX; no per-DEX router, no approval) ---
    // Swaps DIRECTLY against edge.pool, exactly as _swapV2Direct talks to a V2
    // pool. Works on 9mm (Pancake fork) / LibertySwap / Uniswap V3 alike — the
    // swap() + token0/1 ABI is identical; only the callback NAME differs, handled
    // below. The pool's callback PUSHES the input from this contract, so no
    // allowance is ever set. Output is measured by the buy-token balance delta
    // (the pool moves it here), so a thin/partial fill returns fewer tokens and
    // is caught by the final params.minBuyAmount — never a per-DEX-router revert.
    function _swapV3Direct(
        address pool,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        uint256 index
    ) internal {
        // POOL AUTHENTICATION (bounty report). The V3 callback's own check
        // (msg.sender == _v3ExpectedPool()) is self-referential — it only
        // proves the callback came from whatever address THIS call just
        // dialed, which is `pool` itself when `pool` is the attacker's own
        // contract. Prove `pool` is a REAL pool some trusted factory
        // deployed BEFORE binding the callback to it or sending anything.
        _requireTrustedV3Pool(pool, tokenIn, tokenOut, index);

        bool zeroForOne = tokenIn == IUniswapV3Pool(pool).token0();
        if (amountIn > uint256(type(int256).max)) revert AmountOutOfRange();      // a value >= 2**255 would read as a NEGATIVE (exact-output) amount
        uint256 balBefore = _balanceOfSelf(tokenOut);
        // Bind the callback to THIS pool, swap, then clear the binding.
        _setV3ExpectedPool(pool);
        IUniswapV3Pool(pool).swap(
            address(this),
            zeroForOne,
            int256(amountIn),
            zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1,
            ""
        );
        _setV3ExpectedPool(address(0));
        uint256 amountOut = _balanceOfSelf(tokenOut) - balBefore;
        if (amountOut < minAmountOut) {
            _edgeFail(index, pool, PROTO_V3_ROUTER);
        }
    }

    /// @dev Reverts unless SOME trusted factory's own getPool(tokenIn,
    ///      tokenOut, fee) returns exactly `pool` — `fee` read from the
    ///      pool itself, since EdgeSwap carries no separate fee field. A
    ///      fake pool either reverts on fee() (no such function) or returns
    ///      a value that no real factory's getPool maps back to this
    ///      address, so this fails closed either way.
    ///      Algebra-style factories (SwitchX V4 on PulseChain) key pools by
    ///      PAIR, not (pair, fee): the real pool's fee is dynamic, so getPool
    ///      can never map it back (every SwitchX leg reverted UntrustedPool
    ///      after the MG_C1 cutover, 2026-09-16). Each trusted factory is
    ///      also asked poolByPair(tokenIn, tokenOut) via staticcall (a
    ///      factory without that selector simply fails the probe). The
    ///      factory is still the sole authority: only a pool it created
    ///      is returned, so this widens nothing for a fake pool.
    function _requireTrustedV3Pool(address pool, address tokenIn, address tokenOut, uint256 index) private view {
        if (pool == address(0)) revert UntrustedPool(pool, PROTO_V3_ROUTER, index);
        uint24 fee = IUniswapV3Pool(pool).fee();
        uint256 n = trustedV3Factories.length;
        for (uint256 i = 0; i < n; ) {
            address f = trustedV3Factories[i];
            // SolidProof I4: a staticcall, so a factory without getPool is skipped instead of reverting every V3 leg.
            (bool okp, bytes memory retp) = f.staticcall(abi.encodeWithSelector(IUniswapV3Factory.getPool.selector, tokenIn, tokenOut, fee));
            if (okp && retp.length == 32 && abi.decode(retp, (address)) == pool) return;
            (bool ok, bytes memory ret) = f.staticcall(
                abi.encodeWithSelector(0xd9a641e1, tokenIn, tokenOut)); // poolByPair(address,address)
            if (ok && ret.length == 32 && abi.decode(ret, (address)) == pool) return;
            unchecked { ++i; }
        }
        revert UntrustedPool(pool, PROTO_V3_ROUTER, index);
    }

    // The three V3-fork swap callbacks (identical signature, different names):
    // 9mm = pancakeV3SwapCallback, LibertySwap = libertyV3SwapCallback, Uniswap
    // = uniswapV3SwapCallback. All dispatch to ONE handler.
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _v3PayCallback(amount0Delta, amount1Delta);
    }
    function pancakeV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _v3PayCallback(amount0Delta, amount1Delta);
    }
    function libertyV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _v3PayCallback(amount0Delta, amount1Delta);
    }
    /// @dev SwitchX V4 (Algebra-Integral-derived pools, whitepaper-confirmed
    ///      callback name). The REAL pool — resolved by the calldata builder
    ///      via the V4 factory's poolByPair, never the read-only Pancake-compat
    ///      proxy — speaks the standard V3 swap()+token0/1 interface and calls
    ///      back this selector (0x6a5ac18f, verified on-chain). Same guarded
    ///      handler: only the pool bound by the in-flight _swapV3Direct is
    ///      honoured, so this adds zero new attack surface.
    function v4SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external {
        _v3PayCallback(amount0Delta, amount1Delta);
    }

    // --- PSM / Balancer V1 / DODO / Fluid / Ringswap: REMOVED 2026-09-14 ---
    // All five had the identical untrusted-pool pattern the bounty report described
    // for V2/V3 (push or approve to a caller-supplied `pool` address with no
    // on-chain authentication that it's real) and NONE of them appear in
    // any currently-configured routing provider on either chain (grepped
    // config/mainnet_amm_provider_registry.{ethereum,pulsechain}.json —
    // zero hits for dodo/fluid/ringswap/balancer_v1/psm as of this commit).
    // Removing dead, vulnerable code closes the class completely (nothing
    // to exploit) and reclaims the code size STABLE/V3 authentication
    // needs, rather than leaving them gated-but-present. PROTO_PSM/BV1/
    // DODO/FLUID/RINGSWAP now fall through _executeEdge's dispatch to
    // UnknownProtocol — restoring any of these requires writing the same
    // pool-authentication treatment V2/V3/STABLE got, not just uncommenting
    // this diff.

    // hub V3 (2026-10-22): the inline Ekubo leg (PROTO_EKUBO = 10, EKUBO_FACET delegatecall) is REMOVED from the settlement to make room for the adapter dispatch;
    // Ekubo is a second-wave ADAPTER (docs/HUB_V3_ADAPTER_DESIGN_2026_10_22.md). EKUBO_* immutables stay so the constructor signature and the deploy tooling are unchanged.

    /// @dev Leg-vs-key orientation. mode: 0 = ERC20 both sides, 1 = native
    ///      input (leg tokenIn is the wrapper), 2 = native output (leg
    ///      tokenOut is the wrapper), 3 = mismatch (caller fails closed).
    ///      Historically shared by _swapUniV4 (Ekubo-adjacent despite the
    ///      name); as of the 2026-10-02 UniV4 facet split, this main-contract
    ///      copy has no remaining caller (EkuboSwapFacet.sol keeps its own
    ///      independent copy for _swapEkubo's delegatecall target; UniV4's
    ///      own copy now lives in UniV4SwapFacet.sol for the same reason) and
    ///      has been deleted here -- see UniV4SwapFacet.sol's file-level doc
    ///      comment for the full reasoning.

    // --- Uniswap V4 PoolManager Swap (canonical V4) ---
    // 2026-10-02 facet split (docs/FACET_SPLIT_DESIGN_PROPOSAL_2026_09_17.md's own
    // named next candidate after Ekubo -- V4 pools are largely absent from the live
    // routing graph, unlike V2/V3/Stable/Hashflow, which the same doc keeps inline).
    // _swapUniV4's own logic now lives in UniV4SwapFacet.sol, delegatecalled from here
    // exactly like _swapEkubo delegatecalls into EkuboSwapFacet. unlockCallback below
    // CANNOT move into the facet itself: the PoolManager calls back the exact address
    // that called unlock(), which under delegatecall is always this contract's own
    // address, never the facet's -- so unlockCallback stays here as a thin,
    // real-dispatchable wrapper that itself delegatecalls into the facet's own
    // univ4UnlockCallback, mirroring the _swapEkubo pattern one layer deeper. See
    // UniV4SwapFacet.sol's file-level doc comment for the full reasoning, including why
    // this is safe under delegatecall's msg.sender-preservation semantics.
    function _swapUniV4(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) internal {
        address facet = UNIV4_FACET;
        if (facet == address(0)) _edgeFail(index, address(0), PROTO_UNIV4);
        (bool ok, bytes memory ret) = facet.delegatecall(
            abi.encodeWithSelector(
                IUniV4SwapFacet.univ4Swap.selector,
                UNIV4_POOL_MANAGER, tokenIn, tokenOut, amountIn, minAmountOut, extraData, index
            )
        );
        if (!ok) {
            // Bubble the facet's own revert data verbatim -- same selector, same
            // decoded args a direct EdgeSwapFailed(...) revert would have produced
            // (see UniV4SwapFacet.sol's matching error declarations).
            assembly { revert(add(ret, 32), mload(ret)) }
        }
    }

    /// @dev Uniswap V4 unlock re-entry. Honoured ONLY from the PoolManager and
    ///      ONLY while a _swapUniV4 unlock is in flight (slot guard, enforced inside
    ///      the facet this delegatecalls into) -- the manager calls back the account
    ///      that called unlock(), so this pair of checks pins the payload to the
    ///      abi.encoded arguments this contract itself just passed — never
    ///      attacker-supplied bytes. Thin wrapper (2026-10-02 facet split) -- see the
    ///      comment above _swapUniV4 for why this entry point cannot itself move into
    ///      UniV4SwapFacet.sol.
    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        address facet = UNIV4_FACET;
        if (facet == address(0)) revert UnexpectedV4Unlock();
        (bool ok, bytes memory ret) = facet.delegatecall(
            abi.encodeWithSelector(
                IUniV4SwapFacet.univ4UnlockCallback.selector,
                UNIV4_POOL_MANAGER, WRAPPED_NATIVE, data
            )
        );
        if (!ok) {
            assembly { revert(add(ret, 32), mload(ret)) }
        }
        // Verbatim passthrough of the facet's own return bytes -- nothing on this
        // call chain reads unlockCallback's return value (the PoolManager's own
        // unlock() caller, _swapUniV4, already discards it; see UniV4SwapFacet.sol's
        // univ4Swap, which never captures unlock()'s return), so re-encoding through
        // Solidity's type system would add bytecode for a value nothing consumes.
        assembly { return(add(ret, 32), mload(ret)) }
    }

    function _v3PayCallback(int256 amount0Delta, int256 amount1Delta) private {
        // SECURITY: honour the callback ONLY from the pool _swapV3Direct set.
        // Outside a swap the slot is 0, so any external caller (msg.sender != 0)
        // is rejected — no arbitrary-address call surface, no unsolicited pull.
        address pool = _v3ExpectedPool();
        if (msg.sender != pool) revert UnexpectedV3Callback();
        // Pay the POSITIVE delta — the input this contract owes the pool.
        if (amount0Delta > 0) {
            _safeTransfer(IUniswapV3Pool(pool).token0(), pool, uint256(amount0Delta));
        }
        if (amount1Delta > 0) {
            _safeTransfer(IUniswapV3Pool(pool).token1(), pool, uint256(amount1Delta));
        }
    }

    // --- Balancer V2 Vault Swap ---
    function _swapBalancer(
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index,
        uint256 deadline
    ) internal {
        bytes32 poolId = abi.decode(extraData, (bytes32));
        _safeApprove(tokenIn, BALANCER_VAULT, amountIn);
        uint256 amountOut = IBalancerVault(BALANCER_VAULT).swap(
            IBalancerVault.SingleSwap({
                poolId: poolId,
                kind: IBalancerVault.SwapKind.GIVEN_IN,
                assetIn: tokenIn,
                assetOut: tokenOut,
                amount: amountIn,
                userData: ""
            }),
            IBalancerVault.FundManagement({
                sender: address(this),
                fromInternalBalance: false,
                recipient: payable(address(this)),
                toInternalBalance: false
            }),
            minAmountOut,
            deadline
        );
        _safeApprove(tokenIn, BALANCER_VAULT, 0);
        if (amountOut < minAmountOut) {
            _edgeFail(index, BALANCER_VAULT, PROTO_BALANCER);
        }
    }

    // --- Balancer V3 (TIDE) BatchRouter swap, via Permit2 ---
    // Unlike V2/stable (approve venue -> venue pulls), Balancer V3 pulls tokenIn
    // through a Permit2 intermediary, so the leg is a three-step dance to FIXED
    // immutable addresses (BALANCER_V3_PERMIT2, BALANCER_V3_ROUTER):
    //   1. ERC20-approve Permit2 to move exactly amountIn of tokenIn.
    //   2. Permit2.approve(router) for exactly amountIn (approve OVERWRITES; its
    //      transferFrom then decrements, so this is self-clearing to 0 on use).
    //   3. router.swapExactIn(single one-step path) — the router pulls tokenIn
    //      via Permit2 into the Vault and sends tokenOut back to THIS contract.
    // Then the ERC20 allowance to Permit2 is reset to 0 (exact-approve-then-
    // reset): with it at 0 the standing Permit2->router allowance is inert, so
    // nothing can pull this contract's tokens after the leg. edge.pool is the
    // only calldata-supplied address; the Vault validates it (an unregistered
    // pool reverts atomically). Output is measured by balanceOf delta and gated
    // by the final params.minBuyAmount, exactly like the V3 direct path.
    function _swapBalancerV3(
        address pool,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        uint256 index,
        uint256 deadline
    ) internal {
        if (amountIn > type(uint160).max || deadline > type(uint48).max) revert AmountOutOfRange();
        _safeApprove(tokenIn, BALANCER_V3_PERMIT2, amountIn);
        // Permit2 amount is uint160, expiration uint48. Both amountIn (a token
        // balance) and deadline (a unix timestamp, already checked > now in
        // execute) fit their widths for any real trade; a value that did not
        // fit would truncate to a smaller allowance/earlier expiry and revert
        // atomically inside the router — never a silent under-pull.
        IPermit2(BALANCER_V3_PERMIT2).approve(
            tokenIn, BALANCER_V3_ROUTER, uint160(amountIn), uint48(deadline));

        // A Balancer V3 ERC4626 buffer (wrap/unwrap) step encodes the wrapped
        // token ITSELF as the step's `pool`, so `pool == tokenIn` (unwrap:
        // wrapped -> underlying) or `pool == tokenOut` (wrap: underlying ->
        // wrapped). A real pool is a distinct contract and can never equal a
        // token it trades, so this detection has no false positives. Enabling
        // it lets boosted-pool routes move the raw underlying through the buffer
        // (the only thing the old hardcoded isBuffer=false blocked). Security is
        // unchanged: `pool` is still only edge.pool (calldata), the Vault
        // validates the buffer just like a pool (a fake/uninitialised buffer
        // reverts atomically), and output is still balanceOf-delta under the
        // single final floor.
        bool isBuffer = (pool == tokenIn || pool == tokenOut);
        IBalancerV3BatchRouter.SwapPathStep[] memory steps =
            new IBalancerV3BatchRouter.SwapPathStep[](1);
        steps[0] = IBalancerV3BatchRouter.SwapPathStep({
            pool: pool,
            tokenOut: tokenOut,
            isBuffer: isBuffer
        });
        IBalancerV3BatchRouter.SwapPathExactAmountIn[] memory paths =
            new IBalancerV3BatchRouter.SwapPathExactAmountIn[](1);
        paths[0] = IBalancerV3BatchRouter.SwapPathExactAmountIn({
            tokenIn: tokenIn,
            steps: steps,
            exactAmountIn: amountIn,
            minAmountOut: minAmountOut
        });

        uint256 balBefore = _balanceOfSelf(tokenOut);
        // wethIsEth = false: this contract holds wrapped WPLS, never native PLS
        // (it is non-payable). userData empty: no hooks used on routed pools.
        IBalancerV3BatchRouter(BALANCER_V3_ROUTER).swapExactIn(paths, deadline, false, "");
        _safeApprove(tokenIn, BALANCER_V3_PERMIT2, 0);

        uint256 amountOut = _balanceOfSelf(tokenOut) - balBefore;
        if (amountOut < minAmountOut) {
            _edgeFail(index, pool, PROTO_BALANCER_V3);
        }
    }

    // --- PulseX Stable Swap ---
    function _swapStable(
        address pool,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        bytes calldata extraData,
        uint256 index
    ) internal {
        // POOL AUTHENTICATION (bounty report). Same untrusted-pool pattern as
        // V2/V3, via approve-then-call instead of push: a fake `pool`
        // implementing exchange() to just transferFrom() the approval and
        // keep it, returning ok=true, passed every downstream check at
        // minAmountOut=0. No universal factory exists for this protocol
        // shape, so this is a direct allowlist, not a registry call.
        _requireTrustedStablePool(pool, index);

        (int128 coinIndexIn, int128 coinIndexOut) = abi.decode(extraData, (int128, int128));
        _safeApprove(tokenIn, pool, amountIn);

        // Coin indices are always non-negative; measure output by balanceOf
        // delta rather than trusting the return value (older Curve `exchange`
        // returns void).
        uint256 balBefore = _balanceOfSelf(tokenOut);

        // Curve-fork stable pools ship `exchange` with two MUTUALLY-EXCLUSIVE
        // index types, which are DIFFERENT selectors: PulseChain's pools use
        // UINT256 (exchange(uint256,uint256,uint256,uint256) = 0x5b41b908);
        // Ethereum-era Curve uses INT128 (exchange(int128,int128,uint256,
        // uint256) = 0x3df02124). A wrong guess reverts. Try uint256 first
        // (our launch chain), fall back to int128. PROVEN on the live
        // PulseChain USDT/USDC/DAI 3pool 0xe3acfa6c40d53c3faf2aa62d0a715c73-
        // 7071511c on an anvil fork: 0x5b41b908 delivers (1000 USDC ->
        // 999.44 DAI), the int128 selector is absent. The old int128-only
        // typed call bricked every stable leg on mainnet — a bug no mock
        // could show, only a fork of the real pool. (NB: 0x65b2489b is
        // exchange_UNDERLYING, a different function — do not use it here.)
        (bool ok,) = pool.call(
            abi.encodeWithSelector(
                0x5b41b908, // exchange(uint256,uint256,uint256,uint256)
                uint256(uint128(coinIndexIn)), uint256(uint128(coinIndexOut)),
                amountIn, minAmountOut));
        if (!ok) {
            (ok,) = pool.call(
                abi.encodeWithSelector(
                    0x3df02124, // exchange(int128,int128,uint256,uint256)
                    coinIndexIn, coinIndexOut, amountIn, minAmountOut));
        }
        if (!ok) {
            // Saddle-style pools (Synapse nUSD 0x1116898d on Ethereum: the
            // largest excluded stable venue, 2026-09-16) expose NEITHER
            // exchange selector; their swap is swap(uint8 from, uint8 to,
            // uint256 dx, uint256 minDy, uint256 deadline). Same allowlist,
            // same balance-delta measurement below; deadline = now since
            // the settlement's own params.deadline already bounds the tx.
            (ok,) = pool.call(
                abi.encodeWithSelector(
                    0x91695586, // swap(uint8,uint8,uint256,uint256,uint256)
                    uint8(uint128(coinIndexIn)), uint8(uint128(coinIndexOut)),
                    amountIn, minAmountOut, block.timestamp));
        }
        _safeApprove(tokenIn, pool, 0);
        if (!ok) _edgeFail(index, pool, PROTO_STABLE);

        uint256 amountOut = _balanceOfSelf(tokenOut) - balBefore;
        if (amountOut < minAmountOut) {
            _edgeFail(index, pool, PROTO_STABLE);
        }
    }

    /// @dev Direct allowlist check — see trustedStablePools' declaration
    ///      comment for why this protocol shape can't use a registry call.
    function _requireTrustedStablePool(address pool, uint256 index) private view {
        if (_isTrustedStablePool[pool]) return;
        revert UntrustedPool(pool, PROTO_STABLE, index);
    }

    // --- Safe ERC20 wrappers (check return values) ---
    // Handles tokens that return false instead of reverting,
    // AND tokens that return nothing (USDT on Ethereum).
    // Uses inline assembly to avoid MCOPY opcode (Cancun) which
    // is not supported on all EVM chains (PulseChain, BSC, etc).

    /// @dev Like _safeTransfer but returns false instead of reverting.
    function _tryTransfer(address token, address to, uint256 amount) internal returns (bool ok) {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(ptr, 4), to)
            mstore(add(ptr, 36), amount)
            let success := call(gas(), token, 0, ptr, 68, ptr, 32)
            ok := and(success, or(iszero(returndatasize()), and(gt(returndatasize(), 31), eq(mload(ptr), 1))))
        }
    }

    function _safeTransfer(address token, address to, uint256 amount) internal {
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(ptr, 4), to)
            mstore(add(ptr, 36), amount)
            let success := call(gas(), token, 0, ptr, 68, ptr, 32)
            // Check: call succeeded AND (returned nothing OR returned true)
            let ok := and(success, or(iszero(returndatasize()), and(gt(returndatasize(), 31), eq(mload(ptr), 1))))
            if iszero(ok) { mstore(0, 0x3f409f9a00000000000000000000000000000000000000000000000000000000) revert(0, 4) }
        }
    }

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

    // Shared by every path that measures its own output via a before/after
    // balance delta (12 protocol adapters) plus the H1 fee-basis snapshot —
    // was 28 separate inline IERC20(...).balanceOf(address(this)) call sites,
    // each compiling its own STATICCALL + ABI encode/decode under viaIR.
    // Factoring them into one internal function recovered 2,241 bytes
    // (24,943 -> 22,702 deployed, EIP-170 limit 24,576) with ZERO behavior
    // change verified by the full existing test suite plus tests/foundry_h1
    // and tests/foundry_h1_redeploy (all pass, byte-identical trader/fee
    // amounts) — the H1 fix (2026-09-13) pushed the contract 367 bytes over
    // the limit; this is what actually made it deployable again, not a
    // compiler-setting compromise or a weakened safety check.
    function _balanceOfSelf(address token) internal view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
    }

    /// @dev Shared EdgeSwapFailed revert routed through one helper (18 sites) -- a
    ///      pure byte-size reduction to hold the contract under EIP-170.
    function _edgeFail(uint256 index, address pool, uint8 protocol) internal pure {
        revert EdgeSwapFailed(index, pool, protocol);
    }

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

}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.