Skip to content
Verified contractExactMIT

CrossChainPurchaseExecutor

Address0x2dc0c504f7b37028d7d59c4f869d7682a02ba23b
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,423,448
Creation transaction
0x24fbfb4f68…370d55d00c

ethereum/crosschain/CrossChainPurchaseExecutor.sol

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

import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "./ISeaportConsumer.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SignedAuthorization} from "../ZoneAuthorizationTypes.sol";
import {
    ICollectionRegistry,
    COLLECTION_STANDARD_ERC721,
    COLLECTION_STANDARD_ERC1155,
    UNVERIFIED_POLICY_ID
} from "../interfaces/ICollectionRegistry.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title CrossChainPurchaseExecutor
 * @notice Destination-chain settlement agent for cross-chain-currency marketplace purchases.
 *
 * Model (founder-locked 2026-07-26): the BUYER pays from any chain in any currency; the seller
 * receives their listing currency on the listing chain; the NFT stays on the listing chain and is
 * delivered to the buyer there. Only the PAYMENT is cross-chain (one bridge leg, buyer → settlement).
 *
 * Flow: a non-custodial rail (Relay — spec DES-6 D1; the solver executes the destination calls the
 * quote carries) delivers the buyer's funds on THIS chain in the listing's currency and calls either
 * `settlePurchaseNative` (native-priced listing, funds as `msg.value`) or, after an ERC-20 approval to
 * this contract, `settlePurchaseERC20` (ERC-20-priced listing, exactly `price` pulled from the
 * caller). This contract then fills the seller's signed Seaport listing in the SAME transaction,
 * delivering the NFT directly to the buyer via Seaport's `recipient` param. The caller is never
 * trusted: who benefits is bound by parameters and the zone-signed authorization, not `msg.sender`.
 *
 * WHAT IS ACTUALLY ENFORCED HERE (the order is caller-supplied, so nothing about it may be assumed):
 *   1. `order.parameters.zone` must be on the owner-managed allowlist. Only then is it true that "the
 *      marketplace zone still enforces the tier fee + royalties" — an unrestricted or foreign-zoned
 *      order enforces nothing, so it is refused.
 *   2. The first NFT item offered by the order must be exactly (`expectedCollection`,
 *      `expectedTokenId`) — the asset the buyer signed up to receive. Without this binding, whoever
 *      controls the destination calldata could substitute any order (e.g. one whose consideration
 *      pays themselves) and spend the buyer's bridged funds on it.
 *   3. The delivered `msg.value` must cover `price`, and the NFT is delivered to `buyer` via Seaport's
 *      recipient param — never to the caller.
 *   5. The collection must be admitted by the `CollectionRegistry` for the offered standard, under the policy pair
 *      (`policyId`, `policyEpoch`) the zone authorization signed, before any buyer funds go into Seaport. The
 *      collection answers its own `ownerOf` / `balanceOf`, so the delivery postcondition below cannot tell a
 *      collection that reports the buyer while keeping its enforceable ledger on the seller; admission (reviewed,
 *      immutable code, pinned by codehash) is what makes that check meaningful. The postcondition stays as defence in
 *      depth.
 *   4. Closeout L-12: the zone-signed authorization carried in `order.extraData` names a `recipient`,
 *      and it must equal `buyer`. The zone sees only the fulfiller (always THIS contract on the
 *      cross-chain path), so without this binding an authorization issued for buyer A was valid for
 *      anyone who copied the order + `extraData` from the mempool and called this public function
 *      with buyer B — the copy consumed the single-use nonce and took delivery, and the victim's
 *      transaction reverted. Now calldata substitution invalidates the signature.
 *
 * STRICTLY NON-CUSTODIAL + FILL-OR-REVERT: a call either fully settles the purchase or REVERTS. It
 * never retains user funds and never refunds on the wrong chain. If the listing is gone (bought/
 * cancelled) or the delivered amount is short (bad slippage), the call reverts — which fails the rail's
 * destination execution, so the rail refunds the buyer on their SOURCE chain to the quote's `refundTo`
 * address (the backend sets it to the buyer's origin wallet). We deliberately do NOT refund on this
 * (destination) chain, because a buyer who paid on chain A should get their money back on chain A, not
 * be left holding destination-chain currency they never wanted.
 *
 * The rail should route the final swap as EXACT-OUTPUT (deliver exactly `price`) so there is no surplus.
 * Any residual surplus on a SUCCESSFUL fill is forwarded to the buyer here (dust only, success path).
 * Closeout L-13: if the buyer cannot receive that push, the completed purchase is NOT reverted — the
 * surplus is held as a buyer-owned pull balance (`claimSurplusTo` / `claimTokenSurplusTo`) that the
 * owner's rescue functions can never sweep.
 *
 * Multi-unit (partial) cross-chain fills are NOT supported: the M-16 delivery postcondition requires
 * the full offered amount, so quantity / fill fraction need no binding yet.
 */
contract CrossChainPurchaseExecutor is Ownable2Step {
    using SafeERC20 for IERC20;

    ISeaportConsumer public immutable seaport;
    /// @notice The runtime code hash of `seaport`, checked at construction against the canonical hashes below.
    bytes32 public immutable seaportCodehash;
    /// @notice The collection admission boundary (immutable; see the contract notes, point 5).
    ICollectionRegistry public immutable collectionRegistry;

    // The runtime code hashes of canonical Seaport 1.6 (0x0000000000000068F116a894984e2DB1123eB395), one per supported
    // chain: Seaport bakes the chain id into its runtime, so each chain has its own. Compiled in, so whoever deploys
    // this contract cannot widen the set. The same table is pinned in scripts/lib/seaport-codehash.ts, where every
    // deploy script also asserts the connected chain's exact hash.
    bytes32 private constant SEAPORT_CODEHASH_ETHEREUM = 0x74499ac0cce14428e4b41541d5e44f28f5a6882a1051d0118867c2a93cd5aec0; // chain 1
    bytes32 private constant SEAPORT_CODEHASH_BASE = 0x2d5cb8553e21a19550413299c05a6493cc606fb0000b5042328a5ba06bfdaf35; // chain 8453
    bytes32 private constant SEAPORT_CODEHASH_BNB = 0x16bd146d392a011a996f447b813623d4857ba2d7621af38194a009cbc03ab5f4; // chain 56
    bytes32 private constant SEAPORT_CODEHASH_POLYGON = 0x24fd52b9fba5545dabf736449aa4f2beed9562a4a641d2f6c85ca05eeed35d52; // chain 137
    bytes32 private constant SEAPORT_CODEHASH_APECHAIN = 0x1bbbe3ba82d3f18986d3b1a4830b887b406b81ccef0f46cd35677ddcacdb9463; // chain 33139
    bytes32 private constant SEAPORT_CODEHASH_ABSTRACT = 0xc00dc1e5382340b4c57057dbd0d63038ad6ad8aae26c521357316f719e33d50d; // chain 2741
    bytes32 private constant SEAPORT_CODEHASH_ROBINHOOD = 0x95809b70c9659c30188db5fdd87103e24b1a55379af8c851fca393aba0224a00; // chain 4663
    bytes32 private constant SEAPORT_CODEHASH_SEPOLIA = 0xd3c20b1b63b44e7a392b8b95b710186b79cc494f440e07a01545e2fb14901f5a; // chain 11155111
    bytes32 private constant SEAPORT_CODEHASH_BASE_SEPOLIA = 0x7912af42062ec0080cde88360c1429d58984ae16eb3f17af505b815bf6ffc745; // chain 84532
    bytes32 private constant SEAPORT_CODEHASH_BNB_TESTNET = 0xfd5619bc2c5a60cceb14956fabebe0685b1eae3ebf1e6f151252586ed945872a; // chain 97
    bytes32 private constant SEAPORT_CODEHASH_AMOY = 0x69b3b328e4004f72fca80074c5df746a0705f54f9e8ef73818b404c1739c80bc; // chain 80002
    bytes32 private constant SEAPORT_CODEHASH_CURTIS = 0xa3965715a7c92b72b88ae9bcab23c3e575584ded95d870bd0daa32ae7ce1e1b8; // chain 33111
    bytes32 private constant SEAPORT_CODEHASH_ABSTRACT_TESTNET = 0x46e23976cdae2e6f1f6102b0ed76fce9a29badce0ffc0714b8fad2f061a18cd1; // chain 11124
    bytes32 private constant SEAPORT_CODEHASH_ROBINHOOD_TESTNET = 0x3c34f01b93b6bdb7adcc543eb870c27c8357ae3192df0f054365947e0714ece6; // chain 46630

    /// @notice D2: ERC-20 surplus a buyer could not receive at settlement (token => buyer => amount).
    mapping(address => mapping(address => uint256)) public tokenSurplusOwed;
    /// @notice D2: sum of `tokenSurplusOwed` per token — never sweepable by `rescueERC20`.
    mapping(address => uint256) public totalTokenSurplusOwed;

    /// @notice D2: an ERC-20-priced cross-chain purchase was filled. Mirrors `CrossChainPurchaseFilledV2`
    ///         with the payment token named; `priceForwarded` is the amount pulled from the caller.
    event CrossChainPurchaseFilledERC20(
        address indexed buyer,
        address indexed offerer,
        bytes32 indexed orderHash,
        address nftContract,
        uint256 tokenId,
        uint256 quantity,
        address zone,
        address paymentToken,
        uint256 priceForwarded,
        uint256 surplusToBuyer,
        uint256 surplusHeld
    );
    event TokenSurplusHeld(address indexed token, address indexed buyer, uint256 amount);
    event TokenSurplusClaimed(address indexed token, address indexed buyer, address indexed to, uint256 amount);
    event ERC20Rescued(address indexed token, address indexed to, uint256 amount);

    /// @notice D2: the order's payment side is not entirely `paymentToken` (a native or foreign item).
    error PaymentTokenMismatch(address token);
    /// @notice D2: an ERC-20 purchase must move a positive amount.
    error ZeroPrice();

    /// @notice Zones whose orders this executor is willing to fill. A zone is what makes the UnVault
    ///         fee + royalty policy binding on a fill, so only zones the operator has vetted qualify.
    mapping(address => bool) public allowedZones;

    /// @notice Closeout L-13: surplus a buyer could not receive at settlement, held for a pull claim.
    mapping(address => uint256) public surplusOwed;
    /// @notice Sum of `surplusOwed` — the part of the balance that is NOT the owner's to rescue.
    uint256 public totalSurplusOwed;

    /// @dev Closeout I-10: versioned with unambiguous semantics. `msgValue` is what the rail delivered,
    ///      `priceForwarded` is what was sent into Seaport, `surplusToBuyer` the part of the residual that
    ///      was pushed to the buyer and `surplusHeld` the part parked for `claimSurplusTo` (L-13). The
    ///      order hash, asset, quantity and zone identify exactly which Seaport order was filled.
    event CrossChainPurchaseFilledV2(
        address indexed buyer,
        address indexed offerer,
        bytes32 indexed orderHash,
        address nftContract,
        uint256 tokenId,
        uint256 quantity,
        address zone,
        uint256 msgValue,
        uint256 priceForwarded,
        uint256 surplusToBuyer,
        uint256 surplusHeld
    );
    /// @notice Closeout L-13: the surplus push to `buyer` failed; it is held for `claimSurplusTo`.
    event SurplusHeld(address indexed buyer, uint256 amount);
    event SurplusClaimed(address indexed buyer, address indexed to, uint256 amount);
    event ZoneAllowedSet(address indexed zone, bool allowed);
    event ETHRescued(address indexed to, uint256 amount);

    error ZeroAddress();
    error InsufficientDelivery(uint256 received, uint256 price);
    error OrderUnfulfillable();
    error SurplusForwardFailed();
    /// @notice The order routes through a zone that is not on the allowlist.
    error ZoneNotAllowed(address zone);
    /// @dev Raised when the order's type would let Seaport skip the zone callback entirely.
    error ZoneNotEnforced(OrderType orderType);
    /// @notice The order does not offer any NFT item, so there is nothing to bind the payment to.
    error NoOfferedNft();
    error DeliveryNotConfirmed(); // Closeout M-16
    /// @notice The order's offered NFT is not the asset the buyer paid for.
    error UnexpectedAsset(address collection, uint256 tokenId);
    /// @notice `rescueETH` found no balance to sweep.
    error NothingToRescue();
    error RescueFailed();
    /// @notice An ERC-20 rescue left less than the surplus held for buyers (the token moved more than asked).
    error RescueUnderfundsSurplus(uint256 balanceAfter, uint256 held);
    /// @notice Closeout L-12: the order carries no zone authorization to bind the buyer to.
    error MissingAuthorization();
    /// @notice Closeout L-12: the zone-signed authorization names a different recipient than `buyer`.
    error RecipientMismatch(address signedRecipient, address buyer);
    /// @notice Closeout L-13: the pre-existing balance moved during settlement.
    error BalanceInvariantBroken();
    /// @notice Closeout L-24: an immutable dependency has no code.
    error DependencyNotContract(address dependency);
    error NothingToClaim();
    /// @notice An ERC-20 surplus claim did not reach the recipient in full; the claim is kept.
    error SurplusNotReceived(uint256 expected, uint256 received);
    /// @notice G-17: the hot reentrancy guard uses a custom error (was a revert string).
    error Reentrancy();
    /// @notice Closeout I-04: a zone must be a distinct, code-bearing contract — never this executor
    ///         (canonical Seaport skips zone authorization when its caller IS the order's zone).
    error ZoneMustBeContract(address zone);
    /// @notice The zone did not answer `zoneSignerConfigured() == true`: it is not (or no longer provably) verifying the
    ///         signed recipient this executor relies on.
    error ZoneSignerNotConfigured(address zone);
    /// @notice Closeout I-15: the buyer (Seaport offer recipient) may never be this executor.
    error BuyerMustNotBeExecutor();
    /// @notice An ERC-1155 offer whose quantity changes over time: Seaport transfers the amount interpolated at fill
    ///         time, which the delivery check cannot know in advance. Not admitted; the backend refuses it too.
    error TimeVaryingOfferUnsupported(uint256 startAmount, uint256 endAmount);
    /// @notice A consideration recipient's balance did not rise by what the order owes it: Seaport did not route the
    ///         payment the order describes.
    error PayeeNotPaid(address payee, uint256 owed, uint256 received);

    // Minimal reentrancy guard (no external dep).
    uint256 private _lock = 1;
    modifier nonReentrant() {
        if (_lock != 1) revert Reentrancy();
        _lock = 2;
        _;
        _lock = 1;
    }

    /// @notice Renouncing is disabled (owner decision 2026-10-19), as on the bridge and the launchpad: a renounce
    ///         would end every owner power for good. Ownership moves only through the two-step transfer.
    error RenounceDisabled();
    /// @notice The Seaport dependency's runtime code hash is not one of the canonical Seaport 1.6 hashes.
    error SeaportCodehashNotAccepted(bytes32 codehash);
    /// @notice A consideration item whose amount changes over time. Seaport pays the amount interpolated at the fill
    ///         timestamp, so the payee check could only bound it from below; refused before any funds move.
    error TimeVaryingConsiderationUnsupported(uint256 startAmount, uint256 endAmount);
    /// @notice A consideration item pays this executor. Whatever it receives would count as the buyer's unspent rail
    ///         funds and be forwarded to the buyer (a fee leg here would rebate the protocol fee); refused before any
    ///         funds move.
    error PayeeIsExecutor();
    /// @notice The zone's fee recipient is this executor, so every fee leg it requires would pay the executor.
    error FeeRecipientIsExecutor(address zone);
    /// @notice An immutable dependency answers, but not as the contract kind expected.
    error DependencyMismatch(address dependency);
    /// @notice The collection registry does not admit the offered collection for its standard right now.
    error CollectionNotAdmitted(address collection);
    /// @notice The registry's current policy pair for the collection is not the one the authorization signed.
    error CollectionPolicyMismatch(address collection, bytes32 policyId, uint64 policyEpoch);
    /// @notice The collection is blocked in the registry while unrecorded.
    error CollectionBlocked(address collection);
    /// @notice The global unverified lane is closed in the registry.
    error UnverifiedLaneClosed();

    function renounceOwnership() public pure override {
        revert RenounceDisabled();
    }

    /// @param initialOwner UV-313 (review H-4): explicit owner (a CREATE2 factory would otherwise own it).
    ///
    /// `_seaport`'s runtime code hash must be one of the compiled-in canonical hashes. Accepting any chain's entry, not
    /// only this chain's, keeps the init code (and the CREATE2 address) the same on every chain, and is not weaker:
    /// every entry IS canonical Seaport 1.6 code, which settles honestly (consideration to the order's recipients)
    /// whatever chain its immutables name. A copy of that code at another address cannot move a seller's assets
    /// either, because sellers approve canonical Seaport or its conduit, not the copy. A dependency that only forwards
    /// Seaport's view calls has its own code and matches no entry.
    /// @param _collectionRegistry the `CollectionRegistry` (code, and ERC-165 for `ICollectionRegistry`).
    constructor(address _seaport, address _collectionRegistry, address initialOwner) {
        if (initialOwner == address(0)) revert ZeroAddress();
        _transferOwnership(initialOwner);
        if (_seaport == address(0)) revert ZeroAddress();
        // Closeout L-24: a code-less Seaport would yield a live executor that can never fill.
        if (_seaport.code.length == 0) revert DependencyNotContract(_seaport);
        // Identity is the runtime code hash: answering Seaport's view calls proves only the shape, since a contract
        // can forward those reads to the real Seaport while settling differently.
        bytes32 codehash = _seaport.codehash;
        if (!isAcceptedSeaportCodehash(codehash)) revert SeaportCodehashNotAccepted(codehash);
        // Closeout L-24: the shape read-back stays as a cheap sanity check (name and domain separator).
        _requireSeaportIdentity(_seaport);
        seaport = ISeaportConsumer(_seaport);
        seaportCodehash = codehash;
        if (_collectionRegistry.code.length == 0) revert DependencyNotContract(_collectionRegistry);
        (bool ok, bytes memory ret) = _collectionRegistry.staticcall(
            abi.encodeCall(IERC165.supportsInterface, (type(ICollectionRegistry).interfaceId))
        );
        if (!ok || ret.length != 32 || abi.decode(ret, (uint256)) != 1) revert DependencyMismatch(_collectionRegistry);
        collectionRegistry = ICollectionRegistry(_collectionRegistry);
    }

    /// @notice True when `codehash` is the runtime code hash of canonical Seaport 1.6 on a supported chain.
    /// @dev Virtual only so a test-only subclass (ethereum/test/) can add a local Seaport build; this contract's
    ///      deployed code answers from the constants above.
    function isAcceptedSeaportCodehash(bytes32 codehash) public view virtual returns (bool) {
        return codehash == SEAPORT_CODEHASH_ETHEREUM || codehash == SEAPORT_CODEHASH_BASE || codehash == SEAPORT_CODEHASH_BNB
            || codehash == SEAPORT_CODEHASH_POLYGON || codehash == SEAPORT_CODEHASH_APECHAIN
            || codehash == SEAPORT_CODEHASH_ABSTRACT || codehash == SEAPORT_CODEHASH_ROBINHOOD
            || codehash == SEAPORT_CODEHASH_SEPOLIA || codehash == SEAPORT_CODEHASH_BASE_SEPOLIA
            || codehash == SEAPORT_CODEHASH_BNB_TESTNET || codehash == SEAPORT_CODEHASH_AMOY
            || codehash == SEAPORT_CODEHASH_CURTIS || codehash == SEAPORT_CODEHASH_ABSTRACT_TESTNET
            || codehash == SEAPORT_CODEHASH_ROBINHOOD_TESTNET;
    }

    /// @dev Closeout L-24: static-call read-back of the Seaport identity surface.
    function _requireSeaportIdentity(address candidate) private view {
        (bool okName, bytes memory nameData) = candidate.staticcall(abi.encodeWithSelector(ISeaportConsumer.name.selector));
        if (!okName || nameData.length == 0) revert DependencyNotContract(candidate);
        if (keccak256(bytes(abi.decode(nameData, (string)))) != keccak256(bytes("Seaport"))) revert DependencyNotContract(candidate);
        (bool okInfo, bytes memory infoData) = candidate.staticcall(abi.encodeWithSelector(ISeaportConsumer.information.selector));
        if (!okInfo || infoData.length == 0) revert DependencyNotContract(candidate);
        (, bytes32 domainSeparator, ) = abi.decode(infoData, (string, bytes32, address));
        if (domainSeparator == bytes32(0)) revert DependencyNotContract(candidate);
    }

    // ═════════════════════════════════════════════════════════════════════════
    //  ADMIN
    // ═════════════════════════════════════════════════════════════════════════

    /// @notice Add or remove a zone from the fill allowlist.
    /// @dev Only orders restricted to an allowlisted zone can be filled, because only those orders
    ///      have the UnVault fee/royalty policy enforced on them at fulfilment time.
    function setZoneAllowed(address zone, bool allowed) external onlyOwner {
        if (zone == address(0)) revert ZeroAddress();
        // Closeout I-04: an order naming THIS executor as zone would pass the allowlist while Seaport
        // consulted no zone at all; require a distinct, deployed zone implementation.
        if (zone == address(this) || zone.code.length == 0) revert ZoneMustBeContract(zone);
        // The executor's recipient check compares two caller-supplied values; only the zone's signature check binds
        // them. A zone without a signer must therefore never be allowlisted (removing one is always possible).
        if (allowed && !_zoneSignerReady(zone)) revert ZoneSignerNotConfigured(zone);
        // The fee legs the zone requires go to its fee recipient; one that is this executor would be rebated to the
        // buyer. Read back at enable time; every settlement also refuses a leg paying this executor (`_preflight`).
        if (allowed && _zoneFeeRecipient(zone) == address(this)) revert FeeRecipientIsExecutor(zone);
        allowedZones[zone] = allowed;
        emit ZoneAllowedSet(zone, allowed);
    }

    /// @notice Sweep native currency that arrived outside a settle call.
    /// @dev A successful settle forwards its own surplus to the buyer and a failed one reverts, so this
    ///      contract holds ~0 in normal operation. Funds pushed straight into `receive()` (a mis-sent
    ///      transfer, a bridge fallback) would otherwise be stranded forever with no sweep at all.
    ///      Closeout L-13: `nonReentrant` — Seaport pays native consideration DURING the fill, so an
    ///      owner that is also a consideration recipient (the seller, or the fee recipient under the
    ///      same operator) received a callback while the buyer's overdelivery still sat here, and
    ///      could sweep it before the surplus was computed. The sweep now shares the settlement
    ///      guard, and it never touches surplus held for buyers.
    function rescueETH(address to) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 amount = address(this).balance - totalSurplusOwed;
        if (amount == 0) revert NothingToRescue();
        (bool ok, ) = payable(to).call{value: amount}("");
        if (!ok) revert RescueFailed();
        emit ETHRescued(to, amount);
    }

    // ═════════════════════════════════════════════════════════════════════════
    //  SETTLEMENT
    // ═════════════════════════════════════════════════════════════════════════

    /**
     * @notice Fill a seller's native-priced Seaport listing on behalf of a cross-chain buyer, or revert.
     * @param order              the seller's signed Seaport advanced order (the listing); `extraData`
     *                           must carry the zone-signed authorization naming `buyer` as recipient
     * @param price              the exact native consideration the order requires (sum of native consideration items)
     * @param conduitKey         the fulfiller conduit key (bytes32(0) = fulfill directly, no conduit)
     * @param buyer              recipient of the NFT AND of any swap surplus
     * @param expectedCollection the NFT contract the buyer paid to receive
     * @param expectedTokenId    the token id the buyer paid to receive
     *
     * Permissionless + non-custodial + FILL-OR-REVERT: the caller (the rail) supplies the funds; the
     * call fully settles or reverts. On revert, the rail (Relay) refunds the buyer on the SOURCE chain.
     * The buyer's money is bound to a specific asset and a vetted zone by the checks above, so an
     * arbitrary caller can neither redirect the NFT (it goes to `buyer`) nor swap in a different order.
     */
    function settlePurchaseNative(
        AdvancedOrder calldata order,
        uint256 price,
        bytes32 conduitKey,
        address buyer,
        address expectedCollection,
        uint256 expectedTokenId
    ) external payable nonReentrant {
        (bool is1155, uint256 offeredAmount) = _preflight(order, buyer, expectedCollection, expectedTokenId);

        uint256 received = msg.value;
        // Short delivery (bad slippage) → revert so the rail refunds the source chain (never settle partial).
        if (received < price) revert InsufficientDelivery(received, price);
        // Balance not brought in by THIS call (defensive; contract should hold ~0 beyond held surplus).
        uint256 balancePre = address(this).balance - received;

        (uint256 buyer1155Before, uint256 seller1155Before) =
            _snapshotHoldings(order.parameters.offerer, buyer, expectedCollection, expectedTokenId, is1155);
        Payee[] memory payees = _snapshotPayees(order.parameters.consideration, address(0));

        CriteriaResolver[] memory none = new CriteriaResolver[](0);
        // The hash of the order Seaport fills, taken right before the fill: the surplus push below can reach
        // code that bumps the offerer's Seaport counter, which would change a hash computed afterwards.
        bytes32 orderHash = _orderHash(order.parameters);
        // NFT (offer) delivered straight to `buyer` via the recipient param. If the order is gone/
        // unfulfillable this reverts (propagated) or returns false → we revert. Either way the whole
        // destination call fails, and the rail returns the buyer's funds on their SOURCE chain.
        bool ok = seaport.fulfillAdvancedOrder{value: price}(order, none, conduitKey, buyer);
        if (!ok) revert OrderUnfulfillable();

        _verifyDelivery(
            order.parameters.offerer, buyer, expectedCollection, expectedTokenId, is1155, offeredAmount,
            buyer1155Before, seller1155Before
        );
        _verifyPayees(payees, address(0));

        // Closeout L-13: the pre-existing balance must be untouched by the fill — Seaport's
        // consideration callbacks ran above, and nothing that happened there may have moved money
        // out of this contract (the guard on `rescueETH` makes this unreachable; asserting it keeps a
        // future refactor honest).
        if (address(this).balance < balancePre) revert BalanceInvariantBroken();

        // Success path only: forward any surplus (should be ~0 with exact-output routing) to the buyer.
        // Closeout L-13: a buyer that cannot receive the push keeps the completed purchase — the
        // surplus becomes a buyer-owned pull balance instead of reverting the fill.
        uint256 surplus = address(this).balance - balancePre;
        uint256 forwarded;
        if (surplus > 0) {
            (bool s, ) = payable(buyer).call{value: surplus}("");
            if (s) {
                forwarded = surplus;
            } else {
                surplusOwed[buyer] += surplus;
                totalSurplusOwed += surplus;
                emit SurplusHeld(buyer, surplus);
            }
        }
        if (address(this).balance != balancePre + (surplus - forwarded)) revert BalanceInvariantBroken();
        emit CrossChainPurchaseFilledV2(
            buyer,
            order.parameters.offerer,
            orderHash,
            expectedCollection,
            expectedTokenId,
            offeredAmount,
            order.parameters.zone,
            received,
            price,
            forwarded,
            surplus - forwarded
        );
    }

    /**
     * @notice D2: fill a seller's ERC-20-priced Seaport listing on behalf of a cross-chain buyer, or revert.
     * @param order              the seller's signed Seaport advanced order; `extraData` must carry the
     *                           zone-signed authorization naming `buyer` as recipient
     * @param paymentToken       the ERC-20 the listing is priced in; EVERY consideration item must be it
     * @param price              the amount pulled from the caller (the rail approves exactly this first)
     * @param buyer              recipient of the NFT AND of any surplus
     * @param expectedCollection the NFT contract the buyer paid to receive
     * @param expectedTokenId    the token id the buyer paid to receive
     *
     * Same bindings as `settlePurchaseNative` (vetted zone, restricted order type, signed recipient ==
     * `buyer`, concrete asset, M-16 verified delivery). Funds come ONLY from `msg.sender` — never from a
     * parameter and never from a balance this contract already held: exactly `price` is pulled (a
     * fee-on-transfer shortfall reverts), Seaport is approved for exactly `price` with no conduit (so
     * it can pull at most what this call brought in), the approval is cleared after the fill, and the
     * pre-call balance must survive. Any unspent part of `price` goes to the buyer, or is held for
     * `claimTokenSurplusTo` if the push fails or the buyer's balance does not rise by exactly that amount.
     * A push that drains this contract without crediting the buyer breaks the balance check and reverts the fill.
     */
    function settlePurchaseERC20(
        AdvancedOrder calldata order,
        address paymentToken,
        uint256 price,
        address buyer,
        address expectedCollection,
        uint256 expectedTokenId
    ) external nonReentrant {
        if (paymentToken == address(0)) revert ZeroAddress();
        if (paymentToken.code.length == 0) revert DependencyNotContract(paymentToken);
        if (price == 0) revert ZeroPrice();
        (bool is1155, uint256 offeredAmount) = _preflight(order, buyer, expectedCollection, expectedTokenId);
        _requireTokenConsideration(order.parameters.consideration, paymentToken);

        IERC20 token = IERC20(paymentToken);
        uint256 balancePre = token.balanceOf(address(this));
        token.safeTransferFrom(msg.sender, address(this), price);
        // UV-313 follow-up: saturating, so a token whose balance moves the wrong way reverts with the named error.
        uint256 balancePost = token.balanceOf(address(this));
        uint256 received = balancePost > balancePre ? balancePost - balancePre : 0;
        if (received != price) revert InsufficientDelivery(received, price);

        (uint256 buyer1155Before, uint256 seller1155Before) =
            _snapshotHoldings(order.parameters.offerer, buyer, expectedCollection, expectedTokenId, is1155);
        Payee[] memory payees = _snapshotPayees(order.parameters.consideration, paymentToken);

        // No conduit: Seaport pulls the fulfiller's ERC-20 itself, bounded by this exact allowance.
        token.safeApprove(address(seaport), price);
        CriteriaResolver[] memory none = new CriteriaResolver[](0);
        // Taken after the token calls above and right before the fill (see `settlePurchaseNative`).
        bytes32 orderHash = _orderHash(order.parameters);
        bool ok = seaport.fulfillAdvancedOrder(order, none, bytes32(0), buyer);
        if (!ok) revert OrderUnfulfillable();
        // Clear any unspent allowance so no later call can spend this contract's balance through it.
        if (token.allowance(address(this), address(seaport)) != 0) token.safeApprove(address(seaport), 0);

        _verifyDelivery(
            order.parameters.offerer, buyer, expectedCollection, expectedTokenId, is1155, offeredAmount,
            buyer1155Before, seller1155Before
        );
        _verifyPayees(payees, paymentToken);

        uint256 balanceAfter = token.balanceOf(address(this));
        if (balanceAfter < balancePre) revert BalanceInvariantBroken();
        uint256 surplus = balanceAfter - balancePre;
        uint256 forwarded;
        if (surplus > 0) {
            // A push only counts when the buyer's balance rose by exactly `surplus`. A token that reports
            // success without delivering leaves the surplus here, so it is held for the buyer's claim instead.
            uint256 buyerBefore = token.balanceOf(buyer);
            if (_tryTransferToken(paymentToken, buyer, surplus) && token.balanceOf(buyer) == buyerBefore + surplus) {
                forwarded = surplus;
            } else {
                tokenSurplusOwed[paymentToken][buyer] += surplus;
                totalTokenSurplusOwed[paymentToken] += surplus;
                emit TokenSurplusHeld(paymentToken, buyer, surplus);
            }
        }
        if (token.balanceOf(address(this)) != balancePre + (surplus - forwarded)) revert BalanceInvariantBroken();
        emit CrossChainPurchaseFilledERC20(
            buyer,
            order.parameters.offerer,
            orderHash,
            expectedCollection,
            expectedTokenId,
            offeredAmount,
            order.parameters.zone,
            paymentToken,
            price,
            forwarded,
            surplus - forwarded
        );
    }

    /// @notice D2: collect ERC-20 surplus that settlement could not push, to a caller-chosen address.
    function claimTokenSurplusTo(address token, address to) external nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 amount = tokenSurplusOwed[token][msg.sender];
        if (amount == 0) revert NothingToClaim();
        tokenSurplusOwed[token][msg.sender] = 0;
        totalTokenSurplusOwed[token] -= amount;
        // A token can report success while moving less (or nothing). Clearing the claim then would erase
        // the buyer's balance and release it to `rescueERC20`, so the recipient must receive exactly
        // `amount`; otherwise the whole call reverts and the claim and the rescue shield stay as they were.
        uint256 before = IERC20(token).balanceOf(to);
        IERC20(token).safeTransfer(to, amount);
        uint256 afterBal = IERC20(token).balanceOf(to);
        uint256 received = afterBal > before ? afterBal - before : 0;
        if (received != amount) revert SurplusNotReceived(amount, received);
        emit TokenSurplusClaimed(token, msg.sender, to, amount);
    }

    /// @notice D2: sweep ERC-20 that arrived outside a settle call. Never touches surplus held for buyers.
    function rescueERC20(address token, address to) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 balance = IERC20(token).balanceOf(address(this));
        uint256 held = totalTokenSurplusOwed[token];
        if (balance <= held) revert NothingToRescue();
        uint256 amount = balance - held;
        IERC20(token).safeTransfer(to, amount);
        // The sweep may never reach into buyers' held surplus, even for a token that moves more than asked.
        uint256 balanceAfter = IERC20(token).balanceOf(address(this));
        if (balanceAfter < held) revert RescueUnderfundsSurplus(balanceAfter, held);
        emit ERC20Rescued(token, to, amount);
    }

    /// @dev Checks shared by both settle paths, in the order the native path has always applied them.
    function _preflight(
        AdvancedOrder calldata order,
        address buyer,
        address expectedCollection,
        uint256 expectedTokenId
    ) private view returns (bool is1155, uint256 offeredAmount) {
        if (buyer == address(0) || expectedCollection == address(0)) revert ZeroAddress();
        if (buyer == address(this)) revert BuyerMustNotBeExecutor(); // Closeout I-15
        if (!allowedZones[order.parameters.zone]) revert ZoneNotAllowed(order.parameters.zone);
        // Re-checked on every settlement, before the recipient check below relies on the zone's signature check.
        if (!_zoneSignerReady(order.parameters.zone)) revert ZoneSignerNotConfigured(order.parameters.zone);
        // Seaport only calls the zone for RESTRICTED order types. For FULL_OPEN / PARTIAL_OPEN it
        // ignores `zone` entirely, and for CONTRACT the offerer itself is the source of truth — so
        // an allowlisted address sitting in the `zone` field proves nothing on its own, and every
        // fee, royalty and authorization rule the zone enforces would be silently skipped.
        OrderType orderType = order.parameters.orderType;
        if (orderType != OrderType.FULL_RESTRICTED && orderType != OrderType.PARTIAL_RESTRICTED) {
            revert ZoneNotEnforced(orderType);
        }
        // Closeout L-12: the authorization the zone will verify must name THIS buyer as the
        // recipient. Checked BEFORE Seaport so a substituted `buyer` never reaches the fill (and
        // never consumes the authorization's nonce). The zone signs `recipient` into its digest, so
        // editing the field here breaks the signature there.
        (bytes32 signedPolicyId, uint64 signedEpoch) = _requireAuthorizedRecipient(order.extraData, buyer);
        (is1155, offeredAmount) = _requireOfferedAsset(order, expectedCollection, expectedTokenId);
        // Admission before any buyer funds move: the registry must either admit the collection for the offered standard
        // under the pair the authorization signed, or allow the unverified lane when the authorization carries the
        // unverified marker (the zone checks the same in both of its hooks).
        if (signedPolicyId == UNVERIFIED_POLICY_ID) {
            if (signedEpoch != 0) revert CollectionPolicyMismatch(expectedCollection, UNVERIFIED_POLICY_ID, 0);
            (bool ok, bool blocked, bool laneOpen, , bytes32 policyId, uint64 epoch) =
                collectionRegistry.unverifiedStatus(expectedCollection, false);
            if (!ok) {
                if (epoch != 0) revert CollectionPolicyMismatch(expectedCollection, policyId, epoch);
                if (blocked) revert CollectionBlocked(expectedCollection);
                if (!laneOpen) revert UnverifiedLaneClosed();
                revert CollectionNotAdmitted(expectedCollection);
            }
        } else {
            (bool admitted_, bytes32 policyId, uint64 epoch) = collectionRegistry.admitted(
                expectedCollection, is1155 ? COLLECTION_STANDARD_ERC1155 : COLLECTION_STANDARD_ERC721
            );
            if (!admitted_) revert CollectionNotAdmitted(expectedCollection);
            if (policyId != signedPolicyId || epoch != signedEpoch) {
                revert CollectionPolicyMismatch(expectedCollection, policyId, epoch);
            }
        }
        // Every consideration amount must be fixed: Seaport pays the amount interpolated at the fill timestamp, and the
        // payee check after the fill compares against an exact amount owed (both routes, before any funds move). And no
        // item may pay this executor: the surplus forwarded to the buyer is this contract's balance growth, so a fee,
        // royalty, seller or tip leg paid here would go to the buyer.
        ConsiderationItem[] calldata items = order.parameters.consideration;
        for (uint256 i = 0; i < items.length; i++) {
            if (items[i].recipient == address(this)) revert PayeeIsExecutor();
            if (items[i].startAmount != items[i].endAmount) {
                revert TimeVaryingConsiderationUnsupported(items[i].startAmount, items[i].endAmount);
            }
        }
    }

    /// @dev Closeout M-16: snapshot holdings BEFORE the fill so a false-success collection (one that
    ///      no-ops the transfer yet returns true) cannot make us treat a phantom delivery as real,
    ///      suppress the source-chain refund, and pay the seller for nothing. "Exact SENDER and
    ///      recipient balance deltas" (verification 2026-09-08): a recipient-only delta is satisfied by a
    ///      collection that mints the buyer fresh units while the offerer keeps theirs.
    function _snapshotHoldings(address offerer, address buyer, address collection, uint256 tokenId, bool is1155)
        private
        view
        returns (uint256 buyer1155Before, uint256 seller1155Before)
    {
        if (!is1155) return (0, 0);
        buyer1155Before = IERC1155(collection).balanceOf(buyer, tokenId);
        if (offerer != buyer) seller1155Before = IERC1155(collection).balanceOf(offerer, tokenId);
    }

    /// @dev Closeout M-16: verify the POSTCONDITION, not the boolean. On any failure this reverts and
    ///      the rail refunds the buyer's source chain (fill-or-revert). A fully adversarial collection
    ///      can still lie through ownerOf/balanceOf — vetted immutable collections are the safe set.
    function _verifyDelivery(
        address offerer,
        address buyer,
        address collection,
        uint256 tokenId,
        bool is1155,
        uint256 offeredAmount,
        uint256 buyer1155Before,
        uint256 seller1155Before
    ) private view {
        if (is1155) {
            // UV-313 (review): saturating comparisons, so a collection that reports a LOWER balance after the fill
            // reverts with the named error instead of an arithmetic panic.
            uint256 buyerAfter = IERC1155(collection).balanceOf(buyer, tokenId);
            if (buyerAfter < buyer1155Before || buyerAfter - buyer1155Before != offeredAmount) revert DeliveryNotConfirmed();
            if (offerer != buyer) {
                uint256 sellerAfter = IERC1155(collection).balanceOf(offerer, tokenId);
                if (sellerAfter > seller1155Before || seller1155Before - sellerAfter != offeredAmount) {
                    revert DeliveryNotConfirmed();
                }
            }
        } else {
            if (IERC721(collection).ownerOf(tokenId) != buyer) revert DeliveryNotConfirmed();
        }
    }

    /// @dev One consideration recipient: what the order owes it in the settlement currency, and its balance before.
    struct Payee {
        address to;
        uint256 owed;
        uint256 before;
    }

    /// @dev Delivery alone does not show that Seaport paid the order's recipients: the price this contract funds must
    ///      reach them. Records, per distinct recipient of a settlement-currency item (`token`, or native when zero),
    ///      what the order owes it (the item's amount: `_preflight` admits only fixed amounts) and its balance before
    ///      the fill. Items in another currency are not counted: this contract never funds them.
    function _snapshotPayees(ConsiderationItem[] calldata items, address token) private view returns (Payee[] memory payees) {
        uint256 len = items.length;
        payees = new Payee[](len);
        uint256 n;
        for (uint256 i = 0; i < len; i++) {
            ConsiderationItem calldata it = items[i];
            if (token == address(0) ? it.itemType != ItemType.NATIVE : it.itemType != ItemType.ERC20 || it.token != token) {
                continue;
            }
            uint256 owed = it.startAmount;
            uint256 j;
            while (j < n && payees[j].to != it.recipient) j++;
            if (j == n) {
                payees[n] = Payee(it.recipient, 0, _balanceOf(token, it.recipient));
                n++;
            }
            payees[j].owed += owed;
        }
        assembly {
            mstore(payees, n)
        }
    }

    /// @dev After the fill: every recipient's balance rose by at least what the order owes it.
    function _verifyPayees(Payee[] memory payees, address token) private view {
        for (uint256 i = 0; i < payees.length; i++) {
            Payee memory p = payees[i];
            uint256 nowBal = _balanceOf(token, p.to);
            uint256 received = nowBal > p.before ? nowBal - p.before : 0;
            if (received < p.owed) revert PayeeNotPaid(p.to, p.owed, received);
        }
    }

    function _balanceOf(address token, address who) private view returns (uint256) {
        return token == address(0) ? who.balance : IERC20(token).balanceOf(who);
    }

    /// @dev D2: every consideration item must be the listing's ERC-20. A native item would need
    ///      `msg.value` this path never sends, and a second token would be paid from a balance this
    ///      call did not bring in — both are refused before any funds move.
    function _requireTokenConsideration(ConsiderationItem[] calldata items, address paymentToken) private pure {
        uint256 len = items.length;
        if (len == 0) revert PaymentTokenMismatch(address(0));
        for (uint256 i = 0; i < len; i++) {
            if (items[i].itemType != ItemType.ERC20 || items[i].token != paymentToken) {
                revert PaymentTokenMismatch(items[i].token);
            }
        }
    }

    /// @dev Surplus push that reports failure instead of reverting (blocklisting tokens, non-standard returns).
    function _tryTransferToken(address token, address to, uint256 amount) private returns (bool) {
        (bool ok, bytes memory ret) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, amount));
        // A malformed return must count as failure (and hold the surplus), never revert the purchase.
        return ok && (ret.length == 0 || (ret.length == 32 && uint256(bytes32(ret)) == 1));
    }

    /// @notice Closeout L-13: collect surplus that settlement could not push, to a caller-chosen
    ///         address (the buyer's own address is the one that could not receive).
    function claimSurplusTo(address payable to) external nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 amount = surplusOwed[msg.sender];
        if (amount == 0) revert NothingToClaim();
        surplusOwed[msg.sender] = 0;
        totalSurplusOwed -= amount;
        (bool ok, ) = to.call{value: amount}("");
        if (!ok) revert SurplusForwardFailed();
        emit SurplusClaimed(msg.sender, to, amount);
    }

    /// @dev Closeout L-12: decode the SAME bytes the zone verifies and require the signed recipient
    ///      to be `buyer`. An order without an authorization cannot bind a buyer at all, so it is
    ///      refused here (a live zone would refuse it anyway, MP-EVM-07).
    /// @dev Closeout I-10: the Seaport order hash of the filled order — the preimage is the order's
    ///      parameters with the consideration truncated to `totalOriginalConsiderationItems` (tips are
    ///      not part of the identity) plus the offerer's counter, exactly as Seaport derives it.
    function _orderHash(OrderParameters calldata p) private view returns (bytes32) {
        uint256 n = p.totalOriginalConsiderationItems;
        if (n > p.consideration.length) n = p.consideration.length;
        ConsiderationItem[] memory consideration = new ConsiderationItem[](n);
        for (uint256 i = 0; i < n; i++) consideration[i] = p.consideration[i];
        OrderComponents memory c = OrderComponents({
            offerer: p.offerer,
            zone: p.zone,
            offer: p.offer,
            consideration: consideration,
            orderType: p.orderType,
            startTime: p.startTime,
            endTime: p.endTime,
            zoneHash: p.zoneHash,
            salt: p.salt,
            conduitKey: p.conduitKey,
            counter: seaport.getCounter(p.offerer)
        });
        return seaport.getOrderHash(c);
    }

    /// @dev True only when `zone.zoneSignerConfigured()` succeeds within a bounded gas stipend and returns exactly the
    ///      ABI word `true`. Anything else (revert, short or long return data, `false`, a dirty word) is not ready.
    /// @dev The zone's `feeRecipient()`, or zero when it gives no one-word answer (then only `_preflight` guards).
    function _zoneFeeRecipient(address zone) private view returns (address recipient) {
        bool ok;
        uint256 size;
        uint256 word;
        bytes4 sel = 0x46904840; // feeRecipient()
        assembly {
            mstore(0x00, sel)
            ok := staticcall(30000, zone, 0x00, 0x04, 0x00, 0x20)
            size := returndatasize()
            word := mload(0x00)
        }
        if (ok && size == 32 && word <= type(uint160).max) recipient = address(uint160(word));
    }

    function _zoneSignerReady(address zone) private view returns (bool ready) {
        bool ok;
        uint256 size;
        uint256 word;
        bytes4 sel = 0x4a4d830b; // zoneSignerConfigured()
        assembly {
            mstore(0x00, sel)
            ok := staticcall(30000, zone, 0x00, 0x04, 0x00, 0x20)
            size := returndatasize()
            word := mload(0x00)
        }
        ready = ok && size == 32 && word == 1;
    }

    function _requireAuthorizedRecipient(bytes calldata extraData, address buyer)
        private
        pure
        returns (bytes32 policyId, uint64 policyEpoch)
    {
        if (extraData.length == 0) revert MissingAuthorization();
        SignedAuthorization memory auth = abi.decode(extraData, (SignedAuthorization));
        if (auth.recipient != buyer) revert RecipientMismatch(auth.recipient, buyer);
        return (auth.policyId, auth.policyEpoch);
    }

    /// @dev Require the order's FIRST offered NFT item to be exactly the asset the buyer paid for.
    ///      Criteria items are rejected on purpose: they resolve to a merkle root rather than a token
    ///      id, so they cannot bind a cross-chain payment to a specific asset.
    function _requireOfferedAsset(
        AdvancedOrder calldata order,
        address expectedCollection,
        uint256 expectedTokenId
    ) private pure returns (bool is1155, uint256 amount) {
        OfferItem[] calldata offer = order.parameters.offer;
        uint256 len = offer.length;
        for (uint256 i = 0; i < len; ) {
            ItemType t = offer[i].itemType;
            if (t == ItemType.ERC721 || t == ItemType.ERC1155) {
                if (offer[i].token != expectedCollection || offer[i].identifierOrCriteria != expectedTokenId) {
                    revert UnexpectedAsset(offer[i].token, offer[i].identifierOrCriteria);
                }
                // Closeout M-16: return the standard + amount so the caller can verify DELIVERY, not
                // just Seaport's boolean. An ERC-1155 quantity must be fixed: Seaport moves the amount
                // interpolated between start and end at fill time, so a time-varying one is refused here,
                // before any funds move (ERC-721 is always one token).
                if (t == ItemType.ERC1155 && offer[i].startAmount != offer[i].endAmount) {
                    revert TimeVaryingOfferUnsupported(offer[i].startAmount, offer[i].endAmount);
                }
                return (t == ItemType.ERC1155, offer[i].startAmount);
            }
            if (t == ItemType.ERC721_WITH_CRITERIA || t == ItemType.ERC1155_WITH_CRITERIA) {
                revert UnexpectedAsset(offer[i].token, offer[i].identifierOrCriteria);
            }
            unchecked {
                ++i;
            }
        }
        revert NoOfferedNft();
    }

    // Accept native from the rail / Seaport excess returns.
    receive() external payable {}
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/access/Ownable2Step.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() external {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts/token/ERC1155/IERC1155.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
        external
        view
        returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount
    ) external returns (bool);
}

@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 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.
 */
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 apply 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].
     */
    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);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), 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 data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

@openzeppelin/contracts/token/ERC721/IERC721.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

@openzeppelin/contracts/utils/Address.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

ethereum/ZoneAuthorizationTypes.sol

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

/// @notice UV-311: one royalty payment the zone signer attests for THIS fill (absolute amount, in the fill's payment token).
struct RoyaltyPayout {
    address receiver;
    uint256 amount;
}

/// @notice The fill authorization `UnVaultSignedZone` requires in `extraData` (MP-EVM-07), shared with
///         `CrossChainPurchaseExecutor` so the executor can decode the SAME bytes the zone verifies.
/// @dev Closeout L-12: `recipient` binds the account that actually RECEIVES the asset. For a direct
///      fill it equals `fulfiller` (the fulfiller receives). On the cross-chain rail the fulfiller is
///      always the shared executor, so without this field an authorization issued for buyer A was
///      valid for anyone who called the public executor with buyer B — a mempool copy of the order +
///      `extraData` won the single permitted use and took delivery. The zone signs it into the digest;
///      the executor requires it to equal its `buyer` argument before calling Seaport.
/// @dev UV-311 (EIP-712 domain version "2"):
///      - `transferOperator`: the account that will call `transferFrom` on the NFT in this fill (Seaport itself for the
///        zero conduit key, else the conduit). The zone hands it to a Limit Break transfer validator's authorizer hook
///        (`beforeAuthorizedTransfer`) when the collection's validator is on the zone's `authorizerValidators` list.
///        `address(0)` = no authorizer hook for this fill.
///      - `royaltyPayouts`: the signer's royalty payouts for this fill. Used ONLY when the collection has no on-chain
///        royalty source (`SOURCE_NONE` / `SOURCE_UNKNOWN`); then every listed receiver must be paid at least its amount.
///        An empty list on a `SOURCE_NONE` collection attests "no royalty due"; on `SOURCE_UNKNOWN` it is refused.
/// @dev Version "3" adds the token-bound account binding:
///      - `bugAccount`: the ERC-6551 account the sold token owns (a Bug's recorded account), or `address(0)` for a token
///        with none. Which account belongs to the token is attested by the signer, like the royalty payouts.
///      - `bugAccountState`: that account's `state()` when the signer signed. The zone requires the live `state()` to
///        equal it in both phases, so a seller who uses the account after signing (and so bumps its state) cannot
///        sell it emptied. Exception: an operator approval the account granted earlier moves its assets without bumping
///        the state. Ignored when `bugAccount` is zero.
/// @dev Version "4" adds the collection policy binding:
///      - `policyId`, `policyEpoch`: the collection's current pair in the `CollectionRegistry`
///        (`admitted(collection, standard)`) when the signer signed. The zone requires the registry to admit the
///        collection for the order's standard and the live pair to equal the signed one, in `authorizeOrder` and again
///        in `validateOrder`; the cross-chain executor requires the same before it sends buyer funds into Seaport. An
///        authorization signed under an older policy epoch, or for a collection since paused, removed or changed in
///        code, fails everywhere.
///      `extraData` = `abi.encode(SignedAuthorization)`.
struct SignedAuthorization {
    address nftContract;
    address paymentToken;
    uint256 grossSaleAmount;
    uint256 tokenId;
    address fulfiller;
    address recipient;
    uint256 expiration;
    uint256 nonce;
    address transferOperator;
    address bugAccount;
    uint256 bugAccountState;
    bytes32 policyId;
    uint64 policyEpoch;
    RoyaltyPayout[] royaltyPayouts;
    bytes signature;
}

ethereum/crosschain/ISeaportConsumer.sol

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

// Minimal Seaport consumer-side interface + order structs (Seaport 1.6 ABI), kept local so the
// cross-chain executor can call `fulfillAdvancedOrder` without importing the full Seaport package.
// The marketplace's own `SeaportZoneInterface.sol` only covers the ZONE side (Seaport → zone);
// this is the FULFILLER side (executor → Seaport).

enum ItemType {
    NATIVE,
    ERC20,
    ERC721,
    ERC1155,
    ERC721_WITH_CRITERIA,
    ERC1155_WITH_CRITERIA
}

enum OrderType {
    FULL_OPEN,
    PARTIAL_OPEN,
    FULL_RESTRICTED,
    PARTIAL_RESTRICTED,
    CONTRACT
}

enum Side {
    OFFER,
    CONSIDERATION
}

struct OfferItem {
    ItemType itemType;
    address token;
    uint256 identifierOrCriteria;
    uint256 startAmount;
    uint256 endAmount;
}

struct ConsiderationItem {
    ItemType itemType;
    address token;
    uint256 identifierOrCriteria;
    uint256 startAmount;
    uint256 endAmount;
    address payable recipient;
}

struct OrderParameters {
    address offerer;
    address zone;
    OfferItem[] offer;
    ConsiderationItem[] consideration;
    OrderType orderType;
    uint256 startTime;
    uint256 endTime;
    bytes32 zoneHash;
    uint256 salt;
    bytes32 conduitKey;
    uint256 totalOriginalConsiderationItems;
}

/// @dev Closeout I-10: the hash preimage Seaport's `getOrderHash` takes (Seaport 1.6 ABI) —
///      `OrderParameters` minus `totalOriginalConsiderationItems`, plus the offerer's counter.
struct OrderComponents {
    address offerer;
    address zone;
    OfferItem[] offer;
    ConsiderationItem[] consideration;
    OrderType orderType;
    uint256 startTime;
    uint256 endTime;
    bytes32 zoneHash;
    uint256 salt;
    bytes32 conduitKey;
    uint256 counter;
}

struct AdvancedOrder {
    OrderParameters parameters;
    uint120 numerator;
    uint120 denominator;
    bytes signature;
    bytes extraData;
}

struct CriteriaResolver {
    uint256 orderIndex;
    Side side;
    uint256 index;
    uint256 identifier;
    bytes32[] criteriaProof;
}

interface ISeaportConsumer {
    /// Closeout L-24 (verification 2026-09-08): Seaport exposes no ERC-165 interface id, so identity is
    /// proven by a project-specific static-call READ-BACK - `name()` must be "Seaport" and
    /// `information()` must return this chain's non-zero domain separator.
    function name() external view returns (string memory);
    function information() external view returns (string memory version, bytes32 domainSeparator, address conduitController);
    /// @dev `recipient` is where the offer (the NFT) is delivered — lets the executor route the NFT
    ///      straight to the cross-chain buyer. Closeout I-20: canonical Seaport 1.6 is TRUE-OR-REVERT —
    ///      every successful path returns the literal `true` and every other path reverts (invalid
    ///      orders revert rather than resolving to a zero fill). The executor's `!fulfilled` branch is
    ///      kept as defense in depth for a non-canonical runtime behind this interface.
    function fulfillAdvancedOrder(
        AdvancedOrder calldata advancedOrder,
        CriteriaResolver[] calldata criteriaResolvers,
        bytes32 fulfillerConduitKey,
        address recipient
    ) external payable returns (bool fulfilled);

    /// @dev Closeout I-10: the canonical order identity, so the settlement event can name the exact
    ///      Seaport order it filled.
    function getOrderHash(OrderComponents calldata order) external view returns (bytes32 orderHash);

    function getCounter(address offerer) external view returns (uint256 counter);
}

ethereum/interfaces/ICollectionRegistry.sol

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

/// @dev Asset standards. 0 is never admitted.
uint8 constant COLLECTION_STANDARD_ERC721 = 1;
uint8 constant COLLECTION_STANDARD_ERC1155 = 2;

/// @dev Settlement adapter ids. The launch rail is the plain Seaport transfer path; other ids are reserved.
uint8 constant COLLECTION_ADAPTER_SEAPORT = 1;

/// @dev Admission routes, as recorded on each record (`CollectionRecord.route`).
uint8 constant COLLECTION_ROUTE_NONE = 0;
uint8 constant COLLECTION_ROUTE_FACTORY = 1;
uint8 constant COLLECTION_ROUTE_APPROVER = 2;
uint8 constant COLLECTION_ROUTE_OWNER = 3;

/// @dev Reserved `policyId` signed in a zone authorization (with `policyEpoch = 0`) for an unrecorded collection
///      trading on the unverified lane (listings and concrete item offers).
bytes32 constant UNVERIFIED_POLICY_ID = keccak256("unvault.collection.unverified.v1");

/// @dev Reserved `policyId` signed in a zone authorization (with `policyEpoch = 0`) for a criteria-based offer on an
///      unrecorded collection trading on the unverified lane.
bytes32 constant UNVERIFIED_CRITERIA_POLICY_ID = keccak256("unvault.collection.unverified.criteria.v1");

/// @title Collection admission registry (consumer interface)
/// @notice The on-chain admission boundary for every UnVault settlement rail. A rail asks `admitted` before any
///         funds move and refuses a collection it does not admit. Exit paths (cancel, claim, reclaim, withdraw,
///         refund) never consult it.
/// @dev Consumers check at construction: `code.length > 0` and
///      `IERC165(registry).supportsInterface(type(ICollectionRegistry).interfaceId)`.
interface ICollectionRegistry {
    enum Status {
        None,
        Pending,
        Admitted,
        Paused,
        Removed
    }

    struct CollectionRecord {
        uint8 standard; // COLLECTION_STANDARD_*
        uint8 adapter; // COLLECTION_ADAPTER_*
        Status status;
        uint64 policyEpoch; // per collection; increases on every record change, never resets
        uint64 effectiveAt; // Pending: when it may be applied; Admitted: when it was admitted
        address factory; // the trusted factory that registered it, or zero (source = the pinned codehash)
        address implementation; // attested implementation for an upgradeable collection, or zero (immutable)
        address upgradeAuthority; // attested contract upgrade authority for an upgradeable collection, or zero (immutable)
        bytes32 codehash; // EXTCODEHASH pinned at admission
        bytes32 policyId; // keccak256(abi.encode(collection, standard, adapter, factory, implementation, upgradeAuthority, codehash))
        // How and when the current code was admitted. Set when a code is pinned (factory registration, proposal, resume
        // with changed code); a resume with unchanged code keeps both. `admittedAt` is 0 until the first admission of
        // the pinned code. Not part of the policy id.
        uint8 route; // COLLECTION_ROUTE_*
        uint64 admittedAt; // block timestamp of that admission
    }

    event UpgradeableCollectionAttested(
        address indexed collection,
        address indexed implementation,
        address indexed upgradeAuthority,
        uint64 policyEpoch
    );

    event CollectionProposed(
        address indexed collection,
        address indexed proposer,
        uint8 standard,
        uint8 adapter,
        bytes32 codehash,
        uint64 effectiveAt,
        uint64 policyEpoch
    );
    event CollectionAdmitted(
        address indexed collection,
        address indexed factory,
        uint8 standard,
        uint8 adapter,
        bytes32 codehash,
        bytes32 policyId,
        uint64 policyEpoch
    );
    event CollectionVetoed(address indexed collection, uint64 policyEpoch);
    event CollectionPaused(address indexed collection, address indexed by, uint64 policyEpoch);
    event CollectionResumed(address indexed collection, uint64 effectiveAt, uint64 policyEpoch);
    event CollectionRemoved(address indexed collection, uint64 policyEpoch);
    /// @notice Emitted on every record change, after the specific event. Signers drop cached pairs on it.
    event PolicyEpochAdvanced(address indexed collection, uint64 policyEpoch, Status status);
    event FactoryTrusted(address indexed factory);
    event FactoryUntrusted(address indexed factory);
    event CollectionBlocked(address indexed collection, address indexed by);
    event CollectionUnblocked(address indexed collection);
    event UnverifiedLaneClosed(address indexed by);
    event UnverifiedLaneOpened(address indexed by);
    event UnverifiedCollectionOffersUpdated(bool open);

    /// @notice Whether `collection` is admitted for `standard` right now, with its current policy pair.
    /// @dev Never reverts. `ok` is true only when the status is Admitted, `effectiveAt <= block.timestamp`,
    ///      `standard` matches the record, the live EXTCODEHASH equals the pinned one, and the collection does not
    ///      answer the other standard's ERC-165 interface. On `ok == false` the pair is still the current one
    ///      (zero for an unknown collection).
    function admitted(address collection, uint8 standard)
        external
        view
        returns (bool ok, bytes32 policyId, uint64 policyEpoch);

    /// @notice Whether `collection` may trade on the unverified lane right now (and with a criteria-based offer when
    ///         `criteriaOffer` is true).
    /// @dev Never reverts. `ok` is true only when `collection` has contract code, has never been recorded
    ///      (`currentEpoch == 0`), is not blocked (`!blocked`), `laneOpen` is true, and either `!criteriaOffer` or
    ///      `criteriaOffersOpen` is true.
    function unverifiedStatus(address collection, bool criteriaOffer)
        external
        view
        returns (
            bool ok,
            bool blocked,
            bool laneOpen,
            bool criteriaOffersOpen,
            bytes32 currentPolicyId,
            uint64 currentEpoch
        );

    function policyEpoch(address collection) external view returns (uint64);

    function record(address collection) external view returns (CollectionRecord memory);
}

/// @title Factory hook of the collection registry
/// @notice A factory the registry trusts registers each collection it deploys, in the deploy transaction, after the
///         collection's code is in place. The collection is admitted at once with the factory as its source and its
///         live codehash pinned. Requirement on every trusted factory: call this only for an address it has just
///         created with CREATE or CREATE2 in the same call, never as a pass-through for an address supplied by a caller.
interface ICollectionRegistrar {
    function registerFromFactory(address collection, uint8 standard)
        external
        returns (bytes32 policyId, uint64 policyEpoch);
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.