Skip to content
Verified contractPartialMIT

PeddlesNFTMarketplace

Address0x4b22a81722c26bc97c9da3395642ff6ef8d71978
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,374,025
Creation transaction
0x047b06a8bc…643b47a349

src/PeddlesNFTMarketplace.sol

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

/*

               _______  _______  ______   ______   _        _______
      (  ____ )(  ____ \(  __  \ (  __  \ ( \      (  ____ \(  ____ \
      | (    )|| (    \/| (  \  )| (  \  )| (      | (    \/| (    \/
      | (____)|| (__    | |   ) || |   ) || |      | (__    | (_____
      |  _____)|  __)   | |   | || |   | || |      |  __)   (_____  )
      | (      | (      | |   ) || |   ) || |      | (            ) |
      | )      | (____/\| (__/  )| (__/  )| (____/\| (____/\/\____) |
      |/       (_______/(______/ (______/ (_______/(_______/\_______)


      THE STOCK-PAIRED LAUNCHPAD

      Launch tokens and NFTs paired against tokenised stocks.
      100% of supply goes to liquidity, locked from block zero.
      Holders earn the stock you are paired to.

      Website     https://peddles.xyz
      X           https://x.com/PeddlesX
      Telegram    https://t.me/peddlesnews


*/

interface IPeddlesERC721Lite {
    function ownerOf(uint256 tokenId) external view returns (address);
    function getApproved(uint256 tokenId) external view returns (address);
    function isApprovedForAll(address owner, address operator) external view returns (bool);
    function safeTransferFrom(address from, address to, uint256 tokenId) external;
    function transferFrom(address from, address to, uint256 tokenId) external;
}

interface IPeddlesERC1155Lite {
    function balanceOf(address account, uint256 id) external view returns (uint256);
    function isApprovedForAll(address account, address operator) external view returns (bool);
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
}

interface IPeddlesRoyaltyLite {
    function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount);
}

/// @notice The only thing this marketplace needs from a collection in order to know WHO may
/// configure that collection's holder-fee route. Matches `PeddlesArtCollection.owner()` and
/// `PeddlesBondingCollection.owner()`.
interface IPeddlesCollectionOwnerLite {
    function owner() external view returns (address);
}

/// @notice `PeddlesNftHolderRewards`' funding interface, in full. It is balance-delta based: a
/// funder simply transfers the reward asset in (native lands in its `receive()`) and calls the
/// permissionless `sync()`. There is NO callback, NO approval and NO allowlist — do not invent one.
interface IPeddlesHolderRewardsSyncLite {
    function sync() external;
}

interface IMarketplaceERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

/// ============================================================================
/// PeddlesNFTMarketplace — minimal, NON-CUSTODIAL, native-ETH marketplace for the two collection
/// types produced by `PeddlesNFTFactory`: `PeddlesArtCollection` (ERC-721) and
/// `PeddlesBondingCollection` (ERC-1155 of 1-of-1 ids). It also works against any third-party
/// ERC-721 / ERC-1155, which is why every external collection call below is treated as hostile.
///
/// The NFT never enters this contract. Listings are approvals plus bookkeeping; the token moves
/// seller -> buyer directly inside `buy` / `acceptOffer` / `buySigned*`.
///
/// ---- Every wei this contract can hold, and its exit --------------------------------------
/// This is the project's hard no-stuck-funds rule, discharged explicitly. There are exactly four
/// classes of native balance here, they are accounted separately, and each has a named exit:
///
///  1. OFFER ESCROW — `totalEscrowed`. Incremented by exactly `msg.value` when an offer is created,
///     decremented by exactly `offer.price` when it is cancelled or accepted. Exits via
///     `cancelOffer` (refund to the buyer) or `acceptOffer` (`_payout` to seller/fees/royalty).
///     An EXPIRED offer can additionally be cancelled by ANYONE — the refund still goes to
///     `offer.buyer` and nowhere else — so escrow can never be held hostage by an absent buyer.
///     That last sentence is only true because EVERY offer is REQUIRED to carry an expiry:
///     `_makeOffer` rejects `expiresAt == 0` and anything beyond `MAX_OFFER_DURATION`. A previous
///     revision accepted `expiresAt == 0`, and such an offer was never expired, so its escrow had
///     exactly ONE exit — a call from `offer.buyer`. A zero-expiry offer placed against a token
///     that does not exist, from a key later lost, was native currency that nothing on earth could
///     move: `sweepStrayNative` cannot reach it BY DESIGN (escrow is counted in `totalEscrowed`,
///     never in `strayNative()`), and no other function touches it. That is the project's
///     no-stuck-funds rule broken in its most literal form — an exit gated on a condition that can
///     never be met — and it is why the expiry is now mandatory and bounded rather than optional.
///     With the bound in place every offer becomes permissionlessly refundable at a time that is
///     KNOWN when it is created and is at most `MAX_OFFER_DURATION` away.
///  2. FAILED-PUSH CREDITS — `totalCredited` / `credits[account]`. Every outbound payment is
///     PUSHED under a bounded gas stipend; if the push fails (a contract wallet that reverts, one
///     that needs more than the stipend, a hostile royalty receiver, a seller who bricked their own
///     `receive`) the wei is booked as a credit instead of reverting the sale. Exit:
///     `withdrawCredits()`, pull-based, all remaining gas forwarded, callable forever by the
///     credited account and by nobody else.
///  3. STRAY / UNACCOUNTED NATIVE — anything the contract holds beyond (1) + (2). It cannot arrive
///     through any function (there is deliberately NO `receive()`; see below), only through
///     `selfdestruct` or a coinbase payout. Exit: `sweepStrayNative()` — PERMISSIONLESS to call,
///     hard-wired to pay `feeReceiver`, and arithmetically incapable of touching (1) or (2) because
///     it moves at most `address(this).balance - totalEscrowed - totalCredited`. The payment goes
///     out through the SAME push-or-credit primitive as every other outbound leg, so a fee receiver
///     that cannot be paid by push converts the stray into a credit it can pull later instead of
///     reverting the sweep. It used to revert `TransferFailed`, which let one un-payable fee
///     receiver block the sweep outright until the owner called `setFee` — a permissionless exit
///     that an unrelated config value can switch off is not really permissionless.
///  4. ERC-20s and ERC-721s force-sent here — never legitimately held, since this contract is
///     non-custodial in both assets. Exit: `rescueERC20` / `rescueERC721` (owner). An ERC-1155
///     cannot arrive at all: this contract implements no `onERC1155Received`, so a safe transfer to
///     it reverts at the source, and `PeddlesBondingCollection` has no unsafe transfer path.
///
/// NO `receive()`. The previous revision had `receive() external payable {}` with no withdrawal
/// path at all, which stranded every wei anyone sent it. It is not merely given an exit here, it is
/// REMOVED: nothing in the system ever needs to make a bare send to this contract. Refunds from a
/// failed `_push` come back as an unspent value on a failed call, never as an inbound transfer, and
/// every legitimate deposit arrives through a `payable` entry point that accounts for it in the
/// same transaction. Failing closed on an accidental send is strictly better than silently
/// accepting it, and `sweepStrayNative()` still covers the paths a contract cannot refuse.
///
/// INVARIANT, at rest: `address(this).balance >= totalEscrowed + totalCredited`.
///
/// ---- The platform fee cannot rise on an order that already exists ---------------------------
/// A listing and an offer SNAPSHOT `platformFeeBps` when they are created, and a signed order
/// COMMITS to a fee in the signature itself. A fill charges the lower of that and the live fee,
/// so an owner `setFee` can lower what a live order pays but never raise it.
///
/// ---- Holder fee routing (secondary-sale fees for NFT holders) -----------------------------
/// A collection's owner may direct a share of THE PLATFORM FEE — never the seller's proceeds — to
/// that collection's `PeddlesNftHolderRewards` distributor, so holding a piece earns from secondary
/// trading. Authority is `collection.owner()` and nobody else, exactly as in
/// `PeddlesNftStockGraduationOrchestrator.setHolderRewardsRoute`; the protocol owner has no path to
/// redirect it. The protocol does bound how much of ITS OWN fee it is willing to share, via
/// `holderShareCapBps` (owner-settable, applied live at payout as `min(stored, cap)`), because the
/// slice comes out of protocol revenue.
///
/// NOT double-counted with EIP-2981. The two streams are disjoint: the royalty is taken out of the
/// SELLER's proceeds and paid to `royaltyInfo`'s receiver, while the holder share is taken out of
/// the PLATFORM fee. A collection that points both at the same distributor is funded twice from two
/// different pockets — that is two revenue streams, not one counted twice — and the seller's net is
/// bit-for-bit identical whether or not a holder route exists.
///
/// A hostile or gas-hungry distributor can NEVER brick a sale: the push is gas-capped and its
/// failure degrades to paying `feeReceiver` the full platform fee, and the follow-up `sync()` is a
/// gas-capped `try`. If `sync()` fails the wei still sits in the distributor and `sync()` is
/// permissionless, so nothing is lost either way.
/// ============================================================================
contract PeddlesNFTMarketplace {
    uint8 public constant TYPE_ERC721 = 1;
    uint8 public constant TYPE_ERC1155 = 2;

    uint16 public constant BPS = 10_000;
    uint96 public constant MAX_PLATFORM_FEE_BPS = 500; // 5% hard cap
    /// @dev Ceiling for `holderShareCapBps`. 100% of the platform fee may be shared with holders.
    uint16 public constant MAX_HOLDER_SHARE_BPS = 10_000;
    /// @dev Hard ceiling on an HONOURED EIP-2981 royalty, matching the `royaltyBps <= 1000`
    /// constructor cap both Peddles collections already enforce. A third-party collection reporting
    /// more than this is clamped, not obeyed: without it a hostile `royaltyInfo` could return the
    /// seller's entire proceeds and drain every sale to an address the seller never agreed to.
    uint16 public constant MAX_ROYALTY_BPS = 1_000;

    /// @notice The longest an offer's escrow may sit before ANYONE can refund it to its buyer.
    /// @dev PUBLIC so a front-end can bound its own expiry picker off chain instead of guessing and
    /// getting reverted. Every offer must expire, and must expire no later than
    /// `block.timestamp + MAX_OFFER_DURATION` — that pair of bounds is what makes "escrow is always
    /// permissionlessly recoverable" a TOTAL statement rather than one that holds for the offers
    /// that happened to opt in. 90 days is long enough for any real bid and short enough that an
    /// abandoned one is cleared inside a quarter.
    uint64 public constant MAX_OFFER_DURATION = 90 days;

    /// @dev Gas forwarded when PUSHING native currency out. Bounded so one hostile or greedy
    /// recipient cannot burn the transaction's gas; a push that does not fit degrades to a credit,
    /// and `withdrawCredits()` forwards ALL remaining gas so a contract wallet is never locked out.
    uint256 private constant PUSH_GAS = 100_000;
    /// @dev Gas forwarded to a holder-rewards distributor's `sync()`. Mirrors the 250k stipend the
    /// collections use for `onNftTransfer`.
    uint256 private constant SYNC_GAS = 250_000;
    /// @dev Gas cap on every speculative VIEW call into an untrusted collection.
    uint256 private constant VIEW_GAS = 100_000;

    /// @dev secp256k1n / 2. Signatures with `s` above this are the malleable upper half.
    bytes32 private constant HALF_N = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;

    address public owner;
    address public feeReceiver;
    uint96 public platformFeeBps;
    /// @notice Protocol-side ceiling on the share of the platform fee a collection owner may route
    /// to holders. Applied LIVE at payout (`min(stored, cap)`), so lowering it takes effect at once
    /// and does not require touching any collection's stored route.
    uint16 public holderShareCapBps;
    uint256 public nextListingId = 1;
    uint256 public nextOfferId = 1;
    uint256 private _lock = 1;

    /// @notice Native currently escrowed against LIVE offers. `address(this).balance` may never
    /// legitimately fall below `totalEscrowed + totalCredited`.
    uint256 public totalEscrowed;
    /// @notice Native owed to accounts whose push payment failed. Pull-based via `withdrawCredits`.
    uint256 public totalCredited;
    mapping(address => uint256) public credits;

    struct Listing {
        uint256 id;
        address seller;
        address collection;
        uint256 tokenId;
        uint256 amount;
        uint256 price;
        uint8 tokenType;
        bool active;
        uint64 createdAt;
        /// @dev `platformFeeBps` when the listing was opened: the most this listing can be charged.
        uint16 feeBps;
    }

    struct Offer {
        uint256 id;
        address buyer;
        address collection;
        uint256 tokenId;
        uint256 amount;
        uint256 price;
        uint8 tokenType;
        uint64 expiresAt;
        bool active;
        uint64 createdAt;
        /// @dev `platformFeeBps` when the offer was made: the most its acceptance can be charged.
        uint16 feeBps;
    }

    mapping(uint256 => Listing) public listings;
    /// @notice asset -> the listing id currently advertised for it. A HINT for callers, refreshed
    /// whenever the incumbent is no longer fillable; the indexer remains authoritative for
    /// discovery. Uniqueness is enforced per SELLER (`sellerListingOf`), never per asset, so one
    /// seller can never permanently block another from listing the same asset.
    mapping(bytes32 => uint256) public listingOf;
    /// @notice (collection, tokenId, seller) -> that seller's own live listing id.
    mapping(bytes32 => uint256) public sellerListingOf;
    mapping(uint256 => Offer) public offers;
    mapping(bytes32 => uint256) public bestOfferOf;
    mapping(bytes32 => bool) public usedLazyOrder;
    /// @notice Bulk-cancellation counter, mixed into every lazy order hash. Bumping it invalidates
    /// every off-chain order the seller has ever signed, in one transaction.
    mapping(address => uint256) public lazyOrderEpoch;

    /// @notice collection -> the `PeddlesNftHolderRewards` its secondary-fee share is paid into.
    mapping(address => address) public holderRewardsOf;
    /// @notice collection -> share of the PLATFORM FEE routed there, in bps (bounded live by
    /// `holderShareCapBps`).
    mapping(address => uint16) public holderShareBps;

    event Listed(
        uint256 indexed listingId,
        address indexed seller,
        address indexed collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint8 tokenType
    );
    event ListingCancelled(uint256 indexed listingId);
    event Purchased(uint256 indexed listingId, address indexed buyer, address indexed seller, uint256 price);
    event LazyPurchased(bytes32 indexed orderHash, address indexed buyer, address indexed seller, address collection, uint256 tokenId, uint256 price, uint8 tokenType);
    event LazyOrderCancelled(bytes32 indexed orderHash, address indexed seller);
    event LazyOrdersInvalidated(address indexed seller, uint256 epoch);
    event OfferMade(
        uint256 indexed offerId,
        address indexed buyer,
        address indexed collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint8 tokenType,
        uint64 expiresAt
    );
    event OfferCancelled(uint256 indexed offerId);
    event OfferAccepted(uint256 indexed offerId, address indexed seller, address indexed buyer, uint256 price);
    event FeeUpdated(address indexed feeReceiver, uint96 platformFeeBps);
    event HolderShareCapUpdated(uint16 holderShareCapBps);
    event HolderRewardsRouteSet(
        address indexed collection, address indexed collectionOwner, address indexed distributor, uint16 shareBps
    );
    event HolderRewardsFunded(address indexed collection, address indexed distributor, uint256 amount, uint16 shareBps);
    event PaymentCredited(address indexed account, uint256 amount);
    event CreditsWithdrawn(address indexed account, uint256 amount);
    event StraySwept(address indexed to, uint256 amount);
    event Rescued(address indexed asset, address indexed to, uint256 amount);

    error Unauthorized();
    error ReentrantCall();
    error InvalidAddress();
    error InvalidAmount();
    error InvalidPrice();
    error NotOwner();
    error NotApproved();
    error AlreadyListed();
    error ListingInactive();
    error OfferInactive();
    error OfferExpired();
    /// @dev An offer's `expiresAt` is missing (zero), already in the past, or further out than
    /// `MAX_OFFER_DURATION`. Distinct from `OfferExpired`, which means a LIVE offer's clock ran out.
    error InvalidExpiry();
    error InsufficientPayment();
    error TransferFailed();
    error NotCollectionOwner();
    error ShareTooHigh();
    error NothingToWithdraw();

    modifier onlyOwner() {
        if (msg.sender != owner) revert Unauthorized();
        _;
    }

    modifier nonReentrant() {
        if (_lock != 1) revert ReentrantCall();
        _lock = 2;
        _;
        _lock = 1;
    }

    /// @param feeReceiver_       protocol fee destination
    /// @param platformFeeBps_    platform fee, bounded by `MAX_PLATFORM_FEE_BPS`
    /// @param holderShareCapBps_ ceiling on the share of that fee a collection owner may route to
    ///                           NFT holders. SELECTED at deploy, never assumed: 0 disables holder
    ///                           routing outright, 10_000 lets a collection take the whole platform
    ///                           fee for its holders.
    /// @param initialOwner The owner, passed EXPLICITLY rather than taken from `msg.sender`.
    ///        This contract is deployed through the canonical CREATE2 proxy so its address can
    ///        be mined, and under `new X{salt: s}(...)` the caller is that proxy — an
    ///        `owner = msg.sender` constructor would hand the marketplace to
    ///        `0x4e59b448…` and leave it permanently unadministrable. Every other ownable
    ///        contract in the stack takes its owner the same way for the same reason; see
    ///        `ownerIsMsgSender` in `script/PeddlesSalts.sol`, which refuses to mine a salt for
    ///        any contract that does not.
    /// @param holderShareCapBps_ Ceiling on the share of the PLATFORM fee a collection owner may
    ///        route to their holders. Pass 0 to forbid holder routing entirely at deploy time.
    constructor(
        address initialOwner,
        address feeReceiver_,
        uint96 platformFeeBps_,
        uint16 holderShareCapBps_
    ) {
        if (initialOwner == address(0)) revert InvalidAddress();
        if (feeReceiver_ == address(0)) revert InvalidAddress();
        if (platformFeeBps_ > MAX_PLATFORM_FEE_BPS) revert InvalidAmount();
        if (holderShareCapBps_ > MAX_HOLDER_SHARE_BPS) revert ShareTooHigh();
        owner = initialOwner;
        feeReceiver = feeReceiver_;
        platformFeeBps = platformFeeBps_;
        holderShareCapBps = holderShareCapBps_;
        emit FeeUpdated(feeReceiver_, platformFeeBps_);
        emit HolderShareCapUpdated(holderShareCapBps_);
    }

    // NOTE: there is deliberately no `receive()`. See the header.

    // =========================================================================
    // Admin
    // =========================================================================

    function transferOwnership(address nextOwner) external onlyOwner {
        if (nextOwner == address(0)) revert InvalidAddress();
        owner = nextOwner;
    }

    function setFee(address nextReceiver, uint96 nextFeeBps) external onlyOwner {
        if (nextReceiver == address(0)) revert InvalidAddress();
        if (nextFeeBps > MAX_PLATFORM_FEE_BPS) revert InvalidAmount();
        feeReceiver = nextReceiver;
        platformFeeBps = nextFeeBps;
        emit FeeUpdated(nextReceiver, nextFeeBps);
    }

    /// @notice How much of the PLATFORM's own fee a collection owner may direct to NFT holders.
    /// @dev This is the protocol deciding how much of its OWN revenue it shares. It is NOT a lever
    /// over a collection's holder share destination — `holderRewardsOf` is writable only by
    /// `collection.owner()` and there is no code path from here to it.
    function setHolderShareCap(uint16 nextCapBps) external onlyOwner {
        if (nextCapBps > MAX_HOLDER_SHARE_BPS) revert ShareTooHigh();
        holderShareCapBps = nextCapBps;
        emit HolderShareCapUpdated(nextCapBps);
    }

    // =========================================================================
    // Holder fee routing — authority is `collection.owner()`, and nobody else
    // =========================================================================

    /// @notice Route a share of the PLATFORM FEE earned on this collection's secondary sales to its
    /// NFT holders, via a `PeddlesNftHolderRewards` distributor deployed with `NATIVE` as the reward
    /// asset.
    ///
    /// AUTHORITY: `collection.owner()` only — identical to
    /// `PeddlesNftStockGraduationOrchestrator.setHolderRewardsRoute`, down to the `NotCollectionOwner`
    /// error. The marketplace owner cannot set, raise, lower, clear or re-point it.
    /// BOUND: `MAX_HOLDER_SHARE_BPS` here, and `holderShareCapBps` live at payout time.
    /// REVERSIBLE: the collection owner may re-point or zero it whenever they like; that affects
    /// FUTURE sales only. Wei already delivered to a distributor belongs to holders permanently.
    /// NOT A ROYALTY: this comes out of the platform's cut, never the seller's, so enabling it does
    /// not change what a seller receives by a single wei.
    /// @param distributor may be zero only when `shareBps` is zero, i.e. when turning the route off
    function setHolderRewardsRoute(address collection, address distributor, uint16 shareBps) external {
        if (collection == address(0)) revert InvalidAddress();
        if (shareBps > MAX_HOLDER_SHARE_BPS) revert ShareTooHigh();
        if (shareBps > 0 && distributor == address(0)) revert InvalidAddress();

        address collectionOwner = IPeddlesCollectionOwnerLite(collection).owner();
        if (msg.sender != collectionOwner) revert NotCollectionOwner();

        holderRewardsOf[collection] = distributor;
        holderShareBps[collection] = shareBps;
        emit HolderRewardsRouteSet(collection, collectionOwner, distributor, shareBps);
    }

    /// @notice The route actually in force for a collection: where the holder slice goes, and the
    /// EFFECTIVE share after the protocol's live cap. `(address(0), 0)` means "no route", in which
    /// case the whole platform fee goes to `feeReceiver` exactly as it always did.
    /// @dev A zero EFFECTIVE share is reported as `(address(0), 0)`, not as `(distributor, 0)`.
    /// Those two answers mean the same thing to `_payout` — the branch is gated on `shareBps != 0`
    /// either way — but they do NOT mean the same thing to a caller. A UI that reads a non-zero
    /// distributor renders "holder routing: ON" and shows an address that is in fact being paid
    /// nothing, which is precisely the kind of plausible-but-false claim this codebase refuses to
    /// put on a screen. There is exactly one shape for "no route in force", and it is a zero pair:
    /// no stored distributor, a stored share of zero, or a protocol cap of zero all produce it.
    function holderRoute(address collection) public view returns (address distributor, uint16 shareBps) {
        address stored = holderRewardsOf[collection];
        if (stored == address(0)) return (address(0), 0);
        uint16 bps = holderShareBps[collection];
        uint16 cap = holderShareCapBps;
        if (bps > cap) bps = cap;
        if (bps == 0) return (address(0), 0);
        return (stored, bps);
    }

    // =========================================================================
    // Keys and views
    // =========================================================================

    function assetKey(address collection, uint256 tokenId) public pure returns (bytes32) {
        return keccak256(abi.encode(collection, tokenId));
    }

    function sellerAssetKey(address collection, uint256 tokenId, address seller) public pure returns (bytes32) {
        return keccak256(abi.encode(collection, tokenId, seller));
    }

    function getListingForAsset(address collection, uint256 tokenId) external view returns (Listing memory listing) {
        uint256 id = listingOf[assetKey(collection, tokenId)];
        if (id != 0 && listings[id].active) listing = listings[id];
    }

    /// @notice The best offer this contract knows of for an asset. Returns an EMPTY offer once that
    /// offer is cancelled, accepted or expired: the pointer is a hint, not an ordered book, and this
    /// contract cannot enumerate offers to promote a runner-up. The indexer supplies true ordering.
    function getBestOfferForAsset(address collection, uint256 tokenId) external view returns (Offer memory offer) {
        uint256 id = bestOfferOf[assetKey(collection, tokenId)];
        if (id == 0) return offer;
        Offer storage o = offers[id];
        if (!o.active || _offerExpired(o)) return offer;
        offer = o;
    }

    /// @dev THE expiry predicate, defined once so `cancelOffer`, `acceptOffer`, the best-offer
    /// pointer in `_makeOffer` and the view above can never drift apart. An offer is live THROUGH
    /// the block whose timestamp equals `expiresAt`, and expired strictly after it.
    ///
    /// There is deliberately no `expiresAt != 0` guard: `_makeOffer` refuses a zero expiry, so no
    /// offer this contract has ever written can have one. Should a zero ever appear it reads as
    /// EXPIRED here, which is the fail-safe direction in every one of the four call sites — the
    /// escrow becomes permissionlessly refundable TO ITS BUYER and unacceptable, rather than
    /// becoming permanently unrefundable. Silently trapping money is the failure this predicate
    /// exists to make impossible; refusing a sale is not.
    function _offerExpired(Offer storage o) private view returns (bool) {
        return o.expiresAt < block.timestamp;
    }

    /// @notice Native this contract owes to somebody: live offer escrow plus unclaimed credits.
    function reservedNative() public view returns (uint256) {
        return totalEscrowed + totalCredited;
    }

    /// @notice Native this contract holds that is owed to nobody. Sweepable; always zero in normal
    /// operation because every entry point either pays out or escrows its `msg.value` in full.
    function strayNative() public view returns (uint256) {
        uint256 balance = address(this).balance;
        uint256 reserved = reservedNative();
        return balance > reserved ? balance - reserved : 0;
    }

    // =========================================================================
    // Listings
    // =========================================================================

    function listERC721(address collection, uint256 tokenId, uint256 price) external nonReentrant returns (uint256 id) {
        if (collection == address(0)) revert InvalidAddress();
        if (price == 0) revert InvalidPrice();

        IPeddlesERC721Lite nft = IPeddlesERC721Lite(collection);
        if (nft.ownerOf(tokenId) != msg.sender) revert NotOwner();
        if (nft.getApproved(tokenId) != address(this) && !nft.isApprovedForAll(msg.sender, address(this))) revert NotApproved();

        id = _openListing(collection, tokenId, 1, price, TYPE_ERC721);
    }

    function listERC1155(address collection, uint256 tokenId, uint256 amount, uint256 price) external nonReentrant returns (uint256 id) {
        if (collection == address(0)) revert InvalidAddress();
        if (amount == 0) revert InvalidAmount();
        if (price == 0) revert InvalidPrice();

        IPeddlesERC1155Lite nft = IPeddlesERC1155Lite(collection);
        if (nft.balanceOf(msg.sender, tokenId) < amount) revert NotOwner();
        if (!nft.isApprovedForAll(msg.sender, address(this))) revert NotApproved();

        id = _openListing(collection, tokenId, amount, price, TYPE_ERC1155);
    }

    /// @dev Uniqueness is PER SELLER. The previous revision keyed it per asset, which meant a seller
    /// who listed a token and then moved it elsewhere (an OTC sale, another marketplace) left an
    /// `active` listing that only they could cancel — permanently blocking the new owner from ever
    /// listing that token here. Now their stale listing simply loses the advertised slot.
    function _openListing(address collection, uint256 tokenId, uint256 amount, uint256 price, uint8 tokenType)
        private
        returns (uint256 id)
    {
        bytes32 sKey = sellerAssetKey(collection, tokenId, msg.sender);
        uint256 mine = sellerListingOf[sKey];
        if (mine != 0 && listings[mine].active) revert AlreadyListed();

        id = nextListingId++;
        listings[id] = Listing(
            id, msg.sender, collection, tokenId, amount, price, tokenType, true, uint64(block.timestamp),
            uint16(platformFeeBps)
        );
        sellerListingOf[sKey] = id;

        bytes32 key = assetKey(collection, tokenId);
        uint256 current = listingOf[key];
        if (current == 0 || !_fillable(listings[current])) listingOf[key] = id;

        emit Listed(id, msg.sender, collection, tokenId, amount, price, tokenType);
    }

    /// @dev Can this listing still be filled? Every read of the (untrusted) collection is a
    /// gas-capped raw staticcall decoded by hand — NOT `try`/`catch`, because a `try` whose return
    /// data fails to ABI-decode raises an exception the `catch` does not catch, which would hand a
    /// hostile collection a way to revert this contract from a view. A collection that reverts or
    /// answers garbage counts as NOT fillable, which only ever frees the advertised slot and never
    /// moves value.
    function _fillable(Listing storage l) private view returns (bool) {
        if (!l.active) return false;
        bytes memory payload = l.tokenType == TYPE_ERC721
            ? abi.encodeWithSelector(IPeddlesERC721Lite.ownerOf.selector, l.tokenId)
            : abi.encodeWithSelector(IPeddlesERC1155Lite.balanceOf.selector, l.seller, l.tokenId);
        (bool ok, bytes memory data) = l.collection.staticcall{gas: VIEW_GAS}(payload);
        if (!ok || data.length < 32) return false;
        uint256 word = abi.decode(data, (uint256)); // never reverts for a >= 32-byte return
        if (l.tokenType == TYPE_ERC721) return address(uint160(word)) == l.seller;
        return word >= l.amount;
    }

    function cancelListing(uint256 listingId) external nonReentrant {
        Listing storage l = listings[listingId];
        if (!l.active) revert ListingInactive();
        if (l.seller != msg.sender) revert Unauthorized();
        _closeListing(listingId, l);
        emit ListingCancelled(listingId);
    }

    function _closeListing(uint256 listingId, Listing storage l) private {
        l.active = false;
        bytes32 key = assetKey(l.collection, l.tokenId);
        if (listingOf[key] == listingId) listingOf[key] = 0;
        bytes32 sKey = sellerAssetKey(l.collection, l.tokenId, l.seller);
        if (sellerListingOf[sKey] == listingId) sellerListingOf[sKey] = 0;
    }

    function buy(uint256 listingId) external payable nonReentrant {
        Listing storage l = listings[listingId];
        if (!l.active) revert ListingInactive();

        // Cached BEFORE any write or external call. The storage pointer stays valid across
        // `l.active = false` (that write touches a different slot member), and `nonReentrant`
        // forbids re-entry, but a sale must never depend on either fact holding.
        address seller = l.seller;
        address collection = l.collection;
        uint256 tokenId = l.tokenId;
        uint256 amount = l.amount;
        uint256 price = l.price;
        uint8 tokenType = l.tokenType;
        uint16 feeBps = l.feeBps;

        if (msg.value < price) revert InsufficientPayment();
        _closeListing(listingId, l);

        if (tokenType == TYPE_ERC721) {
            IPeddlesERC721Lite(collection).safeTransferFrom(seller, msg.sender, tokenId);
        } else {
            IPeddlesERC1155Lite(collection).safeTransferFrom(seller, msg.sender, tokenId, amount, "");
        }

        _payout(collection, tokenId, seller, price, feeBps);
        _sendOrCredit(msg.sender, msg.value - price);
        emit Purchased(listingId, msg.sender, seller, price);
    }

    // =========================================================================
    // Offers (the only ESCROWED balance in this contract)
    // =========================================================================

    function makeOfferERC721(address collection, uint256 tokenId, uint64 expiresAt) external payable nonReentrant returns (uint256 id) {
        id = _makeOffer(collection, tokenId, 1, TYPE_ERC721, expiresAt);
    }

    function makeOfferERC1155(address collection, uint256 tokenId, uint256 amount, uint64 expiresAt) external payable nonReentrant returns (uint256 id) {
        if (amount == 0) revert InvalidAmount();
        id = _makeOffer(collection, tokenId, amount, TYPE_ERC1155, expiresAt);
    }

    /// @dev EVERY offer must name an expiry, and it must be inside `MAX_OFFER_DURATION`.
    ///
    /// This is the single most important line in the contract for the no-stuck-funds rule, so it is
    /// worth saying why an OPTIONAL expiry was a bug rather than a convenience. `cancelOffer` lets
    /// anyone refund an EXPIRED offer to its buyer; that is the escape hatch which stops escrow from
    /// being stranded by a buyer who has lost their key. An offer with `expiresAt == 0` is never
    /// expired, so the hatch never opens and its only exit is a call from `offer.buyer`. Nothing
    /// else in this contract can move that wei — `sweepStrayNative` is bounded BY DESIGN to
    /// `balance - totalEscrowed - totalCredited`, and live escrow is inside `totalEscrowed`. Offers
    /// need no approval, no existing token and no willing counterparty, so the stranding case is not
    /// exotic: bid on a token id that was never minted, lose the key, and the escrow is gone
    /// forever. An exit gated on a condition that can never be met is not an exit.
    ///
    /// The ALTERNATIVE was to keep accepting `expiresAt == 0` and add a second escape hatch — a
    /// permissionless cancel once an offer is older than some fixed age. It is REJECTED. It leaves
    /// two different liveness rules for the same escrow, each with its own boundary to get wrong,
    /// and it makes the guarantee conditional on a reader noticing the second rule exists. Requiring
    /// the expiry makes the invariant TOTAL and checkable in one place: `expiresAt` is non-zero and
    /// bounded for every row this contract will ever write, so "every offer becomes permissionlessly
    /// refundable within MAX_OFFER_DURATION" is a property of the type, not of a code path. Since
    /// this ships on a fresh deployment there is no legacy zero-expiry escrow to migrate, and the
    /// off-chain cost is one field a UI already had to render.
    function _makeOffer(address collection, uint256 tokenId, uint256 amount, uint8 tokenType, uint64 expiresAt) private returns (uint256 id) {
        if (collection == address(0)) revert InvalidAddress();
        if (msg.value == 0) revert InvalidPrice();
        // Both bounds, one error. `expiresAt == 0` fails the first comparison, so "no expiry" is
        // refused by the same line that refuses an expiry in the past.
        if (expiresAt <= block.timestamp || uint256(expiresAt) > block.timestamp + MAX_OFFER_DURATION) {
            revert InvalidExpiry();
        }

        // Escrow accounting. `msg.value` and `offers[id].price` are the SAME number by construction,
        // which is what makes `totalEscrowed` an exact liability rather than an estimate.
        totalEscrowed += msg.value;

        id = nextOfferId++;
        offers[id] = Offer(
            id, msg.sender, collection, tokenId, amount, msg.value, tokenType, expiresAt, true,
            uint64(block.timestamp), uint16(platformFeeBps)
        );
        bytes32 key = assetKey(collection, tokenId);
        // The incumbent is displaced when it is inactive, EXPIRED, or cheaper. Expiry used to be
        // left out, so a dead-but-uncancelled higher offer kept the pointer and
        // `getBestOfferForAsset` then reported NOTHING for the asset while a live lower offer sat
        // right there — the hint actively hid the only fillable bid. `offers[0]` is the zero struct
        // (ids start at 1), so the `bestId == 0` case falls out of `!best.active` for free.
        Offer storage best = offers[bestOfferOf[key]];
        if (!best.active || _offerExpired(best) || msg.value > best.price) bestOfferOf[key] = id;
        emit OfferMade(id, msg.sender, collection, tokenId, amount, msg.value, tokenType, expiresAt);
    }

    /// @notice Cancel an offer and return its escrow to the buyer.
    /// @dev The buyer may cancel at ANY time, expired or not — expiry blocks acceptance, never
    /// refund, so escrow is never trapped by the clock. Once an offer is EXPIRED anyone may cancel
    /// it: the refund is hard-wired to `offer.buyer` and there is no destination parameter, so a
    /// third party can only ever return somebody else's money to them. That is what stops escrow
    /// from being stranded by a buyer who has lost their key or gone away, and it is the same
    /// permissionless-but-undirectable shape as `PeddlesNftHolderRewards.distributeBatch`.
    ///
    /// If the buyer can no longer RECEIVE native (a contract wallet that was self-destructed,
    /// paused, or whose `receive` now reverts) the refund is booked as a credit rather than
    /// reverting, so one broken buyer can neither brick their own refund nor leave `totalEscrowed`
    /// permanently inflated and the stray sweep permanently blocked.
    ///
    /// Because `_makeOffer` requires a bounded expiry, the permissionless branch is reachable for
    /// EVERY offer, at a time fixed when the offer was made and never more than
    /// `MAX_OFFER_DURATION` away. There is no offer whose escrow depends on its buyer showing up.
    function cancelOffer(uint256 offerId) external nonReentrant {
        Offer storage ofr = offers[offerId];
        if (!ofr.active) revert OfferInactive();
        if (ofr.buyer != msg.sender && !_offerExpired(ofr)) revert Unauthorized();

        address buyer = ofr.buyer;
        uint256 price = ofr.price;
        ofr.active = false;
        totalEscrowed -= price;
        bytes32 key = assetKey(ofr.collection, ofr.tokenId);
        if (bestOfferOf[key] == offerId) bestOfferOf[key] = 0;

        _sendOrCredit(buyer, price);
        emit OfferCancelled(offerId);
    }

    function acceptOffer(uint256 offerId) external nonReentrant {
        Offer storage ofr = offers[offerId];
        if (!ofr.active) revert OfferInactive();
        if (_offerExpired(ofr)) revert OfferExpired();

        address buyer = ofr.buyer;
        address collection = ofr.collection;
        uint256 tokenId = ofr.tokenId;
        uint256 amount = ofr.amount;
        uint256 price = ofr.price;
        uint8 tokenType = ofr.tokenType;
        uint16 feeBps = ofr.feeBps;

        ofr.active = false;
        totalEscrowed -= price;
        bytes32 key = assetKey(collection, tokenId);
        if (bestOfferOf[key] == offerId) bestOfferOf[key] = 0;

        if (tokenType == TYPE_ERC721) {
            IPeddlesERC721Lite nft = IPeddlesERC721Lite(collection);
            if (nft.ownerOf(tokenId) != msg.sender) revert NotOwner();
            if (nft.getApproved(tokenId) != address(this) && !nft.isApprovedForAll(msg.sender, address(this))) revert NotApproved();
            nft.safeTransferFrom(msg.sender, buyer, tokenId);
        } else {
            IPeddlesERC1155Lite nft = IPeddlesERC1155Lite(collection);
            if (nft.balanceOf(msg.sender, tokenId) < amount) revert NotOwner();
            if (!nft.isApprovedForAll(msg.sender, address(this))) revert NotApproved();
            nft.safeTransferFrom(msg.sender, buyer, tokenId, amount, "");
        }

        _payout(collection, tokenId, msg.sender, price, feeBps);
        emit OfferAccepted(offerId, msg.sender, buyer, price);
    }

    // =========================================================================
    // Lazy (off-chain signed) listings
    // =========================================================================

    /// @dev `abi.encode`, not `encodePacked`: every field is fixed-width today, but an encoding whose
    /// safety depends on that staying true is a trap for the next person who edits the struct.
    /// `lazyOrderEpoch[seller]` is mixed in so `cancelAllLazyOrders()` can invalidate everything a
    /// seller ever signed in one transaction. `maxFeeBps` is the most platform fee the seller agreed
    /// to; a fill charges min(maxFeeBps, platformFeeBps).
    function lazyOrderHash(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint8 tokenType,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps
    ) public view returns (bytes32) {
        return keccak256(abi.encode(
            "PEDDLES_LAZY_LISTING_V2",
            block.chainid,
            address(this),
            seller,
            lazyOrderEpoch[seller],
            collection,
            tokenId,
            amount,
            price,
            tokenType,
            nonce,
            deadline,
            maxFeeBps
        ));
    }

    /// @notice Hash of a COLLECTION-WIDE ("floor") order: the seller signs a price, and the BUYER
    /// picks which of the seller's tokens to take. Deliberate, and the seller must understand it —
    /// signing one of these offers every token they hold in that collection at that price, until it
    /// is filled once, cancelled, or its deadline passes.
    function collectionLazyOrderHash(
        address seller,
        address collection,
        uint256 price,
        uint8 tokenType,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps
    ) public view returns (bytes32) {
        return keccak256(abi.encode(
            "PEDDLES_COLLECTION_LAZY_LISTING_V2",
            block.chainid,
            address(this),
            seller,
            lazyOrderEpoch[seller],
            collection,
            price,
            tokenType,
            nonce,
            deadline,
            maxFeeBps
        ));
    }

    /// @notice Cancel ONE signed order on-chain. A signed order with no on-chain cancel is only
    /// revocable by pulling the collection approval, which also kills every other listing the seller
    /// has — so this exists.
    function cancelLazyOrder(
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint8 tokenType,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps
    ) external {
        bytes32 h = lazyOrderHash(msg.sender, collection, tokenId, amount, price, tokenType, nonce, deadline, maxFeeBps);
        if (usedLazyOrder[h]) revert ListingInactive();
        usedLazyOrder[h] = true;
        emit LazyOrderCancelled(h, msg.sender);
    }

    function cancelCollectionLazyOrder(
        address collection,
        uint256 price,
        uint8 tokenType,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps
    ) external {
        bytes32 h = collectionLazyOrderHash(msg.sender, collection, price, tokenType, nonce, deadline, maxFeeBps);
        if (usedLazyOrder[h]) revert ListingInactive();
        usedLazyOrder[h] = true;
        emit LazyOrderCancelled(h, msg.sender);
    }

    /// @notice Invalidate EVERY order this seller has ever signed, in one transaction. The escape
    /// hatch for a leaked signature, a compromised signing key, or a mass re-price.
    function cancelAllLazyOrders() external returns (uint256 epoch) {
        epoch = ++lazyOrderEpoch[msg.sender];
        emit LazyOrdersInvalidated(msg.sender, epoch);
    }

    function buySignedERC721(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 price,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps,
        bytes calldata signature
    ) external payable nonReentrant {
        _buySigned(seller, collection, tokenId, 1, price, _pack(TYPE_ERC721, false, maxFeeBps), nonce, deadline, signature);
    }

    function buySignedERC1155(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps,
        bytes calldata signature
    ) external payable nonReentrant {
        _buySigned(seller, collection, tokenId, amount, price, _pack(TYPE_ERC1155, false, maxFeeBps), nonce, deadline, signature);
    }

    function buySignedCollectionERC721(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 price,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps,
        bytes calldata signature
    ) external payable nonReentrant {
        _buySigned(seller, collection, tokenId, 1, price, _pack(TYPE_ERC721, true, maxFeeBps), nonce, deadline, signature);
    }

    /// @dev The 1155 collection-wide variant fills exactly ONE piece, because every id in a
    /// `PeddlesBondingCollection` is a 1-of-1 and its `safeTransferFrom` rejects `value != 1`.
    function buySignedCollectionERC1155(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 price,
        uint256 nonce,
        uint64 deadline,
        uint16 maxFeeBps,
        bytes calldata signature
    ) external payable nonReentrant {
        _buySigned(seller, collection, tokenId, 1, price, _pack(TYPE_ERC1155, true, maxFeeBps), nonce, deadline, signature);
    }

    /// @dev tokenType | collectionWide << 8 | maxFeeBps << 16, packed into one word so the internal
    /// fill stays within via-IR's stack budget.
    function _pack(uint8 tokenType, bool collectionWide, uint16 maxFeeBps) private pure returns (uint256) {
        return uint256(tokenType) | (collectionWide ? uint256(1 << 8) : uint256(0)) | (uint256(maxFeeBps) << 16);
    }

    function _buySigned(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint256 packed,
        uint256 nonce,
        uint64 deadline,
        bytes calldata signature
    ) private {
        if (seller == address(0) || collection == address(0)) revert InvalidAddress();
        if (amount == 0) revert InvalidAmount();
        if (price == 0) revert InvalidPrice();
        if (deadline != 0 && deadline < block.timestamp) revert OfferExpired();
        if (msg.value < price) revert InsufficientPayment();

        bytes32 h = _signedOrderHash(seller, collection, tokenId, amount, price, packed, nonce, deadline);
        if (usedLazyOrder[h]) revert ListingInactive();
        if (_recoverEthSigned(h, signature) != seller) revert Unauthorized();
        usedLazyOrder[h] = true; // consumed BEFORE any external call: no replay, no reentrant refill

        _fillSigned(seller, collection, tokenId, amount, uint8(packed));
        _payout(collection, tokenId, seller, price, uint16(packed >> 16));
        _sendOrCredit(msg.sender, msg.value - price);
        emit LazyPurchased(h, msg.sender, seller, collection, tokenId, price, uint8(packed));
    }

    /// @dev The order hash for a packed (tokenType | collectionWide << 8 | maxFeeBps << 16) fill.
    function _signedOrderHash(
        address seller,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint256 price,
        uint256 packed,
        uint256 nonce,
        uint64 deadline
    ) private view returns (bytes32) {
        if ((packed >> 8) & 1 == 1) {
            return collectionLazyOrderHash(
                seller, collection, price, uint8(packed), nonce, deadline, uint16(packed >> 16)
            );
        }
        return lazyOrderHash(seller, collection, tokenId, amount, price, uint8(packed), nonce, deadline, uint16(packed >> 16));
    }

    function _fillSigned(address seller, address collection, uint256 tokenId, uint256 amount, uint8 tokenType)
        private
    {
        if (tokenType == TYPE_ERC721) {
            IPeddlesERC721Lite nft = IPeddlesERC721Lite(collection);
            if (nft.ownerOf(tokenId) != seller) revert NotOwner();
            if (nft.getApproved(tokenId) != address(this) && !nft.isApprovedForAll(seller, address(this))) revert NotApproved();
            nft.safeTransferFrom(seller, msg.sender, tokenId);
        } else {
            IPeddlesERC1155Lite nft = IPeddlesERC1155Lite(collection);
            if (nft.balanceOf(seller, tokenId) < amount) revert NotOwner();
            if (!nft.isApprovedForAll(seller, address(this))) revert NotApproved();
            nft.safeTransferFrom(seller, msg.sender, tokenId, amount, "");
        }
    }

    /// @dev Recover an `eth_sign`-prefixed signature. Returns `address(0)` for anything malformed;
    /// every caller compares the result against a non-zero `seller`, so a zero recovery always
    /// fails closed. The upper-half `s` is rejected: replay is already impossible here (the used-set
    /// is keyed on the ORDER hash, not on the signature bytes) but accepting a second valid
    /// encoding of the same signature is a footgun for anything off-chain that keys on the sig.
    function _recoverEthSigned(bytes32 h, bytes calldata sig) private pure returns (address) {
        if (sig.length != 65) return address(0);
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := calldataload(sig.offset)
            s := calldataload(add(sig.offset, 32))
            v := byte(0, calldataload(add(sig.offset, 64)))
        }
        if (uint256(s) > uint256(HALF_N)) return address(0);
        if (v < 27) v += 27;
        if (v != 27 && v != 28) return address(0);
        bytes32 prefixed = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", h));
        return ecrecover(prefixed, v, r, s);
    }

    // =========================================================================
    // Payment
    // =========================================================================

    /// @dev Split `gross` between the holder-rewards distributor (out of the PLATFORM fee), the
    /// platform, the EIP-2981 royalty receiver (out of the SELLER's proceeds) and the seller.
    /// Conservation is exact by construction: `platform + royalty + (gross - platform - royalty)`.
    function _payout(address collection, uint256 tokenId, address seller, uint256 gross, uint16 maxFeeBps)
        private
    {
        // The order's own fee is a CEILING: an owner may lower the live fee for it, never raise it.
        uint256 feeBps = platformFeeBps < maxFeeBps ? platformFeeBps : maxFeeBps;
        uint256 platform = gross * feeBps / BPS;

        // ---- EIP-2981, honoured defensively -------------------------------------------------
        uint256 royalty;
        address royaltyReceiver;
        {
            (address receiver, uint256 reported) = _royaltyOf(collection, tokenId, gross);
            uint256 cap = gross * MAX_ROYALTY_BPS / BPS;
            uint256 honoured = reported > cap ? cap : reported;
            // The second bound is unreachable while MAX_ROYALTY_BPS + MAX_PLATFORM_FEE_BPS < BPS,
            // and is kept so the arithmetic below can never underflow if those caps ever move.
            if (receiver != address(0) && honoured != 0 && honoured <= gross - platform) {
                royaltyReceiver = receiver;
                royalty = honoured;
            }
        }

        // ---- Holder share, out of the platform fee ------------------------------------------
        uint256 holderCut;
        (address distributor, uint16 shareBps) = holderRoute(collection);
        if (platform != 0 && shareBps != 0) {
            uint256 want = platform * shareBps / BPS;
            if (want != 0 && _fundHolderRewards(distributor, want)) {
                holderCut = want;
                emit HolderRewardsFunded(collection, distributor, want, shareBps);
            }
            // A failed push is NOT fatal and NOT lost: `holderCut` stays 0 and the whole platform
            // fee goes to `feeReceiver`. A hostile distributor can cost its own holders their slice
            // and nothing else — it can never brick the sale.
        }

        _sendOrCredit(feeReceiver, platform - holderCut);
        if (royalty != 0) _sendOrCredit(royaltyReceiver, royalty);
        _sendOrCredit(seller, gross - platform - royalty);
    }

    /// @dev EIP-2981, read the paranoid way: a gas-capped raw staticcall, a length check, and a
    /// hand decode into two words so a collection returning a malformed or dirty `address` cannot
    /// raise an uncatchable ABI-decode exception and brick every sale of its own tokens. A
    /// collection that reverts, returns short, or returns nothing simply pays no royalty.
    function _royaltyOf(address collection, uint256 tokenId, uint256 gross)
        private
        view
        returns (address receiver, uint256 amount)
    {
        (bool ok, bytes memory data) = collection.staticcall{gas: VIEW_GAS}(
            abi.encodeWithSelector(IPeddlesRoyaltyLite.royaltyInfo.selector, tokenId, gross)
        );
        if (!ok || data.length < 64) return (address(0), 0);
        (uint256 receiverWord, uint256 amountWord) = abi.decode(data, (uint256, uint256));
        return (address(uint160(receiverWord)), amountWord);
    }

    /// @dev Fund a `PeddlesNftHolderRewards` the only way it accepts funding: transfer the asset in
    /// (native lands in its `receive()`) then poke its permissionless `sync()` so the delta is
    /// recognised in the same transaction. Both calls are gas-capped and neither may revert the
    /// sale. If `sync()` fails the wei is still sitting in the distributor and ANYONE can call
    /// `sync()` later, so nothing is stranded.
    function _fundHolderRewards(address distributor, uint256 amount) private returns (bool ok) {
        (ok,) = distributor.call{value: amount, gas: PUSH_GAS}("");
        if (!ok) return false;
        try IPeddlesHolderRewardsSyncLite(distributor).sync{gas: SYNC_GAS}() {} catch {}
    }

    /// @dev Push native under a bounded stipend; on failure book a credit instead of reverting.
    /// This is what makes "a broken recipient cannot brick a sale, and cannot strand its own money"
    /// true for the buyer's change, the seller's proceeds, the platform fee, the royalty and an
    /// offer refund alike.
    function _sendOrCredit(address to, uint256 amount) private {
        if (amount == 0) return;
        if (to != address(0)) {
            (bool ok,) = payable(to).call{value: amount, gas: PUSH_GAS}("");
            if (ok) return;
        }
        // `to == address(0)` is unreachable (every caller passes a checked non-zero address), but
        // crediting the fee receiver rather than burning to address(0) keeps the invariant total.
        address credited = to == address(0) ? feeReceiver : to;
        credits[credited] += amount;
        totalCredited += amount;
        emit PaymentCredited(credited, amount);
    }

    /// @notice Withdraw native that a failed push booked to you. All remaining gas is forwarded, so
    /// a contract wallet too expensive for the push stipend is never locked out.
    function withdrawCredits() external nonReentrant returns (uint256 amount) {
        amount = credits[msg.sender];
        if (amount == 0) revert NothingToWithdraw();
        credits[msg.sender] = 0;
        totalCredited -= amount;
        (bool ok,) = payable(msg.sender).call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit CreditsWithdrawn(msg.sender, amount);
    }

    // =========================================================================
    // Rescue — the no-stuck-funds rule, discharged
    // =========================================================================

    /// @notice Sweep native that belongs to nobody to `feeReceiver`.
    /// @dev PERMISSIONLESS to call and UNDIRECTABLE: there is no recipient argument and no amount
    /// argument, so neither a keeper nor the owner can name a payee or take more than exists. It is
    /// arithmetically incapable of touching offer escrow or credits, because the amount it moves is
    /// defined as `balance - totalEscrowed - totalCredited`. Nothing can reach this contract through
    /// a normal path, so in practice this only ever collects a `selfdestruct` or coinbase payout —
    /// but "in practice nothing arrives" is not an exit, and the rule requires an exit.
    ///
    /// The payment goes out through `_sendOrCredit`, the SAME primitive as a seller's proceeds, a
    /// royalty, a buyer's change and an offer refund — not a raw all-gas `call` that reverts
    /// `TransferFailed`. It used to be the latter, which meant a `feeReceiver` that cannot be paid
    /// by push (a paused or bricked contract wallet, one that needs more than the stipend) blocked
    /// this exit ENTIRELY until the owner happened to call `setFee`. A permissionless exit that an
    /// unrelated owner-held config value can switch off is not permissionless, and "the owner can
    /// fix it" is exactly the escape-hatch-with-a-precondition shape the rule forbids. Now the
    /// stray always leaves the stray bucket: it is either pushed or booked as a credit to
    /// `feeReceiver`, which is drawn later by `withdrawCredits()` with all gas forwarded. The
    /// accounting identity survives either way — the wei simply moves from term 3 to term 2.
    function sweepStrayNative() external nonReentrant returns (uint256 amount) {
        amount = strayNative();
        if (amount == 0) revert NothingToWithdraw();
        address to = feeReceiver;
        _sendOrCredit(to, amount);
        emit StraySwept(to, amount);
    }

    /// @notice Recover an ERC-20 force-sent here: its whole balance, to `feeReceiver`.
    /// @dev PERMISSIONLESS and UNDIRECTABLE, like `sweepStrayNative` (2026-09-16). It was an owner
    /// rescue of any amount to an owner-chosen address. This contract never legitimately holds an
    /// ERC-20, so nothing here is owed in one.
    ///
    /// NEVER THE ESCROW THROUGH ITS OTHER INTERFACE. Where a token is an ERC-20 view of the native
    /// balance (Arc's USDC: `balanceOf == floor(native / 1e12)`), offer escrow and credits ARE that
    /// token's balance here. So a transfer that lowers this contract's native balance reverts; such a
    /// stray is already native and leaves through `sweepStrayNative`, which cannot reach escrow.
    function rescueERC20(address token) external nonReentrant {
        if (token == address(0)) revert InvalidAddress();
        address to = feeReceiver;
        uint256 amount = IMarketplaceERC20(token).balanceOf(address(this));
        uint256 nativeBefore = address(this).balance;
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IMarketplaceERC20.transfer.selector, to, amount));
        if (!success || (data.length != 0 && !abi.decode(data, (bool)))) revert TransferFailed();
        if (address(this).balance < nativeBefore) revert TransferFailed();
        emit Rescued(token, to, amount);
    }

    /// @notice Recover an ERC-721 force-sent here with an UNSAFE `transferFrom` (the only way one
    /// can arrive — this contract implements no receiver hook, so every safe transfer to it
    /// reverts at the source, which is also why an ERC-1155 can never land here at all).
    /// @dev The marketplace is non-custodial: it never holds a user's NFT as part of any flow, so
    /// this can only ever move an asset that is already lost. PERMISSIONLESS and pays `feeReceiver`
    /// (2026-09-16); it was an owner rescue to an owner-chosen address.
    function rescueERC721(address collection, uint256 tokenId) external nonReentrant {
        if (collection == address(0)) revert InvalidAddress();
        address to = feeReceiver;
        IPeddlesERC721Lite(collection).transferFrom(address(this), to, tokenId);
        emit Rescued(collection, to, tokenId);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "solady/=lib/solady/",
    "@openzeppelin/contracts/=lib/infinity-core/lib/openzeppelin-contracts/contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "infinity-core/=lib/infinity-core/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/infinity-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
    "lib/infinity-core/lib/pancake-create3-factory/:forge-gas-snapshot/=lib/infinity-core/lib/pancake-create3-factory/lib/forge-gas-snapshot/src/",
    "lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
    "lib/infinity-core/lib/pancake-create3-factory/:openzeppelin-contracts/=lib/infinity-core/lib/pancake-create3-factory/lib/openzeppelin-contracts/",
    "lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
    "lib/infinity-core/lib/solmate/:ds-test/=lib/infinity-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
    "lib/infinity-core/:solmate/=lib/infinity-core/lib/solmate/",
    "lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "lib/infinity-core/:openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/infinity-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/infinity-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/infinity-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/infinity-core/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/infinity-core/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/infinity-core/lib/openzeppelin-contracts/",
    "pancake-create3-factory/=lib/infinity-core/lib/pancake-create3-factory/",
    "solmate/=lib/infinity-core/lib/solmate/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.