Skip to content
Verified contractExactMIT

UnVaultSignedZone

Address0xdd9ec652a91e58370bff8ce7c8335d0e2785bd1c
Balance

0 ETH

 

Transactions

7

 

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,436
Creation transaction
0xf1c9d27e22…6610a493af

ethereum/UnVaultSignedZone.sol

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

import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./UnVaultRoyaltyRegistry.sol";
import {IMarketplaceFeePolicy} from "./MarketplaceFeePolicy.sol";
import "./interfaces/SeaportZoneInterface.sol";
import {SignedAuthorization, RoyaltyPayout} from "./ZoneAuthorizationTypes.sol";
import {UnVaultSplitterReads} from "./UnVaultSplitterReads.sol";
import {
    ICollectionRegistry,
    COLLECTION_STANDARD_ERC721,
    COLLECTION_STANDARD_ERC1155,
    UNVERIFIED_POLICY_ID,
    UNVERIFIED_CRITERIA_POLICY_ID
} from "./interfaces/ICollectionRegistry.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/// @title UnVaultSignedZone
/// @notice Seaport zone that enforces UnVault marketplace fee + royalty policy
///         on restricted orders.
/// @dev The order builder must include fee and royalty consideration items.
///      This zone performs defense-in-depth checks at fulfillment.
contract UnVaultSignedZone is Ownable2Step, Pausable, ZoneInterface {
    using ECDSA for bytes32;

    uint256 public constant BPS_DENOMINATOR = 10_000;
    /// @notice Upper bound on the protocol fee: 100%. Founder decision 2026-09-14 (configurability
    ///         round) removed the former 10% ceiling; what stays is `fee + royalty <= price` per sale,
    ///         which `_checkPayouts` enforces with `FeeAndRoyaltyExceedPrice` (a Seaport order escrows
    ///         nothing, so refusing it strands no asset).
    uint256 public constant MAX_FEE_BPS = 10_000;
    /// @notice Mirrored from `UnVaultRoyaltyRegistry.MAX_ROYALTY_BPS` (100% since 2026-09-14); read back
    ///         at construction (Closeout L-24) so a registry of a different generation cannot be wired in.
    uint256 public constant MAX_ROYALTY_BPS = 10_000;

    // ── MP-EVM-07: signed, expiring fill authorization ──────────────────────────────────────────
    //
    // The zone is named for this and never had it on our branch: `extraData` was ignored, empty
    // `extraData` was accepted, and any party could fill any order that merely paid the right fee and
    // royalty. Nothing bound WHO could fill, nothing expired, and no off-chain policy could be applied
    // at fill time. (The authorization existed in the June remediation; our line forked six days
    // before it landed and the rewrite of this file meant a merge could not bring it back.)
    //
    // DIFFERENCE FROM THE JUNE VERSION, deliberately: that one took the sale economics FROM the
    // signature (`auth.grossSaleAmount` etc.) and priced the fee and royalty off them. This one keeps
    // `_deriveOrderContext` as the source of truth — read from the order itself on-chain — and uses
    // the signature only to AUTHENTICATE. The signed values must then MATCH what the order actually
    // contains, so a signature can never authorize a sale different from the one executing, and a
    // signer bug or key compromise cannot mis-price a fill.
    bytes32 private constant EIP712_DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    // Version "2" added `transferOperator` and the signer's `royaltyPayouts` (EIP-712 nested struct array); version "3"
    // adds the token-bound account binding (`bugAccount`, `bugAccountState`); version "4" the collection policy binding
    // (`policyId`, `policyEpoch`, read from the `CollectionRegistry`).
    string private constant AUTHORIZATION_TYPE =
        "ZoneAuthorization(bytes32 orderHash,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)RoyaltyPayout(address receiver,uint256 amount)";
    bytes32 private constant AUTHORIZATION_TYPEHASH = keccak256(bytes(AUTHORIZATION_TYPE));
    bytes32 private constant ROYALTY_PAYOUT_TYPEHASH = keccak256("RoyaltyPayout(address receiver,uint256 amount)");
    bytes32 private constant NAME_HASH = keccak256("UnVaultSignedZone");
    bytes32 private constant VERSION_HASH = keccak256("4");
    /// @notice UV-311: the `extraData` layout, published in `getSeaportMetadata` (schema `EXTRA_DATA_SCHEMA_ID`).
    string public constant EXTRA_DATA_LAYOUT =
        "abi.encode((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,(address receiver,uint256 amount)[] royaltyPayouts,bytes signature))";
    uint256 public constant EXTRA_DATA_SCHEMA_ID = uint256(keccak256("UnVaultSignedZone.extraData.v4"));
    /// @dev G-14: the EIP-712 domain is invariant for the deployment chain — cache it, recompute only
    ///      after a fork (chain id change).
    uint256 private immutable _CACHED_CHAIN_ID;
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;

    /// @notice The backend key authorised to sign fills. Zero disables enforcement — see the
    ///         constructor note; a deployment MUST set this before it is considered live.
    address public zoneSigner;

    /// @notice Consumed authorization nonces, per signer-issued value. Replay-resistance beyond the
    ///         order hash and expiry: an authorization is single-use even within its validity window.
    mapping(uint256 => bool) public usedAuthorizationNonces;

    // Closeout L-12: `SignedAuthorization` now lives in `ZoneAuthorizationTypes.sol` (shared with the
    // cross-chain executor) and carries `recipient`, which this zone binds into the digest. Generic
    // `ZoneParameters` cannot expose the fulfiller-selected recipient, so the zone cannot check it
    // against the fill; the executor enforces `recipient == buyer`, and for a direct fill the
    // backend issues `recipient == fulfiller`.

    event ZoneSignerUpdated(address oldSigner, address newSigner);

    address public immutable seaport;
    UnVaultRoyaltyRegistry public immutable royaltyRegistry;

    /// @notice Closeout M-10: the shared fee-policy registry. The default fee, the
    ///         per-collection tier override, and the fee recipient all live here so
    ///         EVERY settlement rail (this zone and UnVaultAuction) reads one
    ///         canonical value for a collection and an owner update is atomic
    ///         across modules — a collection can no longer be charged a different
    ///         protocol fee depending on which primitive settles the sale.
    IMarketplaceFeePolicy public immutable feePolicy;

    /// @notice The collection admission boundary. Every fill needs the registry to admit the order's collection for its
    ///         standard, with the policy pair the authorization signed (both hooks). Immutable: replacing the registry
    ///         means a new zone; changing admission data never does.
    ICollectionRegistry public immutable collectionRegistry;

    mapping(bytes32 => bool) public cancelledOrderHashes;

    /// @dev Closeout M-09: cumulative gross settled per order hash, so a PARTIALLY fillable order's
    ///      fee and royalty obligations are computed as CUMULATIVE deltas and cannot be rounded to
    ///      zero by slicing the order into tiny fills (or by a coarse-denomination payment token).
    ///      Seaport calls the zone exactly once per fill and only Seaport may call it, so this is a
    ///      faithful running total. A full (non-partial) fill starts from 0 and behaves as before.
    mapping(bytes32 => uint256) public filledGross;

    event OrderHashesCancelled(bytes32[] orderHashes);

    // ── UV-311: royalty sources (mirrors UnVaultRoyaltyRegistry.SOURCE_*, read back at construction) ──
    uint8 private constant SOURCE_NONE = 0;
    uint8 private constant SOURCE_SPLITTER = 1;
    uint8 private constant SOURCE_UNKNOWN = 5;

    // ── UV-311 (review H-3): on-chain payment-token allowlist, written by the owner (the Safe) ──
    /// @notice The default currencies (`address(0)` = the native coin). EMPTY = every currency refused (fail-closed).
    mapping(address => bool) public defaultPaymentTokens;
    /// @notice A collection with its own list uses ONLY that list instead of the default one.
    mapping(address => bool) public collectionUsesOwnPaymentTokens;
    mapping(address => mapping(address => bool)) public collectionPaymentTokens;
    event DefaultPaymentTokenSet(address indexed token, bool allowed);
    event CollectionPaymentTokenSet(address indexed collection, address indexed token, bool allowed);
    event CollectionUsesOwnPaymentTokensSet(address indexed collection, bool usesOwn);

    // ── UV-311: Limit Break authorizer hooks, only for validators the owner (the Safe) lists ──
    /// @notice Transfer validators the zone calls `before/afterAuthorizedTransfer` on. EMPTY at deploy: no hook runs
    ///         until the owner lists a validator that supports authorizers AND has the zone on its authorizer list.
    mapping(address => bool) public authorizerValidators;
    event AuthorizerValidatorSet(address indexed validator, bool enabled);

    /// @notice The only ERC-20 a bid may pay in: the chain's wrapped native coin (immutable WETH9-style), set by the
    ///         owner. Zero until set, and then every ERC-20 bid is refused. A bid's seller is paid through the
    ///         fulfiller's own `recipient`, which Seaport does not pass the zone, so the zone cannot check the seller's
    ///         receipt; bids are therefore limited to a token that cannot report a transfer it did not make.
    address public wrappedNative;
    event WrappedNativeSet(address indexed token);

    /// @notice Emitted on a settled sale so the off-chain Divit funding indexer can credit the
    ///         collection's pool from the royalty actually paid. Observability only — does NOT
    ///         change settlement/fund flow. `paymentToken` is address(0) for native.
    /// @dev Closeout I-10. `royaltyQuoted` is the obligation this fill had to cover: the sum over the
    ///      receivers of each one's floored amount (its cumulative delta for a partial fill), not the
    ///      registry's `totalAmount`, which floors the combined rate once and can be up to (receivers - 1)
    ///      base units larger. `royaltyPaid` is what the receivers were paid by this fill (fee leg excluded),
    ///      counted at most up to each receiver's obligation, so it equals `royaltyQuoted` on every settled
    ///      fill: a payer that sends a receiver more (an extra consideration item or a tip) still reports that sum.
    event DivitSaleFundedV2(address indexed collection, uint256 royaltyQuoted, uint256 royaltyPaid, address paymentToken);
    /// @notice Emitted on `validateOrder` when a fill settles on the unverified lane (`UNVERIFIED_POLICY_ID` or
    ///         `UNVERIFIED_CRITERIA_POLICY_ID`), for the indexer and the site.
    event UnverifiedOrderFilled(
        bytes32 indexed orderHash,
        address indexed collection,
        uint256 tokenId,
        bytes32 policyId
    );

    error OnlySeaport();
    error InvalidSeaport();
    error InvalidRecipient();
    error InvalidFeeBps();
    error MissingNftItem();
    error MissingPaymentItem();
    error CancelledOrder();
    error InvalidPlatformFeePayout();
    error InvalidRoyaltyPayout(address receiver, uint256 requiredAmount, uint256 paidAmount);
    /// @notice The payment side of the order carries more than one fungible currency, so there is no
    ///         single unambiguous sale price to charge the fee and royalty against.
    error MixedPaymentTokens();
    /// @notice The asset side of the order bundles NFTs from more than one collection, so a single
    ///         fee tier / royalty split cannot correctly price the order.
    error MultipleNftContracts();
    /// @notice The asset side of the order bundles more than one NFT. Royalty rates are PER TOKEN
    ///         (`quoteRoyaltyForToken`), but a Seaport bundle carries ONE aggregate consideration and
    ///         no per-item price — so there is no honest way to split the sale across the bundled
    ///         tokens, and any split the zone invented would be unverifiable against the order.
    ///         Bundles are a Phase-2 feature and must be designed with per-item pricing.
    error MultipleNftItems();
    /// @notice The order carries NFTs on BOTH sides — a barter. The zone prices a sale from its
    ///         fungible payment side and has no way to value an NFT, so a barter cannot be charged a
    ///         correct fee or royalty and is refused rather than settled at the value of whatever
    ///         token dust accompanied it.
    error NftOnBothSides();
    /// @notice The protocol fee plus the creator royalty owed on this order exceed its sale price
    ///         (possible since fees and royalties became configurable 0–100%, founder decision
    ///         2026-09-14). Refused by name before any payout is checked.
    error FeeAndRoyaltyExceedPrice();
    /// @notice MP-EVM-07 — fill authorization failures.
    error MissingAuthorization();
    error ZoneSignerCannotBeCleared(); // §7b: one-way — provisioned signer may rotate, never clear
    error ExpiredAuthorization();
    error FulfillerMismatch();
    error AuthorizationAlreadyUsed();
    error AuthorizationMismatch();
    error InvalidAuthorization();
    /// @notice UV-311: the order's currency is not on the collection's (or the default) allowlist.
    error PaymentTokenNotAllowed(address paymentToken);
    /// @notice UV-311: no on-chain royalty source (`source` = NONE or UNKNOWN) and no signer payouts that can stand in.
    error NoRoyaltySource(address collection, uint8 source);
    /// @notice UV-311 (review L-1): a listing whose offer side carries a fungible item next to the NFT.
    error FungibleOnAssetSide();
    /// @notice UV-311: a listed authorizer validator refused to clear its authorization, or ran out of the caller's gas.
    error AuthorizerHookFailed(address validator);
    error AuthorizerHookStarved();
    /// @notice UV-311 (andskur #426 finding 1a): a fill that opens a Limit Break authorization must be the only order in
    ///         the Seaport call. The validator's transient authorization covers the token AND the collection until the
    ///         after-hook, and Seaport runs every transfer of a batch between the authorize and validate phases.
    error AuthorizerBatchNotAllowed();
    /// @notice An ERC-20 payee's balance did not rise by what the fill's consideration promised it (a token that reports
    ///         a transfer without moving the balance, a fee-on-transfer token, or a payee that also paid out the same
    ///         token in the same Seaport call).
    error PaymentNotReceived(address payee, uint256 expected, uint256 received);
    /// @notice The payee's balance gave no readable answer, or `validateOrder` ran without the `authorizeOrder` snapshot.
    error PaymentReceiptUnreadable(address payee);
    /// @notice An ERC-20 bid in a token other than `wrappedNative`.
    error BidTokenNotWrappedNative(address paymentToken);
    /// @notice No zone signer is provisioned yet: every fill is refused until one is (there is no unsigned mode).
    error SignerNotConfigured();
    /// @notice The NFT did not reach `holder`, the account the fill delivers to (`ownerOf` is not it, or its ERC-1155
    ///         balance did not rise by the lot); or, when the fill was authorized, `holder` already owned the ERC-721 or the
    ///         listing's offerer did not.
    error NftNotDelivered(address holder);
    /// @notice An `ownerOf` / `balanceOf` read gave no 32-byte answer, or `validateOrder` ran without the snapshot.
    error DeliveryUnreadable();
    /// @notice A second fill of the same ERC-721 was authorized in one Seaport call. One observed transfer must not
    ///         satisfy two orders (two bids on one token, and a collection that no-ops the second transfer).
    error TokenAlreadyAuthorizedInCall(address collection, uint256 tokenId);
    /// @notice An ERC-1155 listing's offerer did not part with its lot: its balance of the id did not fall by at least
    ///         the lots of the call's authorized listings it offers.
    error NftNotSent(address from);
    /// @notice The same ERC-1155 order was authorized twice in one Seaport call; its lot is counted once.
    error OrderAlreadyAuthorizedInCall(bytes32 orderHash);
    /// @notice UV-311 (andskur #426 finding 1b): after an authorized transfer the NFT is not with the account the fill
    ///         delivers to (the signed recipient of a listing, the NFT consideration recipient of a bid).
    error AuthorizedTransferNotDelivered(address expectedHolder);
    /// @notice UV-311 (andskur #426 finding 2): `extraData` is not the version-2 `SignedAuthorization` layout.
    error UnsupportedAuthorizationVersion();
    /// @notice The collection registry does not admit the order's collection for its standard right now (unknown,
    ///         pending, paused, removed, a changed codehash, or the other standard).
    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();
    /// @notice A criteria-based offer on an unverified collection while the unverified collection-offer switch is off.
    error UnverifiedCriteriaOfferDisabled(address collection);
    /// @dev The token's account was used after the authorization was signed (its `state()` moved on).
    error BugAccountStateChanged(address account, uint256 signedState, uint256 liveState);
    /// @dev The token's account gave no 32-byte `state()` answer within 30,000 gas.
    error BugAccountStateUnreadable(address account);
    error InvalidOwner();
    /// @notice Closeout L-24: an immutable dependency has no code / is not the contract kind expected.
    error DependencyNotContract(address dependency);
    error DependencyMismatch(address dependency);
    /// @dev The Seaport address does not answer as Seaport 1.6 (`name()` "Seaport", `information()` version "1.6").
    error NotSeaport(address seaport);

    /// @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();

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

    /// @param initialOwner UV-311: the owner from the first block (the Safe), so a CreateX deploy needs no init call.
    /// @param _collectionRegistry the `CollectionRegistry` (code, and ERC-165 for `ICollectionRegistry`).
    constructor(
        address _seaport,
        address _royaltyRegistry,
        address _feePolicy,
        address _collectionRegistry,
        address initialOwner
    ) Ownable() {
        if (initialOwner == address(0)) revert InvalidOwner();
        _transferOwnership(initialOwner);
        if (_seaport == address(0)) revert InvalidSeaport();
        if (_royaltyRegistry == address(0)) revert InvalidSeaport();
        if (_feePolicy == address(0)) revert InvalidRecipient();
        // Closeout L-24: immutable dependencies must have CODE and answer the calls this zone makes
        // (identity read-backs), else a mistyped address yields a live zone that can never be fixed.
        if (_seaport.code.length == 0) revert DependencyNotContract(_seaport);
        if (_royaltyRegistry.code.length == 0) revert DependencyNotContract(_royaltyRegistry);
        if (_feePolicy.code.length == 0) revert DependencyNotContract(_feePolicy);
        if (_collectionRegistry.code.length == 0) revert DependencyNotContract(_collectionRegistry);
        if (!_answersInterface(_collectionRegistry, type(ICollectionRegistry).interfaceId)) {
            revert DependencyMismatch(_collectionRegistry);
        }
        collectionRegistry = ICollectionRegistry(_collectionRegistry);
        // `seaport` is immutable and both hooks admit only it: a wrong contract here would refuse canonical Seaport
        // forever. It must say it is Seaport 1.6.
        if (!_isSeaport16(_seaport)) revert NotSeaport(_seaport);
        seaport = _seaport;
        royaltyRegistry = UnVaultRoyaltyRegistry(_royaltyRegistry);
        feePolicy = IMarketplaceFeePolicy(_feePolicy);
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator();
        if (feePolicy.feeRecipient() == address(0)) revert DependencyMismatch(_feePolicy);
        if (feePolicy.platformFeeBps() > MAX_FEE_BPS) revert DependencyMismatch(_feePolicy);
        if (royaltyRegistry.MAX_ROYALTY_BPS() != MAX_ROYALTY_BPS) revert DependencyMismatch(_royaltyRegistry);
        (, , uint256 zeroQuote) = royaltyRegistry.quoteRoyaltyForToken(address(0), 0, 0);
        if (zeroQuote != 0) revert DependencyMismatch(_royaltyRegistry);
        // UV-311: the registry must be the source-aware generation (UV-312) with the same SOURCE_* numbering.
        if (royaltyRegistry.SOURCE_NONE() != SOURCE_NONE || royaltyRegistry.SOURCE_SPLITTER() != SOURCE_SPLITTER
            || royaltyRegistry.SOURCE_UNKNOWN() != SOURCE_UNKNOWN) revert DependencyMismatch(_royaltyRegistry);
    }

    /// @dev Constructor only. True when `target` answers ERC-165 `supportsInterface(interfaceId)` with exactly `true`.
    function _answersInterface(address target, bytes4 interfaceId) private view returns (bool) {
        (bool ok, bytes memory ret) = target.staticcall(abi.encodeCall(IERC165.supportsInterface, (interfaceId)));
        return ok && ret.length == 32 && abi.decode(ret, (uint256)) == 1;
    }

    /// @dev Constructor only (not in the runtime code). True when `s` answers `name()` with exactly
    ///      `abi.encode("Seaport")` and `information()` with a version string of exactly "1.6" in the standard
    ///      `(string, bytes32, address)` encoding. A shape check that rules out a mistyped or wrong-version address; it
    ///      is not a code-hash pin (the deploy script passes the canonical address and reads it back).
    function _isSeaport16(address s) private view returns (bool) {
        (bool ok, bytes memory ret) = s.staticcall(abi.encodeWithSelector(0x06fdde03)); // name()
        if (!ok || keccak256(ret) != keccak256(abi.encode("Seaport"))) return false;
        (ok, ret) = s.staticcall(abi.encodeWithSelector(0xf47b7740)); // information()
        if (!ok || ret.length != 160) return false;
        uint256 offset;
        uint256 len;
        bytes32 version;
        assembly {
            offset := mload(add(ret, 0x20))
            len := mload(add(ret, 0x80))
            version := mload(add(ret, 0xa0))
        }
        return offset == 0x60 && len == 3 && version == bytes32("1.6");
    }

    modifier onlySeaport() {
        if (msg.sender != seaport) revert OnlySeaport();
        _;
    }

    /// @notice Closeout M-10: resolve the protocol fee (bps of sale price) for a
    ///         collection through the shared policy. Fees are set on the policy
    ///         (owner/registrar), so this zone and the auction module always agree.
    function collectionFeeBps(address collection) public view returns (uint256) {
        return feePolicy.collectionFeeBps(collection);
    }

    /// @notice The protocol fee recipient, from the shared policy. Kept as a
    ///         function so the external read ABI is unchanged from the former
    ///         public `feeRecipient` state variable.
    function feeRecipient() public view returns (address) {
        return feePolicy.feeRecipient();
    }

    /// @notice The default protocol fee (bps), from the shared policy. Read-ABI
    ///         compatible with the former public `platformFeeBps` state variable.
    function platformFeeBps() public view returns (uint256) {
        return feePolicy.platformFeeBps();
    }

    /// @notice Z-8 (2026-09-14): the marketplace fee this zone enforces when `seller` sells from
    ///         `collection` — the lower of the collection's normal rate and any applicable discount.
    function effectiveFeeBps(address collection, address seller) public view returns (uint256) {
        return feePolicy.effectiveFeeBps(collection, seller);
    }

    /// @notice Z-8 (2026-09-14): the royalty consideration this zone requires for a sale of `tokenId`
    ///         by `seller` at `salePrice`. For an UnVault collection / echo (a recognised wrapper whose
    ///         splitter reads cleanly) it is TWO items — the creator's full live rate to the splitter's
    ///         creator recipient, and the (possibly discounted) protocol share to its protocol recipient
    ///         — so a discount never shrinks the creator's cut. Every other collection keeps the
    ///         registry quote. Pass `seller = address(0)` when the seller is not yet known (a bid).
    function onPlatformRoyaltyQuote(address collection, uint256 tokenId, uint256 salePrice, address seller)
        external
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount)
    {
        (bool split, UnVaultSplitterReads.Legs memory legs, uint256 protocolBps) = _splitLegs(collection, seller);
        return _royaltyQuote(split, legs, protocolBps, collection, tokenId, salePrice);
    }

    function _splitLegs(address collection, address seller)
        internal
        view
        returns (bool split, UnVaultSplitterReads.Legs memory legs, uint256 protocolBps)
    {
        (split, legs) = UnVaultSplitterReads.read(collection);
        if (split) protocolBps = feePolicy.effectiveProtocolShareBps(collection, seller, legs.protocolBps);
    }

    function _royaltyQuote(
        bool split,
        UnVaultSplitterReads.Legs memory legs,
        uint256 protocolBps,
        address collection,
        uint256 tokenId,
        uint256 salePrice
    ) internal view returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount) {
        if (!split || salePrice == 0) return royaltyRegistry.quoteRoyaltyForToken(collection, tokenId, salePrice);
        receivers = new address[](2);
        amounts = new uint256[](2);
        receivers[0] = legs.creatorRecipient;
        amounts[0] = (salePrice * legs.creatorBps) / BPS_DENOMINATOR;
        receivers[1] = legs.protocolRecipient;
        amounts[1] = (salePrice * protocolBps) / BPS_DENOMINATOR;
        totalAmount = amounts[0] + amounts[1];
    }

    /// @dev UV-311: `_royaltyQuote` plus where it came from. The UnVault split legs are `SOURCE_SPLITTER`.
    function _royaltyQuoteWithSource(
        bool split,
        UnVaultSplitterReads.Legs memory legs,
        uint256 protocolBps,
        address collection,
        uint256 tokenId,
        uint256 salePrice
    ) internal view returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount, uint8 source) {
        if (!split || salePrice == 0) return royaltyRegistry.quoteRoyaltyWithSource(collection, tokenId, salePrice);
        (receivers, amounts, totalAmount) = _royaltyQuote(split, legs, protocolBps, collection, tokenId, salePrice);
        source = SOURCE_SPLITTER;
    }

    /// @notice UV-311: the on-chain royalty this zone enforces for a sale, with its source. When `source` is
    ///         `SOURCE_NONE` (0) or `SOURCE_UNKNOWN` (5) there is no on-chain obligation: the fill needs the signer's
    ///         `royaltyPayouts` instead (NONE: an empty list attests "no royalty due"; UNKNOWN: a non-empty list).
    function royaltyObligation(address collection, uint256 tokenId, uint256 salePrice, address seller)
        external
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount, uint8 source)
    {
        (bool split, UnVaultSplitterReads.Legs memory legs, uint256 protocolBps) = _splitLegs(collection, seller);
        return _royaltyQuoteWithSource(split, legs, protocolBps, collection, tokenId, salePrice);
    }

    // ── UV-311: payment-token allowlist (owner = the Safe; changes take effect immediately) ──

    function setDefaultPaymentTokens(address[] calldata tokens, bool allowed) external onlyOwner {
        for (uint256 i = 0; i < tokens.length; i++) {
            defaultPaymentTokens[tokens[i]] = allowed;
            emit DefaultPaymentTokenSet(tokens[i], allowed);
        }
    }

    function setCollectionPaymentTokens(address collection, address[] calldata tokens, bool allowed) external onlyOwner {
        for (uint256 i = 0; i < tokens.length; i++) {
            collectionPaymentTokens[collection][tokens[i]] = allowed;
            emit CollectionPaymentTokenSet(collection, tokens[i], allowed);
        }
    }

    /// @notice Set the wrapped native coin, the only ERC-20 bids may pay in (`wrappedNative`).
    function setWrappedNative(address token) external onlyOwner {
        wrappedNative = token;
        emit WrappedNativeSet(token);
    }

    function setCollectionUsesOwnPaymentTokens(address collection, bool usesOwn) external onlyOwner {
        collectionUsesOwnPaymentTokens[collection] = usesOwn;
        emit CollectionUsesOwnPaymentTokensSet(collection, usesOwn);
    }

    /// @notice Whether a sale of `collection` may settle in `paymentToken` (`address(0)` = the native coin).
    function isPaymentTokenAllowed(address collection, address paymentToken) public view returns (bool) {
        return collectionUsesOwnPaymentTokens[collection]
            ? collectionPaymentTokens[collection][paymentToken]
            : defaultPaymentTokens[paymentToken];
    }

    /// @notice UV-311: list (or unlist) a transfer validator whose authorizer hooks the zone calls.
    function setAuthorizerValidator(address validator, bool enabled) external onlyOwner {
        authorizerValidators[validator] = enabled;
        emit AuthorizerValidatorSet(validator, enabled);
    }

    function cancelOrders(bytes32[] calldata orderHashes) external onlyOwner {
        uint256 len = orderHashes.length;
        for (uint256 i = 0; i < len; i++) {
            cancelledOrderHashes[orderHashes[i]] = true;
        }
        emit OrderHashesCancelled(orderHashes);
    }

    /// @notice Set the backend key whose signature authorises a fill (MP-EVM-07). Until it is set, every fill is refused.
    function setZoneSigner(address newSigner) external onlyOwner {
        address old = zoneSigner;
        // §7b (self-found, MP-EVM-07 follow-up): the zero state exists ONLY for the pre-provision
        // window, in which the zone refuses every fill. Once a signer is set, it may be ROTATED but never cleared back to zero — clearing it
        // would silently disable fill authorization on a live deployment. Rotation (addr → addr') is
        // still allowed.
        if (old != address(0) && newSigner == address(0)) revert ZoneSignerCannotBeCleared();
        zoneSigner = newSigner;
        emit ZoneSignerUpdated(old, newSigner);
    }

    /// @notice Closeout I-17: every side-effect-free admission check runs HERE, before any transfer,
    ///         so `fulfillAvailableAdvancedOrders` can SKIP a cancelled / paused / expired / unsigned /
    ///         replayed / wrong-fulfiller / malformed / underpaying order instead of reverting the
    ///         whole batch from the post-transfer hook. Nothing is consumed here (the nonce and the
    ///         cumulative fill are committed in `validateOrder`, the transactionally safe phase);
    ///         `validateOrder` re-runs the FULL check because transfers can change external state.
    function authorizeOrder(ZoneParameters calldata zoneParameters)
        external
        override
        onlySeaport
        whenNotPaused
        returns (bytes4 authorizeOrderMagicValue)
    {
        _enforce(zoneParameters, false);
        return this.authorizeOrder.selector;
    }

    function _requireAuthorized(ZoneParameters calldata zoneParameters, _Ctx memory c, bool nftIsCriteria, bool consume)
        internal
        returns (SignedAuthorization memory auth)
    {
        // Fail closed: a zone with no signer refuses every fill, in `authorizeOrder` and `validateOrder` alike. Before,
        // a zero signer skipped every check below, so anyone could present a self-made authorization, and the
        // cross-chain executor's recipient binding (which trusts the zone to verify the signed recipient) fell open.
        address signer = zoneSigner;
        if (signer == address(0)) revert SignerNotConfigured();

        if (zoneParameters.extraData.length == 0) revert MissingAuthorization();
        _requireV4Layout(zoneParameters.extraData);
        auth = abi.decode(zoneParameters.extraData, (SignedAuthorization));

        if (auth.expiration < block.timestamp) revert ExpiredAuthorization();
        if (auth.fulfiller != zoneParameters.fulfiller) revert FulfillerMismatch();
        if (auth.recipient == address(0)) revert AuthorizationMismatch(); // Closeout L-12
        if (usedAuthorizationNonces[auth.nonce]) revert AuthorizationAlreadyUsed();

        // The signature attests to a specific sale. The ORDER is the source of truth for what that
        // sale is, so a mismatch means the signature belongs to a different fill.
        if (
            auth.nftContract != c.nftContract ||
            auth.tokenId != c.tokenId ||
            auth.paymentToken != c.paymentToken ||
            auth.grossSaleAmount != c.grossSaleAmount
        ) revert AuthorizationMismatch();

        // The collection must either be admitted for the order's standard under the policy pair the signer saw, or
        // carry the unverified marker while the collection is unrecorded, not blocked, and the lane (and criteria-offer
        // switch when applicable) is open. Checked in both phases so any change between signing and validation fails.
        if (auth.policyId == UNVERIFIED_POLICY_ID || auth.policyId == UNVERIFIED_CRITERIA_POLICY_ID) {
            if (auth.policyId == UNVERIFIED_CRITERIA_POLICY_ID && !c.isBid) revert AuthorizationMismatch();
            if (auth.policyEpoch != 0) revert CollectionPolicyMismatch(c.nftContract, auth.policyId, 0);
            bool criteriaOffer = (c.isBid && nftIsCriteria) || auth.policyId == UNVERIFIED_CRITERIA_POLICY_ID;
            (bool ok, bool blocked, bool laneOpen, bool criteriaOffersOpen, bytes32 policyId, uint64 epoch) =
                collectionRegistry.unverifiedStatus(c.nftContract, criteriaOffer);
            if (!ok) {
                if (epoch != 0) revert CollectionPolicyMismatch(c.nftContract, policyId, epoch);
                if (blocked) revert CollectionBlocked(c.nftContract);
                if (!laneOpen) revert UnverifiedLaneClosed();
                if (criteriaOffer && !criteriaOffersOpen) revert UnverifiedCriteriaOfferDisabled(c.nftContract);
                revert CollectionNotAdmitted(c.nftContract);
            }
        } else {
            (bool admitted_, bytes32 policyId, uint64 epoch) = collectionRegistry.admitted(
                c.nftContract, c.nftIs1155 ? COLLECTION_STANDARD_ERC1155 : COLLECTION_STANDARD_ERC721
            );
            if (!admitted_) revert CollectionNotAdmitted(c.nftContract);
            if (policyId != auth.policyId || epoch != auth.policyEpoch) {
                revert CollectionPolicyMismatch(c.nftContract, policyId, epoch);
            }
        }

        // The token's account must still be in the state the signer saw (both phases): using the account after signing
        // (`execute`, its own way to move what it holds) bumps its `state()`, so an account emptied that way in the
        // meantime cannot be sold. Exception: an operator approval the account granted earlier (an `approve` or
        // `setApprovalForAll` through `execute`, already in the signed state) lets that operator move its assets without
        // bumping `state()`; this check cannot see that.
        if (auth.bugAccount != address(0)) _requireBugAccountState(auth.bugAccount, auth.bugAccountState);

        if (_digest(zoneParameters.orderHash, auth).recover(auth.signature) != signer) revert InvalidAuthorization();

        // I-17: the nonce is consumed only in the transactionally safe phase (`validateOrder`).
        if (consume) usedAuthorizationNonces[auth.nonce] = true;
        return auth;
    }

    /// @dev The canonical v4 encoding is `0x20 ‖ 13 static words ‖ payouts offset (= 15 words) ‖ signature offset ‖ …`.
    ///      An older authorization ends its head earlier (v3 after 11 static words, v2 after 10), so word 13 of its head
    ///      is a length or array data, not 0x1e0: refused by name instead of a decode panic or a misread.
    function _requireV4Layout(bytes calldata extraData) private pure {
        if (extraData.length < 32 * 16) revert UnsupportedAuthorizationVersion();
        uint256 head;
        uint256 payoutsOffset;
        assembly {
            head := calldataload(extraData.offset)
            payoutsOffset := calldataload(add(extraData.offset, 448)) // 32 + 13 * 32
        }
        if (head != 0x20 || payoutsOffset != 15 * 32) revert UnsupportedAuthorizationVersion();
    }

    /// @dev The account's `state()` (one 32-byte word, read with at most 30,000 gas) must equal `signedState`. A read
    ///      that fails or answers in any other shape fails closed.
    function _requireBugAccountState(address account, uint256 signedState) private view {
        (bool ok, uint256 live) = _staticReadWord(account, abi.encodeWithSelector(0xc19d93fb), 30_000);
        if (!ok) revert BugAccountStateUnreadable(account);
        if (live != signedState) revert BugAccountStateChanged(account, signedState, live);
    }

    /// @dev The EIP-712 digest the zone signer signs (domain "UnVaultSignedZone", version "4").
    function _digest(bytes32 orderHash, SignedAuthorization memory auth) internal view returns (bytes32) {
        uint256 n = auth.royaltyPayouts.length;
        bytes32[] memory payoutHashes = new bytes32[](n);
        for (uint256 i = 0; i < n; i++) {
            payoutHashes[i] = keccak256(
                abi.encode(ROYALTY_PAYOUT_TYPEHASH, auth.royaltyPayouts[i].receiver, auth.royaltyPayouts[i].amount)
            );
        }
        // Two halves of one word-per-field encoding (identical bytes to a single `abi.encode` of all sixteen words),
        // split only to stay within the stack.
        bytes32 structHash = keccak256(
            bytes.concat(
                abi.encode(
                    AUTHORIZATION_TYPEHASH,
                    orderHash,
                    auth.nftContract,
                    auth.paymentToken,
                    auth.grossSaleAmount,
                    auth.tokenId,
                    auth.fulfiller
                ),
                abi.encode(
                    auth.recipient, // Closeout L-12
                    auth.expiration,
                    auth.nonce,
                    auth.transferOperator,
                    auth.bugAccount,
                    auth.bugAccountState,
                    auth.policyId,
                    auth.policyEpoch,
                    keccak256(abi.encodePacked(payoutHashes))
                )
            )
        );
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparator(), structHash)); // G-14
    }

    /// @notice UV-311: the digest the zone signer must sign for `auth` on the order `orderHash` (for the backend's
    ///         cross-check and the golden vectors). `auth.signature` is ignored.
    function hashAuthorization(bytes32 orderHash, SignedAuthorization calldata auth) external view returns (bytes32) {
        return _digest(orderHash, auth);
    }

    /// @notice False on a deployment that has not yet been given a signer; such a zone refuses every fill
    ///         (`SignerNotConfigured`). Deployment scripts and the cross-chain executor's allowlist assert it.
    function zoneSignerConfigured() external view returns (bool) {
        return zoneSigner != address(0);
    }

    /// @notice Halt fulfilment of every restricted order routed through this zone.
    /// @dev Emergency lever: Seaport calls `validateOrder` on every fill, so pausing here stops all
    ///      UnVault-zoned fills without touching Seaport or the sellers' signed orders.
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Resume fulfilment of restricted orders.
    function unpause() external onlyOwner {
        _unpause();
    }

    function validateOrder(ZoneParameters calldata zoneParameters)
        external
        override
        onlySeaport
        whenNotPaused
        returns (bytes4 validOrderMagicValue)
    {
        _enforce(zoneParameters, true);
        return this.validateOrder.selector;
    }

    /// @dev The zone's whole admission policy, shared by `authorizeOrder` (pre-transfer, `effects ==
    ///      false`: nothing written, nothing emitted) and `validateOrder` (post-transfer, `effects ==
    ///      true`: nonce consumed, cumulative fill recorded, `DivitSaleFundedV2` emitted) — Closeout
    ///      I-17. Doc pass 2026-09-09: this named the un-versioned `DivitSaleFunded`, which I-10 renamed
    ///      when it added `paymentToken`; the emit below is and always was the V2 event.
    function _enforce(ZoneParameters calldata zoneParameters, bool effects) internal {
        if (cancelledOrderHashes[zoneParameters.orderHash]) revert CancelledOrder();

        (_Ctx memory c, bool nftIsCriteria) = _deriveOrderContext(zoneParameters);
        // UV-313 (audit L-04 / review L-3): a bid's seller is the token's HOLDER, not the fulfiller (a router, the
        // purchase executor or a matchOrders caller would otherwise get its own seller discount).
        if (c.isBid) {
            c.seller = _bidSeller(
                zoneParameters.orderHash, c.nftContract, c.tokenId, !c.nftIs1155, zoneParameters.fulfiller, effects
            );
        }

        // UV-311 (review H-3): only listed currencies settle.
        if (!isPaymentTokenAllowed(c.nftContract, c.paymentToken)) revert PaymentTokenNotAllowed(c.paymentToken);

        // MP-EVM-07: authenticate the fill against the sale the order actually describes.
        SignedAuthorization memory auth = _requireAuthorized(zoneParameters, c, nftIsCriteria, effects);

        // Closeout M-09: price obligations as CUMULATIVE deltas across partial fills so the total
        // fee/royalty is invariant to how the order is partitioned. `oldGross` is what earlier fills
        // already settled; `newGross` includes this fill. Each obligation this fill must cover is the
        // difference between the cumulative obligation at `newGross` and at `oldGross` — never the
        // floor of this slice alone (which a coarse token or a 1-unit fill could round to zero).
        uint256 oldGross = filledGross[zoneParameters.orderHash];
        uint256 newGross = oldGross + c.grossSaleAmount;
        if (effects) filledGross[zoneParameters.orderHash] = newGross;

        (uint256 totalRoyalty, uint256 royaltyPaid) =
            _checkPayouts(zoneParameters.consideration, c, oldGross, newGross, auth.royaltyPayouts);

        // UV-311: Limit Break authorizer hooks, last, once every other check passed.
        _authorizerHook(
            zoneParameters,
            c,
            auth.transferOperator,
            c.isBid ? c.nftRecipient : auth.recipient,
            effects
        );

        // The NFT actually arrived, whether or not a Limit Break hook was armed above (its own check stays), at the
        // account the authorization delivers to.
        _checkDelivery(
            c,
            zoneParameters.orderHash,
            c.isBid ? address(0) : zoneParameters.offerer,
            c.isBid ? c.nftRecipient : auth.recipient,
            effects
        );

        // The payment actually arrived (ERC-20 only; Seaport's native transfers revert on failure). A listing's payees
        // are checked against a balance snapshot taken before the transfers; a bid must pay in the wrapped native coin.
        // Last, so every policy refusal above keeps its own error.
        if (c.paymentToken != address(0)) {
            if (c.isBid) {
                if (c.paymentToken != wrappedNative) revert BidTokenNotWrappedNative(c.paymentToken);
            } else {
                _checkReceipts(zoneParameters.consideration, c.paymentToken, zoneParameters.fulfiller, effects);
            }
        }

        if (effects) {
            emit DivitSaleFundedV2(c.nftContract, totalRoyalty, royaltyPaid, c.paymentToken);
            if (auth.policyId == UNVERIFIED_POLICY_ID || auth.policyId == UNVERIFIED_CRITERIA_POLICY_ID) {
                emit UnverifiedOrderFilled(zoneParameters.orderHash, c.nftContract, c.tokenId, auth.policyId);
            }
        }
    }

    /// @dev The fee + royalty coverage check for one fill. G-12: the consideration is scanned ONCE
    ///      for every payee (fee recipient + each royalty receiver) instead of once per payee.
    function _checkPayouts(
        ReceivedItem[] calldata consideration,
        _Ctx memory c,
        uint256 oldGross,
        uint256 newGross,
        RoyaltyPayout[] memory signedPayouts
    ) internal view returns (uint256 totalRoyalty, uint256 royaltyPaid) {
        // Z-8 (2026-09-14): the fee and the protocol share are priced for THIS sale's seller (the
        // offerer of a listing, the fulfiller of a bid) — discounts only ever lower them.
        uint256 feeBps = effectiveFeeBps(c.nftContract, c.seller);
        uint256 feeDelta =
            (newGross * feeBps) / BPS_DENOMINATOR - (oldGross * feeBps) / BPS_DENOMINATOR;
        address paymentToken = c.paymentToken;

        (address[] memory receivers, uint256[] memory newRoyalty, uint256[] memory oldRoyalty) =
            _royaltyDeltas(c, oldGross, newGross, feeBps, signedPayouts);
        uint256 len = receivers.length;

        address feeTo = feeRecipient();
        address[] memory payees = new address[](len + 1);
        payees[0] = feeTo;
        for (uint256 i = 0; i < len; i++) payees[i + 1] = receivers[i];
        uint256[] memory paid = _paidToAll(consideration, payees, paymentToken);
        if (paid[0] < feeDelta) revert InvalidPlatformFeePayout();

        for (uint256 i = 0; i < len; i++) {
            address receiver = receivers[i];
            // This fill's obligation to receiver i = its cumulative royalty at newGross minus at
            // oldGross (saturating, in case a mutated config lowered it).
            uint256 royaltyDelta = newRoyalty[i] > oldRoyalty[i] ? newRoyalty[i] - oldRoyalty[i] : 0;
            // A single consideration item must not satisfy two obligations at once: subtract what this
            // address was already credited for this fill (the fee leg, or an earlier duplicate royalty
            // leg) before deciding whether its royalty is covered.
            uint256 consumed = receiver == feeTo ? feeDelta : 0;
            for (uint256 j = 0; j < i; j++) {
                if (receivers[j] == receiver) {
                    consumed += newRoyalty[j] > oldRoyalty[j] ? newRoyalty[j] - oldRoyalty[j] : 0;
                }
            }
            uint256 available = paid[i + 1] > consumed ? paid[i + 1] - consumed : 0;
            if (available < royaltyDelta) {
                revert InvalidRoyaltyPayout(receiver, royaltyDelta, available);
            }
            totalRoyalty += royaltyDelta;
            // I-10: what this receiver was ACTUALLY paid by this fill, its fee leg excluded, counted
            // once per distinct receiver (a repeated receiver's consideration is one payment).
            bool seen;
            for (uint256 j = 0; j < i; j++) {
                if (receivers[j] == receiver) { seen = true; break; }
            }
            if (!seen) {
                uint256 feeLeg = receiver == feeTo ? feeDelta : 0;
                uint256 paidNet = paid[i + 1] > feeLeg ? paid[i + 1] - feeLeg : 0;
                // UV-313 (audit L-03): count at most this receiver's royalty obligation. A receiver that is also
                // the seller (a creator selling its own token) is paid the proceeds too, and those are not royalty.
                uint256 owed;
                for (uint256 j = 0; j < len; j++) {
                    if (receivers[j] == receiver) owed += newRoyalty[j] > oldRoyalty[j] ? newRoyalty[j] - oldRoyalty[j] : 0;
                }
                royaltyPaid += paidNet < owed ? paidNet : owed;
            }
        }
    }

    /// @dev The royalty receivers with their cumulative obligation at `newGross` and at `oldGross`
    ///      (Closeout M-09), priced for the seller (Z-8). The old obligation is matched by receiver ADDRESS, not
    ///      by position: the quote at `oldGross` may name other receivers (an ERC-2981 answer that depends on the
    ///      price, or a configuration changed mid-order), so `oldRoyalty[i]` is the part of what the old quote
    ///      owed `receivers[i]` that this leg absorbs (see `_alignOldRoyalty`). A receiver only in the old quote
    ///      contributes nothing. Also refuses an order whose fee plus royalty exceed its price (configurability
    ///      round 2026-09-14).
    ///
    ///      UV-311, the royalty precedence:
    ///        1. an on-chain source (UnVault split, configured split, ERC-2981, Limit Break backfill) sets the
    ///           obligation; the signer's payouts are then ignored (the signer can still decline to sign);
    ///        2. `SOURCE_NONE` (the collection answered zero / has no ERC-2981): the signer's payouts, an empty list
    ///           meaning "no royalty due";
    ///        3. `SOURCE_UNKNOWN` (the collection could not answer): the signer's payouts, which must not be empty;
    ///           else refused.
    ///      Signer payouts are ABSOLUTE amounts for this fill (the authorization is bound to this fill's gross), so
    ///      there is no cumulative delta: each listed receiver must be paid at least its amount by this fill.
    function _royaltyDeltas(
        _Ctx memory c,
        uint256 oldGross,
        uint256 newGross,
        uint256 feeBps,
        RoyaltyPayout[] memory signedPayouts
    ) internal view returns (address[] memory receivers, uint256[] memory newRoyalty, uint256[] memory oldRoyalty) {
        (bool split, UnVaultSplitterReads.Legs memory legs, uint256 protocolBps) = _splitLegs(c.nftContract, c.seller);
        uint256 newTotal;
        uint8 source;
        (receivers, newRoyalty, newTotal, source) =
            _royaltyQuoteWithSource(split, legs, protocolBps, c.nftContract, c.tokenId, newGross);
        uint256 len;
        if (source == SOURCE_NONE || source == SOURCE_UNKNOWN) {
            if (source == SOURCE_UNKNOWN && signedPayouts.length == 0) {
                revert NoRoyaltySource(c.nftContract, source);
            }
            len = signedPayouts.length;
            receivers = new address[](len);
            newRoyalty = new uint256[](len);
            newTotal = 0;
            for (uint256 i = 0; i < len; i++) {
                if (signedPayouts[i].receiver == address(0)) revert AuthorizationMismatch();
                receivers[i] = signedPayouts[i].receiver;
                newRoyalty[i] = signedPayouts[i].amount;
                newTotal += signedPayouts[i].amount;
            }
            // This fill's price, not the cumulative one: the signed amounts are for this fill alone.
            uint256 fillGross = newGross - oldGross;
            if ((fillGross * feeBps) / BPS_DENOMINATOR + newTotal > fillGross) revert FeeAndRoyaltyExceedPrice();
            oldRoyalty = new uint256[](len);
            return (receivers, newRoyalty, oldRoyalty);
        }
        if ((newGross * feeBps) / BPS_DENOMINATOR + newTotal > newGross) revert FeeAndRoyaltyExceedPrice();
        len = receivers.length;
        if (oldGross == 0) {
            oldRoyalty = new uint256[](len);
        } else {
            (address[] memory oldReceivers, uint256[] memory oldAmounts,,) =
                _royaltyQuoteWithSource(split, legs, protocolBps, c.nftContract, c.tokenId, oldGross);
            oldRoyalty = _alignOldRoyalty(receivers, newRoyalty, oldReceivers, oldAmounts);
        }
    }

    /// @dev Per receiver address `r`: the old quote's total for `r` is spread over `r`'s legs in the new quote, each
    ///      leg absorbing at most its new amount. So, summed over `r`'s legs, `new - old` (saturating per leg) is
    ///      exactly `max(0, newTotal(r) - oldTotal(r))`, whatever the positions and duplicates on either side.
    function _alignOldRoyalty(
        address[] memory receivers,
        uint256[] memory newRoyalty,
        address[] memory oldReceivers,
        uint256[] memory oldAmounts
    ) private pure returns (uint256[] memory oldRoyalty) {
        uint256 len = receivers.length;
        oldRoyalty = new uint256[](len);
        uint256 oldLen = oldReceivers.length < oldAmounts.length ? oldReceivers.length : oldAmounts.length;
        for (uint256 i = 0; i < len; i++) {
            address r = receivers[i];
            bool seen;
            for (uint256 j = 0; j < i; j++) {
                if (receivers[j] == r) {
                    seen = true;
                    break;
                }
            }
            if (seen) continue;
            uint256 remaining;
            for (uint256 k = 0; k < oldLen; k++) {
                if (oldReceivers[k] == r) remaining += oldAmounts[k];
            }
            for (uint256 j = i; j < len && remaining != 0; j++) {
                if (receivers[j] != r) continue;
                uint256 take = newRoyalty[j] < remaining ? newRoyalty[j] : remaining;
                oldRoyalty[j] = take;
                remaining -= take;
            }
        }
    }

    /// @dev G-14: cached EIP-712 domain separator, recomputed only if the chain id changed (fork).
    function _domainSeparator() internal view returns (bytes32) {
        return block.chainid == _CACHED_CHAIN_ID ? _CACHED_DOMAIN_SEPARATOR : _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, address(this)));
    }

    /// @dev Resolve the four facts the fee/royalty policy is priced from: which collection is being
    ///      sold, which token id (when concrete), which currency the buyer pays in, and the sale price.
    ///
    ///      The order SHAPE decides which side carries the price, and the shape is determined by the
    ///      side the NFT sits on — never by scanning for "a fungible item somewhere":
    ///        * NFT on the OFFER side          => LISTING => the price is the CONSIDERATION side.
    ///        * NFT on the CONSIDERATION side  => BID     => the price is the OFFER side.
    ///
    ///      An earlier version instead asked "is there a fungible offer item in the payment token?" and
    ///      took `paymentToken` from the FIRST fungible consideration item. Both inputs are chosen by
    ///      the order author, so a seller listing for 100 WETH could add a 1-wei WETH item to the OFFER
    ///      side and collapse `grossSaleAmount` to 1 (fee and royalty then round to 0), and a dust ERC-20
    ///      placed first in the consideration achieved the same thing. Deriving the price side from the
    ///      asset side removes the author's choice, and requiring one currency per payment side removes
    ///      the dust-token variant.
    function _deriveOrderContext(ZoneParameters calldata zoneParameters)
        internal
        pure
        returns (_Ctx memory c, bool nftIsCriteria)
    {
        // Closeout G-12 (verification 2026-09-08): "parse each side ONCE into a compact context holding
        // NFT identity, payment currency and total". Each side is now walked exactly once, filling one
        // `_SideScan` per side; the shape decision below reads those two structs instead of re-walking
        // the consideration (the NFT-on-both-sides check and the payment total were separate passes).
        _SideScan memory offerSide = _scanSide(zoneParameters.offer.length, zoneParameters, true);
        _SideScan memory considerationSide = _scanSide(zoneParameters.consideration.length, zoneParameters, false);

        if (offerSide.hasNft) {
            // MP-EVM-04 — BARTER. The asset side must be ONE side of the order. An NFT on the
            // consideration side would be a second asset being traded, not a payment, and nothing here
            // can value an NFT — so an order with assets on both sides is refused.
            if (considerationSide.hasNft) revert NftOnBothSides();
            // UV-311 (review L-1): a listing offers the NFT alone. A fungible item beside it would be paid back
            // out of the consideration, so the fee and royalty would be priced on more than the real sale.
            // (A bid's asset side, its consideration, legitimately carries the fee and royalty legs.)
            if (offerSide.hasPayment) revert FungibleOnAssetSide();
            nftIsCriteria = _takeNft(c, offerSide);
            // LISTING => the price is the CONSIDERATION side; the offerer is the seller.
            c.seller = zoneParameters.offerer;
            c.paymentToken = considerationSide.paymentToken;
            c.grossSaleAmount = considerationSide.paymentTotal;
        } else if (considerationSide.hasNft) {
            nftIsCriteria = _takeNft(c, considerationSide);
            // BID => the price is the OFFER side; the fulfiller delivers the NFT, so it is the seller.
            c.seller = zoneParameters.fulfiller;
            c.isBid = true;
            c.paymentToken = offerSide.paymentToken;
            c.grossSaleAmount = offerSide.paymentTotal;
        } else {
            revert MissingNftItem();
        }

        if (c.grossSaleAmount == 0) revert MissingPaymentItem();
    }

    /// @dev The facts the policy is priced from (see `_deriveOrderContext`).
    struct _Ctx {
        address nftContract;
        uint256 tokenId;
        bool nftIs1155;
        uint256 nftAmount;
        address nftRecipient; // a bid's NFT consideration recipient (zero for a listing)
        address paymentToken;
        uint256 grossSaleAmount;
        address seller;
        bool isBid;
    }

    function _takeNft(_Ctx memory c, _SideScan memory side) private pure returns (bool nftIsCriteria) {
        c.nftContract = side.nftContract;
        c.tokenId = side.tokenId;
        c.nftIs1155 = side.nftItemType == ItemType.ERC1155 || side.nftItemType == ItemType.ERC1155_WITH_CRITERIA;
        nftIsCriteria =
            side.nftItemType == ItemType.ERC721_WITH_CRITERIA || side.nftItemType == ItemType.ERC1155_WITH_CRITERIA;
        c.nftAmount = side.nftAmount;
        c.nftRecipient = side.nftRecipient;
    }

    /// @dev UV-311: Limit Break transfer-validator authorizer hooks (Creator Token Standards v5). Only when the
    ///      collection's `getTransferValidator()` is on `authorizerValidators` and the signer named the
    ///      `transferOperator` (Seaport, or the conduit that moves the NFT). Authorize phase:
    ///      `beforeAuthorizedTransfer(operator, token, id)` (ERC-721) or
    ///      `beforeAuthorizedTransferWithAmount(operator, token, id, amount)` (ERC-1155). If the validator refuses
    ///      (authorization mode off, the zone not an authorizer for that collection) the fill goes on WITHOUT the
    ///      authorization: the transfer then passes or fails on the collection's own policy, as without the hook. The
    ///      validator that accepted is carried to the validate phase in transient storage, keyed like `_bidSeller`,
    ///      and there `afterAuthorizedTransfer(token, id)` / `afterAuthorizedTransferWithAmount(token, id)` MUST
    ///      succeed (an authorization left open would let the operator move the token again in this transaction).
    ///      andskur #426 finding 1: the authorization is open for every transfer Seaport makes between the two phases,
    ///      and Limit Break also writes a collection-wide slot. So (a) a fill that opens one must be the only order in the
    ///      Seaport call. Seaport 1.6 passes `authorizeOrder` the hashes of the orders BEFORE this one (its encoder writes
    ///      `orderIndex` as the length) and `validateOrder` all of them, so: 0 in `authorizeOrder` (first) and 1 in
    ///      `validateOrder` (alone). And (b) before the after-hook the NFT must sit with the account this fill delivers
    ///      to: `ownerOf(id) == expectedHolder` (ERC-721), or its balance grew by at least the order amount (ERC-1155).
    function _authorizerHook(
        ZoneParameters calldata zp,
        _Ctx memory c,
        address operator,
        address expectedHolder,
        bool validatePhase
    ) private {
        bytes32 slot = keccak256(abi.encode("unvault.zone.authorizer", zp.orderHash, c.nftContract, c.tokenId));
        if (validatePhase) {
            address armed;
            uint256 balanceBefore;
            assembly {
                armed := tload(slot)
                balanceBefore := tload(add(slot, 1))
                tstore(slot, 0)
                tstore(add(slot, 1), 0)
            }
            if (armed == address(0)) return;
            if (zp.orderHashes.length != 1) revert AuthorizerBatchNotAllowed();
            if (c.nftIs1155) {
                if (_balance1155(c.nftContract, expectedHolder, c.tokenId) < balanceBefore + c.nftAmount) {
                    revert AuthorizedTransferNotDelivered(expectedHolder);
                }
            } else if (_ownerOf(c.nftContract, c.tokenId) != expectedHolder) {
                revert AuthorizedTransferNotDelivered(expectedHolder);
            }
            bytes4 afterSel = c.nftIs1155
                ? bytes4(keccak256("afterAuthorizedTransferWithAmount(address,uint256)"))
                : bytes4(keccak256("afterAuthorizedTransfer(address,uint256)"));
            (bool cleared,) = armed.call(abi.encodeWithSelector(afterSel, c.nftContract, c.tokenId));
            if (!cleared) revert AuthorizerHookFailed(armed);
            return;
        }
        if (operator == address(0)) return;
        address validator = _transferValidator(c.nftContract);
        if (validator == address(0) || !authorizerValidators[validator]) return;
        if (zp.orderHashes.length != 0) revert AuthorizerBatchNotAllowed(); // not the first order of the call
        bytes memory before_ = c.nftIs1155
            ? abi.encodeWithSignature(
                "beforeAuthorizedTransferWithAmount(address,address,uint256,uint256)", operator, c.nftContract, c.tokenId, c.nftAmount
            )
            : abi.encodeWithSignature("beforeAuthorizedTransfer(address,address,uint256)", operator, c.nftContract, c.tokenId);
        uint256 g = gasleft();
        (bool ok,) = validator.call(before_);
        if (!ok) {
            if (gasleft() <= g / 64) revert AuthorizerHookStarved(); // the caller's gas failed it, not the validator
            return;
        }
        uint256 balanceNow = c.nftIs1155 ? _balance1155(c.nftContract, expectedHolder, c.tokenId) : 0;
        assembly {
            tstore(slot, validator)
            tstore(add(slot, 1), balanceNow)
        }
    }

    function _ownerOf(address nft, uint256 id) private view returns (address holder) {
        (bool ok, uint256 raw) = _staticReadWord(nft, abi.encodeWithSelector(0x6352211e, id), gasleft());
        if (ok && raw <= type(uint160).max) holder = address(uint160(raw));
    }

    function _balance1155(address nft, address account, uint256 id) private view returns (uint256 bal) {
        (bool ok, uint256 raw) = _staticReadWord(nft, abi.encodeWithSelector(0x00fdd58e, account, id), gasleft());
        if (ok) bal = raw;
    }

    /// @dev The collection's Creator Token transfer validator (`getTransferValidator()`), or zero.
    function _transferValidator(address collection) private view returns (address validator) {
        (bool ok, uint256 raw) =
            _staticReadWord(collection, abi.encodeWithSelector(bytes4(keccak256("getTransferValidator()"))), 30_000);
        if (ok && raw <= type(uint160).max) validator = address(uint160(raw));
    }

    /// @dev The in-flow receipt check for a listing's ERC-20 payees. Seaport 1.6 calls `authorizeOrder` for every restricted
    ///      order before ANY transfer of the call and `validateOrder` for each after ALL of them (single, basic, available
    ///      and match fills alike), and neither when the caller is the zone. So the check is cumulative per (token, payee):
    ///      the first `authorizeOrder` that names a payee stores its balance (with a set flag, as the balance may be 0),
    ///      and every `authorizeOrder` adds the amount each consideration item pays it. In `validateOrder` every payee's
    ///      balance must have risen by at least that running total, which covers all the orders of the call (and of any
    ///      earlier Seaport call in the same transaction). `>=` because other orders in the call may pay it as well.
    ///      The fulfiller is exempt: it pays the consideration, so a leg it pays to itself needs no receipt proof, and its
    ///      balance nets down by the price (a creator buying from its own collection, the fee recipient buying). Any other
    ///      payee that also pays the same token out in the same call can net lower and is refused (fill it separately).
    ///      No snapshot in `validateOrder` (no authorize phase) and a balance that gives no 32-byte answer fail closed.
    ///      An authorize that reverts (an order `fulfillAvailable*` skips at authorization) rolls its own transient writes
    ///      back. An order whose authorize succeeds and that Seaport then skips in `_updateStatus` (the same order twice in
    ///      one `fulfillAvailable*` call, the first fill completing it) keeps its total, so the call's other validations
    ///      ask for a payment that never moved and the whole call reverts `PaymentNotReceived`. That limits only the
    ///      caller's own batch (no funds move); a caller must not repeat an order within one call.
    function _checkReceipts(ReceivedItem[] calldata consideration, address token, address fulfiller, bool validatePhase)
        private
    {
        uint256 len = consideration.length;
        for (uint256 i = 0; i < len; i++) {
            ReceivedItem calldata item = consideration[i];
            if (item.itemType != ItemType.ERC20 || item.token != token) continue;
            address payee = item.recipient;
            if (payee == fulfiller) continue;
            bytes32 slot = keccak256(abi.encode("unvault.zone.receipt", token, payee));
            (uint256 set, uint256 base, uint256 total) = _tget(slot);
            if (validatePhase) {
                if (set == 0) revert PaymentReceiptUnreadable(payee);
                uint256 bal = _erc20Balance(token, payee);
                uint256 received = bal > base ? bal - base : 0;
                if (received < total) revert PaymentNotReceived(payee, total, received);
            } else {
                if (set == 0) base = _erc20Balance(token, payee);
                _tset(slot, base, total + item.amount);
            }
        }
    }

    /// @dev The NFT delivery check, the twin of `_checkReceipts`, for every authorized fill (listing or bid), independent of
    ///      the Limit Break hook. A collection whose transfer returns without moving the token would otherwise leave the
    ///      seller with the token AND the payment. `from` is a listing's offerer (zero for a bid: a match may be filled by
    ///      a third party) and `holder` who must end with the NFT (the signed recipient of a listing, the NFT consideration
    ///      recipient of a bid). ERC-721: `authorizeOrder` requires that `holder` does not own the token yet and, for a
    ///      listing, that `from` does, and records that it looked; `validateOrder` requires `ownerOf == holder`. ERC-1155: like the receipts, a baseline of `holder`'s balance per (collection, id, holder)
    ///      with a set flag, plus a running total of the lots (already scaled to the fill fraction), and `validateOrder`
    ///      requires the balance to have risen by at least that total; units the holder already had are in the baseline.
    ///      No snapshot and an unreadable read fail closed (`DeliveryUnreadable`). Every `validateOrder` runs after all the
    ///      call's transfers, so a same-call resale of one ERC-721 (bought and resold within one `match`) is refused.
    ///      The ERC-721 snapshot is also a claim: one authorized fill per (collection, token) per Seaport call, so a
    ///      second `authorizeOrder` for the same token reverts (`TokenAlreadyAuthorizedInCall`) before any transfer and
    ///      one transition can never satisfy two orders. `validateOrder` releases the claim, so a later, separate Seaport
    ///      call in the same transaction can trade the token again.
    ///      ERC-1155 per-order binding: the holder's running total alone would count a rise that another order of the
    ///      call made (one the zone does not see, or a listing's offer item Seaport leaves unspent in a match or
    ///      `fulfillAvailable`) toward a zone order. So each fill is also bound to its own side of the transition:
    ///      (a) a listing's offerer must have parted with the lot, as a running total per (collection, id, offerer) that
    ///      `validateOrder` requires its balance to have fallen by; (b) an order is counted once per call (a second
    ///      `authorizeOrder` of the same order hash reverts, so `fulfillAvailable` skips it), released in `validateOrder`;
    ///      (c) the holder's rise must cover the lots of exactly the authorized fills that deliver to it. Several listings
    ///      of one id to one holder (a sweep) still settle: the totals add up per holder and per offerer.
    function _checkDelivery(_Ctx memory c, bytes32 orderHash, address from, address holder, bool validatePhase) private {
        if (!c.nftIs1155) {
            bytes32 slot721 = keccak256(abi.encode("unvault.zone.delivery721", c.nftContract, c.tokenId));
            address owner_ = _ownerOfStrict(c.nftContract, c.tokenId);
            (uint256 set721,,) = _tget(slot721);
            if (validatePhase) {
                if (set721 == 0) revert DeliveryUnreadable();
                if (owner_ != holder) revert NftNotDelivered(holder);
                assembly {
                    tstore(slot721, 0)
                }
            } else {
                if (owner_ == holder || (from != address(0) && owner_ != from)) revert NftNotDelivered(holder);
                if (set721 != 0) revert TokenAlreadyAuthorizedInCall(c.nftContract, c.tokenId);
                _tset(slot721, 0, 0);
            }
            return;
        }
        bytes32 orderSlot = keccak256(abi.encode("unvault.zone.order1155", orderHash));
        uint256 counted;
        assembly {
            counted := tload(orderSlot)
        }
        bytes32 slot = keccak256(abi.encode("unvault.zone.delivery1155", c.nftContract, c.tokenId, holder));
        bytes32 sentSlot = keccak256(abi.encode("unvault.zone.sent1155", c.nftContract, c.tokenId, from));
        (uint256 set, uint256 base, uint256 total) = _tget(slot);
        if (validatePhase) {
            if (set == 0 || counted == 0) revert DeliveryUnreadable();
            assembly {
                tstore(orderSlot, 0)
            }
            uint256 bal = _balance1155Strict(c.nftContract, holder, c.tokenId);
            if (bal < base || bal - base < total) revert NftNotDelivered(holder);
            if (from != address(0)) {
                (uint256 sSet, uint256 sBase, uint256 sTotal) = _tget(sentSlot);
                if (sSet == 0) revert DeliveryUnreadable();
                uint256 fromBal = _balance1155Strict(c.nftContract, from, c.tokenId);
                if (fromBal > sBase || sBase - fromBal < sTotal) revert NftNotSent(from);
            }
        } else {
            if (counted != 0) revert OrderAlreadyAuthorizedInCall(orderHash);
            assembly {
                tstore(orderSlot, 1)
            }
            if (set == 0) base = _balance1155Strict(c.nftContract, holder, c.tokenId);
            _tset(slot, base, total + c.nftAmount);
            if (from != address(0)) {
                (uint256 sSet, uint256 sBase, uint256 sTotal) = _tget(sentSlot);
                if (sSet == 0) sBase = _balance1155Strict(c.nftContract, from, c.tokenId);
                _tset(sentSlot, sBase, sTotal + c.nftAmount);
            }
        }
    }

    function _balance1155Strict(address nft, address account, uint256 id) private view returns (uint256) {
        return _readStrict(nft, abi.encodeWithSelector(0x00fdd58e, account, id));
    }

    /// @dev A transient (set, base, total) triple at `slot`, `slot + 1`, `slot + 2`.
    function _tget(bytes32 slot) private view returns (uint256 set, uint256 base, uint256 total) {
        assembly {
            set := tload(slot)
            base := tload(add(slot, 1))
            total := tload(add(slot, 2))
        }
    }

    function _tset(bytes32 slot, uint256 base, uint256 total) private {
        assembly {
            tstore(slot, 1)
            tstore(add(slot, 1), base)
            tstore(add(slot, 2), total)
        }
    }

    function _ownerOfStrict(address nft, uint256 id) private view returns (address) {
        uint256 word = _readStrict(nft, abi.encodeWithSelector(0x6352211e, id));
        if (word > type(uint160).max) revert DeliveryUnreadable();
        return address(uint160(word));
    }

    /// @dev One staticcall that must return exactly one 32-byte word, else `DeliveryUnreadable`.
    function _readStrict(address target, bytes memory cd) private view returns (uint256 word) {
        (bool ok, uint256 raw) = _staticReadWord(target, cd, gasleft());
        if (!ok) revert DeliveryUnreadable();
        return raw;
    }

    function _erc20Balance(address token, address account) private view returns (uint256 bal) {
        (bool ok, uint256 raw) = _staticReadWord(token, abi.encodeWithSelector(0x70a08231, account), gasleft());
        if (!ok) revert PaymentReceiptUnreadable(account);
        return raw;
    }

    function _staticReadWord(address target, bytes memory cd, uint256 gasLimit) private view returns (bool ok, uint256 word) {
        assembly {
            ok := staticcall(gasLimit, target, add(cd, 0x20), mload(cd), 0x00, 0x20)
            if iszero(eq(returndatasize(), 0x20)) { ok := 0 }
            word := mload(0x00)
        }
    }

    /// @dev UV-313 (audit L-04): the holder of a bid's token. Read in `authorizeOrder` (before any transfer) as the
    ///      ERC-721 `ownerOf`, and carried to `validateOrder` (after the transfer, when the holder is gone) in
    ///      transient storage keyed by the order hash, the token and its identifier, so both phases price the same seller. No single holder (an
    ///      ERC-1155, or `ownerOf` failing) or no authorize phase = `address(0)`: no seller discount, which can only
    ///      raise the charge — an order signed with a holder discount then fails instead of under-paying.
    ///      The holder is priced only when the item is an ERC-721 and the holder is the fulfiller who accepts the bid.
    ///      The collection answers `ownerOf` itself, so on any other answer (an ERC-1155 item on a hybrid contract, a
    ///      router or executor fulfilling, a collection naming some discounted wallet) the seller is `address(0)`.
    function _bidSeller(
        bytes32 orderHash,
        address nftContract,
        uint256 tokenId,
        bool isErc721,
        address fulfiller,
        bool validatePhase
    ) private returns (address holder) {
        // UV-313 follow-up: keyed by (order, token, identifier), not the order alone. A partially fillable criteria bid
        // filled twice in one `fulfillAvailableAdvancedOrders` is authorized twice before either validate; an
        // order-only key let the second authorize overwrite the first holder.
        bytes32 slot = keccak256(abi.encode("unvault.zone.bidSeller", orderHash, nftContract, tokenId));
        if (validatePhase) {
            assembly {
                holder := tload(slot)
                tstore(slot, 0)
            }
            return holder;
        }
        if (isErc721) {
            holder = _ownerOf(nftContract, tokenId);
            if (holder != fulfiller) holder = address(0);
        }
        assembly {
            tstore(slot, holder)
        }
    }

    /// @dev Closeout G-12 (verification 2026-09-08): the compact per-side context — the NFT identity and
    ///      the payment currency + total, produced by ONE pass over that side.
    struct _SideScan {
        bool hasNft;
        address nftContract;
        uint256 tokenId;
        ItemType nftItemType;
        uint256 nftAmount;
        address nftRecipient;
        bool hasPayment;
        ItemType paymentItemType;
        address paymentToken;
        uint256 paymentTotal;
    }

    /// @dev One pass over `offer` (`isOffer`) or `consideration`. Every refusal the two former passes
    ///      made is made here, in the same order: a second NFT collection is `MultipleNftContracts`, a
    ///      second NFT item of the same collection is `MultipleNftItems` (per-token royalties cannot be
    ///      split across one aggregate price), and two different payment currencies on one side are
    ///      `MixedPaymentTokens` (the dust-token pricing variant).
    function _scanSide(uint256 len, ZoneParameters calldata zoneParameters, bool isOffer)
        private
        pure
        returns (_SideScan memory scan)
    {
        for (uint256 i = 0; i < len; i++) {
            ItemType t;
            address token;
            uint256 identifier;
            uint256 amount;
            address recipient;
            if (isOffer) {
                SpentItem calldata item = zoneParameters.offer[i];
                (t, token, identifier, amount) = (item.itemType, item.token, item.identifier, item.amount);
            } else {
                ReceivedItem calldata item = zoneParameters.consideration[i];
                (t, token, identifier, amount, recipient) = (item.itemType, item.token, item.identifier, item.amount, item.recipient);
            }
            if (_isNftItem(t)) {
                if (!scan.hasNft) {
                    scan.hasNft = true;
                    scan.nftContract = token;
                    scan.tokenId = identifier; // I-20: criteria resolved before the hooks
                    scan.nftItemType = t;
                    scan.nftAmount = amount;
                    scan.nftRecipient = recipient;
                } else if (token != scan.nftContract) {
                    revert MultipleNftContracts();
                } else {
                    revert MultipleNftItems();
                }
            } else if (t == ItemType.NATIVE || t == ItemType.ERC20) {
                if (!scan.hasPayment) {
                    scan.hasPayment = true;
                    scan.paymentItemType = t;
                    scan.paymentToken = token;
                } else if (t != scan.paymentItemType || token != scan.paymentToken) {
                    revert MixedPaymentTokens();
                }
                scan.paymentTotal += amount;
            }
        }
    }

    /// @dev True for every Seaport item type that carries an NFT (concrete or criteria-based).
    function _isNftItem(ItemType t) private pure returns (bool) {
        return t == ItemType.ERC721 || t == ItemType.ERC1155 || t == ItemType.ERC721_WITH_CRITERIA
            || t == ItemType.ERC1155_WITH_CRITERIA;
    }

    /// @dev G-12: ONE pass over the consideration crediting every payee slot it pays (a payee that
    ///      appears twice in `payees` is credited in both slots — the per-payee semantics of the old
    ///      repeated scans, without the repeated scans).
    function _paidToAll(
        ReceivedItem[] calldata consideration,
        address[] memory payees,
        address paymentToken
    ) internal pure returns (uint256[] memory paid) {
        uint256 n = payees.length;
        paid = new uint256[](n);
        uint256 len = consideration.length;
        for (uint256 i = 0; i < len; i++) {
            ReceivedItem calldata item = consideration[i];
            if ((item.itemType == ItemType.NATIVE || item.itemType == ItemType.ERC20) && item.token == paymentToken) {
                for (uint256 k = 0; k < n; k++) {
                    if (item.recipient == payees[k]) paid[k] += item.amount;
                }
            }
        }
    }

    // ── Closeout I-16: canonical Seaport zone metadata + ERC-165 ─────────────────────────────────

    /// @notice The zone's name and its `extraData` schema. UV-311 (review: "advertise a SIP-7-style schema"): one
    ///         bespoke schema, id `EXTRA_DATA_SCHEMA_ID` = keccak256("UnVaultSignedZone.extraData.v4"), whose metadata is
    ///         `abi.encode(string extraDataLayout, string eip712Type, string domainName, string domainVersion)`.
    function getSeaportMetadata() external pure override returns (string memory name, Schema[] memory schemas) {
        name = "UnVaultSignedZone";
        schemas = new Schema[](1);
        schemas[0] = Schema({
            id: EXTRA_DATA_SCHEMA_ID,
            metadata: abi.encode(EXTRA_DATA_LAYOUT, AUTHORIZATION_TYPE, "UnVaultSignedZone", "4")
        });
    }

    function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
        return interfaceId == type(ZoneInterface).interfaceId || interfaceId == type(IERC165).interfaceId;
    }
}

@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/security/Pausable.sol

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

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@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/Strings.sol

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

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

@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);
}

@openzeppelin/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

ethereum/MarketplaceFeePolicy.sol

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

import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";

/// @notice Read interface both marketplace settlement modules (UnVaultSignedZone,
///         UnVaultAuction) query at settlement. Closeout M-10: one canonical fee
///         identity — default, per-collection override, presence, and recipient —
///         lives here, not duplicated per module, so a collection cannot pay a
///         different protocol fee depending on which settlement primitive is used
///         and an owner update is atomic across every module.
interface IMarketplaceFeePolicy {
    /// @notice Protocol fee (bps of sale price) for a collection: its tier fee if
    ///         set (an explicit 0 is honored as a promo), else the default.
    function collectionFeeBps(address collection) external view returns (uint256);

    /// @notice The default protocol fee (bps) for a collection with no tier fee set.
    function platformFeeBps() external view returns (uint256);

    /// @notice The account that receives the protocol fee.
    function feeRecipient() external view returns (address);

    /// @notice On-platform discounts (founder decision Z-8, 2026-09-14): the marketplace fee
    ///         actually charged when `seller` sells from `collection` — the LOWER of the normal rate
    ///         (`collectionFeeBps`) and every discount rate that applies (chain, collection, seller).
    function effectiveFeeBps(address collection, address seller) external view returns (uint256);

    /// @notice The protocol share of a royalty charged on our marketplace for an UnVault collection /
    ///         echo — the LOWER of `standardBps` (read live from the collection's splitter by the
    ///         caller) and every protocol-share discount that applies (chain, collection, seller).
    function effectiveProtocolShareBps(address collection, address seller, uint256 standardBps)
        external
        view
        returns (uint256);
}

/// @notice Closeout M-10 (EVM half): the single shared fee-policy registry. Both
///         UnVaultSignedZone and UnVaultAuction hold an immutable reference to one
///         instance and read the default fee, per-collection tier override, and
///         fee recipient from it. Previously each module carried its own
///         independent copy of all three, so the same collection could be charged
///         a different protocol fee on the listing rail vs the auction rail, and a
///         fee change had to be applied to each module separately (non-atomic).
///         The registrar now sets a collection's tier fee ONCE here and it governs
///         every rail identically.
contract MarketplaceFeePolicy is IMarketplaceFeePolicy, Ownable2Step {
    /// @notice Upper bound on any protocol fee (default or per-collection): 100% of the sale price.
    /// @dev Founder decision 2026-09-14 (configurability round): the former 10% ceiling is removed —
    ///      protocol fees are configurable 0–100% by the owner (founder dashboard). The settlement
    ///      modules keep `fee + royalty <= price` per sale: `UnVaultSignedZone` refuses such an order
    ///      and `UnVaultAuction` trims the royalty (it holds escrowed assets and must not revert).
    uint256 public constant MAX_FEE_BPS = 10_000;

    /// @inheritdoc IMarketplaceFeePolicy
    uint256 public platformFeeBps;

    /// @notice The fee recipient (protocol treasury).
    address public feeRecipient;

    /// @dev Tier-driven per-collection fee (bps), keyed by NFT contract. `set`
    ///      distinguishes an explicit 0% (promo) from "unset → use platformFeeBps".
    /// @dev Closeout G-15: ONE slot per collection. `0` = unset (fall back to `platformFeeBps`);
    ///      `feeBps + 1` = configured, so an explicit 0% promotion is stored as `1`. `MAX_FEE_BPS + 1`
    ///      (10_001) still fits a uint16. One SSTORE per set, one SLOAD per lookup.
    mapping(address => uint16) private _collectionFee;

    // ── Fee-increase delay (Hashlock 2026-09-16, "Option B") ────────────────────────────────────
    //
    // Fee DECREASES apply immediately. Fee INCREASES are scheduled and only take effect once
    // `feeIncreaseDelay` has elapsed, announced by an event carrying old value, new value and the
    // effective time — so a misused owner key cannot raise fees without everyone seeing it coming,
    // and open Seaport listings (whose consideration is fixed at signing while the zone prices the
    // fee at fill) get a scheduled re-list window instead of reverting `InvalidPlatformFeePayout`.
    //
    // The delay is a ONE-WAY RATCHET: `0` (immediate, the deploy default so test fixtures and the
    // constructor are unchanged) can be raised by the owner up to `MAX_FEE_INCREASE_DELAY`, never
    // lowered — a lowerable delay would let the same key defeat the timelock in one tx. Production
    // deploys set `FEE_INCREASE_DELAY` (2 days) before handing ownership to the founder multisig.
    // Applying a scheduled increase is permissionless once due.

    /// @notice Hard ceiling on `feeIncreaseDelay` so a mistyped value cannot freeze fee changes.
    uint64 public constant MAX_FEE_INCREASE_DELAY = 30 days;

    /// @notice Seconds a fee INCREASE waits before it can be applied. `0` = immediate.
    uint64 public feeIncreaseDelay;

    struct PendingFee {
        uint16 bps;
        uint64 effectiveAt; // 0 = nothing pending
    }

    /// @notice Scheduled platform-fee increase, if any (`effectiveAt == 0` means none).
    PendingFee public pendingPlatformFee;

    /// @notice Scheduled per-collection fee increase, if any (`effectiveAt == 0` means none).
    mapping(address => PendingFee) public pendingCollectionFee;

    event PlatformFeeUpdated(uint256 oldBps, uint256 newBps);
    event CollectionFeeBpsSet(address indexed collection, uint16 feeBps);
    event FeeRecipientUpdated(address oldRecipient, address newRecipient);
    event FeeIncreaseDelayUpdated(uint64 oldDelay, uint64 newDelay);
    event PlatformFeeIncreaseScheduled(uint256 oldBps, uint256 newBps, uint64 effectiveAt);
    event PlatformFeeIncreaseCancelled(uint256 newBps);
    event CollectionFeeIncreaseScheduled(address indexed collection, uint256 oldBps, uint16 newBps, uint64 effectiveAt);
    event CollectionFeeIncreaseCancelled(address indexed collection, uint16 newBps);

    error InvalidRecipient();
    error InvalidFeeBps();
    error InvalidDelay();
    error NoPendingFee();
    error DelayNotElapsed(uint64 effectiveAt);

    /// @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();

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

    /// @param initialOwner UV-313 (review H-4): the owner is explicit, never the deployer by default, so the contract can
    ///        later be deployed through a CREATE2 factory (the CreateX tooling comes with UV-315; no script uses it yet),
    ///        where the deployer would be the factory contract. Ownership is two-step (Ownable2Step);
    ///        the live policy was one-step `Ownable` while the other marketplace contracts were two-step.
    constructor(address _feeRecipient, uint256 _platformFeeBps, address initialOwner) {
        if (initialOwner == address(0)) revert InvalidRecipient();
        _transferOwnership(initialOwner);
        if (_feeRecipient == address(0)) revert InvalidRecipient();
        if (_platformFeeBps > MAX_FEE_BPS) revert InvalidFeeBps();
        feeRecipient = _feeRecipient;
        platformFeeBps = _platformFeeBps;
    }

    /// @notice Raise the fee-increase delay (one-way ratchet, max `MAX_FEE_INCREASE_DELAY`).
    function setFeeIncreaseDelay(uint64 newDelay) external onlyOwner {
        if (newDelay <= feeIncreaseDelay || newDelay > MAX_FEE_INCREASE_DELAY) revert InvalidDelay();
        uint64 old = feeIncreaseDelay;
        feeIncreaseDelay = newDelay;
        emit FeeIncreaseDelayUpdated(old, newDelay);
    }

    /// @notice Set the default protocol fee. A decrease (or any change while the delay is 0)
    ///         applies now and clears any scheduled increase; an increase is scheduled and must
    ///         be applied via `applyPlatformFee` once `feeIncreaseDelay` has elapsed.
    function setPlatformFee(uint256 newBps) external onlyOwner {
        if (newBps > MAX_FEE_BPS) revert InvalidFeeBps();
        uint256 old = platformFeeBps;
        if (newBps <= old || feeIncreaseDelay == 0) {
            if (pendingPlatformFee.effectiveAt != 0) {
                emit PlatformFeeIncreaseCancelled(pendingPlatformFee.bps);
                delete pendingPlatformFee;
            }
            platformFeeBps = newBps;
            emit PlatformFeeUpdated(old, newBps);
            return;
        }
        uint64 effectiveAt = uint64(block.timestamp) + feeIncreaseDelay;
        pendingPlatformFee = PendingFee({bps: uint16(newBps), effectiveAt: effectiveAt});
        emit PlatformFeeIncreaseScheduled(old, newBps, effectiveAt);
    }

    /// @notice Apply a scheduled platform-fee increase once its delay has elapsed. Permissionless.
    function applyPlatformFee() external {
        PendingFee memory p = pendingPlatformFee;
        if (p.effectiveAt == 0) revert NoPendingFee();
        if (block.timestamp < p.effectiveAt) revert DelayNotElapsed(p.effectiveAt);
        delete pendingPlatformFee;
        uint256 old = platformFeeBps;
        platformFeeBps = p.bps;
        emit PlatformFeeUpdated(old, p.bps);
    }

    /// @notice Cancel a scheduled platform-fee increase.
    function cancelPlatformFeeIncrease() external onlyOwner {
        PendingFee memory p = pendingPlatformFee;
        if (p.effectiveAt == 0) revert NoPendingFee();
        delete pendingPlatformFee;
        emit PlatformFeeIncreaseCancelled(p.bps);
    }

    /// @notice Set the tier-driven protocol fee (bps of sale price) for a
    ///         collection. Called by the owner (registrar) at registration with
    ///         the creator's tier protocol fee. An explicit 0 is honored (promo);
    ///         an unset collection falls back to `platformFeeBps`.
    /// @dev The increase test compares against the collection's CURRENT effective fee
    ///      (`collectionFeeBps`, i.e. the platform default when unset): setting a value at or
    ///      below it applies now; a higher value is scheduled for `applyCollectionFeeBps`.
    function setCollectionFeeBps(address collection, uint16 feeBps) external onlyOwner {
        if (collection == address(0)) revert InvalidRecipient();
        if (feeBps > MAX_FEE_BPS) revert InvalidFeeBps();
        uint256 current = collectionFeeBps(collection);
        if (feeBps <= current || feeIncreaseDelay == 0) {
            PendingFee storage pend = pendingCollectionFee[collection];
            if (pend.effectiveAt != 0) {
                emit CollectionFeeIncreaseCancelled(collection, pend.bps);
                delete pendingCollectionFee[collection];
            }
            _collectionFee[collection] = feeBps + 1; // G-15: encoded presence
            emit CollectionFeeBpsSet(collection, feeBps);
            return;
        }
        uint64 effectiveAt = uint64(block.timestamp) + feeIncreaseDelay;
        pendingCollectionFee[collection] = PendingFee({bps: feeBps, effectiveAt: effectiveAt});
        emit CollectionFeeIncreaseScheduled(collection, current, feeBps, effectiveAt);
    }

    /// @notice Apply a scheduled per-collection fee increase once due. Permissionless.
    function applyCollectionFeeBps(address collection) external {
        PendingFee memory p = pendingCollectionFee[collection];
        if (p.effectiveAt == 0) revert NoPendingFee();
        if (block.timestamp < p.effectiveAt) revert DelayNotElapsed(p.effectiveAt);
        delete pendingCollectionFee[collection];
        _collectionFee[collection] = p.bps + 1;
        emit CollectionFeeBpsSet(collection, p.bps);
    }

    /// @notice Cancel a scheduled per-collection fee increase.
    function cancelCollectionFeeIncrease(address collection) external onlyOwner {
        PendingFee memory p = pendingCollectionFee[collection];
        if (p.effectiveAt == 0) revert NoPendingFee();
        delete pendingCollectionFee[collection];
        emit CollectionFeeIncreaseCancelled(collection, p.bps);
    }

    /// @inheritdoc IMarketplaceFeePolicy
    function collectionFeeBps(address collection) public view returns (uint256) {
        uint16 v = _collectionFee[collection];
        return v == 0 ? platformFeeBps : uint256(v - 1);
    }

    /// @notice Whether a collection carries an explicit tier fee (vs the default).
    function collectionFeeIsSet(address collection) external view returns (bool) {
        return _collectionFee[collection] != 0;
    }

    // ── On-platform discounts (founder decision Z-8, 2026-09-14) ─────────────────────────────────
    //
    // Two independent discount families, each settable at chain level, per collection and per SELLER
    // wallet, 0–100%, owner-only, effective immediately:
    //   FEE      — lowers the marketplace fee. The normal rate is the collection's own fee if set,
    //              else the default; the default itself never competes as a discount, so a
    //              collection's configured fee is never undercut by a lower default.
    //   PROTOCOL — lowers the protocol SHARE of a royalty on UnVault collections / echoes. The
    //              standard share is the splitter's live `protocolFeeBps`; the creator's cut is never
    //              touched. External collections have no protocol share, so this family does not apply.
    // The charged rate is always the LOWEST applicable one, so a discount can only lower a charge.
    // Seller-signed caps in the settlement modules still bound what an order may pay; raising or
    // clearing a discount can make a signed order refuse (zone) or be trimmed (auction), never overpay.
    // Storage (G-15 pattern): `rate + 1` = set, 0 = unset — an explicit 0% discount is stored as 1.

    uint8 public constant DISCOUNT_FEE = 0;
    uint8 public constant DISCOUNT_PROTOCOL = 1;

    uint16[2] private _chainDiscount;
    mapping(address collection => uint16)[2] private _collectionDiscount;
    mapping(address seller => uint16)[2] private _sellerDiscount;

    event ChainDiscountSet(uint8 indexed family, uint16 rateBps);
    event ChainDiscountCleared(uint8 indexed family);
    event CollectionDiscountSet(uint8 indexed family, address indexed collection, uint16 rateBps);
    event CollectionDiscountCleared(uint8 indexed family, address indexed collection);
    event SellerDiscountSet(uint8 indexed family, address indexed seller, uint16 rateBps);
    event SellerDiscountCleared(uint8 indexed family, address indexed seller);

    error InvalidDiscountFamily();

    modifier validDiscount(uint8 family, uint16 rateBps) {
        if (family > DISCOUNT_PROTOCOL) revert InvalidDiscountFamily();
        if (rateBps > MAX_FEE_BPS) revert InvalidFeeBps();
        _;
    }

    // ── UV-313 (audit L-01): raising a discount's rate or clearing it RAISES the effective fee / protocol share,
    //    so it waits `feeIncreaseDelay` like any other increase (it used to apply at once, so a base-fee raise could
    //    be hidden behind a discount and released in one transaction). Setting a new discount or lowering one still
    //    applies immediately. A pending raise is announced, applied permissionlessly once due, or cancelled.
    //    Levels: 0 = chain (target 0), 1 = collection, 2 = seller.
    uint8 public constant LEVEL_CHAIN = 0;
    uint8 public constant LEVEL_COLLECTION = 1;
    uint8 public constant LEVEL_SELLER = 2;

    struct PendingDiscount {
        uint16 encoded; // the value to write: `rate + 1`, or 0 = clear
        uint64 effectiveAt; // 0 = nothing pending
    }

    /// @notice A scheduled discount raise or removal, keyed by `discountKey(family, level, target)`.
    mapping(bytes32 => PendingDiscount) public pendingDiscount;

    event DiscountRaiseScheduled(uint8 indexed family, uint8 indexed level, address indexed target, bool clear, uint16 rateBps, uint64 effectiveAt);
    event DiscountRaiseCancelled(uint8 indexed family, uint8 indexed level, address indexed target);

    error InvalidDiscountLevel();

    function discountKey(uint8 family, uint8 level, address target) public pure returns (bytes32) {
        return keccak256(abi.encode(family, level, target));
    }

    function _discountSlot(uint8 family, uint8 level, address target) private view returns (uint16) {
        if (level == LEVEL_CHAIN) return _chainDiscount[family];
        if (level == LEVEL_COLLECTION) return _collectionDiscount[family][target];
        return _sellerDiscount[family][target];
    }

    function _writeDiscount(uint8 family, uint8 level, address target, uint16 encoded) private {
        if (level == LEVEL_CHAIN) {
            _chainDiscount[family] = encoded;
            if (encoded == 0) emit ChainDiscountCleared(family);
            else emit ChainDiscountSet(family, encoded - 1);
        } else if (level == LEVEL_COLLECTION) {
            _collectionDiscount[family][target] = encoded;
            if (encoded == 0) emit CollectionDiscountCleared(family, target);
            else emit CollectionDiscountSet(family, target, encoded - 1);
        } else {
            _sellerDiscount[family][target] = encoded;
            if (encoded == 0) emit SellerDiscountCleared(family, target);
            else emit SellerDiscountSet(family, target, encoded - 1);
        }
    }

    /// @dev Apply now when the change cannot raise a charge (a new discount, a lower rate) or there is no delay;
    ///      otherwise schedule it. Any pending change for the same slot is replaced.
    function _changeDiscount(uint8 family, uint8 level, address target, uint16 encoded) private {
        uint16 current = _discountSlot(family, level, target);
        // A raise: clearing a set discount, or a higher rate than the one set.
        bool raises = current != 0 && (encoded == 0 || encoded > current);
        bytes32 key = discountKey(family, level, target);
        if (pendingDiscount[key].effectiveAt != 0) {
            delete pendingDiscount[key];
            emit DiscountRaiseCancelled(family, level, target);
        }
        if (!raises || feeIncreaseDelay == 0) {
            _writeDiscount(family, level, target, encoded);
            return;
        }
        uint64 effectiveAt = uint64(block.timestamp) + feeIncreaseDelay;
        pendingDiscount[key] = PendingDiscount({encoded: encoded, effectiveAt: effectiveAt});
        emit DiscountRaiseScheduled(family, level, target, encoded == 0, encoded == 0 ? 0 : encoded - 1, effectiveAt);
    }

    function setChainDiscount(uint8 family, uint16 rateBps) external onlyOwner validDiscount(family, rateBps) {
        _changeDiscount(family, LEVEL_CHAIN, address(0), rateBps + 1);
    }

    function clearChainDiscount(uint8 family) external onlyOwner validDiscount(family, 0) {
        _changeDiscount(family, LEVEL_CHAIN, address(0), 0);
    }

    function setCollectionDiscount(uint8 family, address collection, uint16 rateBps)
        external
        onlyOwner
        validDiscount(family, rateBps)
    {
        if (collection == address(0)) revert InvalidRecipient();
        _changeDiscount(family, LEVEL_COLLECTION, collection, rateBps + 1);
    }

    function clearCollectionDiscount(uint8 family, address collection) external onlyOwner validDiscount(family, 0) {
        _changeDiscount(family, LEVEL_COLLECTION, collection, 0);
    }

    function setSellerDiscount(uint8 family, address seller, uint16 rateBps)
        external
        onlyOwner
        validDiscount(family, rateBps)
    {
        if (seller == address(0)) revert InvalidRecipient();
        _changeDiscount(family, LEVEL_SELLER, seller, rateBps + 1);
    }

    function clearSellerDiscount(uint8 family, address seller) external onlyOwner validDiscount(family, 0) {
        _changeDiscount(family, LEVEL_SELLER, seller, 0);
    }

    /// @notice Apply a scheduled discount raise or removal once due. Permissionless.
    function applyDiscountChange(uint8 family, uint8 level, address target) external {
        if (level > LEVEL_SELLER) revert InvalidDiscountLevel();
        bytes32 key = discountKey(family, level, target);
        PendingDiscount memory p = pendingDiscount[key];
        if (p.effectiveAt == 0) revert NoPendingFee();
        if (block.timestamp < p.effectiveAt) revert DelayNotElapsed(p.effectiveAt);
        delete pendingDiscount[key];
        _writeDiscount(family, level, target, p.encoded);
    }

    /// @notice Cancel a scheduled discount raise or removal.
    function cancelDiscountChange(uint8 family, uint8 level, address target) external onlyOwner {
        bytes32 key = discountKey(family, level, target);
        if (pendingDiscount[key].effectiveAt == 0) revert NoPendingFee();
        delete pendingDiscount[key];
        emit DiscountRaiseCancelled(family, level, target);
    }

    /// @notice The configured discount rates for a (family, collection, seller) — `set == false`
    ///         means no discount at that level.
    function discountsOf(uint8 family, address collection, address seller)
        external
        view
        returns (bool chainSet, uint256 chainBps, bool collectionSet, uint256 collectionBps, bool sellerSet, uint256 sellerBps)
    {
        if (family > DISCOUNT_PROTOCOL) revert InvalidDiscountFamily();
        uint16 c = _chainDiscount[family];
        uint16 k = _collectionDiscount[family][collection];
        uint16 s = _sellerDiscount[family][seller];
        return (c != 0, c == 0 ? 0 : c - 1, k != 0, k == 0 ? 0 : k - 1, s != 0, s == 0 ? 0 : s - 1);
    }

    /// @dev min(normal, every set discount of `family` for (collection, seller)).
    function _lowest(uint8 family, address collection, address seller, uint256 normal) private view returns (uint256 r) {
        r = normal;
        uint16 c = _chainDiscount[family];
        if (c != 0 && c - 1 < r) r = c - 1;
        uint16 k = _collectionDiscount[family][collection];
        if (k != 0 && k - 1 < r) r = k - 1;
        uint16 s = _sellerDiscount[family][seller];
        if (s != 0 && s - 1 < r) r = s - 1;
    }

    /// @inheritdoc IMarketplaceFeePolicy
    function effectiveFeeBps(address collection, address seller) external view returns (uint256) {
        return _lowest(DISCOUNT_FEE, collection, seller, collectionFeeBps(collection));
    }

    /// @inheritdoc IMarketplaceFeePolicy
    function effectiveProtocolShareBps(address collection, address seller, uint256 standardBps)
        external
        view
        returns (uint256)
    {
        return _lowest(DISCOUNT_PROTOCOL, collection, seller, standardBps);
    }

    function setFeeRecipient(address newRecipient) external onlyOwner {
        if (newRecipient == address(0)) revert InvalidRecipient();
        address old = feeRecipient;
        feeRecipient = newRecipient;
        emit FeeRecipientUpdated(old, newRecipient);
    }
}

ethereum/UnVaultRoyaltyRegistry.sol

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

import "@openzeppelin/contracts/access/Ownable.sol";

/// @title UnVault Royalty Registry
/// @notice Single source of truth for per-collection royalty splits used by
///         `UnVaultMarketplace`, `UnVaultAuction`, and any future UnVault settlement
///         surface. Up to `MAX_ROYALTY_RECEIVERS` receivers per collection, total
///         `<= MAX_ROYALTY_BPS` (100% — founder decision 2026-09-14: creator royalties are configurable
///         0–100%; the only bound kept is that the configured total cannot exceed the sale price).
///
///         A collection with NO registered split falls back to the collection's own ERC-2981
///         `royaltyInfo`, clamped to `MAX_ROYALTY_BPS` (the sale price), then to Limit Break's backfill. The quote
///         comes back 0% (`SOURCE_NONE`) only when ERC-2981 answers zero or the collection's ERC-165 explicitly denies
///         ERC-2981; a read that cannot be trusted is `SOURCE_UNKNOWN` and the plain quotes revert (UV-1103). The
///         fallback exists so external collections brought into
///         the marketplace still earn their royalties instead of silently being paid nothing — see
///         the note at the fallback itself. (This header previously said "there is no ERC-2981
///         fallback, by design", which stopped being true when the fallback was added on
///         2026-07-30 and was flagged as stale in the closeout review §10.10.)
/// @dev Configuration is gated on-chain by the collection's `Ownable.owner()`. The
///      registry itself does NOT move funds; it only stores the configuration and
///      exposes views that callers iterate to perform the distribution.
contract UnVaultRoyaltyRegistry {
    /// @notice Basis-point denominator (100% = 10_000).
    uint256 public constant BPS_DENOMINATOR = 10_000;
    /// @notice Hard cap on the total royalty bps that can be configured per collection: 100%.
    /// @dev Founder decision 2026-09-14 (configurability round): the former 10% ceiling is removed —
    ///      creator royalties are configurable 0–100%. What stays is solvency: a collection's total can
    ///      never exceed the sale price, and every settlement surface separately keeps
    ///      `protocol fee + royalty <= price` (the zone refuses, the auction trims the royalty).
    ///      The value is read back by `UnVaultSignedZone` / `UnVaultAuction` at construction (Closeout
    ///      L-24) as a generation check, so a pre-2026-09-14 (10%) registry cannot be wired to them.
    uint256 public constant MAX_ROYALTY_BPS = 10_000;
    /// @notice Maximum number of receivers per collection.
    uint256 public constant MAX_ROYALTY_RECEIVERS = 3;

    /// @dev `bps` is in basis points of sale price.
    struct RoyaltySplit {
        address receiver;
        uint96 bps;
    }

    /// @dev Stored splits per collection. Empty / cleared == NO override: quotes fall back to the
    ///      collection's own ERC-2981 `royaltyInfo` (clamped to the sale price), and only a collection with no
    ///      usable ERC-2981 answer quotes 0% (Closeout I-02).
    mapping(address => RoyaltySplit[]) private _splits;
    /// @notice Sum of bps across the configured splits (0 = no override configured; the quote then
    ///         resumes the ERC-2981 fallback — Closeout I-02). G-22: computed from the bounded
    ///         split array (≤ 3 entries) rather than persisted beside it.
    function totalBpsOf(address nftContract) public view returns (uint256 total) {
        RoyaltySplit[] storage splits = _splits[nftContract];
        uint256 len = splits.length;
        for (uint256 i = 0; i < len; i++) {
            total += uint256(splits[i].bps);
        }
    }

    /// @notice G-17: purpose-specific errors (were revert strings).
    error InvalidContract();
    error LengthMismatch();
    error ReceiverCountOutOfRange();
    error SplitterAuthoritative();
    error ZeroReceiver();
    error ZeroBps();
    error DuplicateReceiver();
    error TotalBpsExceedsCap();
    error NotCollectionOwner();
    error CollectionNotOwnable();
    /// @notice UV-312 (review M-3 / Limit Break point 2): a royalty read failed because the CALLER left it too little
    ///         gas (the 1/64 rule), not because the collection has no royalty. The sale must stop; a retry with more
    ///         gas reads it properly. A fulfiller can therefore never starve the read into "no royalty".
    error RoyaltyReadStarved();
    /// @notice The collection's royalty could not be read (`SOURCE_UNKNOWN`). The plain quotes refuse instead of quoting 0%,
    ///         so a settlement that prices through them (the auction) stops rather than paying no royalty.
    error RoyaltyUnknown(address nftContract);

    // ── UV-312: where a quote came from. A settlement surface that must pay the creator refuses NONE and UNKNOWN. ──
    uint8 public constant SOURCE_NONE = 0; // no royalty: ERC-2981 answered zero, or ERC-165 explicitly denies ERC-2981 (no backfill)
    uint8 public constant SOURCE_SPLITTER = 1; // an UnVault wrapper's pinned RoyaltySplitter
    uint8 public constant SOURCE_CONFIGURED = 2; // a split configured here by the collection's owner/admin
    uint8 public constant SOURCE_ERC2981 = 3; // the collection's own royaltyInfo
    uint8 public constant SOURCE_LB_BACKFILL = 4; // Limit Break's CollectionSettingsRegistry royalty backfill
    uint8 public constant SOURCE_UNKNOWN = 5; // ERC-2981 could not answer and is not denied: malformed answer, any revert (empty included), out of its gas (no backfill)

    // ── UV-312 (andskur, finding 1): how a collection's ERC-2981 read ended ──
    uint8 private constant READ_VALUE = 0; // a receiver and a non-zero amount
    uint8 private constant READ_ZERO = 1; // answered: zero receiver or zero amount
    uint8 private constant READ_UNSUPPORTED = 2; // a failed read (not out of gas) on a collection whose supportsInterface(0x2a55205a) == false
    uint8 private constant READ_UNKNOWN = 3; // malformed answer, out of its gas, or a failed read (empty revert included) not denied by ERC-165

    /// @notice UV-312 (review §8a, Q10): gas forwarded to a collection's `royaltyInfo` (was 30,000) and to the wrapper probe
    ///         `royaltySplitter()` (was 20,000). Bounded on purpose: the auction escrows assets and must stay settleable.
    /// @dev    No separate gas RESERVE constant: when less than `ROYALTY_READ_GAS` is available the EVM itself forwards only
    ///         63/64 of what is left (EIP-150) and keeps 1/64 for this frame, which is enough to run the starvation check
    ///         and revert. That 1/64 is the reserve. The check `gasleft() <= forwarded / 63` after a failed read then
    ///         distinguishes "the caller ran short" (revert `RoyaltyReadStarved`) from "the collection used up its 100,000"
    ///         (`SOURCE_UNKNOWN`): with enough gas the remainder after a 100,000 failure is far above 100,000 / 63 ≈ 1,587.
    uint256 public constant ROYALTY_READ_GAS = 100_000;
    uint256 public constant SPLITTER_PROBE_GAS = 50_000;
    /// @notice Limit Break's Payment Processor v3 CollectionSettingsRegistry (`0x9A1D001A842c5e6C74b33F2aeEdEc07F0Cb20BC4`,
    ///         the same address on all seven chains, code read 2026-10-14), set at deployment; zero = no fallback. Its
    ///         per-collection royalty backfill (receiver + numerator, set by the collection's owner or AccessControl admin)
    ///         is the on-chain fallback when ERC-2981 gives no royalty. An address without code is treated as zero.
    address public immutable lbSettingsRegistry;

    constructor(address lbSettingsRegistry_) {
        lbSettingsRegistry = lbSettingsRegistry_;
    }
    uint256 public constant LB_READ_GAS = 100_000;

    /// @notice Emitted when a collection owner configures (or replaces) splits.
    event CollectionRoyaltiesUpdated(
        address indexed nftContract,
        address indexed updatedBy,
        address[] receivers,
        uint96[] bps,
        uint256 totalBps
    );
    /// @notice Emitted when a collection owner clears the configured splits.
    event CollectionRoyaltiesCleared(address indexed nftContract, address indexed updatedBy);

    /// @notice Configure (or replace) the royalty split for a collection.
    /// @dev Caller MUST be the collection's `Ownable.owner()`. Up to
    ///      `MAX_ROYALTY_RECEIVERS` entries, each with non-zero `bps`, with
    ///      `sum(bps) <= MAX_ROYALTY_BPS` (100%).
    function setCollectionRoyalties(
        address nftContract,
        address[] calldata receivers,
        uint96[] calldata bpsAmounts
    ) external {
        if (nftContract == address(0)) revert InvalidContract();
        if (receivers.length != bpsAmounts.length) revert LengthMismatch();
        if (receivers.length < 1 || receivers.length > MAX_ROYALTY_RECEIVERS) revert ReceiverCountOutOfRange();
        _requireCollectionOwner(nftContract, msg.sender);
        // Closeout M-11(d): a UnVault wrapper's canonical RoyaltySplitter carries BOTH the creator
        // and the PROTOCOL leg and is authoritative. A creator must not be able to register a
        // registry split that drops the protocol leg, so overrides are refused for wrappers; their
        // royalty always resolves through the pinned splitter (see quoteRoyaltyForToken). External
        // (non-wrapper) collections are unaffected.
        // The guard keys on "this is a wrapper", not "a splitter is pinned": a wrapper of an original without
        // ERC-2981 never gets a splitter, its `royaltyInfo` carries the protocol leg alone, and a creator override
        // would take that leg. So any contract whose `royaltySplitter()` answers (even with zero) is refused. A
        // creator's way in stays the bridge's splitter initialisation, which keeps the protocol leg.
        (bool answered,) = _probeSplitter(nftContract);
        if (answered) revert SplitterAuthoritative();

        delete _splits[nftContract];

        uint256 totalBps;
        for (uint256 i = 0; i < receivers.length; i++) {
            if (receivers[i] == address(0)) revert ZeroReceiver();
            if (bpsAmounts[i] == 0) revert ZeroBps();
            for (uint256 j = 0; j < i; j++) {
                if (receivers[j] == receivers[i]) revert DuplicateReceiver();
            }
            totalBps += uint256(bpsAmounts[i]);
            _splits[nftContract].push(RoyaltySplit({receiver: receivers[i], bps: bpsAmounts[i]}));
        }
        if (totalBps > MAX_ROYALTY_BPS) revert TotalBpsExceedsCap();
        emit CollectionRoyaltiesUpdated(nftContract, msg.sender, receivers, bpsAmounts, totalBps);
    }

    /// @notice Remove the configured override for a collection — quotes RESUME the collection's own
    ///         ERC-2981 fallback (Closeout I-02); this is not a 0% royalty.
    /// @dev Caller MUST be the collection's `Ownable.owner()`.
    function clearCollectionRoyalties(address nftContract) external {
        if (nftContract == address(0)) revert InvalidContract();
        _requireCollectionOwner(nftContract, msg.sender);
        delete _splits[nftContract];
        emit CollectionRoyaltiesCleared(nftContract, msg.sender);
    }

    /// @notice Read the configured splits for a collection.
    /// @return receivers  array of receiver addresses, length 0 when unconfigured
    /// @return bps        array of basis-point shares, parallel to `receivers`
    /// @return totalBps   sum of bps (0 when unconfigured)
    function getCollectionRoyalties(address nftContract)
        external
        view
        returns (address[] memory receivers, uint96[] memory bps, uint256 totalBps)
    {
        RoyaltySplit[] storage splits = _splits[nftContract];
        uint256 len = splits.length;
        receivers = new address[](len);
        bps = new uint96[](len);
        for (uint256 i = 0; i < len; i++) {
            receivers[i] = splits[i].receiver;
            bps[i] = splits[i].bps;
            totalBps += uint256(splits[i].bps);
        }
    }

    /// @notice Compute the per-receiver royalty amounts for a hypothetical `salePrice`.
    /// @dev Settlement contracts (marketplace, auction) call this and then distribute the
    ///      amounts via their own pull-payment escrow logic. Enforces
    ///      `total <= MAX_ROYALTY_BPS * salePrice` at call time as defense-in-depth against bps drift.
    /// @dev Closeout I-02 (verification pass 2026-09-09): this said "Returns empty arrays when no
    ///      splits are configured", which was the last surviving statement of the belief the finding
    ///      is about — and the false one. Removing an override does NOT mean zero royalty: with no
    ///      stored split the quote falls back to the collection's ERC-2981 `royaltyInfo` and returns a
    ///      ONE-ELEMENT array (and, for a recognised UnVault wrapper, the address-pinned splitter per
    ///      M-11 (d)). Empty arrays come back only when the collection has no override AND no
    ///      ERC-2981 receiver, or when `salePrice` is zero.
    function quoteRoyalty(address nftContract, uint256 salePrice)
        external
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount)
    {
        return quoteRoyaltyForToken(nftContract, 0, salePrice);
    }

    /// @notice Token-aware variant of {quoteRoyalty}.
    /// @dev Identical to {quoteRoyalty} for a collection with configured splits (they are
    ///      collection-wide). It only differs on the ERC-2981 fallback, where `royaltyInfo` is a
    ///      PER-TOKEN view: quoting every token as id 0 silently mis-prices any collection that varies
    ///      royalties by token. Callers that know the concrete token id should use this one.
    ///      Closeout I-20 (verification 2026-09-08): token id 0 is NOT a collection-level input - it is a
    ///      concrete token id like any other, and on an ERC-2981 collection with per-token rates it
    ///      returns TOKEN 0 royalty, not a collection-wide one. A criteria (collection-level) order must
    ///      quote a token id it will actually settle; there is no collection-level ERC-2981 query.
    ///      A royalty that cannot be read (`SOURCE_UNKNOWN`) reverts `RoyaltyUnknown`; it is never quoted as 0%. No
    ///      royalty at all (`SOURCE_NONE`) still quotes empty arrays. {quoteRoyaltyWithSource} returns both cases.
    /// @param nftContract the collection being sold
    /// @param tokenId     the concrete token id being sold (I-20: there is no collection-level id)
    /// @param salePrice   the sale price the royalty is a percentage of
    function quoteRoyaltyForToken(address nftContract, uint256 tokenId, uint256 salePrice)
        public
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount)
    {
        uint8 source;
        (receivers, amounts, totalAmount, source) = _quote(nftContract, tokenId, salePrice);
        if (source == SOURCE_UNKNOWN) revert RoyaltyUnknown(nftContract);
    }

    /// @notice UV-312: {quoteRoyaltyForToken} plus WHERE the royalty came from (`SOURCE_*`). The zone uses this to refuse a
    ///         sale with no royalty source (`SOURCE_NONE`) or an unreadable one (`SOURCE_UNKNOWN`) instead of settling at
    ///         0%. Order: wrapper splitter → configured split → ERC-2981 → Limit Break backfill. Quotes at `salePrice` (the
    ///         real price). Reverts `RoyaltyReadStarved` when the caller's gas, not the collection, failed a read.
    function quoteRoyaltyWithSource(address nftContract, uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount, uint8 source)
    {
        return _quote(nftContract, tokenId, salePrice);
    }

    function _one(address receiver, uint256 amount, uint256 salePrice, uint8 source)
        private
        pure
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount, uint8 src)
    {
        uint256 cap = (salePrice * MAX_ROYALTY_BPS) / BPS_DENOMINATOR;
        if (amount > cap) amount = cap; // clamp untrusted external answers to the sale price, never revert the sale
        receivers = new address[](1);
        amounts = new uint256[](1);
        receivers[0] = receiver;
        amounts[0] = amount;
        return (receivers, amounts, amount, source);
    }

    function _quote(address nftContract, uint256 tokenId, uint256 salePrice)
        internal
        view
        returns (address[] memory receivers, uint256[] memory amounts, uint256 totalAmount, uint8 source)
    {
        if (salePrice == 0) {
            return (new address[](0), new uint256[](0), 0, SOURCE_NONE);
        }
        // Closeout M-11(d): for a recognized UnVault wrapper the canonical RoyaltySplitter (creator + protocol legs) is
        // authoritative and non-overridable: route the wrapper's ERC-2981 amount to the PINNED splitter.
        address unvaultSplitter = _unvaultSplitter(nftContract);
        if (unvaultSplitter != address(0)) {
            (uint8 wread,, uint256 wamount) = _staticRoyaltyInfo(nftContract, tokenId, salePrice);
            if (wread == READ_UNKNOWN) return (new address[](0), new uint256[](0), 0, SOURCE_UNKNOWN);
            if (wread != READ_VALUE || wamount == 0) return (new address[](0), new uint256[](0), 0, SOURCE_NONE);
            return _one(unvaultSplitter, wamount, salePrice, SOURCE_SPLITTER);
        }
        // G-22: "no override configured" == an empty split array (every stored share is nonzero).
        if (_splits[nftContract].length == 0) {
            // FREEZE AUDIT 2026-07-30 — ERC-2981 FALLBACK (external collections earn their royalties). Closeout M-16: read
            // with a bounded staticcall into a fixed buffer that requires EXACTLY the canonical (address,uint256) return.
            // UV-312: a failed read is UNKNOWN (never 0%), a starved read reverts, and Limit Break's backfill is tried
            // before giving up.
            (uint8 read, address receiver, uint256 amount) = _staticRoyaltyInfo(nftContract, tokenId, salePrice);
            if (read == READ_VALUE) return _one(receiver, amount, salePrice, SOURCE_ERC2981);
            // Limit Break's backfill, applied as their Payment Processor v3 applies it (`_computePaymentSplits`): when
            // the ERC-2981 read fails OR returns a zero amount.
            (address bReceiver, uint256 bNumerator) = _lbBackfill(nftContract);
            if (bReceiver != address(0) && bNumerator != 0) {
                return _one(bReceiver, (salePrice * bNumerator) / BPS_DENOMINATOR, salePrice, SOURCE_LB_BACKFILL);
            }
            return (new address[](0), new uint256[](0), 0, read == READ_UNKNOWN ? SOURCE_UNKNOWN : SOURCE_NONE);
        }
        RoyaltySplit[] storage splits = _splits[nftContract];
        uint256 len = splits.length;
        receivers = new address[](len);
        amounts = new uint256[](len);
        uint256 totalBps;
        for (uint256 i = 0; i < len; i++) {
            receivers[i] = splits[i].receiver;
            amounts[i] = (salePrice * uint256(splits[i].bps)) / BPS_DENOMINATOR;
            totalBps += splits[i].bps;
        }
        // Quit follow-up 2026-09-14 (royalty rounding): the aggregate is floored ONCE; `sum(amounts) <= totalAmount`.
        totalAmount = (salePrice * totalBps) / BPS_DENOMINATOR;
        source = SOURCE_CONFIGURED;
    }

    /// @dev Who may configure a collection's split (UV-312, matching Limit Break's Payment Processor): its `Ownable.owner()`,
    ///      an account holding AccessControl `DEFAULT_ADMIN_ROLE` on it, or the collection contract itself. Low-level reads,
    ///      so a target that returns no data or garbage gives `CollectionNotOwnable` (review L-6: a `try` cannot catch the
    ///      decode failure, which surfaced as a panic).
    function _requireCollectionOwner(address nftContract, address caller) internal view {
        if (caller == nftContract) return;
        (bool ok, bytes memory ret) = nftContract.staticcall(abi.encodeWithSignature("owner()"));
        bool readable = ok && ret.length == 32;
        if (readable && uint256(bytes32(ret)) <= type(uint160).max && address(uint160(uint256(bytes32(ret)))) == caller) return;
        // AccessControl: hasRole(DEFAULT_ADMIN_ROLE = 0x00, caller)
        (bool ok2, bytes memory ret2) =
            nftContract.staticcall(abi.encodeWithSignature("hasRole(bytes32,address)", bytes32(0), caller));
        bool adminReadable = ok2 && ret2.length == 32;
        if (adminReadable && uint256(bytes32(ret2)) == 1) return;
        if (!readable && !adminReadable) revert CollectionNotOwnable();
        revert NotCollectionOwner();
    }

    /// @dev UV-312: the 1/64 rule. After a failed sub-call that was offered `forwarded` gas, a remainder this small means the
    ///      callee got less than `forwarded` because the CALLER ran short — not that the collection misbehaved.
    function _requireNotStarved(uint256 forwarded) private view {
        if (gasleft() <= forwarded / 63) revert RoyaltyReadStarved();
    }

    /// @dev andskur #422 follow-up: decide starvation BEFORE the read too. Under EIP-150 a callee gets at most 63/64 of
    ///      what is left, so it receives its full `forwarded` only if `gasleft() >= forwarded + forwarded / 63` (plus the
    ///      call's own cost; 5,000 covers a cold account access and memory). Without this, a callee that fails INSIDE
    ///      (a proxy whose inner call is starved) can revert empty and hand back enough gas to pass the after-the-fact
    ///      check, so a starved read would classify as "unsupported" (NONE) instead of reverting.
    function _requireBudget(uint256 forwarded) private view {
        if (gasleft() < forwarded + forwarded / 63 + 5_000) revert RoyaltyReadStarved();
    }

    /// @dev UV-312: Limit Break's royalty backfill for `nftContract` from its CollectionSettingsRegistry
    ///      (`getCollectionSettings(collection, [], [])` → `collectionCoreSettings{initialized, paymentSettingsType,
    ///      paymentMethodWhitelistId, royaltyBackfillReceiver, royaltyBackfillNumerator, ...}`). Any failure = none.
    function _lbBackfill(address nftContract) private view returns (address receiver, uint256 numerator) {
        address reg = lbSettingsRegistry;
        if (reg == address(0) || reg.code.length == 0) return (address(0), 0);
        bytes memory cd = abi.encodeWithSelector(0xf88770c9, nftContract, new bytes32[](0), new bytes32[](0));
        bool success;
        uint256 initialized;
        uint256 rawReceiver;
        uint256 rawNumerator;
        uint256 size;
        uint256 forwarded = LB_READ_GAS;
        _requireBudget(forwarded);
        assembly {
            let out := mload(0x40)
            success := staticcall(forwarded, reg, add(cd, 0x20), mload(cd), out, 0xa0)
            size := returndatasize()
            initialized := mload(out)
            rawReceiver := mload(add(out, 0x60))
            rawNumerator := mload(add(out, 0x80))
        }
        if (!success) {
            _requireNotStarved(forwarded);
            return (address(0), 0);
        }
        if (size < 0xa0 || initialized != 1 || rawReceiver > type(uint160).max || rawNumerator > MAX_ROYALTY_BPS) {
            return (address(0), 0);
        }
        return (address(uint160(rawReceiver)), rawNumerator);
    }

    /// @dev Bounded-gas ERC-2981 read that never reverts the caller except when the CALLER starved it (UV-312). Requires
    ///      the exact canonical 64-byte `(address,uint256)` return. Classifies the outcome (`READ_*`):
    ///      VALUE / ZERO for a clean answer; UNSUPPORTED for a failed call that did not exhaust the forwarded gas on a
    ///      collection whose ERC-165 explicitly says it does not support ERC-2981; UNKNOWN for a malformed answer (wrong
    ///      length, dirty address), any failed call on a collection that does not explicitly deny ERC-2981, or running out
    ///      of its 100,000. `royaltyInfo(uint256,uint256)` selector = 0x2a55205a.
    ///      UV-1103 (SBSecurity #89): an empty revert is no longer read as "no ERC-2981". A proxy whose implementation runs
    ///      out of gas keeps its 1/64 under EIP-150 and bubbles an empty revert below the 100,000 threshold, so only the
    ///      collection's explicit ERC-165 denial (not a gas measurement) can make a failed read NONE.
    function _staticRoyaltyInfo(address nftContract, uint256 tokenId, uint256 salePrice)
        private
        view
        returns (uint8 read, address receiver, uint256 amount)
    {
        bytes memory cd = abi.encodeWithSelector(0x2a55205a, tokenId, salePrice);
        uint256 forwarded = ROYALTY_READ_GAS;
        bool success;
        uint256 size;
        uint256 word0;
        uint256 word1;
        _requireBudget(forwarded);
        uint256 g0 = gasleft();
        assembly {
            let out := mload(0x40)
            // UV-312: 100,000 gas (was 30,000; review §8a, Q10). Bounded so an escrowed auction stays settleable.
            success := staticcall(forwarded, nftContract, add(cd, 0x20), mload(cd), out, 0x40)
            size := returndatasize()
            word0 := mload(out)
            word1 := mload(add(out, 0x20))
        }
        if (success) {
            if (size != 0x40 || word0 > type(uint160).max) return (READ_UNKNOWN, address(0), 0);
            if (word0 == 0 || word1 == 0) return (READ_ZERO, address(word0 == 0 ? address(0) : address(uint160(word0))), word1);
            return (READ_VALUE, address(uint160(word0)), word1);
        }
        _requireNotStarved(forwarded);
        // Out of its own gas: it consumed everything it was given (no cheaper way to fail with an empty return).
        if (g0 - gasleft() >= forwarded) return (READ_UNKNOWN, address(0), 0);
        // UV-1103: an empty revert (no royaltyInfo, a bare revert, or a proxy's inner failure) is NONE only on a denial.
        return (_deniesErc2981(nftContract) ? READ_UNSUPPORTED : READ_UNKNOWN, address(0), 0);
    }

    /// @dev True only when the collection answers ERC-165 `supportsInterface(0x2a55205a)` with an explicit false: exactly
    ///      32 bytes equal to 0. No ERC-165, a revert, a malformed answer or running out of its 30,000 is not a denial.
    function _deniesErc2981(address nftContract) private view returns (bool) {
        _requireBudget(30_000);
        (bool ok, bytes memory ret) =
            nftContract.staticcall{gas: 30_000}(abi.encodeWithSelector(0x01ffc9a7, bytes4(0x2a55205a)));
        return ok && ret.length == 32 && uint256(bytes32(ret)) == 0;
    }

    /// @dev Closeout M-11(d): recognize a UnVault wrapper collection by its public
    ///      `royaltySplitter()` accessor. Bounded-gas staticcall that NEVER reverts the caller;
    ///      returns the splitter address, or address(0) when the target is not a recognizable
    ///      wrapper (the call fails, returns the wrong size, or yields a zero/dirty address).
    ///      The selector is computed by `abi.encodeWithSignature` below rather than hard-coded, so
    ///      there is no literal to drift. (Doc pass 2026-09-09: this line read
    ///      "`royaltySplitter()` selector = 0x`" — the value was missing and the backtick unbalanced.)
    function _unvaultSplitter(address nftContract) private view returns (address splitter) {
        (, splitter) = _probeSplitter(nftContract);
    }

    /// @dev The `royaltySplitter()` probe behind `_unvaultSplitter`. `answered` is true when the call succeeded with
    ///      exactly one 32-byte word, whatever its value: the contract implements the wrapper convention.
    ///      `splitter` is that word when it is a clean address, else zero.
    function _probeSplitter(address nftContract) private view returns (bool answered, address splitter) {
        bytes memory cd = abi.encodeWithSignature("royaltySplitter()");
        uint256 forwarded = SPLITTER_PROBE_GAS;
        _requireBudget(forwarded); // a starved probe must not turn a wrapper into "not a wrapper"
        bool success;
        assembly {
            let out := mload(0x40)
            success := staticcall(forwarded, nftContract, add(cd, 0x20), mload(cd), out, 0x20)
            answered := and(success, eq(returndatasize(), 0x20))
            if answered {
                let word := mload(out)
                if iszero(shr(160, word)) { splitter := word }
            }
        }
    }
}

ethereum/UnVaultSplitterReads.sol

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

/// @title UnVaultSplitterReads
/// @notice Bounded, never-reverting reads of an UnVault collection's canonical `RoyaltySplitter`, used by
///         the marketplace settlement modules to charge the on-platform protocol-share discount
///         (founder decision Z-8, 2026-09-14) without ever reducing the creator's cut.
/// @dev Mirrors the registry's M-11 (d)/M-16 posture: every read is a gas-capped staticcall that must
///      return exactly one canonical 32-byte word; anything else is "not readable" and the caller falls
///      back to the plain registry quote (full rate, pro-rata through the splitter). A wrapper is
///      recognised by its public `royaltySplitter()` accessor, exactly as `UnVaultRoyaltyRegistry` does.
library UnVaultSplitterReads {
    struct Legs {
        address splitter;
        address creatorRecipient;
        address protocolRecipient;
        uint256 creatorBps;
        uint256 protocolBps;
    }

    uint256 private constant READ_GAS = 20_000;

    /// @return ok   true only when the collection is a recognised wrapper AND all four splitter values
    ///              read cleanly with creatorBps + protocolBps <= 10_000
    /// @return legs the live splitter values
    function read(address nftContract) internal view returns (bool ok, Legs memory legs) {
        (bool hasSplitter, uint256 splitterWord) = _word(nftContract, abi.encodeWithSignature("royaltySplitter()"));
        if (!hasSplitter || splitterWord == 0 || splitterWord >> 160 != 0) return (false, legs);
        legs.splitter = address(uint160(splitterWord));
        (bool a, uint256 creatorBps) = _word(legs.splitter, abi.encodeWithSignature("creatorFeeBps()"));
        (bool b, uint256 protocolBps) = _word(legs.splitter, abi.encodeWithSignature("protocolFeeBps()"));
        (bool c, uint256 creatorRecipient) = _word(legs.splitter, abi.encodeWithSignature("creatorRecipient()"));
        (bool d, uint256 protocolRecipient) = _word(legs.splitter, abi.encodeWithSignature("protocolRecipient()"));
        if (!(a && b && c && d)) return (false, legs);
        if (creatorRecipient >> 160 != 0 || protocolRecipient >> 160 != 0) return (false, legs);
        if (creatorRecipient == 0 || protocolRecipient == 0) return (false, legs);
        if (creatorBps > 10_000 || protocolBps > 10_000 || creatorBps + protocolBps > 10_000) return (false, legs);
        legs.creatorBps = creatorBps;
        legs.protocolBps = protocolBps;
        legs.creatorRecipient = address(uint160(creatorRecipient));
        legs.protocolRecipient = address(uint160(protocolRecipient));
        return (true, legs);
    }

    function _word(address target, bytes memory cd) private view returns (bool ok, uint256 word) {
        if (target.code.length == 0) return (false, 0);
        assembly {
            let out := mload(0x40)
            let success := staticcall(READ_GAS, target, add(cd, 0x20), mload(cd), out, 0x20)
            if and(success, eq(returndatasize(), 0x20)) {
                ok := 1
                word := mload(out)
            }
        }
    }
}

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/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);
}

ethereum/interfaces/SeaportZoneInterface.sol

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

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

// Adapted from Seaport ZoneInterface/consideration structs.
// Kept local so UnVault zone logic can compile/test without importing the
// entire Seaport repository as a hard dependency.

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

struct SpentItem {
    ItemType itemType;
    address token;
    uint256 identifier;
    uint256 amount;
}

struct ReceivedItem {
    ItemType itemType;
    address token;
    uint256 identifier;
    uint256 amount;
    address recipient;
}

struct ZoneParameters {
    bytes32 orderHash;
    address fulfiller;
    address offerer;
    SpentItem[] offer;
    ReceivedItem[] consideration;
    bytes extraData;
    bytes32[] orderHashes;
    uint256 startTime;
    uint256 endTime;
    bytes32 zoneHash;
}

/// @notice Closeout I-16: the canonical Seaport 1.6 zone metadata shape (seaport-types `Schema`).
struct Schema {
    uint256 id;
    bytes metadata;
}

/// @notice Closeout I-16: mirrors the complete seaport-types 1.6 `ZoneInterface` — ERC-165 plus
///         `getSeaportMetadata` beside the two settlement hooks. Integrations, registries and
///         validation tooling discover zones through this surface; a partial copy made them
///         classify the zone as unsupported.
interface ZoneInterface is IERC165 {
    function authorizeOrder(ZoneParameters calldata zoneParameters)
        external
        returns (bytes4 authorizeOrderMagicValue);

    function validateOrder(ZoneParameters calldata zoneParameters)
        external
        returns (bytes4 validOrderMagicValue);

    /// @notice The zone's name and the SIP schemas it enforces.
    /// @dev Doc pass 2026-09-09: `view` here, `pure` in `UnVaultSignedZone`. Both are legal for a
    ///      caller, but this file exists to MIRROR the zone's surface, so the copy should match.
    function getSeaportMetadata() external pure returns (string memory name, Schema[] memory schemas);
}
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.