Skip to content
Verified contractPartialMIT

EarthmetaBuyRouter

Address0xa024ae10078f8358facd124f050d4bf5b19e121e
Balance

0 ETH

 

Transactions

6

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,179,458
Creation transaction
0x27d023514d…513f185a8e

project/contracts/payments/EarthmetaBuyRouter.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IMarketplace} from "../interfaces/IMarketplace.sol";
import {IPrimarySale} from "../interfaces/IPrimarySale.sol";

/// @dev The Uniswap V3 `SwapRouter` (the ORIGINAL, 0xE592427A…1564 — measured
///      5,151 gas cheaper than SwapRouter02 for our shape). Exact-output only:
///      both sinks take an exact amount and neither refunds.
interface ISwapRouterV3 {
    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);

    /// @dev `PeripheryImmutableState.WETH9`. Present on both SwapRouter and
    ///      SwapRouter02, and the constructor's proof that `swapRouter_` really
    ///      is a Uniswap router wired to the SAME WETH this contract unwraps.
    function WETH9() external view returns (address);
}

/// @dev Uniswap's Permit2, signature-transfer half only.
interface IPermit2 {
    struct TokenPermissions {
        address token;
        uint256 amount;
    }

    struct PermitTransferFrom {
        TokenPermissions permitted;
        uint256 nonce;
        uint256 deadline;
    }

    struct SignatureTransferDetails {
        address to;
        uint256 requestedAmount;
    }

    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @dev Constructor probe only: a typo'd Permit2 has no domain separator.
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

/// @dev Canonical WETH9. `withdraw` pushes native ether back with a bare `call`,
///      which is why this contract has a `receive` at all.
interface IWETH9 {
    function deposit() external payable;

    function withdraw(uint256 amount) external;
}

/// @dev The slice of {EarthmetaMarketplace} the router uses. `usdt()` is read in
///      the constructor so a mis-wired settlement asset cannot be deployed.
interface IMarketplaceFill {
    function fillFor(IMarketplace.Listing calldata order, bytes calldata sig, address buyer) external;

    function usdt() external view returns (address);
}

/// @title EarthmetaBuyRouter
/// @author EarthMeta 2026.
/// @notice One transaction, six pay-in currencies, both products: the buyer
///         brings ETH, WETH, USDT, USDC or EMT and walks away owning the NFT.
///
///         The router converts the buyer's asset into the ONE currency each sink
///         already speaks — USDT for a marketplace fill, native ETH for a
///         primary sale — and settles in the same transaction. Nothing about
///         either sink changes: live listings are not re-signed, sellers do not
///         sign a second authorization per currency, and adding a seventh
///         pay-in token later is a new router deploy, not a migration.
///
/// @dev IMMUTABLE BY CONSTRUCTION. No owner, no proxy, no setter, no upgrade
///      path. The only storage is `stopped`; everything else — both sinks, both
///      allow-lists, the guardian — is fixed at deploy time and readable from
///      the bytecode. The one thing that can change after deployment is the
///      guardian flipping `stopped` to true, one way, forever.
///
///      It holds NO funds and NO allowance between transactions. Every entry
///      point ends by sweeping native, `tokenIn`, `tokenOut` and WETH to the
///      buyer and then ASSERTING all four are zero ({DustLeft}). That is what
///      bounds `EM_FIAT_OPERATOR` on the marketplace to "a role over nothing":
///      there is never a balance here for the role to spend.
///
///      Sweep BEFORE assert, deliberately: a griefer's 1-wei donation becomes a
///      gift to the next buyer instead of a permanent denial of service.
///
///      ── WHAT THIS CONTRACT DOES NOT DO ─────────────────────────────────────
///
///      **It does not bound the price of a buy.** The only economic bound on
///      what a buy costs is the `maxIn` the caller supplies, which is pulled in
///      full and handed to Uniswap as `amountInMaximum`; the unspent remainder
///      is refunded. There is no oracle here and no `sqrtPriceLimitX96`, so a
///      sandwich can extract up to `maxIn - fairAmountIn` and this contract
///      cannot tell that apart from "the pool moved". The real bound is the
///      server-side slippage cap in the quote service, per token. What the
///      contract DOES bound is the venue: the immutable pool allow-list means a
///      compromised quote source can only route through a real, arbitraged pool
///      the deployer chose — not one it created and prices at will — and the
///      15-minute deadline ceiling bounds how long a stuck transaction stays
///      exposed. An immutable per-token notional cap was considered and
///      rejected: the day a legitimate price outgrows it, the rail stops and
///      the only fix is a redeploy.
///
///      **It does not stop wash trading.** {SelfDeal} compares two addresses,
///      exactly as `EarthmetaMarketplace.sol:188` does, so one actor with two
///      wallets defeats both — as they already can through the permissionless
///      `fill()`. See the exposures note in `docs/buy-router.md`.
///
///      **It does not insulate the EMT oracle from EMT pay-ins.** The EMT route
///      trades the SAME EMT/USDT pool (0x30403a62…) that `EmtUsdtTwapOracle`
///      consults, so every EMT-funded buy sells EMT into the pool that prices
///      the seller's payout out of the marketplace reserve. Sustained EMT-in
///      volume therefore drains `reserveEmt` faster per dollar of sales, and at
///      the band floor `rawEmtUsdX18` reverts `PriceOutOfBand` and EVERY fill
///      stops, in every currency. Bounding that is a notional cap in the quote
///      service plus pool-depth monitoring; it cannot be done from here.
///
///      **It has no rescue function, by design.** A token mis-sent to this
///      address is swept to the next buyer who happens to route through it, and
///      a token that is on no route — or an ERC-721 — is lost forever. There is
///      no owner, no sweep and no upgrade to add one with, because any
///      `spend(target, calldata)` seam would let a caller drain the swapped
///      output mid-transaction. Support cannot recover funds sent here: this
///      address is a router, never a deposit address.
///
///      **It cannot be restarted.** See {stop}.
contract EarthmetaBuyRouter is ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    // ─────────────────────────────────────────────────────────────────────────
    // Types
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice One Uniswap V3 pool the deployer allows this router to trade in.
    /// @dev An UNORDERED pair: `{USDC, WETH, 500}` and `{WETH, USDC, 500}` are
    ///      the same entry, because Uniswap itself sorts the tokens.
    /// @param tokenA One endpoint. Must be on the pay-in allow-list.
    /// @param tokenB The other endpoint. Must be on the pay-in allow-list.
    /// @param fee    A canonical tier: 100, 500, 3000 or 10000.
    struct Pool {
        address tokenA;
        address tokenB;
        uint24 fee;
    }

    /// @notice How the buyer's `tokenIn` is authorised for this one pull.
    /// @param kind     0 = none (a prior `approve`), 1 = EIP-2612, 2 = Permit2.
    /// @param value    The permitted amount (≥ `maxIn`).
    /// @param nonce    Permit2 nonce; ignored by the EIP-2612 path.
    /// @param deadline The permit's own deadline (NOT the swap deadline).
    /// @param sig      65-byte EIP-2612 signature, or the Permit2 signature blob.
    struct Permit {
        uint8 kind;
        uint256 value;
        uint256 nonce;
        uint256 deadline;
        bytes sig;
    }

    /// @notice Everything about the money leg of a buy.
    /// @dev The caller NAMES a route; it never supplies one. Every hop is looked
    ///      up as a whole `(tokenA, tokenB, fee)` triple in the immutable pool
    ///      allow-list fixed at deploy time, and the router encodes the Uniswap
    ///      path itself from the triples it matched.
    ///
    ///      Checking the fee TIER alone was not enough, and this is the reason:
    ///      a Uniswap V3 pool for any (tokenA, tokenB, enabled fee) is created
    ///      permissionlessly by anyone — `UniswapV3Factory.createPool` +
    ///      `initialize` — and `exactOutputSingle`/`exactOutput` address it
    ///      deterministically from (tokens, fee) with no registry and no
    ///      liquidity check. So an attacker could create a REAL pair at a DEAD
    ///      tier (USDC/USDT at 1%, say), seed one nominal position at an absurd
    ///      price, become its only counterparty, and every component of that
    ///      route would still pass a per-token + per-tier allow-list. The pool
    ///      list closes it: pool selection belongs to the deployer.
    /// @param tokenIn  What the buyer pays with. `address(0)` = native ETH, and
    ///                 only {buyListed} accepts it.
    /// @param maxIn    Pulled from `msg.sender` IN FULL; the unspent remainder
    ///                 is refunded in the same transaction.
    /// @param mid      `address(0)` for a single hop, else an allow-listed hop
    ///                 token (EMT reaches WETH as EMT → USDT → WETH).
    /// @param feeIn    Fee tier of the `tokenIn` → (`mid` or settlement) pool.
    ///                 That whole pool must be on the allow-list, not just the
    ///                 tier.
    /// @param feeOut   Fee tier of the `mid` → settlement pool, likewise
    ///                 allow-listed as a whole; MUST be 0 when `mid` is 0.
    /// @param deadline The SWAP deadline, supplied by the caller and capped at
    ///                 15 minutes. Never the listing's expiry, never the
    ///                 voucher's: those can be months out, and a transaction
    ///                 stuck in the mempool would then execute at whatever
    ///                 price the pool has drifted to.
    /// @param permit   The pull authorization (see {Permit}).
    struct Pay {
        address tokenIn;
        uint256 maxIn;
        address mid;
        uint24 feeIn;
        uint24 feeOut;
        uint256 deadline;
        Permit permit;
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Errors
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice The guardian has killed this router. Redeploy; there is no restart.
    error Stopped();
    /// @notice Only the guardian Safe may call {stop}.
    error NotGuardian(address caller);
    /// @notice `tokenIn` (or `address(0)` for native where native is refused) is
    ///         not on the immutable pay-in allow-list.
    error TokenNotAllowed(address token);
    /// @notice A pool fee tier outside the immutable set (or non-zero `feeOut`
    ///         on a single-hop route).
    error FeeNotAllowed(uint24 fee);
    /// @notice A hop token outside the immutable set, or one that collides with
    ///         an endpoint of the route.
    error MidNotAllowed(address mid);
    /// @notice The route names a Uniswap pool the deployer did not allow-list.
    ///         This is what stops a caller routing a buy through a pool they
    ///         created and are the only liquidity in.
    error PoolNotAllowed(address tokenA, address tokenB, uint24 fee);
    /// @notice A constructor wire is the zero address or has no code. Every one
    ///         of them is immutable, so this is the last moment it can be said.
    error NotAContract(address subject);
    /// @notice Two constructor wires are the same address.
    error DuplicateAddress(address subject);
    /// @notice A constructor wire has code but does not answer the interface it
    ///         is supposed to implement.
    error ProbeFailed(address subject);
    /// @notice The swap router's own `WETH9()` is not the WETH this router
    ///         unwraps — a mis-paired router/WETH would revert every buy.
    error WethMismatch(address routerWeth, address weth);
    /// @notice The swap deadline is further out than {MAX_DEADLINE}.
    error DeadlineTooFar(uint256 deadline, uint256 ceiling);
    /// @notice The buyer is the listing's own maker.
    /// @dev Pre-empts the marketplace's own `seller == buyer` refusal
    ///      (EarthmetaMarketplace.sol:188) with a named error and — because it
    ///      fires BEFORE the swap — without the buyer having paid a pool fee for
    ///      the privilege.
    ///
    ///      It is NOT a wash-trade guard, and this contract does not claim to be
    ///      one. Both this check and the marketplace's compare exactly two
    ///      addresses, so one actor holding two wallets defeats both — as they
    ///      already can through the permissionless `fill()`, which predates this
    ///      router. Wash trading against the EMT reserve is a product decision
    ///      recorded in the exposures, deliberately not smuggled in here.
    error SelfDeal();
    /// @notice `msg.sender` is not the voucher's buyer.
    error NotBuyer(address expected, address caller);
    /// @notice The voucher does not settle in native ETH. This router implements
    ///         exactly one settlement path per product; anything else is refused
    ///         loudly rather than half-handled.
    error WrongCurrency(address currency);
    /// @notice The voucher names a different payer, so it was not signed for
    ///         THIS router.
    error NotOurVoucher(address payer);
    /// @notice `msg.value` did not match what the chosen pay-in path requires.
    error BadValue(uint256 sent, uint256 expected);
    /// @notice The swap did not deliver the exact amount the sink will take.
    error SwapShort(uint256 got, uint256 need);
    /// @notice Value was left in the router after the sweep. Never reachable on
    ///         a well-behaved token; it is the backstop that keeps the
    ///         `EM_FIAT_OPERATOR` role attached to an empty contract.
    error DustLeft(address token, uint256 amount);
    /// @notice Native ether arrived from something other than the WETH contract.
    error NotWeth(address sender);

    // ─────────────────────────────────────────────────────────────────────────
    // Events
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice A secondary-market fill was routed. `spent` is what the buyer
    ///         actually paid of `maxIn`.
    event ListedBought(
        address indexed buyer,
        address indexed tokenIn,
        address nft,
        uint256 tokenId,
        uint256 priceUSDT,
        uint256 spent
    );

    /// @notice A primary sale was fronted. `spent` is what the buyer actually
    ///         paid of `maxIn`.
    event PrimaryBought(
        address indexed buyer,
        address indexed tokenIn,
        uint8 assetType,
        uint256 assetId,
        uint256 priceWei,
        uint256 spent
    );

    /// @notice The guardian killed the router, permanently.
    /// @param by The guardian that pulled it.
    event RouterStopped(address indexed by);

    /// @notice One Uniswap pool the deployer chose, emitted once per pool from
    ///         the constructor. The allow-list is immutable and stored as
    ///         hashes, so these logs (plus {isAllowedPool}) are how a frontend
    ///         or an ops read-back enumerates it.
    /// @param tokenA One endpoint, exactly as it was supplied.
    /// @param tokenB The other endpoint.
    /// @param fee    The pool's fee tier.
    event PoolAllowed(address indexed tokenA, address indexed tokenB, uint24 fee);

    // ─────────────────────────────────────────────────────────────────────────
    // Configuration (immutable)
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice The furthest out a caller may push the swap deadline.
    uint256 public constant MAX_DEADLINE = 15 minutes;

    /// @notice {EarthmetaMarketplace}. The router holds `EM_FIAT_OPERATOR` here
    ///         and nothing anywhere else.
    address public immutable MK;
    /// @notice {PrimarySale}. The router holds NO role here and needs none.
    address public immutable PS;
    /// @notice The marketplace's settlement asset, asserted equal to `MK.usdt()`.
    address public immutable USDT;
    /// @notice Canonical WETH. Also the primary sale's settlement hop.
    address public immutable WETH;
    /// @notice Uniswap V3 SwapRouter.
    address public immutable SWAP;
    /// @notice Uniswap Permit2.
    address public immutable PERMIT2;
    /// @notice The 2-of-3 Safe that may {stop} this router.
    address public immutable GUARDIAN;

    /* solhint-disable var-name-mixedcase */
    address private immutable TOKEN_0;
    address private immutable TOKEN_1;
    address private immutable TOKEN_2;
    address private immutable TOKEN_3;
    address private immutable TOKEN_4;
    address private immutable TOKEN_5;
    address private immutable TOKEN_6;
    address private immutable TOKEN_7;
    uint256 private immutable TOKEN_COUNT;

    address private immutable MID_0;
    address private immutable MID_1;
    uint256 private immutable MID_COUNT;

    uint24 private immutable FEE_0;
    uint24 private immutable FEE_1;
    uint24 private immutable FEE_2;
    uint24 private immutable FEE_3;
    uint256 private immutable FEE_COUNT;

    bytes32 private immutable POOL_0;
    bytes32 private immutable POOL_1;
    bytes32 private immutable POOL_2;
    bytes32 private immutable POOL_3;
    bytes32 private immutable POOL_4;
    bytes32 private immutable POOL_5;
    bytes32 private immutable POOL_6;
    bytes32 private immutable POOL_7;
    uint256 private immutable POOL_COUNT;
    /* solhint-enable var-name-mixedcase */

    // ─────────────────────────────────────────────────────────────────────────
    // Storage — one flag, and nothing else, ever
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice One-way kill switch. Once true, both entry points revert forever.
    bool public stopped;

    // ─────────────────────────────────────────────────────────────────────────
    // Construction
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Wire the router to its two sinks, its swap venue and its guardian.
    /// @param marketplace_ {EarthmetaMarketplace}.
    /// @param primarySale_ {PrimarySale}.
    /// @param usdt_        Must equal `IMarketplaceFill(marketplace_).usdt()`.
    /// @param weth_        Canonical WETH; must also appear in `tokensIn_` and
    ///                     must be the WETH the swap router itself reports.
    /// @param swapRouter_  Uniswap V3 SwapRouter.
    /// @param permit2_     Uniswap Permit2.
    /// @param guardian_    The 2-of-3 Safe holding {stop}. Must be a CONTRACT.
    /// @param tokensIn_    Pay-in allow-list, ≤ 8, must contain `weth_` + `usdt_`.
    /// @param mids_        Hop allow-list, ≤ 2, a subset of `tokensIn_`.
    /// @param pools_       Uniswap pool allow-list, ≤ 8, every endpoint drawn
    ///                     from `tokensIn_` and every tier canonical. The set of
    ///                     distinct tiers across these pools is what
    ///                     {allowedFees} reports, and must be ≤ 4.
    ///
    /// @dev Nothing is hard-coded to a mainnet address, which is the whole
    ///      reason the suite runs on a local chain with no RPC and no secrets.
    ///
    ///      EVERY argument here is permanent. There is no setter, no proxy and
    ///      no owner, so a wrong address is a redeploy plus a role rotation, and
    ///      some wrong addresses are silent: a `guardian_` the team does not
    ///      control is a router with no kill switch, and the only way to
    ///      discover it is to call {stop}, which destroys the router. So each
    ///      wire is probed here for what it claims to be — code, uniqueness, and
    ///      an interface call that only the real thing can answer. Deploy
    ///      through `scripts/ops/deploy-buy-router.ts`, which re-checks all of
    ///      this against the address book before it spends any gas.
    constructor(
        address marketplace_,
        address primarySale_,
        address usdt_,
        address weth_,
        address swapRouter_,
        address permit2_,
        address guardian_,
        address[] memory tokensIn_,
        address[] memory mids_,
        Pool[] memory pools_
    ) {
        // ── The seven permanent wires ────────────────────────────────────────
        // Non-zero is not a check. Each must have CODE (an EOA guardian is a
        // missing kill switch; an EOA sink is a buy that reverts forever) and
        // each must be distinct (a copy-paste that repeats an address would
        // otherwise deploy and fail only on the first real buy). Then each is
        // asked to prove, through its own interface, that it is what the deploy
        // script claims — the one thing a constructor argument cannot be
        // corrected for afterwards.
        _checkWires([marketplace_, primarySale_, usdt_, weth_, swapRouter_, permit2_, guardian_]);
        _probeWires(marketplace_, primarySale_, usdt_, weth_, swapRouter_, permit2_);

        MK = marketplace_;
        PS = primarySale_;
        USDT = usdt_;
        WETH = weth_;
        SWAP = swapRouter_;
        PERMIT2 = permit2_;
        GUARDIAN = guardian_;

        // ── Pay-in allow-list ────────────────────────────────────────────────
        address[8] memory t = _buildTokens(tokensIn_, weth_, usdt_);
        TOKEN_0 = t[0];
        TOKEN_1 = t[1];
        TOKEN_2 = t[2];
        TOKEN_3 = t[3];
        TOKEN_4 = t[4];
        TOKEN_5 = t[5];
        TOKEN_6 = t[6];
        TOKEN_7 = t[7];
        TOKEN_COUNT = tokensIn_.length;

        // ── Hop allow-list ───────────────────────────────────────────────────
        address[2] memory mm = _buildMids(tokensIn_, mids_);
        MID_0 = mm[0];
        MID_1 = mm[1];
        MID_COUNT = mids_.length;

        // ── Pool allow-list, and the fee set derived from it ─────────────────
        (bytes32[8] memory pk, uint24[4] memory ff, uint256 f) = _buildPools(tokensIn_, pools_);
        POOL_0 = pk[0];
        POOL_1 = pk[1];
        POOL_2 = pk[2];
        POOL_3 = pk[3];
        POOL_4 = pk[4];
        POOL_5 = pk[5];
        POOL_6 = pk[6];
        POOL_7 = pk[7];
        POOL_COUNT = pools_.length;

        FEE_0 = ff[0];
        FEE_1 = ff[1];
        FEE_2 = ff[2];
        FEE_3 = ff[3];
        FEE_COUNT = f;
    }

    /// @dev Every wire has REAL code and none repeats. Constructor only.
    ///
    ///      "Has code" stopped meaning "is a contract" when EIP-7702 shipped in
    ///      Prague. A delegated EOA carries exactly 23 bytes — `0xef0100` plus
    ///      the 20-byte delegate — and passes a bare `code.length == 0` test
    ///      while still being one private key that can remove the delegation at
    ///      any moment.
    ///
    ///      For six of the seven wires that is a curiosity. For the GUARDIAN it
    ///      is the whole point of the check: the design rests on `stop()` — one
    ///      way, no restart, not vetoable by the Timelock canceller — living
    ///      behind a 2-of-3 Safe, and this constructor is the last moment the
    ///      claim can be made, because the address is immutable afterwards. A
    ///      7702 key set as guardian would hold that lever alone, and the only
    ///      way to find out would be to pull it.
    ///
    ///      EIP-3541 forbids deploying code that begins with 0xEF, so the shape
    ///      below can only ever be a delegation and never a real contract.
    function _checkWires(address[7] memory wires) private view {
        for (uint256 i = 0; i < 7; i++) {
            address a = wires[i];
            if (a == address(0) || a.code.length == 0 || _is7702(a)) revert NotAContract(a);
            for (uint256 j = 0; j < i; j++) {
                if (wires[j] == a) revert DuplicateAddress(a);
            }
        }
    }

    /// @dev Is `a` an EIP-7702 delegated EOA rather than a contract?
    /// @return True for exactly `0xef0100 ‖ <20-byte delegate>`, 23 bytes.
    function _is7702(address a) private view returns (bool) {
        if (a.code.length != 23) return false;
        bytes memory prefix = new bytes(3);
        assembly {
            extcodecopy(a, add(prefix, 0x20), 0, 3)
        }
        return prefix[0] == 0xef && prefix[1] == 0x01 && prefix[2] == 0x00;
    }

    /// @dev An all-zero {IPrimarySale-SellAuthorization}, for the constructor's
    ///      identity probe. `authBinding` is `pure`, so nothing about the values
    ///      matters — only that the ABI the router encodes is the one the
    ///      deployed contract decodes.
    function _zeroAuth() private pure returns (IPrimarySale.SellAuthorization memory) {
        return
            IPrimarySale.SellAuthorization({
                seller: address(0),
                assetType: 0,
                assetId: 0,
                minSellerWei: 0,
                minPriceWei: 0,
                currency: address(0),
                expiry: 0,
                nonce: 0
            });
    }

    /// @dev Each wire answers for itself. Constructor only.
    function _probeWires(
        address marketplace_,
        address primarySale_,
        address usdt_,
        address weth_,
        address swapRouter_,
        address permit2_
    ) private view {
        // A settlement asset that is not the marketplace's own would make every
        // fill swap to the wrong token and revert late, after the buyer paid the
        // swap. Read it, do not trust the deploy script.
        if (IMarketplaceFill(marketplace_).usdt() != usdt_) revert TokenNotAllowed(usdt_);
        // `authBinding`, not `paused()`. The old probe distinguished nothing:
        // four other live contracts in the same address book answer `paused()`,
        // so a `primarySale_` pointing at any of them — or at the PrimarySale
        // IMPLEMENTATION rather than its proxy — passed it. `authBinding` exists
        // nowhere else in the suite, and it is `keccak256(abi.encode(auth))` of
        // the very struct `settle` re-hashes against `voucher.authHash`. So one
        // read proves the wire IS the primary sale and that its
        // `SellAuthorization` layout still matches the one this contract
        // encodes — the drift that would otherwise revert `AuthMismatch` on
        // every router-fronted land sale, with the seller's signature valid.
        //
        // An all-zero authorization is used deliberately: the function is
        // `pure`, so the values are irrelevant and only the ABI has to agree.
        try IPrimarySale(primarySale_).authBinding(_zeroAuth()) returns (bytes32 h) {
            if (h == bytes32(0)) revert ProbeFailed(primarySale_);
        } catch {
            revert ProbeFailed(primarySale_);
        }
        try IPermit2(permit2_).DOMAIN_SEPARATOR() returns (bytes32 ds) {
            if (ds == bytes32(0)) revert ProbeFailed(permit2_);
        } catch {
            revert ProbeFailed(permit2_);
        }
        // The router's OWN WETH, not ours: this single read proves swapRouter_
        // is a Uniswap router AND that it is paired with the WETH we unwrap.
        try ISwapRouterV3(swapRouter_).WETH9() returns (address routerWeth) {
            if (routerWeth != weth_) revert WethMismatch(routerWeth, weth_);
        } catch {
            revert ProbeFailed(swapRouter_);
        }
        // Both settlement assets must at least answer like an ERC-20.
        // solhint-disable-next-line no-empty-blocks
        try IERC20(usdt_).balanceOf(address(this)) returns (uint256) {} catch {
            revert ProbeFailed(usdt_);
        }
        // solhint-disable-next-line no-empty-blocks
        try IERC20(weth_).balanceOf(address(this)) returns (uint256) {} catch {
            revert ProbeFailed(weth_);
        }
    }

    /// @dev Validate the pay-in allow-list and widen it to the immutable slots.
    ///      Both settlement assets must themselves be payable-in: otherwise a
    ///      buyer already holding one is forced through a pointless swap, and
    ///      the `tokenIn == tokenOut` short-circuit is dead code.
    function _buildTokens(
        address[] memory tokensIn_,
        address weth_,
        address usdt_
    ) private pure returns (address[8] memory t) {
        uint256 n = tokensIn_.length;
        if (n == 0 || n > 8) revert TokenNotAllowed(address(0));
        bool hasWeth;
        bool hasUsdt;
        for (uint256 i = 0; i < n; i++) {
            address a = tokensIn_[i];
            if (a == address(0)) revert TokenNotAllowed(a);
            for (uint256 j = 0; j < i; j++) {
                if (tokensIn_[j] == a) revert TokenNotAllowed(a);
            }
            if (a == weth_) hasWeth = true;
            if (a == usdt_) hasUsdt = true;
            t[i] = a;
        }
        if (!hasWeth) revert TokenNotAllowed(weth_);
        if (!hasUsdt) revert TokenNotAllowed(usdt_);
    }

    /// @dev Validate the hop allow-list. Belt and braces since the pool list
    ///      arrived: a hop token with no allow-listed pool on both sides is
    ///      already unreachable. Kept because it fails EARLIER and with a more
    ///      specific error, and because it is the list the frontend picker reads.
    function _buildMids(
        address[] memory tokensIn_,
        address[] memory mids_
    ) private pure returns (address[2] memory mm) {
        uint256 m = mids_.length;
        if (m > 2) revert MidNotAllowed(address(0));
        for (uint256 i = 0; i < m; i++) {
            address a = mids_[i];
            if (a == address(0)) revert MidNotAllowed(a);
            for (uint256 j = 0; j < i; j++) {
                if (mids_[j] == a) revert MidNotAllowed(a);
            }
            if (!_inList(tokensIn_, a)) revert MidNotAllowed(a);
            mm[i] = a;
        }
    }

    /// @dev Validate the pool allow-list, derive the distinct fee set from it,
    ///      and log every pool so the set can be enumerated off-chain.
    function _buildPools(
        address[] memory tokensIn_,
        Pool[] memory pools_
    ) private returns (bytes32[8] memory pk, uint24[4] memory ff, uint256 f) {
        uint256 pn = pools_.length;
        if (pn == 0 || pn > 8) revert PoolNotAllowed(address(0), address(0), 0);
        for (uint256 i = 0; i < pn; i++) {
            address a = pools_[i].tokenA;
            address b = pools_[i].tokenB;
            uint24 fee = pools_[i].fee;
            if (fee != 100 && fee != 500 && fee != 3000 && fee != 10000) revert FeeNotAllowed(fee);
            if (a == b || !_inList(tokensIn_, a) || !_inList(tokensIn_, b)) {
                revert PoolNotAllowed(a, b, fee);
            }
            bytes32 k = _poolKey(a, b, fee);
            for (uint256 j = 0; j < i; j++) {
                if (pk[j] == k) revert PoolNotAllowed(a, b, fee);
            }
            pk[i] = k;

            bool seen;
            for (uint256 j = 0; j < f; j++) {
                if (ff[j] == fee) seen = true;
            }
            if (!seen) {
                if (f == 4) revert FeeNotAllowed(fee);
                ff[f] = fee;
                f++;
            }
            emit PoolAllowed(a, b, fee);
        }
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Entry points
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Buy a listed NFT with any allow-listed asset (or native ETH).
    /// @dev Settlement currency is ALWAYS USDT, because that is the only thing
    ///      `fillFor` pulls (`EarthmetaMarketplace.sol:205`). The NFT recipient
    ///      is ALWAYS `msg.sender` — there is deliberately no `recipient`
    ///      parameter and therefore no gifting surface.
    /// @param pay   The money leg.
    /// @param order The seller's signed listing, forwarded verbatim.
    /// @param sig   The seller's EIP-712 signature over `order`.
    function buyListed(
        Pay calldata pay,
        IMarketplace.Listing calldata order,
        bytes calldata sig
    ) external payable nonReentrant {
        if (stopped) revert Stopped();
        // Named, and BEFORE the swap: the marketplace's own `seller == buyer`
        // check would otherwise fire after the buyer already paid the pool. It
        // is a two-address comparison, not a wash-trade guard — see {SelfDeal}.
        if (order.maker == msg.sender) revert SelfDeal();

        bool native = pay.tokenIn == address(0);
        address tokenIn = _validate(pay, true);
        // Before the pull, so `spent` below is a delta and a donated balance
        // cannot understate what this buyer actually paid.
        uint256 inBefore = IERC20(native ? WETH : tokenIn).balanceOf(address(this));
        _take(pay, native);
        _swapExactOut(tokenIn, USDT, pay, order.priceUSDT);

        IERC20(USDT).forceApprove(MK, order.priceUSDT);
        IMarketplaceFill(MK).fillFor(order, sig, msg.sender);
        IERC20(USDT).forceApprove(MK, 0);

        uint256 spent = _settleUp(tokenIn, USDT, msg.sender, native, pay.maxIn, inBefore);
        emit ListedBought(msg.sender, pay.tokenIn, order.nft, order.tokenId, order.priceUSDT, spent);
    }

    /// @notice Buy a new land or city with any allow-listed ERC-20.
    /// @dev Settlement currency is ALWAYS native ETH — for a city and for a
    ///      land, today and after the next token is added. That is what keeps
    ///      `auth.currency == voucher.currency` (`PrimarySale.sol:692`) true
    ///      against the seller's ONE existing ETH authorization, so no seller
    ///      ever signs twice.
    ///
    ///      Native ETH is refused here on purpose: an ETH buyer calls
    ///      `PrimarySale.settle` directly as their own payer, so a guardian
    ///      {stop} degrades to "ETH still works", never to "the primary sale is
    ///      down".
    ///
    ///      `auth` and `sellerAuthSig` are passed through verbatim.
    /// @param pay           The money leg (ERC-20 only).
    /// @param v             The merchant-signed voucher, naming THIS router as payer.
    /// @param merchantSig   The merchant's EIP-712 signature over `v`.
    /// @param auth          The seller's authorization (ignored for a city).
    /// @param sellerAuthSig The seller's EIP-712 signature over `auth`.
    function buyPrimary(
        Pay calldata pay,
        IPrimarySale.SaleVoucher calldata v,
        bytes calldata merchantSig,
        IPrimarySale.SellAuthorization calldata auth,
        bytes calldata sellerAuthSig
    ) external nonReentrant {
        if (stopped) revert Stopped();
        // Without this, anyone holding a published voucher bundle could burn the
        // buyer's nonce and flip the sold flag while the billed buyer never
        // paid — and the `maxIn` refund would land on the wrong address.
        if (msg.sender != v.buyer) revert NotBuyer(v.buyer, msg.sender);
        if (v.currency != address(0)) revert WrongCurrency(v.currency);
        if (v.payer != address(this)) revert NotOurVoucher(v.payer);

        address tokenIn = _validate(pay, false);
        // See `buyListed`: a delta, so a donation cannot understate `spent`.
        uint256 inBefore = IERC20(tokenIn).balanceOf(address(this));
        _take(pay, false);
        _swapExactOut(tokenIn, WETH, pay, v.priceWei);

        // `_pull` is an equality against `msg.value` with no `receive()` and no
        // refund path anywhere in PrimarySale (PrimarySale.sol:774), which is
        // why every swap in this contract is exact-OUTPUT.
        IWETH9(WETH).withdraw(v.priceWei);
        IPrimarySale(PS).settle{value: v.priceWei}(v, merchantSig, auth, sellerAuthSig);

        uint256 spent = _settleUp(tokenIn, WETH, msg.sender, false, pay.maxIn, inBefore);
        emit PrimaryBought(msg.sender, pay.tokenIn, v.assetType, v.assetId, v.priceWei, spent);
    }

    /// @notice Kill the router. Guardian only, one way, no restart.
    /// @dev One-way because a reversible switch is a standing power to
    ///      re-enable a contract that was killed for cause. Re-arming is a
    ///      redeploy: one transaction plus two config flips, and there is no
    ///      state to migrate because the router never holds anything.
    ///
    ///      KNOW THE RECOVERY COST BEFORE PULLING THIS. The replacement router
    ///      needs `EM_FIAT_OPERATOR` on the marketplace, and that role's admin
    ///      is `DEFAULT_ADMIN_ROLE` (no `_setRoleAdmin` anywhere in the suite).
    ///      Today `DEFAULT_ADMIN` is the deployer EOA, so re-arming takes
    ///      minutes. After the Phase 7 Timelock handover it is a Timelock
    ///      operation at `minDelaySeconds` = 43,200 — **12 hours** — proposed
    ///      and executed by the Safe. Meanwhile `stop()` is NOT a Timelock
    ///      operation, so the `canceller` cannot veto it: one ~$5 transaction
    ///      from the guardian takes the multi-currency rails down for half a day
    ///      and nobody can cancel or undo it.
    ///
    ///      Two consequences, both deliberate. Pick a `guardian_` that is NOT
    ///      the same Safe that governs the Timelock, so a single compromised key
    ///      set cannot both destroy the router and be the only thing able to
    ///      replace it. And reach for the reversible levers first: revoking
    ///      `EM_FIAT_OPERATOR` closes the marketplace leg alone, rotating the
    ///      backend's payer constant closes the primary leg alone with no chain
    ///      transaction at all, and `pause()` on either sink is instant. This is
    ///      the last lever, not the first.
    function stop() external {
        if (msg.sender != GUARDIAN) revert NotGuardian(msg.sender);
        stopped = true;
        emit RouterStopped(msg.sender);
    }

    /// @notice The only legitimate inbound ether is the WETH unwrap.
    /// @dev An open `receive` on an immutable contract with no sweep is a
    ///      donation and griefing surface.
    receive() external payable {
        if (msg.sender != WETH) revert NotWeth(msg.sender);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Views — the frontend picker and the backend preflight read these, so the
    // UI can never offer a token the contract will refuse.
    // ─────────────────────────────────────────────────────────────────────────

    /// @notice Whether `token` may be paid in.
    /// @param token The candidate pay-in token.
    /// @return Whether it is on the immutable allow-list.
    function isAllowedToken(address token) public view returns (bool) {
        if (token == address(0)) return false;
        uint256 n = TOKEN_COUNT;
        for (uint256 i = 0; i < n; i++) {
            if (_tokenAt(i) == token) return true;
        }
        return false;
    }

    /// @notice Whether any allow-listed pool uses `fee`.
    /// @dev Informational, for the frontend picker. A route is checked as a
    ///      whole pool by {isAllowedPool}; a tier alone authorises nothing.
    /// @param fee The candidate Uniswap V3 fee tier.
    /// @return Whether some allow-listed pool trades at that tier.
    function isAllowedFee(uint24 fee) public view returns (bool) {
        uint256 n = FEE_COUNT;
        for (uint256 i = 0; i < n; i++) {
            if (_feeAt(i) == fee) return true;
        }
        return false;
    }

    /// @notice Whether `mid` may be used as a hop token.
    /// @param mid The candidate hop token.
    /// @return Whether it is on the immutable allow-list.
    function isAllowedMid(address mid) public view returns (bool) {
        if (mid == address(0)) return false;
        uint256 n = MID_COUNT;
        for (uint256 i = 0; i < n; i++) {
            if (_midAt(i) == mid) return true;
        }
        return false;
    }

    /// @notice The full pay-in allow-list, in deploy order.
    /// @return out Every token the router will accept.
    function allowedTokens() external view returns (address[] memory out) {
        uint256 n = TOKEN_COUNT;
        out = new address[](n);
        for (uint256 i = 0; i < n; i++) out[i] = _tokenAt(i);
    }

    /// @notice The full hop allow-list, in deploy order.
    /// @return out Every token the router will route through.
    function allowedMids() external view returns (address[] memory out) {
        uint256 n = MID_COUNT;
        out = new address[](n);
        for (uint256 i = 0; i < n; i++) out[i] = _midAt(i);
    }

    /// @notice Whether a whole Uniswap pool is on the immutable allow-list.
    /// @dev This, not {isAllowedFee}, is the check a route actually faces. The
    ///      pair is unordered.
    /// @param tokenA One endpoint.
    /// @param tokenB The other endpoint.
    /// @param fee    The pool's fee tier.
    /// @return Whether the router will trade in that pool.
    function isAllowedPool(address tokenA, address tokenB, uint24 fee) public view returns (bool) {
        if (tokenA == address(0) || tokenB == address(0) || tokenA == tokenB) return false;
        bytes32 k = _poolKey(tokenA, tokenB, fee);
        uint256 n = POOL_COUNT;
        for (uint256 i = 0; i < n; i++) {
            if (_poolAt(i) == k) return true;
        }
        return false;
    }

    /// @notice The allow-listed pools, as their keys, in deploy order.
    /// @dev The triples themselves are in the constructor's {PoolAllowed} logs;
    ///      these keys let an ops read-back prove the on-chain set equals the
    ///      intended one without trusting a log index.
    /// @return out `keccak256(abi.encode(lowerToken, higherToken, fee))` each.
    function allowedPoolKeys() external view returns (bytes32[] memory out) {
        uint256 n = POOL_COUNT;
        out = new bytes32[](n);
        for (uint256 i = 0; i < n; i++) out[i] = _poolAt(i);
    }

    /// @notice The distinct fee tiers across the allow-listed pools.
    /// @dev Informational: a tier being here does NOT mean any pair may be
    ///      traded at it. {isAllowedPool} is the binding check.
    /// @return out Every pool fee tier the router will use.
    function allowedFees() external view returns (uint24[] memory out) {
        uint256 n = FEE_COUNT;
        out = new uint24[](n);
        for (uint256 i = 0; i < n; i++) out[i] = _feeAt(i);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Internals
    // ─────────────────────────────────────────────────────────────────────────

    /// @dev Deadline ceiling + pay-in allow-list. Returns the EFFECTIVE input
    ///      token: native ETH is wrapped immediately, so everything downstream
    ///      deals in ERC-20s only.
    function _validate(Pay calldata p, bool nativeAllowed) private view returns (address tokenIn) {
        uint256 ceiling = block.timestamp + MAX_DEADLINE;
        if (p.deadline > ceiling) revert DeadlineTooFar(p.deadline, ceiling);

        tokenIn = p.tokenIn;
        if (tokenIn == address(0)) {
            if (!nativeAllowed) revert TokenNotAllowed(address(0));
            return WETH;
        }
        if (!isAllowedToken(tokenIn)) revert TokenNotAllowed(tokenIn);
    }

    /// @dev Pull EXACTLY `maxIn`, and only ever from `msg.sender`. A
    ///      caller-supplied `from` would make this contract a universal
    ///      allowance drainer across both products.
    function _take(Pay calldata p, bool native) private {
        if (native) {
            if (msg.value != p.maxIn) revert BadValue(msg.value, p.maxIn);
            IWETH9(WETH).deposit{value: msg.value}();
            return;
        }
        if (msg.value != 0) revert BadValue(msg.value, 0);

        Permit calldata pm = p.permit;
        if (pm.kind == 2) {
            // Permit2 IS the transfer here, so it cannot be swallowed.
            IPermit2(PERMIT2).permitTransferFrom(
                IPermit2.PermitTransferFrom({
                    permitted: IPermit2.TokenPermissions({token: p.tokenIn, amount: pm.value}),
                    nonce: pm.nonce,
                    deadline: pm.deadline
                }),
                IPermit2.SignatureTransferDetails({to: address(this), requestedAmount: p.maxIn}),
                msg.sender,
                pm.sig
            );
            return;
        }
        if (pm.kind == 1 && pm.sig.length == 65) {
            // A permit broadcast publicly can be replayed or front-run, and a
            // permit that has already been consumed reverts. Swallowing it means
            // a griefer cannot brick an otherwise-valid buy: if the allowance
            // is already there, the pull below simply succeeds.
            bytes32 r = bytes32(pm.sig[0:32]);
            bytes32 s = bytes32(pm.sig[32:64]);
            uint8 vv = uint8(pm.sig[64]);
            // solhint-disable-next-line no-empty-blocks
            try IERC20Permit(p.tokenIn).permit(msg.sender, address(this), pm.value, pm.deadline, vv, r, s) {} catch {}
        }
        IERC20(p.tokenIn).safeTransferFrom(msg.sender, address(this), p.maxIn);
    }

    /// @dev Exact-OUTPUT swap into the sink's currency, along a path this
    ///      contract builds itself out of pools the DEPLOYER chose. A no-op when
    ///      the buyer already holds the settlement asset.
    ///
    ///      What this does NOT do: bound the price. `amountInMaximum` is the
    ///      caller's `maxIn` and there is no oracle here, so the worst a sandwich
    ///      can take is `maxIn - fairAmountIn`. That bound is set off-chain, in
    ///      the quote service, and it is the reason the pool list exists: a
    ///      route now runs through a real, arbitraged pool the deployer picked,
    ///      where extraction costs the attacker capital, rather than through one
    ///      they own outright and can price at anything.
    function _swapExactOut(address tokenIn, address tokenOut, Pay calldata p, uint256 amountOut) private {
        if (tokenIn != tokenOut) {
            if (p.mid == address(0)) {
                if (p.feeOut != 0) revert FeeNotAllowed(p.feeOut);
                if (!isAllowedPool(tokenIn, tokenOut, p.feeIn)) {
                    revert PoolNotAllowed(tokenIn, tokenOut, p.feeIn);
                }
                IERC20(tokenIn).forceApprove(SWAP, p.maxIn);
                ISwapRouterV3(SWAP).exactOutputSingle(
                    ISwapRouterV3.ExactOutputSingleParams({
                        tokenIn: tokenIn,
                        tokenOut: tokenOut,
                        fee: p.feeIn,
                        recipient: address(this),
                        deadline: p.deadline,
                        amountOut: amountOut,
                        amountInMaximum: p.maxIn,
                        sqrtPriceLimitX96: 0
                    })
                );
            } else {
                if (!isAllowedMid(p.mid) || p.mid == tokenIn || p.mid == tokenOut) revert MidNotAllowed(p.mid);
                if (!isAllowedPool(tokenIn, p.mid, p.feeIn)) {
                    revert PoolNotAllowed(tokenIn, p.mid, p.feeIn);
                }
                if (!isAllowedPool(p.mid, tokenOut, p.feeOut)) {
                    revert PoolNotAllowed(p.mid, tokenOut, p.feeOut);
                }
                IERC20(tokenIn).forceApprove(SWAP, p.maxIn);
                // V3 encodes an exact-OUTPUT path in reverse: out, feeOut, mid, feeIn, in.
                ISwapRouterV3(SWAP).exactOutput(
                    ISwapRouterV3.ExactOutputParams({
                        path: abi.encodePacked(tokenOut, p.feeOut, p.mid, p.feeIn, tokenIn),
                        recipient: address(this),
                        deadline: p.deadline,
                        amountOut: amountOut,
                        amountInMaximum: p.maxIn
                    })
                );
            }
            // No standing allowance at rest. `forceApprove` also survives USDT's
            // "must reset to zero first" behaviour.
            IERC20(tokenIn).forceApprove(SWAP, 0);
        }

        // Believe the balance, not the return value: a pool (or a hostile
        // router) that reports success while delivering short must not reach
        // the sink, where the failure would be a late, unnamed revert.
        uint256 have = IERC20(tokenOut).balanceOf(address(this));
        if (have < amountOut) revert SwapShort(have, amountOut);
    }

    /// @dev Sweep, THEN assert zero. Returns what the buyer actually spent of
    ///      `maxIn`, for the indexer.
    ///
    ///      Sweeping before asserting is the whole point: a griefer who donates
    ///      1 wei of `tokenIn` to this address would otherwise make every
    ///      subsequent buy revert {DustLeft} forever. Swept first, the donation
    ///      is simply a gift to the next buyer.
    function _settleUp(
        address tokenIn,
        address tokenOut,
        address to,
        bool native,
        uint256 maxIn,
        uint256 inBefore
    ) private returns (uint256 spent) {
        // A DELTA, not a balance. The earlier form read the absolute balance and
        // called the whole of it the unspent remainder of `maxIn`, which is only
        // true when the router held none of `tokenIn` on entry. Anyone can send
        // a token to this address — the sweep makes that harmless for the MONEY
        // (it becomes a gift to this buyer) but it silently corrupted the
        // number: with a donation D the event reported `maxIn - D - amountIn`,
        // and a large enough D reported ZERO for a real purchase. `spent` is the
        // only place the pay-in cost is published, so an indexer, a support tool
        // and the per-currency volume monitoring all read a figure the buyer
        // could set to nothing at no cost to themselves.
        //
        // `inBefore` is snapshotted by the caller immediately before `_take`, so
        // what the router received is `(inBefore + maxIn)` and what is left over
        // is the current balance. Saturating, because a fee-on-transfer pay-in
        // delivers less than `maxIn` and must not underflow here.
        uint256 leftIn = IERC20(native ? WETH : tokenIn).balanceOf(address(this));
        uint256 had = inBefore + maxIn;
        spent = leftIn >= had ? 0 : had - leftIn;

        _sweep(tokenOut, to);
        if (native) {
            uint256 w = IERC20(WETH).balanceOf(address(this));
            if (w > 0) IWETH9(WETH).withdraw(w);
        } else {
            if (tokenIn != tokenOut) _sweep(tokenIn, to);
            if (WETH != tokenIn && WETH != tokenOut) _sweep(WETH, to);
        }

        uint256 bal = address(this).balance;
        if (bal > 0) {
            // solhint-disable-next-line avoid-low-level-calls
            (bool ok, ) = to.call{value: bal}("");
            if (!ok) {
                // A contract buyer with a reverting `receive` must not be able
                // to strand its own purchase. Wrap and hand over an ERC-20
                // instead — no `pendingEth` ledger, nothing at rest.
                IWETH9(WETH).deposit{value: bal}();
                IERC20(WETH).safeTransfer(to, bal);
            }
        }

        _requireZero(tokenIn);
        _requireZero(tokenOut);
        _requireZero(WETH);
        if (address(this).balance != 0) revert DustLeft(address(0), address(this).balance);
    }

    /// @dev Push a whole balance out. Never partial: the router keeps nothing.
    function _sweep(address token, address to) private {
        uint256 bal = IERC20(token).balanceOf(address(this));
        if (bal > 0) IERC20(token).safeTransfer(to, bal);
    }

    function _requireZero(address token) private view {
        uint256 bal = IERC20(token).balanceOf(address(this));
        if (bal != 0) revert DustLeft(token, bal);
    }

    function _tokenAt(uint256 i) private view returns (address) {
        if (i == 0) return TOKEN_0;
        if (i == 1) return TOKEN_1;
        if (i == 2) return TOKEN_2;
        if (i == 3) return TOKEN_3;
        if (i == 4) return TOKEN_4;
        if (i == 5) return TOKEN_5;
        if (i == 6) return TOKEN_6;
        return TOKEN_7;
    }

    function _midAt(uint256 i) private view returns (address) {
        return i == 0 ? MID_0 : MID_1;
    }

    /// @dev Unordered pool key: Uniswap sorts the tokens itself, so the
    ///      allow-list must not care which way round the deployer wrote them.
    function _poolKey(address a, address b, uint24 fee) private pure returns (bytes32) {
        return a < b ? keccak256(abi.encode(a, b, fee)) : keccak256(abi.encode(b, a, fee));
    }

    function _inList(address[] memory list, address a) private pure returns (bool) {
        uint256 n = list.length;
        for (uint256 i = 0; i < n; i++) {
            if (list[i] == a) return true;
        }
        return false;
    }

    function _poolAt(uint256 i) private view returns (bytes32) {
        if (i == 0) return POOL_0;
        if (i == 1) return POOL_1;
        if (i == 2) return POOL_2;
        if (i == 3) return POOL_3;
        if (i == 4) return POOL_4;
        if (i == 5) return POOL_5;
        if (i == 6) return POOL_6;
        return POOL_7;
    }

    function _feeAt(uint256 i) private view returns (uint24) {
        if (i == 0) return FEE_0;
        if (i == 1) return FEE_1;
        if (i == 2) return FEE_2;
        return FEE_3;
    }
}

npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

npm/@openzeppelin/[email protected]/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also applies here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _reentrancyGuardStorageSlot().asBoolean().tload();
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

npm/@openzeppelin/[email protected]/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

project/contracts/interfaces/IMarketplace.sol

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

/// @title IMarketplace
/// @author EarthMeta 2026.
/// @notice Self-service EIP-712 marketplace. Buyers pay in USDT (escrowed);
///         sellers, royalty recipients, and the protocol are paid in EMT from a
///         pre-funded reserve, priced by the TWAP oracle. Listing and cancelling
///         are gasless/off-chain (signatures); the only on-chain cost is the fill.
interface IMarketplace {
    /// @notice A seller's signed listing (gasless to create).
    /// @param maker The seller (and current NFT owner).
    /// @param nft The collection address.
    /// @param tokenId The token id for sale.
    /// @param priceUSDT The ask, denominated in USDT (6 decimals).
    /// @param start Unix time the listing becomes valid.
    /// @param expiry Unix time the listing expires.
    /// @param salt Uniqueness salt (distinguishes otherwise-identical orders).
    /// @param nonce The maker's order nonce (orders below `nonces[maker]` are void).
    struct Listing {
        address maker;
        address nft;
        uint256 tokenId;
        uint256 priceUSDT;
        uint64 start;
        uint64 expiry;
        uint256 salt;
        uint256 nonce;
    }

    /// @notice A buyer's signed offer on a specific token (gasless to create).
    /// @param taker The bidder (and USDT payer).
    /// @param nft The collection address.
    /// @param tokenId The token id being bid on.
    /// @param priceUSDT The bid, denominated in USDT (6 decimals).
    /// @param start Unix time the offer becomes valid.
    /// @param expiry Unix time the offer expires.
    /// @param salt Uniqueness salt.
    /// @param nonce The taker's order nonce.
    struct Offer {
        address taker;
        address nft;
        uint256 tokenId;
        uint256 priceUSDT;
        uint64 start;
        uint64 expiry;
        uint256 salt;
        uint256 nonce;
    }

    event Filled(
        bytes32 indexed orderHash,
        address indexed seller,
        address indexed buyer,
        address nft,
        uint256 tokenId,
        uint256 priceUSDT,
        uint256 emtPaid
    );
    event OfferAccepted(
        bytes32 indexed orderHash,
        address indexed seller,
        address indexed buyer,
        address nft,
        uint256 tokenId,
        uint256 priceUSDT,
        uint256 emtPaid
    );
    event OrderCancelled(bytes32 indexed orderHash, address indexed maker);
    /// @notice An order cancelled by the platform's EM_ORDER_JANITOR key
    ///         (`cancelOrdersFor`), not by its signer. Same effect as
    ///         `OrderCancelled`: the hash is consumed and no fill path accepts it.
    event OrderCancelledByJanitor(bytes32 indexed orderHash, address indexed janitor);
    event NonceIncremented(address indexed maker, uint256 newNonce);
    event Credited(address indexed account, uint256 emtAmount);
    event Withdrawn(address indexed account, uint256 emtAmount);
    event ReserveFunded(address indexed from, uint256 emtAmount);
    event UsdtSwept(address indexed to, uint256 amount);
    event EmtSkimmed(address indexed to, uint256 amount);
    event FeeBpsSet(uint256 bps);
    event NftAllowed(address indexed nft, bool allowed);
}

project/contracts/interfaces/IPrimarySale.sol

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

/// @title IPrimarySale
/// @author EarthMeta 2026.
/// @notice The slice of {PrimarySale} a periphery contract needs in order to
///         front `settle` as the bound payer.
/// @dev The two structs below MUST stay byte-for-byte identical to the ones in
///      `contracts/payments/PrimarySale.sol` — same fields, same order, same
///      types. `settle` re-hashes the seller's authorization as
///      `keccak256(abi.encode(auth))` and compares it to `voucher.authHash`
///      (PrimarySale.sol:689), so a single reordered or widened field would make
///      every router-fronted land sale revert `AuthMismatch` even though the
///      seller's signature is perfectly valid. `BuyRouter.abi.test.ts` pins both
///      the selector and that hash against the real contract.
interface IPrimarySale {
    /// @notice A merchant-signed sale of an asset that has no token yet.
    /// @dev Mirrors `PrimarySale.SaleVoucher` (PrimarySale.sol:171-187).
    struct SaleVoucher {
        address buyer;
        uint8 assetType;
        uint256 assetId;
        uint256 parentId;
        string uri;
        uint256 param;
        uint256 priceWei;
        address currency;
        uint8 payoutMode;
        address seller;
        bytes32 authHash;
        address payer;
        bytes32 orderRef;
        uint256 nonce;
        uint256 deadline;
    }

    /// @notice The seller's own price authorization.
    /// @dev Mirrors `PrimarySale.SellAuthorization` (PrimarySale.sol:202-211).
    struct SellAuthorization {
        address seller;
        uint8 assetType;
        uint256 assetId;
        uint256 minSellerWei;
        uint256 minPriceWei;
        address currency;
        uint256 expiry;
        uint256 nonce;
    }

    /// @notice Buy an asset that has no on-chain token yet.
    /// @dev `msg.sender` must equal `voucher.payer`; the NFT is minted to
    ///      `voucher.buyer`. No role is required of the caller.
    function settle(
        SaleVoucher calldata voucher,
        bytes calldata merchantSig,
        SellAuthorization calldata auth,
        bytes calldata sellerAuthSig
    ) external payable;

    /// @notice The value a voucher's `authHash` must carry for `auth`.
    /// @dev `keccak256(abi.encode(auth))`. Read by the router's CONSTRUCTOR as
    ///      its identity probe for the PrimarySale wire, and it proves two
    ///      things at once that `paused()` proves neither of:
    ///
    ///      1. IDENTITY. `paused()` is answered by four other live contracts in
    ///         the same address book — the marketplace, the collections, the
    ///         staking — so a mis-wired `primarySale_` sails through it. Nothing
    ///         else in the suite has `authBinding`.
    ///      2. LAYOUT. It is `abi.encode` of the very struct `settle` re-hashes
    ///         and compares to `voucher.authHash`, so a `SellAuthorization` that
    ///         has drifted from the deployed one fails HERE, at deploy time,
    ///         instead of making every router-fronted LAND sale revert
    ///         `AuthMismatch` while the seller's signature is perfectly valid.
    function authBinding(SellAuthorization calldata auth) external pure returns (bytes32);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.