Skip to content
Verified contractExactMIT

GloomblesRR

Address0x64c32eb3a4b4c33dc6cf94e89a5542dd30c99b3a
Balance

0 ETH

 

Transactions

14,060

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,590,379
Creation transaction
0x1001afd1af…628169932f

src/GloomblesRR.sol

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

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {Base64} from "solady/utils/Base64.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";
import {INonFungibleSeaDropToken} from "./seadrop/INonFungibleSeaDropToken.sol";
import {ISeaDropTokenContractMetadata} from "./seadrop/ISeaDropTokenContractMetadata.sol";
import {ISeaDrop} from "./seadrop/ISeaDrop.sol";
import {GloomblesStorage} from "./GloomblesStorage.sol";
import {
    PublicDrop,
    AllowListData,
    TokenGatedDropStage,
    SignedMintValidationParams
} from "./seadrop/SeaDropStructs.sol";

/// @title  GloomblesRR
/// @notice Fully on-chain pixel PFPs with a verifiable re-roll. Each token mints
///         with an instantly-assigned unique combo (color + one trait per slot);
///         the holder can re-roll it up to MAX_REROLLS times, gated by a 24h
///         cooldown, each roll powered by a future-blockhash commit-reveal (no oracle).
/// @dev    Launch-friendly: NO daily reveal, NO VRF subscription, NO external indexer.
///         Re-roll is commit->finalize: reRoll() commits to a future block; once mined,
///         the permissionless finalizeReRoll() (relayer/keeper or the holder) applies it.
///
///         RARITY TIERS: each color and each per-slot trait has a weight. Draws
///         are weighted, so tiers (common…legendary) are just relative weights
///         set at deploy. Live population counts (`colorPop`, `slotPop`) are kept
///         ON-CHAIN and updated on every mint + re-roll, so realized rarity is
///         readable without an indexer. Designed rarity (the weights) is fixed up
///         front; realized rarity moves as pieces mint and re-roll.
///
///         ALL-TIME UNIQUENESS: every combo ever assigned is permanently reserved
///         in `usedCombo`; rejection-sampling guarantees no piece ever shares art
///         with any other, past or present.
contract GloomblesRR is GloomblesStorage {
    using Strings for uint256;

    // The shared storage layout (Token struct, all constants, all state vars,
    // events, errors, and the view/pure helpers _ruleKey/_traitKey/_nonzero/
    // comboSpace/_assertComboSpace) lives in GloomblesStorage so the owner-gated
    // fallback() delegatecall module (MultiConfigureImpl) sees the same slots.

    // ───────────────────────────────────────────────────────── constructor ──

    constructor(uint256 _maxSupply, address _multiConfigureImpl)
        GloomblesStorage("gloombles", "GLOOM")
    {
        if (_maxSupply == 0) revert InvalidConfig();
        // The module is the fallback's delegatecall target; a codeless address (EOA /
        // address(0)) would make delegatecall return success and SILENTLY no-op every
        // owner config call (incl. freezeConfig). Reject it at construction — the impl is
        // immutable (no setter), so this is the only place it can be validated. (audit LOW-6)
        if (_multiConfigureImpl.code.length == 0) revert InvalidConfig();
        maxSupply = _maxSupply;
        multiConfigureImpl = _multiConfigureImpl; // delegatecall target for multiConfigure (Upgrade B)
        // Default 5% royalty to the deployer; owner can change via setRoyaltyInfo.
        _royaltyInfo = RoyaltyInfo({royaltyAddress: msg.sender, royaltyBps: 500});
    }

    // ─────────────────────────────────────────────────── multiConfigure proxy ──
    // OpenSea Studio "Publish" calls multiConfigure(...) on the token. The full
    // function would blow the EIP-170 limit, so it lives in multiConfigureImpl and is
    // reached via this owner-gated delegatecall (runs in THIS token's storage). (B1)
    fallback() external {
        if (msg.sender != owner()) revert NotOwner();
        address impl = multiConfigureImpl;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if iszero(ok) { revert(0, returndatasize()) }
            return(0, returndatasize())
        }
    }

    // ──────────────────────────────────────────────────────────────── mint ──

    // The standalone public mint() was removed (audit LOW-1): minting is
    // OpenSea-only via mintSeaDrop, so there is no second door that could bypass
    // SeaDrop's allowlist / per-wallet / pricing enforcement. ownerMint remains
    // for team/promo allocations.

    /// @notice Owner mint (team/promo allocations, and seeding test wallets).
    function ownerMint(address to, uint256 quantity) external onlyOwner {
        for (uint256 i; i < quantity; i++) {
            _mintTo(to);
        }
    }

    function _mintTo(address to) internal returns (uint256 tokenId) {
        if (totalMinted >= maxSupply) revert SoldOut();
        if (colorWeights.length == 0 || slotWeights.length == 0) revert NotConfigured();
        // No mints once a reveal is committed. Tokens minted after scheduleReveal fall
        // outside the rotation snapshot (identity-mapped, combo readable) → rarity-snipe.
        // mintSeaDrop already guards this; enforcing it here also closes ownerMint. (audit M-1)
        if (revealBlock != 0) revert MintClosed();

        // Public token ids are 1-based (the collection runs 1..maxSupply), but the
        // combo / re-roll / reveal state is keyed by a 0-based STORAGE id
        // (sid = tokenId - 1) so the reveal rotation domain stays [0, revealSupply)
        // and the shift bijection is unchanged. At mint (pre-reveal) sid == the
        // 0-based index by definition.
        uint256 sid = totalMinted;
        tokenId = totalMinted + 1;
        // Update supply + per-wallet counters BEFORE _safeMint: SeaDrop reads
        // getMintStats() to enforce limits, and a malicious onERC721Received
        // hook must never see stale counts (the interface mandates this order).
        unchecked {
            totalMinted++;
            _numberMinted[to]++;
        }
        _safeMint(to, tokenId);

        // Pre-defined 1/1: this storage id was reserved (setOneOfOnes) with a fixed
        // exclusive combo already written to _slots/_comboHash/_tokens[sid].colorId +
        // its hash reserved. Materialize it — count it into the live population + emit —
        // WITHOUT drawing or overwriting the combo. It stays Normal-tier but locked
        // (reRoll / merge revert LockedOneOfOne). At reveal it scatters to a random id.
        if (_isOneOfOne[sid]) {
            Token storage o = _tokens[sid];
            _incCounts(o.colorId, _slots[sid]);
            emit Minted(tokenId, to, _comboHash[sid]);
            return tokenId;
        }

        uint256 seed =
            uint256(keccak256(abi.encode(block.prevrandao, block.timestamp, tokenId, to)));
        // mintMode = true: mints are Normal tier — special (Epic/Legendary) traits are
        // won by rolling, never drawn at mint. The trait COUNT is drawn from the mint
        // distribution (mint diversity); _uniqueCombo spills up if a sparse count is full.
        (uint16 colorId, uint16[] memory slots, bytes32 hash) =
            _uniqueCombo(seed, _drawMintCount(seed), true, true); // mint: mintMode + spillUp
        _commitCombo(sid, slots, hash);
        // Mints start at a drawn count (1..MINT_TRAITS), Normal tier; the evolve
        // rolls grow the count toward MAX_TRAITS and the final roll gambles on tier.
        // lastRerollAt = 0 so the FIRST re-roll is available immediately; the 24h
        // cooldown only applies BETWEEN re-rolls (set on each fulfillment).
        _tokens[sid] = Token({
            colorId: colorId,
            rerollCount: 0,
            lastRerollAt: 0,
            rollPending: false,
            tier: TIER_NORMAL,
            traitCount: _countFilled(slots) // the drawn mint count (after any spill-up)
        });
        _incCounts(colorId, slots);

        emit Minted(tokenId, to, hash);
    }

    // ────────────────────────────────────────────────────────────── reroll ──

    /// @notice Live per-roll fee. `rerollPrice`: 0 = free (default), type(uint256).max = DYNAMIC
    ///         (auto-scales with block.basefee so it only ever charges ~the keeper's finalize
    ///         cost), any other value = that flat fee. The dapp reads this and sends it (padded —
    ///         basefee can rise before the tx mines; the contract refunds the overage).
    function currentRerollFee() public view returns (uint256) {
        uint256 p = rerollPrice;
        if (p != type(uint256).max) return p; // 0 = free, else the flat amount
        return REROLL_FINALIZE_GAS * (block.basefee + REROLL_FEE_TIP) * REROLL_FEE_BPS / 10_000;
    }

    /// @notice Step 1 of 2 — commit a re-roll to a future block. The art does NOT
    ///         change yet; once block.number > commit+REROLL_DELAY, finalizeReRoll
    ///         applies it (the dapp's relayer/keeper or the holder — permissionless).
    function reRoll(uint256 tokenId) external payable nonReentrant {
        // Re-rolls open at the reveal: you re-roll the art you can SEE, and the
        // reveal rotation must be fixed before any combo state mutates.
        if (!revealed) revert NotRevealed();
        uint256 fee = currentRerollFee(); // gas-scaled (or flat rerollPrice override)
        if (msg.value < fee) revert WrongPrice();
        _commitReroll(tokenId, block.number + REROLL_DELAY);
        _refundOverpay(fee);
    }

    /// @notice Batch re-roll: commit MANY of your gloombles in ONE signature. Every token
    ///         shares the same future entropy block — outcomes are DISTINCT (each seed mixes
    ///         sid + count) but not statistically independent (one blockhash drives the whole
    ///         batch); all-time uniqueness still holds. The keeper finalizes them together.
    ///         Fee is rerollPrice * count.
    ///         All-or-nothing: reverts whole if ANY id is ineligible (not owner / locked /
    ///         pending / capped / on cooldown), so nothing commits unless everything can.
    function reRollMany(uint256[] calldata tokenIds) external payable nonReentrant {
        if (!revealed) revert NotRevealed();
        uint256 n = tokenIds.length;
        if (n == 0) revert InvalidConfig();
        uint256 fee = currentRerollFee() * n;
        if (msg.value < fee) revert WrongPrice();
        uint256 entropyBlock = block.number + REROLL_DELAY; // shared by the whole batch
        for (uint256 i; i < n; ++i) _commitReroll(tokenIds[i], entropyBlock);
        _refundOverpay(fee);
    }

    /// @dev Per-token commit shared by reRoll + reRollMany: validate eligibility, mark the
    ///      roll pending, and arm `entropyBlock` for the future-blockhash reveal.
    function _commitReroll(uint256 tokenId, uint256 entropyBlock) private {
        if (_ownerOf(tokenId) != msg.sender) revert NotOwner();
        uint256 sid = _sid(tokenId);
        Token storage t = _tokens[sid];
        if (_isOneOfOne[sid]) revert LockedOneOfOne(); // pre-defined 1/1: fixed art, never rolls
        if (t.tier != TIER_NORMAL) revert TierLocked(); // Epic/Legendary freeze the look
        if (t.rollPending) revert RollPending();
        if (t.rerollCount >= MAX_REROLLS) revert MaxRerollsReached();
        // 2 re-rolls per cooldown window: the 24h wait applies only before STARTING a new
        // pair (after every 2nd re-roll). rerollCount here is the count BEFORE this roll, so
        // it's even (>0) exactly at pair starts.
        if (t.rerollCount % 2 == 0 && t.rerollCount > 0
            && block.timestamp - t.lastRerollAt < REROLL_COOLDOWN) revert CooldownActive();
        // CEI: mark pending + commit the entropy block before any refund call.
        t.rollPending = true;
        _rerollBlock[sid] = entropyBlock;
        emit ReRollRequested(tokenId, entropyBlock, t.rerollCount + 1);
    }

    /// @dev Refund any overpay above `fee` (called after all state writes — CEI).
    function _refundOverpay(uint256 fee) private {
        uint256 refund = msg.value - fee;
        if (refund > 0) {
            (bool ok,) = msg.sender.call{value: refund}("");
            if (!ok) revert RefundFailed();
        }
    }

    /// @notice Step 2 of 2 — PERMISSIONLESS finalize once the entropy block is mined.
    ///         Identical effect to the old VRF callback; the seed is the blockhash.
    /// @dev    NOT nonReentrant: the whole draw is internal storage (no external call,
    ///         no value transfer), so there is no reentrancy surface — and dropping the
    ///         guard lets finalizeReRollMany isolate each id via a try/catch self-call.
    function finalizeReRoll(uint256 tokenId) external {
        uint256 sid = _sid(tokenId);
        if (!_tokens[sid].rollPending) revert NoPendingRoll();
        uint256 eb = _rerollBlock[sid];
        if (block.number <= eb) revert RerollNotReady();
        bytes32 entropy = blockhash(eb);
        if (entropy == bytes32(0)) revert RerollEntropyExpired(); // >256 blocks late -> resetStuckRoll
        _applyReroll(sid, entropy);
    }

    /// @notice Keeper batch: finalize many in one tx. Each id runs in an ISOLATED
    ///         self-call, so ANY revert — not pending / block not mined / entropy
    ///         expired / combo-space exhausted — SKIPS just that id and the rest of the
    ///         batch proceeds. One poisoned id can never revert the whole batch (audit
    ///         M-2). Caller sizes the array to fit block gas (~20-40/tx).
    /// @dev    Caller MUST COMPUTE the gas limit (~1.5M + n*per-id) and never ESTIMATE it:
    ///         the loop breaks while gasleft() < 1.5M, that break SUCCEEDS having finalized
    ///         nothing, and eth_estimateGas converges on exactly that degenerate no-op — a
    ///         keeper on estimated gas then sweeps zero tokens forever while reporting healthy
    ///         tx hashes. The keeper (web /api/cron/finalize) computes the limit AND asserts
    ///         receipt.gasUsed to catch a no-op. An on-chain `attempted==0` revert was dropped
    ///         to stay under the EIP-170 size limit; re-add it when GloomblesRR is slimmed
    ///         (move code into the delegatecall impl) for mainnet. (see task #23)
    function finalizeReRollMany(uint256[] calldata tokenIds) external {
        for (uint256 i; i < tokenIds.length; ++i) {
            if (gasleft() < 1_500_000) break;
            try this.finalizeReRoll(tokenIds[i]) {} catch {}
        }
    }

    /// @dev Shared finalize body (single + batch). Decodes the roll outcome from the
    ///      entropy blockhash: every roll EVOLVES the trait count (reshuffle / +1 / +2),
    ///      and a drawn special trait claims its tier (rarity-as-status) + freezes the
    ///      gloomble. All outcomes are non-destructive — see ROLL-MECHANIC-SPEC.md.
    function _applyReroll(uint256 sid, bytes32 entropy) private {
        Token storage t = _tokens[sid];
        delete _rerollBlock[sid];
        bytes32 oldHash = _comboHash[sid];
        uint256 seed = uint256(keccak256(abi.encode(entropy, address(this), sid, t.rerollCount)));
        // Every roll EVOLVES: 75% reshuffle (count unchanged) / 20% +1 trait / 5% +2,
        // capped at MAX_TRAITS. The draw can also land an unclaimed special trait, which
        // _redraw claims + sets the tier (which then freezes the gloomble). No gamble.
        uint256 r = seed % 100;
        uint8 newCount = t.traitCount;
        if (r >= 95) newCount += 2;
        else if (r >= 75) newCount += 1;
        if (newCount > MAX_TRAITS) newCount = MAX_TRAITS;
        _redraw(sid, t, seed, newCount, false);

        unchecked {
            t.rerollCount += 1;
        }
        t.lastRerollAt = uint64(block.timestamp);
        t.rollPending = false;

        emit ReRolled(_tid(sid), oldHash, _comboHash[sid], t.rerollCount);
        emit MetadataUpdate(_tid(sid)); // ERC-4906: art changed → marketplaces refresh this token (M-3)
    }

    /// @dev Redraw a token's combo to `newCount` filled categories, moving population
    ///      counts and reserving the fresh unique combo. Used by the evolve rolls
    ///      (mintMode=false — specials can land) and by merge (mintMode=true — special-free).
    function _redraw(uint256 sid, Token storage t, uint256 seed, uint8 newCount, bool mintMode) private {
        _decCounts(t.colorId, _slots[sid]);
        (uint16 colorId, uint16[] memory slots, bytes32 newHash) = _uniqueCombo(seed, newCount, mintMode, false);
        _commitCombo(sid, slots, newHash);
        t.colorId = colorId;
        t.traitCount = _countFilled(slots); // actual fill (caps at the categories that exist)
        _incCounts(colorId, slots);
        // Claim any drawn special trait (cap-1) and set the tier — a non-zero tier
        // freezes the gloomble (reRoll reverts TierLocked).
        _applyTier(sid, colorId, slots);
    }

    /// @notice Recover a token whose committed re-roll fell out of the 256-block
    ///         blockhash window (never finalized in time). Callable by the holder or
    ///         owner. STICKY RE-COMMIT (audit MED-4): instead of CANCELLING the roll —
    ///         which would let a holder trivially peek at the (now-public) outcome, discard
    ///         a bad one, and fish again — it RE-ARMS the SAME roll (rollPending stays true,
    ///         rerollCount unchanged, no fee) with a fresh entropy block. An honest holder
    ///         whose keeper failed loses nothing.
    ///         CAVEAT (audit 2026-07-10, LOW): the re-armed entropy is a NEW, INDEPENDENT
    ///         future blockhash, so the anti-fishing property is keeper-liveness-contingent,
    ///         not structural. Under a SUSTAINED keeper outage a holder could peek the
    ///         re-armed outcome, decline to finalize, wait out another 256-block window,
    ///         reset again, and repeat — shopping across independent outcomes without
    ///         consuming a roll. In practice finalizeReRoll is PERMISSIONLESS (the keeper or
    ///         any observer finalizes the moment the re-armed block matures) and each cycle
    ///         costs ~52 min, so a live keeper closes the window immediately. Fully structural
    ///         fix (deferred, EIP-170): cap resets, or derive the re-armed entropy from the
    ///         ORIGINAL commit so no fresh outcome is ever exposed.
    function resetStuckRoll(uint256 tokenId) external nonReentrant {
        _requireMinted(tokenId);
        if (_ownerOf(tokenId) != msg.sender && msg.sender != owner()) revert NotOwner();
        uint256 sid = _sid(tokenId);
        Token storage t = _tokens[sid];
        if (!t.rollPending) revert RollNotStuck();
        uint256 entropyBlock = _rerollBlock[sid];
        // "stuck" only once the 256-block blockhash window has fully passed.
        if (block.number <= entropyBlock + _BLOCKHASH_WINDOW) revert RollNotStuck();
        // Re-arm the SAME roll (rollPending stays true, rerollCount unchanged) with a
        // fresh future entropy block. RollReset reports the expired block; ReRollRequested
        // re-notifies the relayer/keeper of the new one.
        uint256 newEntropyBlock = block.number + REROLL_DELAY;
        _rerollBlock[sid] = newEntropyBlock;
        emit RollReset(tokenId, entropyBlock);
        emit ReRollRequested(tokenId, newEntropyBlock, t.rerollCount + 1);
    }

    /// @notice MERGE (sacrifice): burn MERGE_BURN of your gloombles to COMPLETE an
    ///         incomplete held `hostId` into a full MAX_TRAITS "Mythic". The burned ones
    ///         are pure sacrifice (their traits do NOT transfer); the host keeps its token
    ///         id + provenance, is completed to a fresh unique MAX_TRAITS combo at Normal
    ///         tier (specials are still won by rolling, never minted or merged), and is
    ///         granted MERGE_ROLLS fresh rolls to chase a Legendary. ONE merge per host:
    ///         the _hostMerged flag (set below) blocks any re-merge — robust even if the trait
    ///         file has fewer than MAX_TRAITS reachable categories (so a forged host caps below
    ///         10), so the Mythic count is bounded by distinct hosts. Deflationary: the
    ///         MERGE_BURN sacrifices leave circulation forever (net -MERGE_BURN supply per merge).
    /// @dev    No `nonReentrant`: merge makes NO external call (OZ `_burn` has no receiver hook;
    ///         _redraw/_decCounts/_incCounts are internal storage), so reentrancy is impossible.
    function merge(uint256 hostId, uint256[] calldata burnIds) external {
        if (!revealed) revert NotRevealed();
        if (burnIds.length != MERGE_BURN) revert MergeInvalid();
        if (_ownerOf(hostId) != msg.sender) revert NotOwner();
        uint256 hsid = _sid(hostId);
        Token storage h = _tokens[hsid];
        if (_isOneOfOne[hsid]) revert LockedOneOfOne(); // a 1/1's fixed art can't be merged away
        if (h.tier != TIER_NORMAL) revert TierLocked(); // a special host is frozen
        // One merge per host — authoritative regardless of trait count (works even when the trait
        // file has fewer than MAX_TRAITS reachable categories, so a forged host caps below 10).
        // ...and a host ALREADY at MAX_TRAITS has nothing to complete, so it is turned away here
        // rather than paying five tokens to redraw at the same count.
        //
        // NOTE ON THE ROLL BUDGET (deliberate, confirmed by the owner): the write below is an
        // ASSIGNMENT, not a clamp. Merging sets the host to exactly MERGE_ROLLS remaining no
        // matter what it had spent, so a token that exhausted all MAX_REROLLS first reaches
        // MAX_REROLLS + MERGE_ROLLS = 8 lifetime rolls, and a token that merges with a full
        // budget FORFEITS the unspent remainder down to MERGE_ROLLS. Both directions are
        // intended: the merge grant is a fresh allowance attached to the forged Mythic, not a
        // top-up of the original budget. MAX_REROLLS is therefore a per-phase cap, not a
        // lifetime one — say "5 rolls, then 3 more after a forge" in holder-facing copy, never
        // "5 total". Folded into one branch to save bytecode.
        if (_hostMerged[hsid] || h.traitCount >= MAX_TRAITS) revert MergeHostComplete();
        if (h.rollPending) revert RollPending();

        // Burn the sacrifices — each must be owned, eligible, and distinct from the host.
        // (A duplicate id reverts on its 2nd pass: ownerOf of an already-burned token != caller.)
        for (uint256 i = 0; i < MERGE_BURN; i++) {
            uint256 bid = burnIds[i];
            if (bid == hostId) revert MergeInvalid();
            if (_ownerOf(bid) != msg.sender) revert NotOwner();
            uint256 bsid = _sid(bid);
            Token storage b = _tokens[bsid];
            if (_isOneOfOne[bsid]) revert LockedOneOfOne(); // a 1/1 can never be sacrificed
            if (b.tier != TIER_NORMAL) revert TierLocked(); // Epic/Legendary are frozen
            // A Mythic (or forged host) is terminal — it leaves the merge loop forever and can
            // never be a sacrifice. Two conditions, one error (kept single to stay under the
            // EIP-170 size limit): by STATUS (traitCount >= MAX_TRAITS) so a naturally-evolved
            // 11-trait Mythic is covered, AND by provenance (_hostMerged) so a forged host that
            // capped below MAX_TRAITS on a too-small trait file is still protected.
            if (b.traitCount >= MAX_TRAITS || _hostMerged[bsid]) revert NotBurnable();
            if (b.rollPending) revert RollPending();
            _decCounts(b.colorId, _slots[bsid]); // remove the sacrifice from live population
            _burn(bid);
        }

        // Ascend the host to a fresh, unique, special-free MAX_TRAITS Mythic.
        uint256 seed =
            uint256(keccak256(abi.encode(block.prevrandao, block.timestamp, hostId, h.rerollCount)));
        _redraw(hsid, h, seed, MAX_TRAITS, true); // mintMode=true -> no special on the merge itself

        // Grant MERGE_ROLLS fresh rolls (the host now starts at 10, so all are
        // Legendary-eligible), available immediately. Reuses the reroll budget by
        // leaving (MAX_REROLLS - MERGE_ROLLS) "used".
        h.rerollCount = MAX_REROLLS - MERGE_ROLLS;
        h.lastRerollAt = 0;
        h.rollPending = false;
        _hostMerged[hsid] = true; // forged — can never be a merge host again

        emit Merged(hostId, burnIds, h.traitCount);
        emit MetadataUpdate(hostId); // ERC-4906: host ascended to a new combo → refresh it (M-3)
    }

    // ──────────────────────────────────────────── combo derivation + counts ──

    function _commitCombo(uint256 sid, uint16[] memory slots, bytes32 hash) private {
        usedCombo[hash] = true;
        unchecked {
            usedComboCount++;
        }
        _slots[sid] = slots;
        _comboHash[sid] = hash;
    }

    function _incCounts(uint16 colorId, uint16[] memory slots) private {
        _bumpPop(0, colorId, true);
        unchecked {
            for (uint256 i = 0; i < slots.length; i++) {
                if (slots[i] != 0) _bumpPop(i + 1, slots[i], true);
            }
        }
    }

    function _decCounts(uint16 colorId, uint16[] memory slots) private {
        _bumpPop(0, colorId, false);
        unchecked {
            for (uint256 i = 0; i < slots.length; i++) {
                if (slots[i] != 0) _bumpPop(i + 1, slots[i], false);
            }
        }
    }

    /// @dev Draw a mint's starting trait count from the mint distribution (mintCountWeights).
    ///      Empty/never-set => the fixed MINT_TRAITS baseline (back-compat). Reuses the
    ///      shared weighted picker — the 1-based index it returns IS the trait count.
    function _drawMintCount(uint256 seed) private view returns (uint8) {
        if (mintCountWeights.length == 0) return MINT_TRAITS;
        return uint8(_weightedPick(mintCountWeights, mintCountTotalWeight, keccak256(abi.encode(seed, "mc"))));
    }

    /// @dev Rejection-sample from `seed` for a combo that's (a) not yet used, (b) violates
    ///      no trait-exclusion rule, and (c) draws no forbidden special (mint rejects all;
    ///      a roll rejects claimed specials + a Legendary below MAX_TRAITS). At MINT, if a
    ///      low count's combo space is exhausted, the count SPILLS UP toward MINT_TRAITS so
    ///      a sparse mint can never brick; rolls hold their exact evolved count.
    function _uniqueCombo(uint256 seed, uint8 targetCount, bool mintMode, bool spillUp)
        private
        view
        returns (uint16 colorId, uint16[] memory slots, bytes32 hash)
    {
        // spillUp (real mints only): a sparse count may exhaust its small combo space, so
        // escalate UP toward MINT_TRAITS. Rolls and merge hold their exact count (a merge
        // is mintMode=true but targetCount=MAX_TRAITS, so it must NOT escalate down).
        uint8 maxCount = spillUp ? MINT_TRAITS : targetCount;
        for (uint8 tc = targetCount; tc <= maxCount; tc++) {
            for (uint256 a = 0; a < _MAX_DRAW_ATTEMPTS; a++) {
                (colorId, slots, hash) = _drawCombo(uint256(keccak256(abi.encode(seed, tc, a))), tc);
                if (
                    !usedCombo[hash] && !_violatesRules(colorId, slots)
                        && !_rejectSpecials(colorId, slots, mintMode)
                ) {
                    return (colorId, slots, hash);
                }
            }
        }
        revert ComboSpaceExhausted();
    }

    /// @dev Weighted draw of one combo with `targetCount` filled categories (body color +
    ///      filled slots). MANDATORY slots (mandatorySlotMask) ALWAYS fill — every gloomble
    ///      gets that base (e.g. background + mouth + shadow), so none is a bare blob. The
    ///      remaining "trait count" is then drawn over the OPTIONAL slots (a seeded subset
    ///      fills, the rest stay 0). The trait VALUE inside each filled slot is its per-slot
    ///      weight table — value rarity and count are independent axes. Mask 0 => every slot
    ///      is optional (the original behavior; back-compat for any config that sets no
    ///      mandatory slots). The realized count clamps at the base (1 + #mandatory).
    function _drawCombo(uint256 seed, uint8 targetCount)
        private
        view
        returns (uint16 colorId, uint16[] memory slots, bytes32 hash)
    {
        colorId = _weightedPick(colorWeights, colorTotalWeight, keccak256(abi.encode(seed, "color")));
        slots = new uint16[](slotWeights.length);
        uint256[] memory pool = new uint256[](slots.length);
        uint256 poolLen;
        uint256 fill;
        // Scoped block keeps mask/n/i/mand off the stack before the Fisher-Yates loop
        // (avoids "stack too deep" without via_ir, which would blow the EIP-170 limit).
        {
            uint256 mask = mandatorySlotMask;
            uint256 mand;
            for (uint256 i = 0; i < slots.length; i++) {
                if (slotTotalWeight[i] == 0) continue; // not fillable
                if ((mask >> i) & 1 == 1) {
                    // MANDATORY slot — always filled on every gloomble.
                    slots[i] = _weightedPick(slotWeights[i], slotTotalWeight[i], keccak256(abi.encode(seed, "val", i)));
                    unchecked { mand++; }
                } else {
                    pool[poolLen] = i; // OPTIONAL candidate
                    unchecked { poolLen++; }
                }
            }
            // count beyond color + the always-present mandatory base
            fill = uint256(targetCount) > 1 + mand ? uint256(targetCount) - 1 - mand : 0;
        }
        if (fill > poolLen) fill = poolLen;

        // Partial Fisher-Yates over the OPTIONAL pool; the unpicked optional slots stay 0.
        for (uint256 k = 0; k < fill; k++) {
            uint256 j = k + (uint256(keccak256(abi.encode(seed, "pick", k))) % (poolLen - k));
            (pool[k], pool[j]) = (pool[j], pool[k]);
            slots[pool[k]] =
                _weightedPick(slotWeights[pool[k]], slotTotalWeight[pool[k]], keccak256(abi.encode(seed, "val", pool[k])));
        }
        hash = keccak256(abi.encode(colorId, slots));
    }

    /// @dev True if `colorId` + `slots` trip any trait-exclusion rule. O(rules), one
    ///      packed SLOAD each — NOT O(slots^2) mapping probes. A rule fires only when
    ///      BOTH sides are present on the combo, so it is symmetric and order-free.
    ///      idB == 0 is a WILDCARD matching any filled trait in catB. Category 0 is the
    ///      body color (always present); category s+1 is slot s.
    ///
    ///      The out-of-range SKIP is load-bearing, not defensive noise. setForbiddenPairs
    ///      bounds-checks against slotWeights.length AT CALL TIME, but setTraits is
    ///      re-callable pre-mint and rebuilds slotWeights at any arity without revisiting
    ///      existing rules. Shrinking the slot count therefore strands a rule pointing
    ///      past the end, and an unguarded slots[ca - 1] panics (0x32) in the uncatchable
    ///      outer frame — killing mint, re-roll AND merge. freezeConfig does not catch it
    ///      either (comboSpace never evaluates rules), so that state can be frozen
    ///      permanently: an unmintable collection with no recovery path. setTraits now
    ///      also reverts loudly on a stranded rule; this skip is the belt to that braces.
    function _violatesRules(uint16 colorId, uint16[] memory slots) private view returns (bool) {
        uint256 nr = forbiddenRules.length;
        uint256 ns = slots.length;
        for (uint256 r = 0; r < nr; r++) {
            ForbiddenRule storage fr = forbiddenRules[r];
            uint16 ca = fr.catA;
            if (ca > ns || fr.catB > ns) continue; // stranded by a later setTraits arity change
            uint16 ha = ca == 0 ? colorId : slots[ca - 1];
            if (ha == 0 || ha != fr.idA) continue; // side A absent
            uint16 cb = fr.catB;
            uint16 hb = cb == 0 ? colorId : slots[cb - 1];
            if (hb == 0) continue; // side B category not filled
            uint16 ib = fr.idB;
            if (ib == 0 || hb == ib) return true; // wildcard, or the exact forbidden id
        }
        return false;
    }

    /// @dev Pick a 1-based id from `weights` proportional to weight.
    function _weightedPick(uint32[] storage weights, uint256 total, bytes32 s)
        private
        view
        returns (uint16)
    {
        // `acc += weights[i]` on a uint32[] storage array compiles to one SLOAD *and one
        // keccak of the array base* PER ELEMENT — but 8 uint32 weights already share a
        // 32-byte word, so 7 of every 8 SLOADs are pure waste. With ~11 picks per draw over
        // tables up to 51 entries this scan measured 79,077 gas/roll. Hoist the keccak,
        // load one word at a time, and shift the 8 lanes out of it. Dynamic-array data
        // lives at keccak256(slot), packed low-lane-first, so lane i is word[(i%8)*32].
        uint256 r = uint256(s) % total;
        uint256 n = weights.length;
        uint256 base;
        assembly {
            mstore(0x00, weights.slot) // 0x00-0x40 is designated scratch space
            base := keccak256(0x00, 0x20)
        }
        uint256 acc;
        uint256 i;
        while (i < n) {
            uint256 word;
            assembly { word := sload(add(base, shr(3, i))) } // shr(3,i) == i/8 == word index
            uint256 lim = i + 8;
            if (lim > n) lim = n;
            while (i < lim) {
                acc += uint32(word);
                if (r < acc) return uint16(i + 1);
                word >>= 32;
                unchecked { ++i; }
            }
        }
        return uint16(n); // unreachable when total == sum(weights)
    }

    // ──────────────────────────────────────────────────────────────── views ──

    // comboSpace() and the _assertComboSpace()/_ruleKey()/_traitKey()/_nonzero()
    // helpers live in GloomblesStorage (shared with the config module). The
    // setForbiddenPairs/setSpecialTraits OWNER setters moved to MultiConfigureImpl
    // (reached via the owner-gated fallback delegatecall) to fit EIP-170.

    /// @dev True if a combo must be rejected for special-trait reasons. At mint, reject
    ///      ANY special (mints are Normal — specials are won by rolling); on a roll, reject
    ///      an already-CLAIMED special (cap-1) OR a LEGENDARY whenever the combo's REALIZED
    ///      trait count is below MAX_TRAITS. The gate keys off _countFilled(slots) (the
    ///      actual fill, capped by the fillable-slot count) — NOT the requested draw count —
    ///      so a Legendary is only ever claimed on a true full 11-trait combo (MAX_TRAITS =
    ///      body color + all 10 accessory slots), making every Legendary a "Mythic Legendary".
    ///      FINAL DESIGN: the apex is 11 traits. The final trait file must expose 10 accessory
    ///      slots so 11 is reachable (art-gated). Do NOT lower this gate to 10.
    function _rejectSpecials(uint16 colorId, uint16[] memory slots, bool mintMode)
        private
        view
        returns (bool)
    {
        if (specialTraitCount == 0) return false;
        bool gateLegendary = _countFilled(slots) < MAX_TRAITS; // Legendary only at a real MAX_TRAITS(11) fill: color + all 10 slots (FINAL)
        uint8 ct = traitTier[_traitKey(0, colorId)];
        if (ct > 0 && (mintMode || specialClaimed[_traitKey(0, colorId)] || (ct == TIER_LEGENDARY && gateLegendary))) {
            return true;
        }
        uint256 n = slots.length;
        for (uint256 s = 0; s < n; s++) {
            if (slots[s] == 0) continue;
            bytes32 k = _traitKey(uint16(s + 1), slots[s]);
            uint8 st = traitTier[k];
            if (st > 0 && (mintMode || specialClaimed[k] || (st == TIER_LEGENDARY && gateLegendary))) {
                return true;
            }
        }
        return false;
    }

    /// @dev Claim any special traits in the combo (cap-1) and set the token's tier to the
    ///      rarest one. Called after a roll commits; a non-zero tier freezes the gloomble.
    function _applyTier(uint256 sid, uint16 colorId, uint16[] memory slots) private {
        if (specialTraitCount == 0) return;
        uint8 tier;
        bytes32 ck = _traitKey(0, colorId);
        if (traitTier[ck] > 0) {
            specialClaimed[ck] = true;
            tier = traitTier[ck];
        }
        uint256 n = slots.length;
        for (uint256 s = 0; s < n; s++) {
            if (slots[s] == 0) continue;
            bytes32 k = _traitKey(uint16(s + 1), slots[s]);
            uint8 st = traitTier[k];
            if (st > 0) {
                specialClaimed[k] = true;
                if (st > tier) tier = st;
            }
        }
        if (tier > 0) _tokens[sid].tier = tier;
    }

    // The flat re-roll fee (default 0) is the public `rerollPrice` getter (GloomblesStorage);
    // the dapp reads that directly and sends it as msg.value on the commit.

    // rerollsLeft + rerollCooldownRemaining were removed (byte budget for reRollMany): both
    // are pure derivations of getToken (rerollCount, lastRerollAt) — the dapp computes them
    // client-side from MAX_REROLLS (5) + REROLL_COOLDOWN (24h), which are public constants.

    function slotsOf(uint256 tokenId) external view returns (uint16[] memory) {
        _requireMinted(tokenId);
        return _slots[_sid(tokenId)];
    }

    function getToken(uint256 tokenId) external view returns (Token memory) {
        _requireMinted(tokenId);
        return _tokens[_sid(tokenId)];
    }

    /// @notice Whether a token is a pre-defined 1/1 character (fixed exclusive art,
    ///         locked: no re-roll, not mergeable; sits outside the rarity ladder).
    function isOneOfOneToken(uint256 tokenId) external view returns (bool) {
        _requireMinted(tokenId);
        return _isOneOfOne[_sid(tokenId)];
    }

    /// @notice The combo hash a token currently wears (reveal-rotation aware).
    ///         Same ABI as the old public-mapping getter.
    function comboHashOf(uint256 tokenId) external view returns (bytes32) {
        _requireMinted(tokenId); // clean NonexistentToken (not a tokenId-1 underflow panic)
        return _comboHash[_sid(tokenId)];
    }


    /// @notice The committed entropy block for a token's pending re-roll (0 if none).
    ///         The dapp/keeper waits for block.number > this, then calls finalizeReRoll.
    function rerollEntropyBlock(uint256 tokenId) external view returns (uint256) {
        _requireMinted(tokenId);
        return _rerollBlock[_sid(tokenId)];
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireMinted(tokenId);
        // Placeholder pre-reveal, or if no renderer is set yet (renderer is configured at
        // deploy and locked via freezeRenderer; the address(0) case is a safe fallback only).
        // No renderer wired yet (deploy-time only): tiny inline fallback. Once the renderer is
        // set, PRE-REVEAL art lives there too (the placeholder image is a stored raster too big
        // for this contract's EIP-170 headroom), so delegate the unrevealed metadata to it.
        if (address(renderer) == address(0)) return _placeholderURI(tokenId);
        if (!revealed) return renderer.placeholderURI(tokenId);
        Token storage t = _tokens[_sid(tokenId)];
        return renderer.tokenURI(tokenId, _slots[_sid(tokenId)], t.colorId, true);
    }

    /// @dev Shared pre-reveal metadata — a "mystery gloomble" until reveal() flips.
    /// @dev Minimal fallback, reached ONLY before a renderer is wired (a deploy-time window that
    ///      never coincides with a live mint). The real pre-reveal art is renderer.placeholderURI.
    ///      Kept image-less on purpose so it costs almost nothing against the 6-byte headroom.
    function _placeholderURI(uint256 tokenId) private pure returns (string memory) {
        return string.concat(
            'data:application/json;utf8,{"name":"Gloomble #', tokenId.toString(),
            ' (unrevealed)","description":"An unrevealed gloomble. The art reveals soon."}'
        );
    }

    // ───────────────────────────────────────────────────────────── admin ──
    // The owner config setters setRenderer / setTraits / setMintConfig /
    // freezeConfig (plus setForbiddenPairs / setSpecialTraits above) moved to
    // MultiConfigureImpl, reached via the owner-gated fallback() delegatecall, to
    // fit the EIP-170 code-size limit. They run in THIS token's storage.

    // ── shift reveal ──
    // The reveal decides which token wears which combo, by rotating the
    // token->combo mapping a random distance. Two-step: the owner COMMITS to a
    // future block (whose hash nobody can know yet), then ANYONE finalizes with
    // that block's hash once it exists. The owner never sees the entropy while
    // still able to act on it, and can't stall a shift they dislike (finalize is
    // permissionless). Residual bias: only the entropy block's proposer, by
    // discarding their own block — economically irrational here.

    /// @notice Commit to the future entropy block. Must be >= MIN_REVEAL_DELAY
    ///         ahead (past proposer lookahead). Re-scheduling is allowed only
    ///         before the entropy exists or after it expired unused — never in
    ///         the live window, so there is no peek-then-re-roll option.
    /// @dev    IRREVERSIBLE FOR MINTING: once called, `revealBlock != 0` permanently closes
    ///         ALL minting (ownerMint + mintSeaDrop, via _mintTo) with no reopen. Never call
    ///         until the public mint is 100% complete. (audit round-3 L)
    function scheduleReveal(uint256 blockNumber) external onlyOwner {
        if (revealed) revert AlreadyRevealed();
        if (totalMinted == 0) revert NotConfigured();
        // Every reserved 1/1 must already be minted AND fall inside the rotation domain
        // [0, revealSupply=totalMinted) so it scatters to a random public id. If the
        // highest reserved sid hasn't minted yet, revealing now would strand it (never
        // minted) or identity-map it (deterministic, snipeable). (1/1 audit MED)
        if (oneOfOneCount > 0 && _oneOfOneMaxSid >= totalMinted) revert OneOfOneUnminted();
        if (blockNumber < block.number + MIN_REVEAL_DELAY) revert InvalidConfig();
        if (
            revealBlock != 0 && block.number > revealBlock
                && block.number <= revealBlock + _BLOCKHASH_WINDOW
        ) revert RevealEntropyLive();
        revealBlock = blockNumber;
        // Snapshot the rotation domain NOW, before the entropy exists: if it were
        // read at finalize, anyone could re-roll the shift (hash % supply) by
        // minting in the window. Window/post-reveal mints are identity-mapped.
        revealSupply = totalMinted;
        emit RevealScheduled(blockNumber);
    }

    /// @notice Flip every token from the placeholder to its real art, rotated by
    ///         a distance nobody could predict at commit time. PERMISSIONLESS
    ///         once the entropy block has passed. One-way. If the 256-block
    ///         blockhash window is missed, reverts — owner re-schedules.
    function finalizeReveal() external {
        if (revealed) revert AlreadyRevealed();
        if (revealBlock == 0) revert RevealNotScheduled();
        if (block.number <= revealBlock) revert RevealNotReady();
        bytes32 entropy = blockhash(revealBlock);
        if (entropy == bytes32(0)) revert RevealEntropyExpired();
        uint256 rand = uint256(keccak256(abi.encode(entropy, address(this))));
        // Map into [1, revealSupply-1] when supply > 1 so the rotation is never the
        // identity (shift 0 = no hiding, the worst anti-snipe outcome). With one
        // token there's nothing to hide, so shift stays 0. (audit LOW)
        revealShift = revealSupply > 1 ? 1 + (rand % (revealSupply - 1)) : 0;
        revealed = true;
        emit Revealed(revealShift, revealSupply);
        // Every token just flipped from the placeholder to its real art — tell every
        // marketplace to re-pull the whole collection at once. (ERC-4906, audit M-3)
        emit BatchMetadataUpdate(0, type(uint256).max);
    }

    /// @dev Storage id for a token's combo/re-roll state. Public token ids are
    ///      1-based; the storage domain is the 0-based index idx = tokenId - 1.
    ///      That index is identity before the reveal and for tokens minted after
    ///      it; pre-reveal tokens rotate by revealShift. A bijection over
    ///      [0, revealSupply), so all-time uniqueness and the population counters
    ///      are untouched.
    function _sid(uint256 tokenId) internal view returns (uint256) {
        uint256 idx = tokenId - 1; // 1-based id -> 0-based storage index
        if (!revealed || idx >= revealSupply) return idx;
        unchecked {
            return (idx + revealShift) % revealSupply;
        }
    }

    /// @dev Inverse of _sid (storage id -> 1-based public token id), for events.
    function _tid(uint256 sid) internal view returns (uint256) {
        if (!revealed || sid >= revealSupply) return sid + 1;
        unchecked {
            return ((sid + revealSupply - revealShift) % revealSupply) + 1;
        }
    }

    // freezeConfig / setTraits / setMintConfig moved to MultiConfigureImpl
    // (owner-gated fallback delegatecall) for EIP-170. comboSpace()/_assertComboSpace
    // are shared via GloomblesStorage.

    /// @notice Push the contract's collected re-roll fees to the owner-set keeperWallet.
    ///         PERMISSIONLESS by design: the destination is fixed by the owner, so an
    ///         auto-replenish keeper can trigger it WITHOUT holding the owner key — the worst
    ///         a caller can do is send the fees to where the owner already pointed them. No
    ///         reentrancy guard needed: it mutates no state and only forwards the balance to a
    ///         fixed address (a reentrant call just finds a 0 balance). withdraw() (owner →
    ///         any address, for treasury) lives in MultiConfigureImpl via the owner fallback.
    function sweepToKeeper() external {
        address k = keeperWallet;
        if (k == address(0)) revert NotConfigured();
        (bool ok,) = k.call{value: address(this).balance}("");
        if (!ok) revert WithdrawFailed();
    }

    function _requireMinted(uint256 tokenId) private view {
        if (_ownerOf(tokenId) == address(0)) revert NonexistentToken();
    }

    // ──────────────────────────────────────────────── SeaDrop (OpenSea mint) ──
    // We implement INonFungibleSeaDropToken so an OpenSea-deployed SeaDrop
    // contract can host + promote the public mint. It collects payment, enforces
    // limits via getMintStats(), then calls mintSeaDrop() — which runs our normal
    // unique-combo assignment. Re-rolls, on-chain art, and reveal are unchanged.

    modifier onlyAllowedSeaDrop(address seaDropImpl) {
        if (!_allowedSeaDrop[seaDropImpl]) revert OnlyAllowedSeaDrop();
        _;
    }

    /// @notice Mint, restricted to an allowed SeaDrop contract. Each token still
    ///         gets an instantly-assigned, all-time-unique combo via _mintTo.
    /// @dev    nonReentrant: _mintTo uses _safeMint, and a token may be registered
    ///         with multiple SeaDrop contracts — guard against a malicious
    ///         onERC721Received re-entering through another SeaDrop.
    function mintSeaDrop(address minter, uint256 quantity)
        external
        override
        nonReentrant
        onlyAllowedSeaDrop(msg.sender)
    {
        // Close the public mint once a reveal is committed: tokens minted after
        // scheduleReveal fall outside the rotation snapshot (identity-mapped) and
        // their combo is readable, which would let late minters rarity-snipe. So
        // the public mint must finish before scheduling the reveal.
        if (revealBlock != 0) revert MintClosed();
        if (totalMinted + quantity > maxSupply) revert SoldOut();
        for (uint256 i; i < quantity; i++) {
            _mintTo(minter);
        }
    }

    /// @notice Mint stats SeaDrop reads to enforce per-wallet + supply limits.
    function getMintStats(address minter)
        external
        view
        override
        returns (uint256 minterNumMinted, uint256 currentTotalSupply, uint256 maxSupply_)
    {
        return (_numberMinted[minter], totalMinted, maxSupply);
    }

    /// @notice Set which SeaDrop contracts may call mintSeaDrop. Owner only.
    function updateAllowedSeaDrop(address[] calldata allowedSeaDrop) external override onlyOwner {
        for (uint256 i; i < _enumeratedAllowedSeaDrop.length; i++) {
            _allowedSeaDrop[_enumeratedAllowedSeaDrop[i]] = false;
        }
        for (uint256 i; i < allowedSeaDrop.length; i++) {
            _allowedSeaDrop[allowedSeaDrop[i]] = true;
        }
        _enumeratedAllowedSeaDrop = allowedSeaDrop;
        emit AllowedSeaDropUpdated(allowedSeaDrop);
    }

    // ── drop-config forwarding (owner configures the drop on the SeaDrop side) ──

    function updatePublicDrop(address seaDropImpl, PublicDrop calldata publicDrop)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updatePublicDrop(publicDrop);
    }

    function updateAllowList(address seaDropImpl, AllowListData calldata allowListData)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updateAllowList(allowListData);
    }

    function updateTokenGatedDrop(
        address seaDropImpl,
        address allowedNftToken,
        TokenGatedDropStage calldata dropStage
    ) external override onlyOwner onlyAllowedSeaDrop(seaDropImpl) {
        ISeaDrop(seaDropImpl).updateTokenGatedDrop(allowedNftToken, dropStage);
    }

    function updateDropURI(address seaDropImpl, string calldata dropURI)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updateDropURI(dropURI);
    }

    function updateCreatorPayoutAddress(address seaDropImpl, address payoutAddress)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updateCreatorPayoutAddress(payoutAddress);
    }

    function updateAllowedFeeRecipient(address seaDropImpl, address feeRecipient, bool allowed)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updateAllowedFeeRecipient(feeRecipient, allowed);
    }

    function updateSignedMintValidationParams(
        address seaDropImpl,
        address signer,
        SignedMintValidationParams memory signedMintValidationParams
    ) external override onlyOwner onlyAllowedSeaDrop(seaDropImpl) {
        ISeaDrop(seaDropImpl).updateSignedMintValidationParams(signer, signedMintValidationParams);
    }

    function updatePayer(address seaDropImpl, address payer, bool allowed)
        external
        override
        onlyOwner
        onlyAllowedSeaDrop(seaDropImpl)
    {
        ISeaDrop(seaDropImpl).updatePayer(payer, allowed);
    }

    // ── collection metadata + royalties (ISeaDropTokenContractMetadata) ──

    function setBaseURI(string calldata uri) external override onlyOwner {
        _tokenBaseURI = uri;
        emit BatchMetadataUpdate(0, type(uint256).max);
    }

    function setContractURI(string calldata newContractURI) external override onlyOwner {
        _contractURI = newContractURI;
        emit ContractURIUpdated(newContractURI);
    }

    function setMaxSupply(uint256 newMaxSupply) external override onlyOwner {
        if (configFrozen) revert ConfigLocked();
        if (newMaxSupply < totalMinted) {
            revert NewMaxSupplyCannotBeLessThenTotalMinted(newMaxSupply, totalMinted);
        }
        if (newMaxSupply > type(uint64).max) revert CannotExceedMaxSupplyOfUint64(newMaxSupply);
        maxSupply = newMaxSupply;
        emit MaxSupplyUpdated(newMaxSupply);
    }

    function setProvenanceHash(bytes32 newProvenanceHash) external override onlyOwner {
        if (totalMinted > 0) revert ProvenanceHashCannotBeSetAfterMintStarted();
        bytes32 old = _provenanceHash;
        _provenanceHash = newProvenanceHash;
        emit ProvenanceHashUpdated(old, newProvenanceHash);
    }

    function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external override onlyOwner {
        if (newInfo.royaltyAddress == address(0)) revert RoyaltyAddressCannotBeZeroAddress();
        if (newInfo.royaltyBps > MAX_ROYALTY_BPS) revert InvalidRoyaltyBasisPoints(newInfo.royaltyBps);
        _royaltyInfo = newInfo;
        emit RoyaltyInfoUpdated(newInfo.royaltyAddress, newInfo.royaltyBps);
    }

    function baseURI() external view override returns (string memory) {
        return _tokenBaseURI;
    }

    function contractURI() external view override returns (string memory) {
        return _contractURI;
    }

    function provenanceHash() external view override returns (bytes32) {
        return _provenanceHash;
    }

    function royaltyAddress() external view override returns (address) {
        return _royaltyInfo.royaltyAddress;
    }

    function royaltyBasisPoints() external view override returns (uint256) {
        return _royaltyInfo.royaltyBps;
    }

    /// @inheritdoc IERC2981
    function royaltyInfo(uint256, uint256 salePrice)
        external
        view
        override
        returns (address receiver, uint256 royaltyAmount)
    {
        receiver = _royaltyInfo.royaltyAddress;
        royaltyAmount = (salePrice * _royaltyInfo.royaltyBps) / 10_000;
    }

    /// @notice A gloomble cannot change hands while a re-roll is pending.
    /// @dev    ANTI-SNIPE / ANTI-DUMP. A roll is commit-reveal: once the committed
    ///         entropy block is mined its blockhash is public, so the outcome is fully
    ///         computable off-chain — but it is not APPLIED until someone calls
    ///         finalizeReRoll. A freely transferable token inside that gap hands one
    ///         side of every trade a known answer: a bot can compute that a pending roll
    ///         lands an unclaimed Epic and buy the token off a standing listing priced
    ///         before the roll, and a holder who computes a bad outcome can dump into a
    ///         resting bid before it resolves. Neither counterparty can see what the
    ///         other does. Closing the transfer closes both.
    ///
    ///         This CANNOT strand a token. finalizeReRoll is permissionless, so the
    ///         holder, the keeper, or even the would-be buyer can clear the pending
    ///         state with one cheap tx (the dapp exposes it as "reveal now"). A keeper
    ///         outage therefore delays a transfer; it never blocks one. If the 256-block
    ///         blockhash window lapses first, resetStuckRoll re-arms with fresh entropy
    ///         and the same escape applies.
    ///
    ///         Mint (from == 0) can carry no pending roll. Burn (to == 0) is untouched —
    ///         merge already rejects a pending host or sacrifice.
    function _update(address to, uint256 tokenId, address auth)
        internal
        override
        returns (address from)
    {
        from = super._update(to, tokenId, auth);
        if (from != address(0) && to != address(0) && _tokens[_sid(tokenId)].rollPending) {
            revert RollPending();
        }
    }

    /// @notice Advertise the SeaDrop, metadata, and royalty interfaces so OpenSea
    ///         recognizes this as a SeaDrop token and reads royalties.
    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC721, IERC165)
        returns (bool)
    {
        return interfaceId == type(INonFungibleSeaDropToken).interfaceId
            || interfaceId == type(ISeaDropTokenContractMetadata).interfaceId
            || interfaceId == type(IERC2981).interfaceId
            || interfaceId == 0x49064906 // ERC-4906 (MetadataUpdate / BatchMetadataUpdate) — audit L-5
            || super.supportsInterface(interfaceId);
    }

    /// @notice Renouncing ownership is permanently DISABLED. The collection must stay
    ///         owned through launch and the post-launch renderer/gas shakeout —
    ///         renouncing would brick scheduleReveal/finalizeReveal and every owner
    ///         setter with no recovery. Ownership is still transferable. (audit L-1)
    function renounceOwnership() public override {
        revert RenounceDisabled();
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     *
     * NOTE: ERC-2981 allows setting the royalty to 100% of the price. In that case all the price would be sent to the
     * royalty receiver and 0 tokens to the seller. Contracts dealing with royalty should consider empty transfers.
     */
    function royaltyInfo(
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (address receiver, uint256 royaltyAmount);
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    mapping(uint256 tokenId => address) private _owners;

    mapping(address owner => uint256) private _balances;

    mapping(uint256 tokenId => address) private _tokenApprovals;

    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual returns (uint256) {
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if:
     * - `spender` does not have approval from `owner` for `tokenId`.
     * - `spender` does not have approval to manage all of `owner`'s assets.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        unchecked {
            _balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                _balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                _balances[to] += 1;
            }
        }

        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC-721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        _tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/utils/ERC721Utils.sol)

pragma solidity ^0.8.20;

import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";

/**
 * @dev Library that provide common ERC-721 utility functions.
 *
 * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
 *
 * _Available since v5.1._
 */
library ERC721Utils {
    /**
     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC721Received(
        address operator,
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    // Token rejected
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC721Receiver implementer
                    revert IERC721Errors.ERC721InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

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

lib/openzeppelin-contracts/contracts/utils/Strings.sol

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

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

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @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;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @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) {
        uint256 localValue = value;
        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] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        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);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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 towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 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.

            uint256 twos = denominator & (0 - denominator);
            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²⁵⁶ / 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²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, 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;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * 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;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

lib/solady/src/utils/Base64.sol

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

/// @notice Library to encode strings in Base64.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
/// @author Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos - <[email protected]>.
library Base64 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    ENCODING / DECODING                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
    /// See: https://datatracker.ietf.org/doc/html/rfc4648
    /// @param fileSafe  Whether to replace '+' with '-' and '/' with '_'.
    /// @param noPadding Whether to strip away the padding.
    function encode(bytes memory data, bool fileSafe, bool noPadding)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let dataLength := mload(data)

            if dataLength {
                // Multiply by 4/3 rounded up.
                // The `shl(2, ...)` is equivalent to multiplying by 4.
                let encodedLength := shl(2, div(add(dataLength, 2), 3))

                // Set `result` to point to the start of the free memory.
                result := mload(0x40)

                // Store the table into the scratch space.
                // Offsetted by -1 byte so that the `mload` will load the character.
                // We will rewrite the free memory pointer at `0x40` later with
                // the allocated size.
                // The magic constant 0x0670 will turn "-_" into "+/".
                mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
                mstore(0x3f, xor("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0670)))

                // Skip the first slot, which stores the length.
                let ptr := add(result, 0x20)
                let end := add(ptr, encodedLength)

                let dataEnd := add(add(0x20, data), dataLength)
                let dataEndValue := mload(dataEnd) // Cache the value at the `dataEnd` slot.
                mstore(dataEnd, 0x00) // Zeroize the `dataEnd` slot to clear dirty bits.

                // Run over the input, 3 bytes at a time.
                for {} 1 {} {
                    data := add(data, 3) // Advance 3 bytes.
                    let input := mload(data)

                    // Write 4 bytes. Optimized for fewer stack operations.
                    mstore8(0, mload(and(shr(18, input), 0x3F)))
                    mstore8(1, mload(and(shr(12, input), 0x3F)))
                    mstore8(2, mload(and(shr(6, input), 0x3F)))
                    mstore8(3, mload(and(input, 0x3F)))
                    mstore(ptr, mload(0x00))

                    ptr := add(ptr, 4) // Advance 4 bytes.
                    if iszero(lt(ptr, end)) { break }
                }
                mstore(dataEnd, dataEndValue) // Restore the cached value at `dataEnd`.
                mstore(0x40, add(end, 0x20)) // Allocate the memory.
                // Equivalent to `o = [0, 2, 1][dataLength % 3]`.
                let o := div(2, mod(dataLength, 3))
                // Offset `ptr` and pad with '='. We can simply write over the end.
                mstore(sub(ptr, o), shl(240, 0x3d3d))
                // Set `o` to zero if there is padding.
                o := mul(iszero(iszero(noPadding)), o)
                mstore(sub(ptr, o), 0) // Zeroize the slot after the string.
                mstore(result, sub(encodedLength, o)) // Store the length.
            }
        }
    }

    /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
    /// Equivalent to `encode(data, false, false)`.
    function encode(bytes memory data) internal pure returns (string memory result) {
        result = encode(data, false, false);
    }

    /// @dev Encodes `data` using the base64 encoding described in RFC 4648.
    /// Equivalent to `encode(data, fileSafe, false)`.
    function encode(bytes memory data, bool fileSafe)
        internal
        pure
        returns (string memory result)
    {
        result = encode(data, fileSafe, false);
    }

    /// @dev Decodes base64 encoded `data`.
    ///
    /// Supports:
    /// - RFC 4648 (both standard and file-safe mode).
    /// - RFC 3501 (63: ',').
    ///
    /// Does not support:
    /// - Line breaks.
    ///
    /// Note: For performance reasons,
    /// this function will NOT revert on invalid `data` inputs.
    /// Outputs for invalid inputs will simply be undefined behaviour.
    /// It is the user's responsibility to ensure that the `data`
    /// is a valid base64 encoded string.
    function decode(string memory data) internal pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            let dataLength := mload(data)

            if dataLength {
                let decodedLength := mul(shr(2, dataLength), 3)

                for {} 1 {} {
                    // If padded.
                    if iszero(and(dataLength, 3)) {
                        let t := xor(mload(add(data, dataLength)), 0x3d3d)
                        // forgefmt: disable-next-item
                        decodedLength := sub(
                            decodedLength,
                            add(iszero(byte(30, t)), iszero(byte(31, t)))
                        )
                        break
                    }
                    // If non-padded.
                    decodedLength := add(decodedLength, sub(and(dataLength, 3), 1))
                    break
                }
                result := mload(0x40)

                // Write the length of the bytes.
                mstore(result, decodedLength)

                // Skip the first slot, which stores the length.
                let ptr := add(result, 0x20)
                let end := add(ptr, decodedLength)

                // Load the table into the scratch space.
                // Constants are optimized for smaller bytecode with zero gas overhead.
                // `m` also doubles as the mask of the upper 6 bits.
                let m := 0xfc000000fc00686c7074787c8084888c9094989ca0a4a8acb0b4b8bcc0c4c8cc
                mstore(0x5b, m)
                mstore(0x3b, 0x04080c1014181c2024282c3034383c4044484c5054585c6064)
                mstore(0x1a, 0xf8fcf800fcd0d4d8dce0e4e8ecf0f4)

                for {} 1 {} {
                    // Read 4 bytes.
                    data := add(data, 4)
                    let input := mload(data)

                    // Write 3 bytes.
                    // forgefmt: disable-next-item
                    mstore(ptr, or(
                        and(m, mload(byte(28, input))),
                        shr(6, or(
                            and(m, mload(byte(29, input))),
                            shr(6, or(
                                and(m, mload(byte(30, input))),
                                shr(6, mload(byte(31, input)))
                            ))
                        ))
                    ))
                    ptr := add(ptr, 3)
                    if iszero(lt(ptr, end)) { break }
                }
                mstore(0x40, add(end, 0x20)) // Allocate the memory.
                mstore(end, 0) // Zeroize the slot after the bytes.
                mstore(0x60, 0) // Restore the zero slot.
            }
        }
    }
}

src/GloomblesStorage.sol

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

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IGloomblesRenderer} from "./IGloomblesRenderer.sol";
import {INonFungibleSeaDropToken} from "./seadrop/INonFungibleSeaDropToken.sol";

/// @title  GloomblesStorage
/// @notice Shared storage + config layout for GloomblesRR and its owner-gated
///         delegatecall module (MultiConfigureImpl). Both contracts inherit this
///         abstract base so they observe the EXACT SAME storage layout — the
///         module's setters write named state variables (no assembly) that land
///         in the token's storage when reached via fallback() delegatecall.
/// @dev    The state-variable ORDER here is load-bearing: it fixes slots 8..42
///         (see .layout-before.txt). Do not reorder. Vars the module writes are
///         `internal` (not `private`) so both contracts can name them; widening
///         visibility does NOT change slots.
abstract contract GloomblesStorage is ERC721, Ownable, ReentrancyGuard, INonFungibleSeaDropToken {
    // ─────────────────────────────────────────────────────────── constants ──

    uint8 public constant MAX_REROLLS = 5;
    uint256 public constant REROLL_COOLDOWN = 24 hours;
    uint256 internal constant _MAX_DRAW_ATTEMPTS = 256; // rejection-sampling cap
    // Dynamic re-roll fee = FINALIZE_GAS * (block.basefee + tip) * margin/1e4. Auto-scales with gas
    // so it only ever charges ~what the keeper spends to finalize a roll; a nonzero rerollPrice
    // overrides it flat. Internal (no getters, EIP-170) — read the live number via currentRerollFee().
    // SET FROM LIVE SEPOLIA MEASUREMENT, NOT FROM THE BENCH. Measured 2026-07-19 against the
    // deployed final-art collection (2,862 minted, 296 traits, 31 specials, 26 rules):
    //     10-roll batch -> 1,959,102 gas => 195,910 / roll
    //      3-roll batch ->   618,694 gas => 206,231 / roll
    // Those two points fit cost(n) ~= 44,233 + 191,487n, i.e. ~44k FIXED per transaction plus
    // ~191k per roll. Per-roll cost therefore RISES as the batch shrinks:
    //     n=1 235,720 | n=2 213,604 | n=3 206,231 | n=10 195,910
    // and n=1 is the COMMON case, not the edge: the cron fires every 2 minutes and will
    // usually find one or two matured rolls, so the keeper is at its most expensive exactly
    // when volume is lowest.
    //
    // PRICED FOR FAIRNESS TO HOLDERS, NOT FOR THE KEEPER'S WORST BATCHING.
    //
    // Finalize cost per roll depends almost entirely on BATCH SIZE, and the keeper — not the
    // holder — chooses that. Measured live on Sepolia 2026-07-19 (real keeper receipts,
    // final art, 2,862 minted), gas PER ROLL:
    //     n=1 343,331 | n=2 233,204 | n=3 206,231 | n=10 195,910 | n=25 166,000
    // Decomposed: ~159k is the MARGINAL work of one roll; the other ~185k is one-time COLD
    // STORAGE warming (trait weight tables, the 26 rules, mandatory slots, revealShift,
    // population counters) that the FIRST roll in a batch pays and every later roll inherits
    // warm. A lone roll is not expensive because rolling is expensive — it pays the whole
    // warm-up bill by itself.
    //
    // So charge the cost of a WELL-BATCHED roll. 180_000 * REROLL_FEE_BPS (1.30x) collects
    // 234,000, which covers n=2 (the floor the cron enforces via MIN_BATCH) and yields a
    // 1.19x markup at n=10 and 1.41x at n=25. A rare URGENT single loses ~109k, absorbed
    // many times over by that surplus.
    //
    // An earlier 300_000 was sized to the n=1 worst case so the owner could never subsidise
    // a single roll. It achieved that, but at 2.35x the keeper's actual cost on a full batch
    // — a fee marked up over 2x and presented to holders as gas. Rejected as unfair. The
    // right lever for the single-roll case is the CRON'S BATCHING (MIN_BATCH/URGENT_BLOCKS),
    // not a permanent surcharge on everyone.
    //
    // Two earlier values were wrong in a different way and are worth remembering:
    //   130_000 came from test/GasBench.t.sol (~121k), which omits the specials and
    //           mint-count weights, so it under-measured production by ~35%.
    //   210_000 came from extrapolating a two-point fit (n=3, n=10) down to n=1: it predicted
    //           235,720 against a real 365,409, 55% off. Two points fit two parameters
    //           exactly, so the model had no residual to expose the error.
    // Both passed their tests. Only real receipts caught either one. Re-measure on-chain
    // after ANY change to _redraw, the counters, or the trait file.
    uint256 internal constant REROLL_FINALIZE_GAS = 180_000;
    // Keeper priority tip assumed by the fee, added over basefee. THIS DOMINATES THE FEE WHEN
    // GAS IS CHEAP, which on modern mainnet is most of the time: at a 0.036 gwei basefee a
    // 1 gwei tip was 96% of what a holder paid — charging them for a priority fee the keeper
    // does not even spend, since the cron pays min(suggested, cap) and a quiet network
    // suggests far less. Measured effect of 1 gwei -> 0.1 gwei on the fee per roll:
    //     basefee 0.036 gwei : 0.000242 -> 0.000032 ETH  (7.5x cheaper)
    //     basefee 3 gwei     : 0.000936 -> 0.000725 ETH
    //     basefee 20 gwei    : 0.004914 -> 0.004703 ETH
    // Keeper coverage stays a flat ~1.41x in ALL of those conditions, because the tip was a
    // floor being billed rather than a cost being incurred.
    //
    // 0.1 gwei is safe for this workload specifically: finalize has a 256-block (~50 min)
    // blockhash window, so slow inclusion is fine — it is not a trade that must land now.
    // The cron mirrors this in MAX_TIP_WEI, and is allowed to bid ABOVE it only for a batch
    // approaching window expiry, where being included matters more than the margin.
    uint256 internal constant REROLL_FEE_TIP = 0.1 gwei;
    uint256 internal constant REROLL_FEE_BPS = 13_000; // 1.30x drift/variance margin
    /// @dev Trait-count progression. A gloomble mints with MINT_TRAITS filled
    ///      categories (body color + slots); the evolve rolls (1..MAX_REROLLS-1) grow
    ///      the count toward MAX_TRAITS. Internal (EIP-170) — read the live count per
    ///      token via getToken().traitCount. Mint fills UP TO 9 accessory slots:
    ///      traitCount = body color + up to 9 slots, so mint spans 5..10. The full
    ///      10-slot character (traitCount 11 = Mythic) is MERGE/EVOLVE-ONLY — the
    ///      earned pinnacle, never minted. Higher counts are RARER per the weights.
    ///      11 = body color + all 10 filled accessory slots.
    ///
    ///      HISTORY (this value is the rarity ladder, so it is worth stating plainly):
    ///      MINT_TRAITS was 7 under the old 7-slot art, where the ladder read
    ///      Common 7 / Uncommon 8 / Rare 9 / Super Rare 10 / Mythic 11 and evolve had
    ///      four rungs of headroom. The final 10-slot art moved it to 10, so mint now
    ///      spans 5..10 of 11 and evolve has ONE rung left — a `+2` roll clamps to
    ///      MAX_TRAITS immediately. That is deliberate: with 10 slots, minting below 10
    ///      leaves most characters visibly incomplete, and the pinnacle is meant to be
    ///      the earned 11 rather than a common mint outcome. The per-count weights in
    ///      setMintCountWeights carry the rarity (higher count = rarer), NOT this
    ///      constant. Changing it recompiles to a fresh GloomblesRR — it is not
    ///      configurable post-deploy — so it is a launch-time decision, not a knob.
    uint8 internal constant MINT_TRAITS = 10;
    uint8 internal constant MAX_TRAITS = 11;
    /// @notice Merge (sacrifice): burn MERGE_BURN of your gloombles to ascend a held
    ///         "host" to a full MAX_TRAITS Mythic; the host then gets MERGE_ROLLS fresh
    ///         rolls to chase a Legendary. The burned ones are pure sacrifice (their
    ///         traits don't transfer) — it's a deflationary sink.
    uint8 public constant MERGE_BURN = 5;
    uint8 public constant MERGE_ROLLS = 3;
    /// @dev Quality tiers, reachable only on the final (ascension) roll. Internal —
    ///      read the tier per token via getToken().tier.
    uint8 internal constant TIER_NORMAL = 0;
    uint8 internal constant TIER_EPIC = 1;
    uint8 internal constant TIER_LEGENDARY = 2;
    /// @notice Re-roll entropy block = block.number + REROLL_DELAY. Unknowable when the
    ///         holder signs the commit. Deliberately SHORT (~1 min) to keep re-roll snappy,
    ///         and shorter than MIN_REVEAL_DELAY=64 (below): 5 blocks sits INSIDE the ~2-epoch
    ///         beacon proposer lookahead, so a self-building validator who is also a holder
    ///         could in principle grind the blockhash of a slot they will propose to bias
    ///         their OWN roll toward an unclaimed cap-1 special. Accepted as a LOW residual
    ///         (audit 2026-07-10): no funds at risk; ~85-95% of validators build via mev-boost
    ///         and cannot grind; proposal slots are rare; self-building forfeits MEV; and
    ///         cooldown/MAX_REROLLS throttle attempts — economically irrational for a cosmetic
    ///         trait. To fully close it: raise past 64 (costs ~13 min finalize) or fold
    ///         prevrandao of a >=2-epoch-out block into the seed (costs bytecode; EIP-170).
    uint256 public constant REROLL_DELAY = 5;
    /// @notice Owner-config guard rail: royalties can never be set above 10%.
    uint256 internal constant MAX_ROYALTY_BPS = 1_000; // 10% (internal, no getter — EIP-170 headroom)
    /// @notice scheduleReveal must target a block at least this far ahead — past
    ///         the ~2-epoch proposer lookahead, so the entropy block's proposer
    ///         is unknown when the owner commits to it.
    uint256 public constant MIN_REVEAL_DELAY = 64;
    /// @dev blockhash() only serves the 256 most recent blocks; past that the
    ///      scheduled entropy is unrecoverable and the owner must re-schedule.
    uint256 internal constant _BLOCKHASH_WINDOW = 256;

    // ───────────────────────────────────────────────────────────── storage ──

    struct Token {
        uint16 colorId;
        uint8 rerollCount;
        uint64 lastRerollAt;
        bool rollPending;
        uint8 tier; // 0 Normal, 1 Epic, 2 Legendary (set on the ascension roll)
        uint8 traitCount; // filled categories incl. color (MINT_TRAITS..MAX_TRAITS)
    }

    /// @notice Collection cap. Mutable so the SeaDrop interface's setMaxSupply
    ///         works (OpenSea reads/writes this when configuring the drop).
    uint256 public override maxSupply;

    // Per-token combo + re-roll state, keyed by STORAGE id (see _sid): identity
    // until the reveal, then pre-reveal tokens read through the reveal rotation.
    // External readers use getToken / slotsOf / comboHashOf / tokens, which remap.
    mapping(uint256 sid => Token) internal _tokens;
    mapping(uint256 sid => uint16[]) internal _slots; // per slot, trait id (1-based; 0 = none)
    mapping(uint256 sid => bytes32) internal _comboHash;

    /// @notice Every combo ever assigned, permanently reserved (all-time unique).
    mapping(bytes32 comboHash => bool) public usedCombo;
    uint256 public usedComboCount;

    // Weighted trait config (combo = colorId + one pick per slot).
    uint32[] public colorWeights; // colorWeights[i] -> weight of color id (i+1)
    uint256 internal colorTotalWeight; // internal, no getter (EIP-170 headroom)
    uint32[][] public slotWeights; // slotWeights[s][i] -> weight of trait id (i+1) in slot s
    uint256[] public slotTotalWeight; // per-slot weight sum (0 => slot always "none")

    // Live population (realized rarity, on-chain — no indexer).
    //
    // PACKED: 8 x uint32 counters per storage word, key = (cat << 32) | (id >> 3), where
    // cat 0 = body color and cat s+1 = slot s. Unpacked, every counter owned a full slot,
    // so a redraw paid ~22 COLD 5,000-gas SSTOREs and a 25-roll batch touched ~250 distinct
    // cold slots — measured at ~100k gas/roll, 43% of a finalize. Co-locating a category's
    // counters drops that batch to ~41 words, after which every write is a warm-dirty
    // 100-gas SSTORE. The public getters below keep the SAME selectors and return types as
    // the auto-getters they replace, so the ABI is byte-identical and the dapp's on-chain
    // rarity reads (web/src/lib/liveRarity.ts, leaderboardCore.ts) need no change.
    mapping(uint256 packedKey => uint256 eightCounters) internal _popWords;
    uint256 private __popGap; // was a second mapping — keeps every slot index below unchanged

    function _popKey(uint256 cat, uint16 id) private pure returns (uint256) {
        return (cat << 32) | (uint256(id) >> 3); // id is uint16 so id>>3 < 2^13, never collides
    }

    /// @notice Live count of gloombles wearing body colour `id`.
    function colorPop(uint16 id) public view returns (uint32) {
        return uint32(_popWords[_popKey(0, id)] >> ((uint256(id) & 7) << 5));
    }

    /// @notice Live count of gloombles wearing trait `id` in `slot`.
    function slotPop(uint8 slot, uint16 id) public view returns (uint32) {
        return uint32(_popWords[_popKey(uint256(slot) + 1, id)] >> ((uint256(id) & 7) << 5));
    }

    /// @dev Increment/decrement one packed lane. The decrement adds 0xffffffff and masks,
    ///      i.e. it wraps within the 32-bit lane exactly as the previous `unchecked` uint32
    ///      decrement did — no borrow can escape into a neighbouring counter.
    function _bumpPop(uint256 cat, uint16 id, bool up) internal {
        uint256 k = _popKey(cat, id);
        uint256 sh = (uint256(id) & 7) << 5;
        uint256 w = _popWords[k];
        unchecked {
            uint256 v = ((w >> sh) & 0xffffffff) + (up ? 1 : uint256(0xffffffff));
            _popWords[k] = (w & ~(uint256(0xffffffff) << sh)) | ((v & 0xffffffff) << sh);
        }
    }

    /// @notice Trait-exclusion rules. A rule forbids (catA, idA) from co-occurring with
    ///         category catB — either a specific idB, or ANY filled trait in catB when
    ///         idB == 0 (WILDCARD). The draw rejects + redraws any combo that hits one
    ///         (reusing the uniqueness rejection sampling). Category 0 = body color;
    ///         category s+1 = slot s. Set via setForbiddenPairs, locked by freezeConfig.
    ///         The check is symmetric in effect — a rule fires only when BOTH sides are
    ///         present — so (A,B) and (B,A) are equivalent and order does not matter.
    ///
    /// @dev    An ARRAY, not a pair-keyed mapping. _violatesRules runs on EVERY draw
    ///         attempt, and probing a mapping for all C(n,2)+n category pairs cost 55
    ///         cold SLOADs (~115k gas) per attempt on the 10-slot trait file — that is
    ///         what took batched finalize from ~109k to ~243k gas per roll when the art
    ///         went from 7 slots to 10. Iterating rules instead is O(rules), and the
    ///         WILDCARD is what makes that a win: "these 2 hoodies forbid all 51 hats"
    ///         collapses from 102 pair entries into 2 rules. Fields are packed so one
    ///         rule is a single storage slot.
    struct ForbiddenRule {
        uint16 catA;
        uint16 idA;
        uint16 catB;
        uint16 idB; // 0 = WILDCARD: any filled trait in catB
    }

    ForbiddenRule[] internal forbiddenRules;

    /// @dev Hard cap on the rule count, enforced in setForbiddenPairs.
    ///
    ///      _violatesRules iterates this array on every draw attempt, so rule COUNT is
    ///      the cost driver — the opposite of the pair-keyed mapping this replaced, whose
    ///      cost was fixed at C(n,2)+n probes (55 for a 10-slot fill) no matter how many
    ///      rules existed. The two designs cross over at ~55 rules: below that the array
    ///      wins, above it the array is strictly worse than what it replaced.
    ///
    ///      Capping BELOW the crossover makes "never worse than the old design" an
    ///      invariant rather than a convention. It also makes the natural mistake
    ///      unloadable: "2 hoodies forbid all 51 hats" enumerated as id-level pairs is
    ///      102 entries and now REVERTS, forcing the 2-rule WILDCARD form (idB = 0) the
    ///      draw is designed around.
    ///
    ///      This bounds the damage; it cannot force the OPTIMAL encoding. 32 id-level
    ///      rules where 2 wildcards would do still passes — 16x off optimal, but bounded
    ///      and still cheaper than the mapping. The deploy generator collapses groups
    ///      into wildcards automatically; this is the backstop for hand-written config.
    uint256 internal constant MAX_FORBIDDEN_RULES = 32;

    /// @notice Active trait-exclusion rule count (0 => the draw skips the check).
    function forbiddenPairCount() public view returns (uint256) {
        return forbiddenRules.length;
    }

    /// @notice Special (Epic/Legendary) trait designation, set from the trait file via
    ///         setSpecialTraits. Key = _traitKey(category, traitId); value 1 = Epic,
    ///         2 = Legendary, 0 = normal. Category 0 = body color; category s+1 = slot s.
    ///         A gloomble's tier (Token.tier) is the rarest special trait it holds, and
    ///         drawing any special FREEZES the gloomble (no more rolls).
    mapping(bytes32 traitKey => uint8 tier) internal traitTier;
    /// @notice cap-1: a special trait, once drawn, is claimed forever — never drawn again.
    mapping(bytes32 traitKey => bool) internal specialClaimed;
    uint256 public specialTraitCount; // 0 => fast-path: skip all special-trait checks

    // Mint / re-roll economics. rerollPrice is a flat fee (default 0), set via
    // setMintConfig. Commit-reveal needs no oracle funding; a small fee can self-fund
    // the relayer that sends finalizeReRoll (see UPGRADES-TO-PORT.md, part D).
    uint256 public mintPrice;
    uint256 internal rerollPrice; // no getter (EIP-170); read the live fee via currentRerollFee()
    /// @notice One-way config freeze (audit hardening): once set, the trait
    ///         weights and maxSupply are permanently locked — not even the owner
    ///         can change them. Call freezeConfig() right before opening the mint.
    bool public configFrozen;
    uint256 public totalMinted;
    /// @notice Until revealed, tokenURI returns a placeholder ("mystery gloomble").
    ///         Combos are still assigned at mint (uniqueness + live rarity intact),
    ///         but WHICH token wears WHICH combo is decided only at the reveal, by
    ///         rotating the token->combo mapping a random distance (see _sid). So
    ///         nobody — owner included — can rarity-snipe unrevealed tokens.
    bool public revealed;
    /// @notice Entropy block committed by scheduleReveal. Its (then-unknowable)
    ///         blockhash decides the rotation; finalizeReveal is permissionless
    ///         so the owner can't peek at the entropy and stall.
    uint256 public revealBlock;
    /// @notice Rotation distance applied to pre-reveal tokens (set at finalize).
    uint256 public revealShift;
    /// @notice totalMinted at SCHEDULE time — the rotation domain. Snapshotted
    ///         before the entropy exists so minting in the reveal window can't
    ///         grind the modulus (shift = hash % revealSupply). Tokens minted
    ///         after the schedule map to themselves.
    uint256 public revealSupply;

    /// @dev Per-token committed entropy block for an in-flight re-roll (0 if none),
    ///      keyed by storage id. finalizeReRoll reads blockhash(_rerollBlock[sid]).
    mapping(uint256 sid => uint256 entropyBlock) internal _rerollBlock;

    /// @dev multiConfigure logic lives in a delegatecall impl (keeps the token under
    ///      the EIP-170 limit). The owner-gated fallback() forwards to it. (Upgrade B1)
    address internal multiConfigureImpl;

    IGloomblesRenderer public renderer;

    // ───────────────────────────────────────────────────────────── SeaDrop ──
    // OpenSea-hosted mint: the SeaDrop singleton calls mintSeaDrop() on us after
    // collecting payment. We expose getMintStats() so it can enforce per-wallet
    // and max-supply limits, and forward drop config to it from the owner.

    mapping(address seaDrop => bool allowed) internal _allowedSeaDrop;
    address[] internal _enumeratedAllowedSeaDrop;
    mapping(address minter => uint256 count) internal _numberMinted;

    // Collection metadata (ISeaDropTokenContractMetadata). Our token art is fully
    // on-chain via tokenURI(), so baseURI is unused; contractURI feeds OpenSea's
    // collection page, provenanceHash documents the (already-on-chain) ordering.
    string internal _tokenBaseURI;
    string internal _contractURI;
    bytes32 internal _provenanceHash;
    RoyaltyInfo internal _royaltyInfo;

    /// @notice Pre-defined 1/1 characters. A reserved STORAGE id holds a fixed,
    ///         hand-set combo of EXCLUSIVE traits (no generated gloomble can wear
    ///         them), set before any mint via setOneOfOnes, instead of a generated
    ///         combo. A 1/1 is permanently LOCKED: it can't re-roll, and can't be a
    ///         merge host or sacrifice. The shift-reveal rotation scatters the
    ///         reserved sids onto random public ids, so which minter pulls a 1/1 is
    ///         fair + un-snipeable. 1/1s count INSIDE maxSupply and sit OUTSIDE the
    ///         rarity ladder (no tier, not ranked). Keyed by STORAGE id (see _sid).
    mapping(uint256 sid => bool) internal _isOneOfOne;
    uint256 public oneOfOneCount;
    /// @dev Highest reserved 1/1 storage id. scheduleReveal requires totalMinted to
    ///      exceed it, so every reserved 1/1 has minted AND falls inside the reveal
    ///      rotation domain [0, revealSupply) — guaranteeing it scatters to a random
    ///      public id (fair) and is never stranded unminted. (1/1 audit MED)
    uint256 internal _oneOfOneMaxSid;

    /// @notice Per-mint trait-count distribution: weights for counts 1..length
    ///         (length <= MINT_TRAITS). A mint draws its starting trait count from these
    ///         weights instead of always minting at MINT_TRAITS, so the collection has
    ///         genuine mint diversity (a few "bare" color-only gloombles, many sparse
    ///         ones, ~a third at the MINT_TRAITS cap). EMPTY => every mint uses the fixed
    ///         MINT_TRAITS baseline (back-compat). If a low count's small combo space is
    ///         exhausted, the draw SPILLS UP to a higher count so mint never bricks.
    ///         Set via setMintCountWeights (pre-mint, lockable). (mint-distribution)
    uint32[] public mintCountWeights; // mintCountWeights[i] -> weight of trait count (i+1)
    uint256 internal mintCountTotalWeight; // internal, no getter (EIP-170 headroom)

    /// @notice Bitmask of MANDATORY slot categories (bit i set => slot i is always filled
    ///         on every gloomble — e.g. background, mouth, shadow). The body color is always
    ///         present too, so the trait-count floor is 1 + (number of mandatory slots). The
    ///         trait-count game then plays out over the OPTIONAL (non-mandatory) slots. 0 =>
    ///         every slot optional (back-compat). Set via setMandatorySlots. (mandatory-base)
    uint256 internal mandatorySlotMask; // internal, no getter (EIP-170 headroom)

    /// @notice Fixed destination for sweepToKeeper() — the finalize-keeper hot wallet. The
    ///         owner sets it (setKeeperWallet); then ANYONE can call sweepToKeeper() to push
    ///         collected re-roll fees to it, so an auto-replenish keeper never needs the owner
    ///         key in a server. Appended (new slot) — existing layout unchanged. (keeper-replenish)
    address public keeperWallet;

    /// @notice True once a host has been forged via merge(). Authoritative "one merge per host"
    ///         guard — works even when the trait file has fewer than MAX_TRAITS reachable
    ///         categories (so a forged host caps below 10 and the trait-count check wouldn't fire).
    ///         Appended (new slot) — existing layout unchanged. (merge-loophole fix)
    mapping(uint256 => bool) internal _hostMerged;

    /// @notice One-way renderer lock. Once set (freezeRenderer, in the config module), setRenderer
    ///         reverts — not even the owner can swap the art wrapper, so the on-chain art becomes
    ///         immutable/trustless. Kept SEPARATE from configFrozen so the renderer can stay
    ///         swappable through the post-launch tokenURI-gas shakeout, then be locked when
    ///         confident. `internal` (not `public`): GloomblesRR is at the EIP-170 limit (7 bytes
    ///         spare) so it can't afford the auto-getter; the one-way RendererFrozen event is the
    ///         public proof-of-lock. Appended (new slot) — existing layout unchanged. (audit M-3)
    bool internal rendererFrozen;

    // ────────────────────────────────────────────────────────────── events ──

    event Minted(uint256 indexed tokenId, address indexed to, bytes32 comboHash);
    event ReRollRequested(uint256 indexed tokenId, uint256 indexed entropyBlock, uint8 rerollNumber);
    event ReRolled(uint256 indexed tokenId, bytes32 oldCombo, bytes32 newCombo, uint8 rerollCount);
    event RollReset(uint256 indexed tokenId, uint256 indexed entropyBlock);
    event ForbiddenPairsUpdated(uint256 totalForbidden);
    event SpecialTraitsUpdated(uint256 totalSpecial);
    event RevealScheduled(uint256 blockNumber);
    event Revealed(uint256 shift, uint256 supply);
    // Config-change observability (audit hardening): every owner setter emits.
    event RendererUpdated(address indexed renderer);
    event TraitsUpdated(uint256 colorCount, uint256 slotCount);
    event MintConfigUpdated(uint256 mintPrice, uint256 rerollPrice);
    event ConfigFrozen();
    event Merged(uint256 indexed hostId, uint256[] burned, uint8 traitCount);
    event OneOfOnesSet(uint256 totalOneOfOne);
    event MintCountWeightsUpdated(uint256 buckets);
    event MandatorySlotsUpdated(uint256 mask);
    event KeeperWalletUpdated(address keeper);
    event RendererFrozen();
    /// @notice ERC-4906 single-token metadata refresh — emitted when one token's art
    ///         changes (reroll / merge) so marketplaces re-pull just that token.
    ///         (BatchMetadataUpdate, the whole-collection signal used on reveal + renderer
    ///         swap, comes from the SeaDrop metadata interface.) (audit M-3)
    event MetadataUpdate(uint256 _tokenId);

    // ────────────────────────────────────────────────────────────── errors ──

    error SoldOut();
    error WrongPrice();
    error RefundFailed();
    error NotConfigured();
    error NotOwner();
    error RollPending();
    error RollNotStuck();
    error NoPendingRoll();
    error TierLocked();
    error RerollNotReady();
    error RerollEntropyExpired();
    error MaxRerollsReached();
    error CooldownActive();
    error ComboSpaceExhausted();
    error InsufficientComboSpace();
    error MintClosed();
    error NonexistentToken();
    error InvalidConfig();
    error WithdrawFailed();
    error RenounceDisabled();
    error ConfigLocked();
    error AlreadyRevealed();
    error NotRevealed();
    error RevealNotScheduled();
    error RevealNotReady();
    error RevealEntropyExpired();
    error RevealEntropyLive();
    error MergeInvalid();
    error MergeHostComplete(); // host already has MAX_TRAITS — merge only completes an incomplete one
    error LockedOneOfOne(); // 1/1s are fixed: can't re-roll, can't be a merge host or sacrifice
    /// @dev A Mythic or forged host can never be a merge sacrifice — it leaves the loop forever.
    ///      Fires on STATUS (traitCount >= MAX_TRAITS, so a naturally-evolved Mythic counts) OR
    ///      provenance (_hostMerged, so a forged host that capped below MAX on a too-small trait
    ///      file is still caught). One error (not two) to stay under the EIP-170 size limit.
    error NotBurnable();
    error OneOfOneUnminted(); // scheduleReveal: a reserved 1/1 sid hasn't minted yet

    // ───────────────────────────────────────────────────────── constructor ──

    constructor(string memory n, string memory s) ERC721(n, s) Ownable(msg.sender) {}

    // ──────────────────────────────────────────── shared view/pure helpers ──

    /// @dev Canonical (order-independent) key for a forbidden trait pair. Category 0 =
    ///      body color; category s+1 = slot s.
    function _ruleKey(uint16 catA, uint16 idA, uint16 catB, uint16 idB) internal pure returns (bytes32) {
        if (catA > catB || (catA == catB && idA > idB)) {
            (catA, idA, catB, idB) = (catB, idB, catA, idA);
        }
        return keccak256(abi.encode(catA, idA, catB, idB));
    }

    /// @dev Key for a single (category, trait) — category 0 = color, s+1 = slot s.
    function _traitKey(uint16 cat, uint16 id) internal pure returns (bytes32) {
        return keccak256(abi.encode(cat, id));
    }

    function _nonzero(uint32[] storage weights) internal view returns (uint256 c) {
        uint256 n = weights.length;
        for (uint256 i = 0; i < n; i++) {
            if (weights[i] > 0) c++;
        }
    }

    /// @notice Total combinatorial space (product of nonzero-weight options).
    function comboSpace() public view returns (uint256 space) {
        space = _nonzero(colorWeights);
        uint256 n = slotWeights.length;
        for (uint256 i = 0; i < n; i++) {
            uint256 c = _nonzero(slotWeights[i]);
            if (c > 0) space *= c;
        }
    }

    /// @dev Count nonzero-weight trait ids in `cat` that are NOT special. Trait ids are
    ///      1-based (id = i + 1); category 0 = body color, category s+1 = slot s — the
    ///      same encoding _rejectSpecials/_traitKey use.
    function _nonSpecialNonzero(uint16 cat, uint32[] storage weights)
        internal
        view
        returns (uint256 c)
    {
        uint256 n = weights.length;
        for (uint256 i = 0; i < n; i++) {
            if (weights[i] > 0 && traitTier[_traitKey(cat, uint16(i + 1))] == 0) c++;
        }
    }

    /// @notice Combo space reachable AT MINT. Mints are Normal tier and reject EVERY
    ///         special (specials are won by rolling), so specials are excluded here. If
    ///         the body-color category has no non-special option this is 0 — mint can
    ///         never draw a color and the config is un-mintable.
    /// @dev    CAVEAT (mint-distribution): this counts FULLY-saturated combos (every
    ///         fillable slot filled). A mint actually fills at most MINT_TRAITS-1 slots,
    ///         and the spill-up ceiling draws at count MINT_TRAITS, so when there are MORE
    ///         than MINT_TRAITS-1 fillable slots this OVER-counts the true mint space. It
    ///         stays a safe over-estimate only while the reachable count-MINT_TRAITS space
    ///         comfortably exceeds maxSupply — which it does by orders of magnitude at any
    ///         realistic Gloombles config (e.g. 9 slots: C(9,6)·colors·v^6 ≈ tens of
    ///         millions vs a 3,333 supply). It would only mislead at a tens-of-millions
    ///         maxSupply with a wide trait table; size accordingly if ever scaling there.
    function _mintComboSpace() internal view returns (uint256 space) {
        space = _nonSpecialNonzero(0, colorWeights);
        uint256 n = slotWeights.length;
        for (uint256 i = 0; i < n; i++) {
            uint256 c = _nonSpecialNonzero(uint16(i + 1), slotWeights[i]);
            if (c > 0) space *= c; // a slot with only specials can still draw "none"
        }
    }

    /// @dev All-time uniqueness reserves one combo per mint AND per re-roll, forever,
    ///      so the combo space must hold maxSupply*(MAX_REROLLS+1) distinct combos or
    ///      _uniqueCombo eventually reverts and minting/re-rolls brick. Enforced at
    ///      setTraits + freezeConfig so a launch can't be sealed into a dead config.
    function _assertComboSpace() internal view {
        if (comboSpace() < maxSupply * (uint256(MAX_REROLLS) + 1)) revert InsufficientComboSpace();
        // comboSpace() counts specials too, but mint REJECTS every special — so the
        // special-free mint space must still cover the supply, else mint exhausts
        // rejection sampling and bricks while the check above passes. (audit MED-3)
        if (_mintComboSpace() < maxSupply) revert InsufficientComboSpace();
    }

    /// @dev Filled categories (body color + non-zero slots) in a combo. traitCount is
    ///      derived from this so it can never exceed the configured categories. Shared
    ///      by GloomblesRR (mint/redraw) and MultiConfigureImpl (setOneOfOnes).
    function _countFilled(uint16[] memory slots) internal pure returns (uint8 c) {
        c = 1; // body color is always present
        uint256 n = slots.length;
        for (uint256 i = 0; i < n; i++) {
            if (slots[i] != 0) {
                unchecked { c++; }
            }
        }
    }
}

src/IGloomblesRenderer.sol

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

/// @title IGloomblesRenderer
/// @notice Renders a token's on-chain SVG + metadata from its live state.
/// @dev Kept separate from the core contract so the (large) pixel-SVG trait
///      library and assembly logic can be deployed/upgraded independently of
///      the value-bearing ERC-721. The core passes a fully-resolved snapshot
///      of token state; the renderer is pure presentation.
interface IGloomblesRenderer {
    /// @param tokenId           the token being rendered
    /// @param revealedTraitIds  per-slot trait id, length == number revealed; 0 = unrevealed slot
    /// @param colorId           current body color id
    /// @param isGrown           whether the reveal sequence has finished
    /// @return uri              a data: URI (application/json;base64) per ERC-721 metadata
    function tokenURI(
        uint256 tokenId,
        uint16[] calldata revealedTraitIds,
        uint16 colorId,
        bool isGrown
    ) external view returns (string memory uri);

    /// @notice The pre-reveal placeholder metadata, shared by every token until reveal.
    /// @dev    Lives here (not inline in the core) because the art is a stored raster too big
    ///         for the core's EIP-170 headroom. Same image for all tokens; only the name/id vary.
    function placeholderURI(uint256 tokenId) external view returns (string memory uri);
}

src/seadrop/INonFungibleSeaDropToken.sol

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

// Vendored from ProjectOpenSea/seadrop (src/interfaces/INonFungibleSeaDropToken.sol).
// This is the interface OpenSea's SeaDrop contract recognizes via ERC-165 and
// calls into to drive an OpenSea-hosted mint. Pragma widened to `^0.8.17`.
import {ISeaDropTokenContractMetadata} from "./ISeaDropTokenContractMetadata.sol";
import {
    AllowListData,
    PublicDrop,
    TokenGatedDropStage,
    SignedMintValidationParams
} from "./SeaDropStructs.sol";

interface INonFungibleSeaDropToken is ISeaDropTokenContractMetadata {
    error OnlyAllowedSeaDrop();

    event AllowedSeaDropUpdated(address[] allowedSeaDrop);

    function updateAllowedSeaDrop(address[] calldata allowedSeaDrop) external;

    function mintSeaDrop(address minter, uint256 quantity) external;

    function getMintStats(address minter)
        external
        view
        returns (uint256 minterNumMinted, uint256 currentTotalSupply, uint256 maxSupply);

    function updatePublicDrop(address seaDropImpl, PublicDrop calldata publicDrop) external;

    function updateAllowList(address seaDropImpl, AllowListData calldata allowListData) external;

    function updateTokenGatedDrop(
        address seaDropImpl,
        address allowedNftToken,
        TokenGatedDropStage calldata dropStage
    ) external;

    function updateDropURI(address seaDropImpl, string calldata dropURI) external;

    function updateCreatorPayoutAddress(address seaDropImpl, address payoutAddress) external;

    function updateAllowedFeeRecipient(address seaDropImpl, address feeRecipient, bool allowed)
        external;

    function updateSignedMintValidationParams(
        address seaDropImpl,
        address signer,
        SignedMintValidationParams memory signedMintValidationParams
    ) external;

    function updatePayer(address seaDropImpl, address payer, bool allowed) external;
}

src/seadrop/ISeaDrop.sol

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

// Minimal slice of ProjectOpenSea/seadrop's ISeaDrop — only the config setters
// our token forwards to (the token is the authorized caller; SeaDrop checks
// msg.sender == nftContract). Signatures match the deployed SeaDrop contract
// exactly so the forwarding calls land. Mint enforcement lives in SeaDrop.
import {
    AllowListData,
    PublicDrop,
    TokenGatedDropStage,
    SignedMintValidationParams
} from "./SeaDropStructs.sol";

interface ISeaDrop {
    function updatePublicDrop(PublicDrop calldata publicDrop) external;

    function updateAllowList(AllowListData calldata allowListData) external;

    function updateTokenGatedDrop(
        address allowedNftToken,
        TokenGatedDropStage calldata dropStage
    ) external;

    function updateDropURI(string calldata dropURI) external;

    function updateCreatorPayoutAddress(address payoutAddress) external;

    function updateAllowedFeeRecipient(address feeRecipient, bool allowed) external;

    function updateSignedMintValidationParams(
        address signer,
        SignedMintValidationParams calldata signedMintValidationParams
    ) external;

    function updatePayer(address payer, bool allowed) external;
}

src/seadrop/ISeaDropTokenContractMetadata.sol

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

// Vendored from ProjectOpenSea/seadrop (src/interfaces/ISeaDropTokenContractMetadata.sol).
// IERC2981 import repointed to our OZ v5 remapping; pragma widened to `^0.8.17`.
import {IERC2981} from "@openzeppelin/contracts/interfaces/IERC2981.sol";

interface ISeaDropTokenContractMetadata is IERC2981 {
    error CannotExceedMaxSupplyOfUint64(uint256 newMaxSupply);
    error NewMaxSupplyCannotBeLessThenTotalMinted(uint256 got, uint256 totalMinted);
    error ProvenanceHashCannotBeSetAfterMintStarted();
    error InvalidRoyaltyBasisPoints(uint256 basisPoints);
    error RoyaltyAddressCannotBeZeroAddress();

    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
    event ContractURIUpdated(string newContractURI);
    event MaxSupplyUpdated(uint256 newMaxSupply);
    event ProvenanceHashUpdated(bytes32 previousHash, bytes32 newHash);
    event RoyaltyInfoUpdated(address receiver, uint256 bps);

    struct RoyaltyInfo {
        address royaltyAddress;
        uint96 royaltyBps;
    }

    function setBaseURI(string calldata tokenURI) external;
    function setContractURI(string calldata newContractURI) external;
    function setMaxSupply(uint256 newMaxSupply) external;
    function setProvenanceHash(bytes32 newProvenanceHash) external;
    function setRoyaltyInfo(RoyaltyInfo calldata newInfo) external;

    function baseURI() external view returns (string memory);
    function contractURI() external view returns (string memory);
    function maxSupply() external view returns (uint256);
    function provenanceHash() external view returns (bytes32);
    function royaltyAddress() external view returns (address);
    function royaltyBasisPoints() external view returns (uint256);
}

src/seadrop/SeaDropStructs.sol

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

// Vendored verbatim from ProjectOpenSea/seadrop (src/lib/SeaDropStructs.sol).
// These are pure data structs with no dependencies — version-agnostic, so they
// compile cleanly under our 0.8.24 toolchain while staying byte-compatible with
// the SeaDrop contract OpenSea deploys. Pragma widened from `0.8.17` to `^0.8.17`.

/**
 * @notice A struct defining public drop data. Fits in one storage slot.
 */
struct PublicDrop {
    uint80 mintPrice; // 80/256 bits
    uint48 startTime; // 128/256 bits
    uint48 endTime; // 176/256 bits
    uint16 maxTotalMintableByWallet; // 224/256 bits
    uint16 feeBps; // 240/256 bits
    bool restrictFeeRecipients; // 248/256 bits
}

/**
 * @notice A struct defining token gated drop stage data. Fits in one storage slot.
 */
struct TokenGatedDropStage {
    uint80 mintPrice; // 80/256 bits
    uint16 maxTotalMintableByWallet; // 96/256 bits
    uint48 startTime; // 144/256 bits
    uint48 endTime; // 192/256 bits
    uint8 dropStageIndex; // non-zero. 200/256 bits
    uint32 maxTokenSupplyForStage; // 232/256 bits
    uint16 feeBps; // 248/256 bits
    bool restrictFeeRecipients; // 256/256 bits
}

/**
 * @notice A struct defining mint params for an allow list.
 */
struct MintParams {
    uint256 mintPrice;
    uint256 maxTotalMintableByWallet;
    uint256 startTime;
    uint256 endTime;
    uint256 dropStageIndex; // non-zero
    uint256 maxTokenSupplyForStage;
    uint256 feeBps;
    bool restrictFeeRecipients;
}

/**
 * @notice A struct defining token gated mint params.
 */
struct TokenGatedMintParams {
    address allowedNftToken;
    uint256[] allowedNftTokenIds;
}

/**
 * @notice A struct defining allow list data (for minting an allow list).
 */
struct AllowListData {
    bytes32 merkleRoot;
    string[] publicKeyURIs;
    string allowListURI;
}

/**
 * @notice A struct defining min/max params to validate for signed mints.
 */
struct SignedMintValidationParams {
    uint80 minMintPrice; // 80/256 bits
    uint24 maxMaxTotalMintableByWallet; // 104/256 bits
    uint40 minStartTime; // 144/256 bits
    uint40 maxEndTime; // 184/256 bits
    uint40 maxMaxTokenSupplyForStage; // 224/256 bits
    uint16 minFeeBps; // 240/256 bits
    uint16 maxFeeBps; // 256/256 bits
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@chainlink/contracts/=lib/chainlink-brownie-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/",
    "chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.