Skip to content
Verified contractExactMIT

Onchain0m

Address0x79410e29d8dfdfdb48ba7622f9ca537c89923bf0
Balance

0 ETH

 

Transactions

612

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 25 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,970,024
Creation transaction
0xd4ebbcf767…b622439070

33 files

src/Onchain0m.sol

// SPDX-License-Identifier: MIT
//
//                                       !   ___
//                                       !  / _ \
//                                       ! | | | |  _ __ ___
//                                       ! | | | | | '_ ` _ \
//                                       ! | |_| | | | | | | |
//                                       .  \___/  |_| |_| |_|
//
//                                  \XX]                        ]XX\
//                               [{{nXXj{{{{{[            [{{{{{jXXn{{[
//                               uXXXXXXXXXXXu            uXXXXXXXXXXXu
//                               uXXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXu
//                               uXXXXXXXXXXXXXXX      XXXXXXXXXXXXXXXu
//                               uXXXXXXXXXXXu            uXXXXXXXXXXXu
//                               fxxcXXvxxxxxf            fxxcXXXXXcxxf
//                                  \XX]                     \XXXXX\
//                                  ...          cccccc      .......
//                                               XXXXXX
//                               uXXi        ^XXXXXXXXXXXX^        iXXu
//                               uXXi        ^XXXXXXXXXXXX^        iXXu
//                                  \XX]     ^XXX      XXX^     ]XX\
//                                  \XXt]]<  ']]]      ]]]'  <]]tXX\
//                                  \XXXXX\                  \XXXXX\
//                                     ]XXXXXu   XXXXXX   uXXXXX]
//                                     ]XXXXXu   XXXXXX   uXXXXX]
//                                     ]XXXXXXXXXXXXXXXXXXXXXXXX]
//                                     ?cczXXXXXXXXXXXXXXXXXXzcc?
//                                        iXXXXXXXXXXXXXXXXXXi
//                                        .""IXXX""""""XXXI"".
//                                           ^XXX      XXX^
//
//                            ++++++"     "++++++      ++++++"     "++++++
//                            XXXXXXi     iXXXXXX      XXXXXXi     iXXXXXX
//                               uXXi        ^XXX         uXXi        ^XXX
//                               uXXi        ^XXX         uXXi        ^XXX
//                               uXXi     iXXXXXX      XXXXXXi     iXXu
//                               uXXi     iXXXXXX      XXXXXXi     iXXu
//
pragma solidity 0.8.28;

import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import { IERC4906 } from "@openzeppelin/contracts/interfaces/IERC4906.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {
    ReentrancyGuardTransient
} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { Base64 } from "solady/utils/Base64.sol";

import { IPaletteAssets } from "./lib/IPaletteAssets.sol";
import { IZeroStaticRenderer } from "./zero/interfaces/IZeroStaticRenderer.sol";
import { IZeroHtmlTemplateStore } from "./zero/interfaces/IZeroHtmlTemplateStore.sol";
import { IOnchain9mSource } from "./zero/interfaces/IOnchain9mSource.sol";
import { Onchain9mSourceBinding } from "./zero/lib/Onchain9mSourceBinding.sol";

// slither-disable-next-line missing-inheritance
contract Onchain0mRendererGuard {
    uint8 private constant _HEAVY = 1;
    uint8 private constant _MEGA = 2;
    uint8 private constant _LIGHT = 3;

    error RendererAssetsMismatch();
    error RendererComponentMissing();
    error RendererVersionMismatch();
    error RendererProfileMismatch();
    error RendererSpecMismatch();
    error RendererTemplateMismatch();
    error RendererSourceMismatch();

    // slither-disable-start naming-convention
    IPaletteAssets private immutable _ASSETS;
    IOnchain9mSource private immutable _SOURCE_ONCHAIN9M;
    uint256 private immutable _SOURCE_CHAIN_ID;
    bytes32 private immutable _SOURCE_BINDING_HASH;
    bytes32 private immutable _SOURCE_9M_COMMITMENT;
    bytes32 private immutable _RENDER_SPEC_HASH;
    bytes32 private immutable _ANIMATION_TEMPLATE_HASH;
    bytes32 private immutable _PROFILE_ROOT;
    uint8 private immutable _RENDER_VERSION;
    bytes32 public immutable CONFIG_HASH;
    // slither-disable-end naming-convention

    constructor(
        IOnchain9mSource sourceOnchain9m_,
        bytes32 assetRoot_,
        bytes32 renderSpecHash_,
        bytes32 animationTemplateHash_,
        bytes32 profileRoot_,
        uint8 renderVersion_
    ) {
        Onchain9mSourceBinding.Binding memory sourceBinding =
            Onchain9mSourceBinding.load(sourceOnchain9m_);
        bytes32 sourceCommitment = Onchain9mSourceBinding.commitment(sourceBinding, assetRoot_);
        _ASSETS = sourceBinding.assets;
        _SOURCE_ONCHAIN9M = sourceOnchain9m_;
        _SOURCE_CHAIN_ID = sourceBinding.chainId;
        _SOURCE_BINDING_HASH = sourceBinding.bindingHash;
        _SOURCE_9M_COMMITMENT = sourceCommitment;
        _RENDER_SPEC_HASH = renderSpecHash_;
        _ANIMATION_TEMPLATE_HASH = animationTemplateHash_;
        _PROFILE_ROOT = profileRoot_;
        _RENDER_VERSION = renderVersion_;
        CONFIG_HASH = Onchain9mSourceBinding.configHash(
            sourceCommitment, renderSpecHash_, animationTemplateHash_, profileRoot_, renderVersion_
        );
    }

    function assets() external view returns (IPaletteAssets) {
        return _ASSETS;
    }

    function sourceOnchain9m() external view returns (IOnchain9mSource) {
        return _SOURCE_ONCHAIN9M;
    }

    function sourceChainId() external view returns (uint256) {
        return _SOURCE_CHAIN_ID;
    }

    function sourceBindingHash() external view returns (bytes32) {
        return _SOURCE_BINDING_HASH;
    }

    function source9mCommitment() external view returns (bytes32) {
        return _SOURCE_9M_COMMITMENT;
    }

    function rendererCommitment(IZeroStaticRenderer candidate) public view returns (bytes32) {
        _validate(candidate);
        return keccak256(
            abi.encode(
                address(this),
                address(this).codehash,
                CONFIG_HASH,
                address(candidate),
                address(candidate).codehash,
                _staticModules(candidate),
                _animationModules(candidate)
            )
        );
    }

    function _validate(IZeroStaticRenderer candidate) private view {
        if (address(candidate).code.length == 0) revert RendererComponentMissing();
        if (
            address(candidate.assets()) != address(_ASSETS)
                || address(candidate.composer().assets()) != address(_ASSETS)
        ) revert RendererAssetsMismatch();
        if (
            address(candidate.composer().sourceOnchain9m()) != address(_SOURCE_ONCHAIN9M)
                || candidate.composer().sourceBindingHash() != _SOURCE_BINDING_HASH
        ) revert RendererSourceMismatch();
        if (address(candidate.composer().kernel()) != address(candidate.kernel())) {
            revert RendererComponentMissing();
        }
        if (
            candidate.renderVersion() != _RENDER_VERSION
                || candidate.kernel().renderVersion() != _RENDER_VERSION
        ) {
            revert RendererVersionMismatch();
        }
        if (candidate.kernel().renderSpecHash() != _RENDER_SPEC_HASH) {
            revert RendererSpecMismatch();
        }

        address composer_ = address(candidate.composer());
        address kernel_ = address(candidate.kernel());
        address pngEncoder_ = address(candidate.pngEncoder());
        address svgRenderer_ = address(candidate.svgRenderer());
        address templateStore_ = address(candidate.htmlTemplateStore());
        address animationRenderer_ = address(candidate.animationRenderer());
        if (
            composer_.code.length == 0 || kernel_.code.length == 0 || pngEncoder_.code.length == 0
                || svgRenderer_.code.length == 0 || templateStore_.code.length == 0
                || animationRenderer_.code.length == 0
        ) revert RendererComponentMissing();

        IZeroHtmlTemplateStore templateStore = IZeroHtmlTemplateStore(templateStore_);
        if (
            !templateStore.isSealed() || templateStore.templateLength() == 0
                || templateStore.templateHash() != _ANIMATION_TEMPLATE_HASH
                || candidate.templateHash() != _ANIMATION_TEMPLATE_HASH
                || address(candidate.animationRenderer().templateStore()) != templateStore_
        ) revert RendererTemplateMismatch();

        if (
            candidate.kernel().profileRoot() != _PROFILE_ROOT
                || candidate.profileHash(_HEAVY) != candidate.kernel().profileHash(_HEAVY)
                || candidate.profileHash(_MEGA) != candidate.kernel().profileHash(_MEGA)
                || candidate.profileHash(_LIGHT) != candidate.kernel().profileHash(_LIGHT)
        ) {
            revert RendererProfileMismatch();
        }
    }

    function _staticModules(IZeroStaticRenderer candidate) private view returns (bytes32) {
        address composer_ = address(candidate.composer());
        address kernel_ = address(candidate.kernel());
        address pngEncoder_ = address(candidate.pngEncoder());
        address svgRenderer_ = address(candidate.svgRenderer());
        return keccak256(
            abi.encode(
                composer_,
                composer_.codehash,
                kernel_,
                kernel_.codehash,
                pngEncoder_,
                pngEncoder_.codehash,
                svgRenderer_,
                svgRenderer_.codehash
            )
        );
    }

    function _animationModules(IZeroStaticRenderer candidate) private view returns (bytes32) {
        address templateStore_ = address(candidate.htmlTemplateStore());
        address animationRenderer_ = address(candidate.animationRenderer());
        return keccak256(
            abi.encode(
                templateStore_,
                templateStore_.codehash,
                animationRenderer_,
                animationRenderer_.codehash,
                _ANIMATION_TEMPLATE_HASH
            )
        );
    }
}

/// @title Onchain0m — the 0m//TX burn-to-transmission collection
/// @notice Issuance is a holder-initiated `Onchain9m.safeTransferFrom(holder, Onchain0m, tokenId)`.
///         The receiver callback forwards the carrier to `0x…dEaD` and mints the same-ID OPEN 0m
///         back to the holder. Anyone may then call `lockTransmission(tokenId)` to derive the
///         final seed and LVL from a committed window of future block hashes.
/// @dev No owner, minter, signer, allowlist, renderer setter, payable path, withdrawal, rescue, or
///      upgrade. The guardian can pause/unpause new openings and permanently renounce that power.
// slither-disable-next-line missing-inheritance
contract Onchain0m is ERC721, IERC721Receiver, IERC4906, ReentrancyGuardTransient {
    /// @notice The conventional dead address every transmitted carrier is forwarded to.
    address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
    /// @notice EIP-2935 historical block-hash contract (Ethereum protocol address, Pectra).
    address public constant HISTORY_CONTRACT = 0x0000F90827F1C53a10cb7A02335B175320002935;
    /// @notice The entropy anchor is the next block after the opening block.
    /// @dev Its hash cannot be read from inside the opening transaction, so a receiver cannot
    ///      inspect the resolved sample window and revert-grind the carrier.
    uint64 public constant ENTROPY_ANCHOR_DELAY = 1;
    /// @notice Smallest number of blocks between the entropy anchor and the first sampled block.
    uint64 public constant MIN_ENTROPY_DELAY = 1;

    /// @notice Number of distinct blocks the window START is spread across.
    /// @dev The first sample lands in `[anchor + 1, anchor + 4]`.
    uint64 public constant ENTROPY_DELAY_SPREAD = 4;

    /// @notice How many consecutive blocks contribute one salted bit each to a transmission.
    /// @dev One bit per block bounds producer influence: control of `t` blocks of a window reaches
    ///      at most `2^t` bit patterns for fixed other inputs. This does not establish unbiased traits.
    uint64 public constant ENTROPY_SAMPLE_COUNT = 16;

    /// @notice The entropy schedule as one binding word:
    ///         `anchorDelay << 192 | min << 128 | spread << 64 | count`.
    /// @dev Packing the four values keeps `_transmissionKey`'s `abi.encode` inside the
    ///      non-viaIR stack limit.
    uint256 public constant ENTROPY_DELAY_BINDING = (uint256(ENTROPY_ANCHOR_DELAY) << 192)
        | (uint256(MIN_ENTROPY_DELAY) << 128) | (uint256(ENTROPY_DELAY_SPREAD) << 64)
        | uint256(ENTROPY_SAMPLE_COUNT);
    /// @notice Number of historical block hashes EIP-2935 serves.
    uint64 public constant HISTORY_WINDOW = 8191;
    /// @notice How many recent blocks the EVM's own `BLOCKHASH` opcode can still answer for.
    /// @dev Recent native hashes are preferred. The pinned EIP-2935 contract is consulted when
    ///      the native answer is unavailable; both sources supply the same canonical header hash.
    uint64 public constant NATIVE_BLOCKHASH_WINDOW = 256;
    /// @notice Theoretical ceiling on the pinned 9m source token-ID domain.
    uint256 public constant MAX_SOURCE_ID_DOMAIN = 7_331;

    uint8 public constant PROFILE_HEAVY = 1;
    uint8 public constant PROFILE_MEGA = 2;
    uint8 public constant PROFILE_LIGHT = 3;
    uint8 public constant PROFILE_1337 = 4;
    uint8 public constant PROFILE_5KU11 = 5;
    uint8 public constant PROTOCOL_VERSION = 1;
    /// @notice Maximum queue entries inspected after one successful opening.
    /// @dev Revealed tokens leave the queue immediately. One burn may fund only the oldest pending
    ///      entry; remaining work stays permissionless for another burn, holder, or backstop locker.
    uint8 public constant AUTO_LOCK_STEPS = 1;
    /// @notice Gas that must remain before the queue drain attempts one more reveal.
    /// @dev The drain checks this budget before each step. Keep it above the measured worst-case
    ///      canonical reveal cost, including the history-contract path and queue bookkeeping.
    uint256 public constant AUTO_LOCK_GAS_FLOOR = 300_000;

    /// @notice Maximum blocks a guardian pause can hold new openings before it auto-expires.
    /// @dev ~30 days at 12s mainnet blocks. The pause is a launch gate + emergency stop.
    uint64 public constant MAX_PAUSE_BLOCKS = 216_000;
    /// @notice Minimum produced blocks issuance stays open before the guardian may pause again.
    /// @dev ~24 hours at 12s mainnet blocks. Missed slots only lengthen the wall-clock window.
    uint64 public constant MIN_OPEN_BLOCKS = 7_200;

    /// @dev Exclusive outcome thresholds over `[0, 10_000)`: 1337 0.25% / 5KU11 0.4% /
    ///      MEGA 7.5% / HVY 54.85% / LITE 37%.
    uint256 private constant _ROLL_MODULUS = 10_000;
    uint256 private constant _ROLL_1337_MAX = 25;
    uint256 private constant _ROLL_5KU11_MAX = 65;
    uint256 private constant _ROLL_MEGA_MAX = 815;
    uint256 private constant _ROLL_HEAVY_MAX = 6_300;

    /// @notice Separates the final entropy commitment from every other hash in the protocol.
    /// @dev The full anchor hash selects one of four bounded sample-window offsets but is not part
    ///      of final entropy, preventing it from becoming an additional 256-bit proposer input.
    bytes32 public constant TRANSMISSION_ENTROPY_DOMAIN_V1 = keccak256("m1n7-807.0m-tx.entropy.v1");
    bytes32 public constant ART_SEED_DOMAIN_V1 = keccak256("m1n7-807.0m-tx.art-seed.v1");
    bytes32 public constant GLITCH_PROFILE_DOMAIN_V1 =
        keccak256("m1n7-807.0m-tx.glitch-profile.v1");
    bytes32 public constant SOURCE_SNAPSHOT_DOMAIN_V1 =
        keccak256("m1n7-807.0m-tx.source-snapshot.v1");
    bytes32 public constant RENDER_KEY_DOMAIN_V1 = keccak256("m1n7-807.0m-tx.render-key.v1");
    bytes32 public constant OPEN_ART_SEED_DOMAIN_V1 = keccak256("m1n7-807.0m-tx.open-art-seed.v1");
    /// @notice Separates the reveal-target draw from every other hash this contract computes.
    bytes32 public constant TARGET_OFFSET_DOMAIN_V1 = keccak256("m1n7-807.0m-tx.target-offset.v1");

    /// @notice Separates each per-block, per-token entropy sample from every other hash here.
    /// @dev The token id is in the preimage, so one candidate header gives each in-flight
    ///      transmission an independent bit rather than moving all of them together.
    bytes32 public constant ENTROPY_SAMPLE_DOMAIN_V1 =
        keccak256("m1n7-807.0m-tx.entropy-sample.v1");

    bytes32 public constant TRANSMISSION_KEY_DOMAIN_V1 =
        keccak256("m1n7-807.0m-tx.transmission-key.v1");

    // ── packed token word layout ────────────────────────────────────────────────────────────────
    // bits   0..15  baseIndex        (uint16)   bits 160..199  lockedAt      (uint40)
    // bits  16..31  bgIndex          (uint16)   bits 200..201  profile low   (2 bits)
    // bits  32..95  entropyAnchorBlock(uint64) bits 202..203  state         (2 bits)
    // bits  96..159 finalSeed        (uint64)   bits 204..211  renderVersion (uint8)
    //                                           bits 212..214  sampleOffset   (3 bits; LOCKED only)
    //                                           bit  215       profile high  (1 bit)
    //                                           bits 216..255  reserved (MUST stay zero)
    uint256 private constant _BG_SHIFT = 16;
    uint256 private constant _ENTROPY_ANCHOR_SHIFT = 32;
    uint256 private constant _SEED_SHIFT = 96;
    uint256 private constant _LOCKED_AT_SHIFT = 160;
    uint256 private constant _PROFILE_SHIFT = 200;
    uint256 private constant _STATE_SHIFT = 202;
    uint256 private constant _RENDER_VERSION_SHIFT = 204;
    uint256 private constant _SAMPLE_OFFSET_SHIFT = 212;
    uint256 private constant _PROFILE_HIGH_SHIFT = 215;
    /// @dev The offset spans 1..4, so reads mask to three bits and cannot pick up the reserved
    ///      bits above it.
    uint256 private constant _SAMPLE_OFFSET_MASK = 7;

    error NewTransmissionsArePaused();
    error NewTransmissionsNotPaused();
    error PauseCooldownActive(uint64 cooldownUntilBlock);
    error NotGuardian();
    error GuardianAuthorityRenounced();
    error UntrustedCaller();
    error UnsupportedIngress();
    error SourceIdOutOfDomain();
    error TransmissionAlreadyOpened();
    error SourceNotHeld();
    error SourceBindingChanged();
    error SourcePicksMalformed();
    error SourceForwardFailed();
    error SourceDomainMismatch();
    error TransmissionNotOpen();
    error TransmissionNotLocked();
    error AlreadyLocked();
    error EntropyAnchorNotReached();
    error TargetNotReached();
    error TargetExpired();
    error HistoryLookupFailed();
    error HistoryHashUnavailable();
    error HistoryContractMismatch();
    error AssetsNotSealed();
    error AssetsEmpty();
    error BadRenderVersion();
    error RendererGuardMismatch();
    error MissingProvenance();
    error ZeroAddress();
    error NonexistentToken();

    enum TransmissionState {
        NONE,
        OPEN,
        LOCKED
    }

    /// @notice The immutable art identity inputs of a LOCKED transmission.
    struct ArtParams {
        uint16 baseIndex;
        uint16 bgIndex;
        uint64 seed;
        uint8 profile;
        uint8 renderVersion;
    }

    struct CollectionProvenance {
        bytes32 assetRoot;
        bytes32 renderSpecHash;
        bytes32 animationTemplateHash;
        bytes32 profileRoot;
    }

    /// @dev Memory carrier for the exact source tuple; keeps the receiver callback off the stack
    ///      limit under the non-viaIR release profile.
    struct SourceRead {
        uint16 baseIndex;
        uint16 bgIndex;
        uint256 streakDay;
        uint256 mintNumber;
        uint64 mintedAt;
        bytes32 callsign;
    }

    /// @dev Intermediate LOCK values used to pack stored fields and emit commitment evidence.
    struct LockDerivation {
        bytes32 entropyAnchorHash;
        uint8 sampleOffset;
        uint16 entropySampleBits;
        bytes32 entropyCommitment;
        uint64 seed;
        uint8 profile;
        uint40 lockedAt;
        bytes32 renderKey;
        bytes32 transmissionKey;
    }

    /// @dev Static tuples keep the preimages inside the non-viaIR stack limit.
    ///      `abi.encode(domain, tuple)` is byte-identical to the flattened arguments.
    struct EntropyPreimage {
        uint256 chainId;
        address collection;
        address source;
        uint256 tokenId;
        bytes32 snapshot;
        uint64 entropyAnchorBlock;
        uint64 firstSampleBlock;
        uint16 entropySampleBits;
    }

    struct TransmissionKeyPreimage {
        bytes32 snapshot;
        address burnAddress;
        address historyContract;
        bytes32 historyCodehash;
        uint64 historyWindow;
        uint256 entropyDelayBinding;
        uint64 entropyAnchorBlock;
        bytes32 entropyAnchorHash;
        uint64 firstSampleBlock;
        uint16 entropySampleBits;
        bytes32 entropyCommitment;
        bytes32 renderKey;
        uint40 lockedAt;
        uint256 chainId;
        address collection;
    }

    event TransmissionOpened(
        uint256 indexed tokenId,
        address indexed originalTransmitter,
        uint64 indexed entropyAnchorBlock,
        uint16 baseIndex,
        uint16 bgIndex,
        uint256 sourceStreakDay,
        uint256 sourceMintNumber,
        uint64 sourceMintedAt,
        bytes32 sourceCallsign,
        bytes32 sourceSnapshotHash,
        uint8 protocolVersion
    );

    /// @dev `entropyAnchorHash` preserves the canonical reveal anchor in the receipt.
    ///      `entropySampleBits` is the extracted vector, LSB = the first sampled block. The raw
    ///      sample-block hashes are not emitted; a verifier reads them from its own node.
    event TransmissionLocked(
        uint256 indexed tokenId,
        uint64 indexed entropyAnchorBlock,
        uint64 indexed firstSampleBlock,
        bytes32 entropyAnchorHash,
        uint16 entropySampleBits,
        bytes32 entropyCommitment,
        uint64 seed,
        uint8 profile,
        uint64 lockedAt,
        uint8 renderVersion,
        bytes32 renderKey,
        bytes32 transmissionKey
    );

    /// @dev The one terminal transition that otherwise emits no log: an OPEN transmission whose reveal
    ///      window has fully lapsed. Best-effort — emitted when the auto-lock drain reaches and removes
    ///      the expired head; `transmissionExpired(tokenId)` is the authoritative per-token check.
    event TransmissionExpired(uint256 indexed tokenId, uint64 indexed entropyAnchorBlock);

    /// @param pausedUntilBlock the block through which new openings stay paused; the pause auto-expires
    ///        after this block even if the guardian never unpauses (anti-brick safety window).
    event NewTransmissionsPaused(address indexed guardian, uint64 pausedUntilBlock);
    event NewTransmissionsUnpaused(address indexed guardian);
    /// @dev One-way. After this the collection has NO operational authority of any kind.
    event GuardianRenounced(address indexed guardian);

    // slither-disable-start naming-convention
    /// @notice The pinned production 9m collection. Read-only apart from the receiver's own
    ///         same-call forward of a carrier it transiently owns.
    IOnchain9mSource public immutable NINE_M;
    /// @notice Highest valid source token ID; pinned at deploy and equal to 9m `maxSupply()` then.
    uint256 public immutable SOURCE_ID_MAX;
    /// @notice The only operational authority: pause/unpause NEW openings, and permanently
    ///         renounce that power. Remains readable after renunciation.
    address public immutable GUARDIAN;
    /// @notice Runtime code hash the EIP-2935 history contract had at deploy time.
    bytes32 public immutable HISTORY_CODEHASH;
    /// @notice Render version pinned from the bound renderer facade at deploy time.
    uint8 public immutable COLLECTION_RENDER_VERSION;

    /// @dev Fixed coordinates for the collection image in `contractURI`. Constant, so the
    ///      collection art can never drift, and glitched, so it is never a clean source frame.
    uint256 private constant COLLECTION_IMAGE_BASE_INDEX = 0;
    uint256 private constant COLLECTION_IMAGE_BG_INDEX = 0;
    uint64 private constant COLLECTION_IMAGE_SEED = 0x1337;
    uint8 private constant COLLECTION_IMAGE_PROFILE = 2;

    IPaletteAssets internal immutable ASSETS;
    uint256 private immutable _SOURCE_CHAIN_ID;
    bytes32 private immutable _SOURCE_BINDING_HASH;
    bytes32 private immutable _SOURCE_9M_COMMITMENT;
    uint256 private immutable _NUM_BASE;
    uint256 private immutable _NUM_BACKGROUNDS;
    bytes32 private immutable _ASSET_ROOT;
    bytes32 private immutable _RENDER_SPEC_HASH;
    bytes32 private immutable _ANIMATION_TEMPLATE_HASH;
    bytes32 private immutable _PROFILE_ROOT;
    IZeroStaticRenderer private immutable _RENDERER;
    bytes32 private immutable _RENDERER_COMMITMENT;
    Onchain0mRendererGuard private immutable _RENDERER_GUARD;
    // slither-disable-end naming-convention

    /// @dev THE one custom per-token storage word. No second mapping, no supply counter, no
    ///      stored hash or commitment slot.
    mapping(uint256 => uint256) private _tokenWord;

    /// @dev New openings are paused while `block.number <= _pausedUntilBlock`; zero means unpaused.
    ///      Deploys paused (see MAX_PAUSE_BLOCKS for the auto-expiry rationale).
    uint64 private _pausedUntilBlock;

    /// @dev A new pause is refused while `block.number <= _pauseCooldownUntilBlock`, guaranteeing
    ///      MIN_OPEN_BLOCKS complete produced blocks after expiry or explicit unpause. Packs with
    ///      `_pausedUntilBlock` and `_guardianRenounced` in one storage slot.
    uint64 private _pauseCooldownUntilBlock;

    /// @dev One-way switch disabling the pause authority. `GUARDIAN` stays immutable and readable.
    bool private _guardianRenounced;

    constructor(
        IOnchain9mSource sourceOnchain9m_,
        uint256 sourceIdMax_,
        IZeroStaticRenderer renderer_,
        Onchain0mRendererGuard rendererGuard_,
        CollectionProvenance memory provenance_,
        address guardian_,
        bytes32 expectedHistoryCodehash_
    ) ERC721("0m//TX", "0m") {
        if (guardian_ == address(0)) revert ZeroAddress();
        if (
            expectedHistoryCodehash_ == bytes32(0) || HISTORY_CONTRACT.code.length == 0
                || HISTORY_CONTRACT.codehash != expectedHistoryCodehash_
        ) revert HistoryContractMismatch();

        Onchain9mSourceBinding.Binding memory sourceBinding =
            Onchain9mSourceBinding.load(sourceOnchain9m_);
        IPaletteAssets assets_ = sourceBinding.assets;
        if (!assets_.isSealed()) revert AssetsNotSealed();
        uint256 bases = assets_.numBase();
        uint256 backgrounds = assets_.numBackgrounds();
        if (bases == 0 || backgrounds == 0) revert AssetsEmpty();
        if (
            sourceIdMax_ == 0 || sourceIdMax_ > MAX_SOURCE_ID_DOMAIN
                || sourceIdMax_ != sourceOnchain9m_.maxSupply()
        ) revert SourceDomainMismatch();
        if (
            provenance_.assetRoot == bytes32(0) || provenance_.renderSpecHash == bytes32(0)
                || provenance_.animationTemplateHash == bytes32(0)
                || provenance_.profileRoot == bytes32(0)
        ) revert MissingProvenance();

        bytes32 sourceCommitment =
            Onchain9mSourceBinding.commitment(sourceBinding, provenance_.assetRoot);
        NINE_M = sourceOnchain9m_;
        SOURCE_ID_MAX = sourceIdMax_;
        GUARDIAN = guardian_;
        HISTORY_CODEHASH = expectedHistoryCodehash_;
        ASSETS = assets_;
        _SOURCE_CHAIN_ID = sourceBinding.chainId;
        _SOURCE_BINDING_HASH = sourceBinding.bindingHash;
        _SOURCE_9M_COMMITMENT = sourceCommitment;
        _NUM_BASE = bases;
        _NUM_BACKGROUNDS = backgrounds;
        _ASSET_ROOT = provenance_.assetRoot;
        _RENDER_SPEC_HASH = provenance_.renderSpecHash;
        _ANIMATION_TEMPLATE_HASH = provenance_.animationTemplateHash;
        _PROFILE_ROOT = provenance_.profileRoot;

        uint8 version = renderer_.renderVersion();
        if (version == 0) revert BadRenderVersion();
        COLLECTION_RENDER_VERSION = version;
        _RENDERER_GUARD = rendererGuard_;
        bytes32 expectedGuardConfig = Onchain9mSourceBinding.configHash(
            sourceCommitment,
            provenance_.renderSpecHash,
            provenance_.animationTemplateHash,
            provenance_.profileRoot,
            version
        );
        if (
            address(rendererGuard_).code.length == 0
                || rendererGuard_.source9mCommitment() != sourceCommitment
                || rendererGuard_.CONFIG_HASH() != expectedGuardConfig
        ) revert RendererGuardMismatch();
        _RENDERER = renderer_;
        // Permanently binds the renderer graph selected at construction. Deployment tooling verifies
        // representative renderer outputs with direct `eth_call` probes before deploying the collection.
        _RENDERER_COMMITMENT = rendererGuard_.rendererCommitment(renderer_);

        // Deploys paused with an auto-expiring safety window (MAX_PAUSE_BLOCKS): issuance opens either
        // when the guardian unpauses after launch verification, or automatically after the window. The
        // following MIN_OPEN_BLOCKS are an enforced cooldown, so neither a lost nor a hostile key can
        // permanently brick the sole issuance path.
        _pausedUntilBlock = uint64(block.number) + MAX_PAUSE_BLOCKS;
        _pauseCooldownUntilBlock = _pausedUntilBlock + MIN_OPEN_BLOCKS;
        emit NewTransmissionsPaused(guardian_, _pausedUntilBlock);
    }

    // ── authenticated ingress ───────────────────────────────────────────────────────────────────

    /// @notice The single primary issuance path, called by the pinned 9m contract during a
    ///         holder-initiated `safeTransferFrom(holder, Onchain0m, tokenId)`.
    /// @dev Ordering is `checks → packed word → dead-address forward → safe mint → events`. Any
    ///      failure reverts the whole transaction and returns the 9m to `from`.
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
        external
        nonReentrant
        returns (bytes4)
    {
        if (_isPaused()) revert NewTransmissionsArePaused();
        if (msg.sender != address(NINE_M)) revert UntrustedCaller();
        // Owner's own safe transfer with empty receiver data only: an approved operator cannot
        // direct someone else's carrier. The four-argument overload with empty bytes is accepted.
        if (operator != from || from == address(0) || data.length != 0) {
            revert UnsupportedIngress();
        }
        if (tokenId == 0 || tokenId > SOURCE_ID_MAX) revert SourceIdOutOfDomain();
        if (_tokenWord[tokenId] != 0 || _ownerOf(tokenId) != address(0)) {
            revert TransmissionAlreadyOpened();
        }
        if (NINE_M.ownerOf(tokenId) != address(this)) revert SourceNotHeld();
        if (address(NINE_M.assets()) != address(ASSETS)) revert SourceBindingChanged();

        SourceRead memory source = _readSource(tokenId);
        // The word stores only the future anchor. The sample window cannot be resolved until that
        // block is mined, after this whole transaction (including the holder callback) is final.
        _tokenWord[tokenId] = _openWord(source);

        NINE_M.transferFrom(address(this), BURN_ADDRESS, tokenId);
        if (NINE_M.ownerOf(tokenId) != BURN_ADDRESS) revert SourceForwardFailed();

        // Effect before interaction: append to the pending FIFO — the sole source of totalSupply() —
        // BEFORE _safeMint's receiver callback, so a contract holder reading totalSupply() /
        // lockQueueState() / readyToLock() mid-callback sees a consistent supply. The append cannot be
        // re-entered: every queue mutator is nonReentrant.
        _appendToLockQueue(tokenId);

        _safeMint(from, tokenId);

        // A contract holder's mint callback may interleave logs. Consumers identify this event by
        // emitter/topic/token, not by log adjacency.
        _emitOpened(tokenId, from, uint64(_tokenWord[tokenId] >> _ENTROPY_ANCHOR_SHIFT), source);
        emit MetadataUpdate(tokenId);

        // Never strict: a burn must not fail because someone else's reveal is not ready. Runs after the
        // mint because it only finalizes OTHER tokens' ready reveals, never the one just opened.
        _drainLockQueue(AUTO_LOCK_STEPS, AUTO_LOCK_GAS_FLOOR);

        return IERC721Receiver.onERC721Received.selector;
    }

    /// @dev Opening indices never change or get reused. Links preserve FIFO order when any token
    ///      is removed, while the next opening index remains the lifetime supply.
    function _appendToLockQueue(uint256 tokenId) private {
        uint256 queue = _lockQueue;
        uint16 head = uint16(queue);
        uint16 tail = uint16(queue >> 16);
        uint16 previousId = uint16(queue >> 32);
        // Every source id opens at most once, so at most SOURCE_ID_MAX entries are ever appended.
        // The fixed array is sized to the theoretical maximum and therefore cannot wrap/overwrite.
        _pendingLockQueue[tail] = uint16(tokenId);
        _pendingLockLinks[tokenId] = uint48(previousId) | (uint48(tail) << 32);
        if (previousId == 0) {
            head = tail;
        } else {
            _pendingLockLinks[previousId] |= uint48(tokenId) << 16;
        }
        ++tail;
        _lockQueue = uint256(head) | (uint256(tail) << 16) | (tokenId << 32);
    }

    /// @dev Called once per queued token, after a successful lock or removal of an expired head.
    ///      No scan or array shift is needed, even for an out-of-order batch reveal.
    function _removeFromLockQueue(uint256 tokenId) private {
        uint256 links = _pendingLockLinks[tokenId];
        uint16 previousId = uint16(links);
        uint16 nextId = uint16(links >> 16);
        uint16 queueIndex = uint16(links >> 32);
        uint256 queue = _lockQueue;
        uint16 head = uint16(queue);
        uint16 tail = uint16(queue >> 16);
        uint16 lastId = uint16(queue >> 32);
        if (previousId == 0) {
            head = nextId == 0 ? tail : uint16(_pendingLockLinks[nextId] >> 32);
        } else {
            _pendingLockLinks[previousId] = uint48(
                (uint256(_pendingLockLinks[previousId]) & ~(uint256(type(uint16).max) << 16))
                    | (uint256(nextId) << 16)
            );
        }
        if (nextId == 0) {
            lastId = previousId;
        } else {
            _pendingLockLinks[nextId] = uint48(
                (uint256(_pendingLockLinks[nextId]) & ~uint256(type(uint16).max)) | previousId
            );
        }
        delete _pendingLockQueue[queueIndex];
        delete _pendingLockLinks[tokenId];
        _lockQueue = uint256(head) | (uint256(tail) << 16) | (uint256(lastId) << 32);
    }

    /// @notice Advance the pending FIFO, finalizing ready heads and removing expired heads.
    /// @dev Permissionless and caller-funded. Successful locks remove their own entries.
    /// @param maxSteps Upper bound on queue entries inspected.
    /// @return processed How many queue entries were removed.
    function drainLockQueue(uint256 maxSteps) external nonReentrant returns (uint256 processed) {
        // Gas floor 0: the caller sets its own budget and no third party's burn is at risk.
        return _drainLockQueue(maxSteps, 0);
    }

    /// @dev Advances the FIFO over expired entries and finalizes any ready head.
    ///      Stops at the first head that is OPEN and not yet resolvable.
    /// @param gasFloor Gas that must remain to enter another step; 0 disables the check.
    function _drainLockQueue(uint256 maxSteps, uint256 gasFloor)
        private
        returns (uint256 processed)
    {
        for (uint256 i; i < maxSteps; ++i) {
            uint256 queue = _lockQueue;
            uint16 head = uint16(queue);
            if (head == uint16(queue >> 16)) break;
            // Never enter a step this transaction may not be able to finish.
            if (gasleft() < gasFloor) break;
            uint256 pendingId = _pendingLockQueue[head];
            uint256 word = _tokenWord[pendingId];
            uint64 anchorBlock = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
            if (block.number <= anchorBlock || block.number - anchorBlock <= HISTORY_WINDOW) {
                if (!_lock(pendingId, false)) break;
            } else {
                // Expiry does not change the token's OPEN state or entropy commitment.
                _removeFromLockQueue(pendingId);
                emit TransmissionExpired(pendingId, anchorBlock);
            }
            ++processed;
        }
    }

    // ── permissionless lock ─────────────────────────────────────────────────────────────────────

    /// @notice Finalize an OPEN transmission from its future anchor and sixteen-block sample window.
    /// @dev Permissionless, one-time, owner-independent, and available while paused. Accepts no
    ///      caller-supplied entropy.
    function lockTransmission(uint256 tokenId) external nonReentrant {
        _lock(tokenId, true);
    }

    /// @notice Lock several transmissions in one transaction, skipping any that are not ready.
    /// @dev Ids that are already locked, not yet at their target, or past the history window are
    ///      skipped rather than reverted.
    /// @return locked How many of the supplied ids were finalized by this call.
    function lockTransmissions(uint256[] calldata tokenIds)
        external
        nonReentrant
        returns (uint256 locked)
    {
        for (uint256 i; i < tokenIds.length; ++i) {
            if (_lock(tokenIds[i], false)) ++locked;
        }
    }

    /// @dev The shared body. `strict` reverts on a token that cannot be locked; the batch path
    ///      passes `false` so it can skip and continue.
    function _lock(uint256 tokenId, bool strict) private returns (bool) {
        uint256 word = _tokenWord[tokenId];
        TransmissionState state = _stateOf(word);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.LOCKED) {
            if (strict) revert AlreadyLocked();
            return false;
        }
        if (state != TransmissionState.OPEN) {
            if (strict) revert TransmissionNotOpen();
            return false;
        }

        // `_tryHistoryBlockHash` refuses an unrecognized history runtime per lookup; a pre-gate
        // here would make the blockhash fallback unreachable.
        uint64 entropyAnchorBlock_ = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        if (block.number <= entropyAnchorBlock_) {
            if (strict) revert EntropyAnchorNotReached();
            return false;
        }
        // The anchor is the oldest required hash, so expiry is measured from it rather than from
        // the later resolved sample window.
        if (block.number - entropyAnchorBlock_ > HISTORY_WINDOW) {
            if (strict) revert TargetExpired();
            return false;
        }

        (uint8 status, bytes32 anchorHash, uint64 firstSampleBlock) =
            _tryResolveSampleWindow(tokenId, word, entropyAnchorBlock_);
        if (status != 0) {
            if (strict) {
                // slither-disable-next-line incorrect-equality
                if (status == 1) revert HistoryLookupFailed();
                revert HistoryHashUnavailable();
            }
            return false;
        }

        // A block's hash becomes available only in the following block.
        if (block.number <= firstSampleBlock + ENTROPY_SAMPLE_COUNT - 1) {
            if (strict) revert TargetNotReached();
            return false;
        }

        // `_derive` fills every remaining field before it can be consumed.
        // slither-disable-next-line uninitialized-local
        LockDerivation memory d;
        d.entropyAnchorHash = anchorHash;
        d.sampleOffset = uint8(firstSampleBlock - entropyAnchorBlock_);
        (status, d) = _derive(tokenId, word, entropyAnchorBlock_, firstSampleBlock, d);
        if (status != 0) {
            if (strict) {
                // slither-disable-next-line incorrect-equality
                if (status == 1) revert HistoryLookupFailed();
                revert HistoryHashUnavailable();
            }
            return false;
        }

        word |= (uint256(d.seed) << _SEED_SHIFT) | (uint256(d.lockedAt) << _LOCKED_AT_SHIFT)
            | (uint256(d.profile & 3) << _PROFILE_SHIFT)
            | (uint256(d.profile >> 2) << _PROFILE_HIGH_SHIFT)
            | (uint256(d.sampleOffset) << _SAMPLE_OFFSET_SHIFT);
        // OPEN (01) -> LOCKED (10): clear then set, so no other bit of the word is disturbed.
        word = (word & ~(uint256(3) << _STATE_SHIFT))
            | (uint256(uint8(TransmissionState.LOCKED)) << _STATE_SHIFT);
        _tokenWord[tokenId] = word;
        _removeFromLockQueue(tokenId);

        _emitLocked(tokenId, entropyAnchorBlock_, firstSampleBlock, d);
        emit MetadataUpdate(tokenId);
        return true;
    }

    /// @dev Event emission lives in its own frame so the receiver/lock bodies stay inside the
    ///      non-viaIR stack limit under the release optimizer profile.
    function _emitOpened(
        uint256 tokenId,
        address from,
        uint64 entropyAnchorBlock_,
        SourceRead memory s
    ) private {
        emit TransmissionOpened(
            tokenId,
            from,
            entropyAnchorBlock_,
            s.baseIndex,
            s.bgIndex,
            s.streakDay,
            s.mintNumber,
            s.mintedAt,
            s.callsign,
            _snapshotHash(tokenId, s),
            PROTOCOL_VERSION
        );
    }

    function _emitLocked(
        uint256 tokenId,
        uint64 entropyAnchorBlock_,
        uint64 firstSampleBlock,
        LockDerivation memory d
    ) private {
        emit TransmissionLocked(
            tokenId,
            entropyAnchorBlock_,
            firstSampleBlock,
            d.entropyAnchorHash,
            d.entropySampleBits,
            d.entropyCommitment,
            d.seed,
            d.profile,
            d.lockedAt,
            COLLECTION_RENDER_VERSION,
            d.renderKey,
            d.transmissionKey
        );
    }

    // ── guardian ────────────────────────────────────────────────────────────────────────────────

    /// @notice Pause NEW receiver openings. Locking, reads, and ERC-721 transfers continue.
    function pause() external {
        _onlyGuardian();
        if (_isPaused()) revert NewTransmissionsArePaused();
        if (block.number <= uint256(_pauseCooldownUntilBlock)) {
            revert PauseCooldownActive(_pauseCooldownUntilBlock);
        }
        _pausedUntilBlock = uint64(block.number) + MAX_PAUSE_BLOCKS;
        _pauseCooldownUntilBlock = _pausedUntilBlock + MIN_OPEN_BLOCKS;
        emit NewTransmissionsPaused(msg.sender, _pausedUntilBlock);
    }

    /// @notice Resume NEW receiver openings and start the minimum forced-open window.
    function unpause() external {
        _onlyGuardian();
        if (!_isPaused()) revert NewTransmissionsNotPaused();
        _pausedUntilBlock = 0;
        _pauseCooldownUntilBlock = uint64(block.number) + MIN_OPEN_BLOCKS;
        emit NewTransmissionsUnpaused(msg.sender);
    }

    /// @notice Permanently destroy the pause authority.
    /// @dev One-way and guardian-only. Refused while paused so the final act leaves issuance open.
    ///      Locking, transfers, and views are unaffected.
    function renounceGuardian() external {
        _onlyGuardian();
        // Requiring an open state guarantees that renunciation happens with issuance live.
        if (_isPaused()) revert NewTransmissionsArePaused();
        _guardianRenounced = true;
        emit GuardianRenounced(msg.sender);
    }

    function newTransmissionsPaused() external view returns (bool) {
        return _isPaused();
    }

    /// @notice The block through which new openings are paused (0 after explicit unpause). The pause
    ///         auto-expires after this block even without guardian action.
    function pausedUntilBlock() external view returns (uint64) {
        return _pausedUntilBlock;
    }

    /// @notice The inclusive block through which another guardian pause is refused.
    function pauseCooldownUntilBlock() external view returns (uint64) {
        return _pauseCooldownUntilBlock;
    }

    /// @notice Whether the pause authority has been permanently destroyed.
    function guardianRenounced() external view returns (bool) {
        return _guardianRenounced;
    }

    function _onlyGuardian() private view {
        if (_guardianRenounced) revert GuardianAuthorityRenounced();
        if (msg.sender != GUARDIAN) revert NotGuardian();
    }

    /// @dev New openings are paused while the current block is within the pause window.
    function _isPaused() private view returns (bool) {
        return _pausedUntilBlock != 0 && block.number <= uint256(_pausedUntilBlock);
    }

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

    function transmissionStatus(uint256 nineMTokenId)
        external
        view
        returns (
            TransmissionState state,
            uint64 firstSampleBlock,
            uint64 finalSeed,
            uint40 lockedAt,
            uint8 finalProfile,
            bytes32 sourceSnapshotHash_,
            bytes32 renderKey_
        )
    {
        uint256 word = _tokenWord[nineMTokenId];
        state = _stateOf(word);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.NONE) return (state, 0, 0, 0, 0, bytes32(0), bytes32(0));
        (, firstSampleBlock,) = _sampleWindowStatus(nineMTokenId, word, state);
        finalSeed = uint64(word >> _SEED_SHIFT);
        lockedAt = uint40(word >> _LOCKED_AT_SHIFT);
        finalProfile = _profileOf(word);
        sourceSnapshotHash_ = _snapshotHash(nineMTokenId, _snapshotOf(nineMTokenId, word));
        // No art identity exists before LOCK, so no render key is exposed while OPEN.
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.LOCKED) {
            renderKey_ = renderKey(_artOf(word), NINE_M.tokenUsername(nineMTokenId));
        }
    }

    /// @notice The future block whose hash resolves this transmission's sample window.
    function entropyAnchorBlock(uint256 nineMTokenId) public view returns (uint64) {
        uint256 word = _tokenWord[nineMTokenId];
        // slither-disable-next-line incorrect-equality
        if (_stateOf(word) == TransmissionState.NONE) revert NonexistentToken();
        return uint64(word >> _ENTROPY_ANCHOR_SHIFT);
    }

    /// @notice Last block in which every hash needed to lock can still be read from EIP-2935.
    /// @dev The anchor is the oldest required hash and therefore expires before every sample.
    function lastLockBlock(uint256 nineMTokenId) public view returns (uint64) {
        return entropyAnchorBlock(nineMTokenId) + HISTORY_WINDOW;
    }

    /// @notice Whether an OPEN transmission's reveal window has fully lapsed, so it can never lock.
    /// @dev Distinguishes a permanently-expired OPEN transmission from a freshly-opened one — a
    ///      distinction `transmissionStatus` alone cannot make, since both read state OPEN with
    ///      firstSampleBlock 0 before the anchor is mined. Returns false for NONE, LOCKED, and
    ///      OPEN-still-within-window.
    function transmissionExpired(uint256 nineMTokenId) external view returns (bool) {
        uint256 word = _tokenWord[nineMTokenId];
        // slither-disable-next-line incorrect-equality
        if (_stateOf(word) != TransmissionState.OPEN) return false;
        uint64 anchorBlock = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        return block.number > anchorBlock && block.number - anchorBlock > HISTORY_WINDOW;
    }

    /// @notice The exact resolved block range whose hashes decide this transmission's art.
    /// @dev Both ends inclusive. Reverts `EntropyAnchorNotReached` before the anchor is mined; use
    ///      `sampleWindowStatus` for a non-reverting probe.
    function sampleWindow(uint256 nineMTokenId)
        public
        view
        returns (uint64 firstSampleBlock, uint64 finalSampleBlock)
    {
        uint256 word = _tokenWord[nineMTokenId];
        TransmissionState state = _stateOf(word);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.NONE) revert NonexistentToken();
        uint64 anchorBlock = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.LOCKED) {
            firstSampleBlock =
                anchorBlock + uint8((word >> _SAMPLE_OFFSET_SHIFT) & _SAMPLE_OFFSET_MASK);
            return (firstSampleBlock, firstSampleBlock + ENTROPY_SAMPLE_COUNT - 1);
        }
        if (block.number <= anchorBlock) revert EntropyAnchorNotReached();
        if (block.number - anchorBlock > HISTORY_WINDOW) revert TargetExpired();
        (uint8 status,, uint64 resolvedFirst) =
            _tryResolveSampleWindow(nineMTokenId, word, anchorBlock);
        // slither-disable-next-line incorrect-equality
        if (status == 1) revert HistoryLookupFailed();
        if (status != 0) revert HistoryHashUnavailable();
        firstSampleBlock = resolvedFirst;
        finalSampleBlock = firstSampleBlock + ENTROPY_SAMPLE_COUNT - 1;
    }

    /// @notice Non-reverting schedule view for OPEN/LOCKED UI and sweepers.
    /// @return entropyAnchorBlock_ The future anchor committed at OPEN.
    /// @return resolved Whether the anchor hash is available and the window is known.
    function sampleWindowStatus(uint256 nineMTokenId)
        external
        view
        returns (
            uint64 entropyAnchorBlock_,
            bool resolved,
            uint64 firstSampleBlock,
            uint64 finalSampleBlock
        )
    {
        uint256 word = _tokenWord[nineMTokenId];
        TransmissionState state = _stateOf(word);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.NONE) revert NonexistentToken();
        entropyAnchorBlock_ = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        (resolved, firstSampleBlock, finalSampleBlock) =
            _sampleWindowStatus(nineMTokenId, word, state);
    }

    function sourceSnapshot(uint256 nineMTokenId)
        public
        view
        returns (
            uint16 baseIndex,
            uint16 bgIndex,
            uint256 sourceStreakDay,
            uint256 sourceMintNumber,
            uint64 sourceMintedAt,
            bytes32 sourceCallsign
        )
    {
        uint256 word = _tokenWord[nineMTokenId];
        // slither-disable-next-line incorrect-equality
        if (_stateOf(word) == TransmissionState.NONE) revert NonexistentToken();
        SourceRead memory s = _snapshotOf(nineMTokenId, word);
        return (s.baseIndex, s.bgIndex, s.streakDay, s.mintNumber, s.mintedAt, s.callsign);
    }

    /// @notice The permanent commitment binding the exact source tuple this transmission consumed.
    function sourceSnapshotHash(uint256 nineMTokenId) public view returns (bytes32) {
        uint256 word = _tokenWord[nineMTokenId];
        // slither-disable-next-line incorrect-equality
        if (_stateOf(word) == TransmissionState.NONE) revert NonexistentToken();
        return _snapshotHash(nineMTokenId, _snapshotOf(nineMTokenId, word));
    }

    /// @notice The immutable art identity of a LOCKED transmission.
    function tokenArt(uint256 tokenId)
        external
        view
        returns (ArtParams memory art, bytes32 renderKey_)
    {
        uint256 word = _tokenWord[tokenId];
        // Only LOCKED transmissions have a finalized art identity.
        if (_stateOf(word) != TransmissionState.LOCKED) revert TransmissionNotLocked();
        art = _artOf(word);
        renderKey_ = renderKey(art, NINE_M.tokenUsername(tokenId));
    }

    /// @notice The deterministic seed used only for an existing token's OPEN logo art.
    /// @dev It is independent from future-block entropy and never becomes the LOCKED art seed.
    function openArtSeed(uint256 tokenId) public view returns (uint64) {
        uint256 word = _tokenWord[tokenId];
        // slither-disable-next-line incorrect-equality
        if (_stateOf(word) == TransmissionState.NONE) revert NonexistentToken();
        return uint64(
            uint256(
                keccak256(
                    abi.encode(
                        OPEN_ART_SEED_DOMAIN_V1,
                        block.chainid,
                        address(this),
                        tokenId,
                        uint16(word),
                        uint16(word >> _BG_SHIFT),
                        uint64(word >> _ENTROPY_ANCHOR_SHIFT),
                        uint8(word >> _RENDER_VERSION_SHIFT)
                    )
                )
            )
        );
    }

    /// @notice `keccak256(RENDER_KEY_DOMAIN_V1, baseIndex, bgIndex, seed, profile, renderVersion,
    ///         label)` — the immutable art identity hash.
    function renderKey(ArtParams memory art, bytes32 label) public pure returns (bytes32) {
        return keccak256(
            abi.encode(
                RENDER_KEY_DOMAIN_V1,
                art.baseIndex,
                art.bgIndex,
                art.seed,
                art.profile,
                art.renderVersion,
                label
            )
        );
    }

    /// @notice The raw packed word. Zero means the ID has never opened.
    function tokenDataWord(uint256 tokenId) external view returns (uint256) {
        return _tokenWord[tokenId];
    }

    /// @notice Pending FIFO head and lifetime opening count. Removed indices are never reused;
    ///         `tailIndex - headIndex` can include cleared slots and is not the pending count.
    function lockQueueState()
        external
        view
        returns (uint16 headIndex, uint16 tailIndex, uint16 headTokenId)
    {
        uint256 queue = _lockQueue;
        headIndex = uint16(queue);
        tailIndex = uint16(queue >> 16);
        if (headIndex < tailIndex) headTokenId = _pendingLockQueue[headIndex];
    }

    function pendingLockAt(uint16 queueIndex) external view returns (uint16) {
        return _pendingLockQueue[queueIndex];
    }

    /// @notice Number of 0m//TX tokens in existence.
    /// @dev Derived from the lifetime opening index, never decremented: the tail advances once per
    ///      successful opening and there is no burn path. Not `ERC721Enumerable` — `tokenByIndex`
    ///      and `tokenOfOwnerByIndex` are neither implemented nor advertised.
    function totalSupply() external view returns (uint256) {
        return uint16(_lockQueue >> 16);
    }

    /// @notice Whether `lockTransmission(tokenId)` would succeed in this block.
    /// @dev A full dry run of the lock preconditions, including the all-or-nothing sample sweep.
    function canLock(uint256 tokenId) public view returns (bool) {
        uint256 word = _tokenWord[tokenId];
        if (_stateOf(word) != TransmissionState.OPEN) return false;

        uint64 anchorBlock = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        if (block.number <= anchorBlock) return false;
        if (block.number - anchorBlock > HISTORY_WINDOW) return false;

        (uint8 status,, uint64 firstSampleBlock) =
            _tryResolveSampleWindow(tokenId, word, anchorBlock);
        if (status != 0) return false;
        if (block.number <= firstSampleBlock + ENTROPY_SAMPLE_COUNT - 1) return false;

        // Every sampled hash must be readable or the derivation fails as a whole.
        bytes32 snapshot = _snapshotHash(tokenId, _snapshotOf(tokenId, word));
        (status,) = _sampleBits(tokenId, snapshot, firstSampleBlock);
        // slither-disable-next-line incorrect-equality
        return status == 0;
    }

    /// @notice The queued token ids in `[from, from + count)` that would lock in this block.
    /// @dev Builds a `lockTransmissions` batch in one call. Removed slots read as id 0 and are
    ///      skipped.
    function readyToLock(uint16 from, uint16 count) external view returns (uint256[] memory ids) {
        uint16 tail = uint16(_lockQueue >> 16);
        if (from >= tail || count == 0) return new uint256[](0);
        uint256 end = uint256(from) + uint256(count);
        if (end > tail) end = tail;

        uint256[] memory buffer = new uint256[](end - from);
        // Zero-initialized by Solidity and used as the write index from the first iteration.
        // slither-disable-next-line uninitialized-local
        uint256 found;
        for (uint256 i = from; i < end; ++i) {
            uint256 pendingId = _pendingLockQueue[uint16(i)];
            if (pendingId != 0 && canLock(pendingId)) {
                buffer[found] = pendingId;
                ++found;
            }
        }
        ids = new uint256[](found);
        for (uint256 j; j < found; ++j) {
            ids[j] = buffer[j];
        }
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        uint256 word = _tokenWord[tokenId];
        TransmissionState state = _stateOf(word);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.NONE || _ownerOf(tokenId) == address(0)) {
            revert NonexistentToken();
        }
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.OPEN) return _openTokenUri(tokenId, word);

        SourceRead memory s = _snapshotOf(tokenId, word);
        return _RENDERER.tokenURI(
            tokenId,
            s.baseIndex,
            s.bgIndex,
            s.streakDay,
            s.mintNumber,
            s.mintedAt,
            s.callsign,
            uint64(word >> _SEED_SHIFT),
            _profileOf(word)
        );
    }

    /// @notice Collection-level metadata, rendered fully onchain.
    /// @dev Mirrors the shape 9m publishes from `PaletteRenderer.collectionURI`. The image is a
    ///      glitched composition from fixed coordinates — never a clean source image or a URL.
    function contractURI() external view returns (string memory) {
        string memory image = string.concat(
            "data:image/svg+xml;base64,",
            Base64.encode(
                bytes(
                    _RENDERER.svg(
                        COLLECTION_IMAGE_BASE_INDEX,
                        COLLECTION_IMAGE_BG_INDEX,
                        COLLECTION_IMAGE_SEED,
                        COLLECTION_IMAGE_PROFILE
                    )
                )
            )
        );
        string memory json = string.concat(
            "{\"name\":\"0m\",\"description\":\"A 9m is the carrier. The carrier does not return.",
            " The TRACE does. 0m is what came back. fully onchain. 1337 af.\",\"image\":\"",
            image,
            "\",\"featured_image\":\"",
            image,
            "\",\"external_link\":\"https://1337skulls.xyz/\"}"
        );
        return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
    }

    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC721, IERC165)
        returns (bool)
    {
        return interfaceId == bytes4(0x49064906) // ERC-4906 metadata update
            || interfaceId == type(IERC721Receiver).interfaceId
            || super.supportsInterface(interfaceId);
    }

    // ── composability root (bound byte-for-byte by ZeroGlitch32FacadeV1) ────────────────────────

    function renderer() external view returns (IZeroStaticRenderer) {
        return _RENDERER;
    }

    /// @dev Always true because the constructor binds the renderer immutably.
    function rendererFrozen() external pure returns (bool) {
        return true;
    }

    function rendererCommitment() external view returns (bytes32) {
        return _RENDERER_COMMITMENT;
    }

    function sourceChainId() external view returns (uint256) {
        return _SOURCE_CHAIN_ID;
    }

    // ── source and provenance bindings ──────────────────────────────────────────────────────────

    function assets() external view returns (IPaletteAssets) {
        return ASSETS;
    }

    function sourceOnchain9m() external view returns (IOnchain9mSource) {
        return NINE_M;
    }

    function sourceBindingHash() external view returns (bytes32) {
        return _SOURCE_BINDING_HASH;
    }

    function source9mCommitment() external view returns (bytes32) {
        return _SOURCE_9M_COMMITMENT;
    }

    function rendererGuard() external view returns (Onchain0mRendererGuard) {
        return _RENDERER_GUARD;
    }

    function collectionProvenance()
        external
        view
        returns (
            bytes32 assetRoot,
            bytes32 renderSpecHash,
            bytes32 animationTemplateHash,
            bytes32 profileRoot
        )
    {
        return (_ASSET_ROOT, _RENDER_SPEC_HASH, _ANIMATION_TEMPLATE_HASH, _PROFILE_ROOT);
    }

    // ── internals ───────────────────────────────────────────────────────────────────────────────

    /// @dev Reads and range-checks the live source tuple at opening time.
    function _readSource(uint256 tokenId) private view returns (SourceRead memory s) {
        uint256 picks = NINE_M.tokenPicks(tokenId);
        // 9m packs picks as `baseIndex | bgIndex << 16`; anything above bit 31 means the live ABI
        // is not the one this collection was bound to.
        if (picks >> 32 != 0) revert SourcePicksMalformed();
        uint256 baseIndex = picks & type(uint16).max;
        uint256 bgIndex = (picks >> 16) & type(uint16).max;
        if (baseIndex >= _NUM_BASE || bgIndex >= _NUM_BACKGROUNDS) revert SourcePicksMalformed();

        uint256 meta = NINE_M.tokenMeta(tokenId);
        if (meta >> 96 != 0) revert SourcePicksMalformed();
        s.baseIndex = uint16(baseIndex);
        s.bgIndex = uint16(bgIndex);
        s.streakDay = meta & type(uint16).max;
        s.mintNumber = (meta >> 16) & type(uint16).max;
        s.mintedAt = uint64(meta >> 32);
        s.callsign = NINE_M.tokenUsername(tokenId);
    }

    /// @dev Rebuilds the source tuple for an existing transmission: base/background come from the
    ///      immutable packed snapshot, the stable provenance fields from the pinned 9m contract.
    function _snapshotOf(uint256 tokenId, uint256 word) private view returns (SourceRead memory s) {
        uint256 meta = NINE_M.tokenMeta(tokenId);
        s.baseIndex = uint16(word);
        s.bgIndex = uint16(word >> _BG_SHIFT);
        s.streakDay = meta & type(uint16).max;
        s.mintNumber = (meta >> 16) & type(uint16).max;
        s.mintedAt = uint64(meta >> 32);
        s.callsign = NINE_M.tokenUsername(tokenId);
    }

    function _snapshotHash(uint256 tokenId, SourceRead memory s) private view returns (bytes32) {
        return keccak256(
            abi.encode(
                SOURCE_SNAPSHOT_DOMAIN_V1,
                _SOURCE_CHAIN_ID,
                address(NINE_M),
                tokenId,
                s.baseIndex,
                s.bgIndex,
                s.streakDay,
                s.mintNumber,
                s.mintedAt,
                s.callsign,
                address(ASSETS),
                _ASSET_ROOT
            )
        );
    }

    /// @dev The complete LOCK derivation from the packed word, stable 9m getters, immutable
    ///      bindings, and the fixed sample window.
    /// @return status 0 = derived, 1 = history call failed or malformed, 2 = block no longer
    ///         served. Non-reverting so a burn's pay-it-forward reveal cannot fail the burn.
    function _derive(
        uint256 tokenId,
        uint256 word,
        uint64 entropyAnchorBlock_,
        uint64 firstSampleBlock,
        LockDerivation memory d
    ) private view returns (uint8 status, LockDerivation memory) {
        SourceRead memory s = _snapshotOf(tokenId, word);
        bytes32 snapshot = _snapshotHash(tokenId, s);
        (status, d.entropySampleBits) = _sampleBits(tokenId, snapshot, firstSampleBlock);
        if (status != 0) return (status, d);
        // Solidity zero-initializes memory structs; every field is assigned before encoding.
        // slither-disable-next-line uninitialized-local
        EntropyPreimage memory entropyInput;
        entropyInput.chainId = block.chainid;
        entropyInput.collection = address(this);
        entropyInput.source = address(NINE_M);
        entropyInput.tokenId = tokenId;
        entropyInput.snapshot = snapshot;
        entropyInput.entropyAnchorBlock = entropyAnchorBlock_;
        entropyInput.firstSampleBlock = firstSampleBlock;
        entropyInput.entropySampleBits = d.entropySampleBits;
        d.entropyCommitment = keccak256(abi.encode(TRANSMISSION_ENTROPY_DOMAIN_V1, entropyInput));
        d.seed = uint64(uint256(keccak256(abi.encode(d.entropyCommitment, ART_SEED_DOMAIN_V1))));
        // keccak256 is uniform over 2^256, so the mod-10_000 bias is below 2^-243. Rejection
        // sampling is not used, keeping the roll a single function of the entropy commitment.
        // slither-disable-next-line weak-prng
        uint256 roll = uint256(keccak256(abi.encode(d.entropyCommitment, GLITCH_PROFILE_DOMAIN_V1)))
            % _ROLL_MODULUS;
        d.profile = roll < _ROLL_1337_MAX
            ? PROFILE_1337
            : roll < _ROLL_5KU11_MAX
                ? PROFILE_5KU11
                : roll < _ROLL_MEGA_MAX
                    ? PROFILE_MEGA
                    : roll < _ROLL_HEAVY_MAX ? PROFILE_HEAVY : PROFILE_LIGHT;
        d.lockedAt = uint40(block.timestamp);
        d.renderKey = renderKey(
            ArtParams({
                baseIndex: s.baseIndex,
                bgIndex: s.bgIndex,
                seed: d.seed,
                profile: d.profile,
                renderVersion: COLLECTION_RENDER_VERSION
            }),
            s.callsign
        );
        d.transmissionKey = _transmissionKey(snapshot, entropyAnchorBlock_, firstSampleBlock, d);
        return (0, d);
    }

    /// @dev One salted bit per sampled block, LSB = the first block of the window. The bit comes
    ///      from a keccak over the domain tag, the block hash, the snapshot, the token id, and the
    ///      sample index — not the raw hash — so grinding one header controls one bit of one
    ///      transmission.
    function _sampleBits(uint256 tokenId, bytes32 snapshot, uint64 firstSampleBlock)
        private
        view
        returns (uint8 status, uint16 bits)
    {
        for (uint64 i; i < ENTROPY_SAMPLE_COUNT; ++i) {
            (uint8 s, bytes32 blockHash) = _tryHistoryBlockHash(firstSampleBlock + i);
            if (s != 0) return (s, 0);
            uint256 sample = uint256(
                keccak256(abi.encode(ENTROPY_SAMPLE_DOMAIN_V1, blockHash, snapshot, tokenId, i))
            );
            bits |= uint16((sample & 1) << i);
        }
        return (0, bits);
    }

    /// @dev Binds the complete conversion: source snapshot, burn address, the full EIP-2935
    ///      binding, the sample window and its extracted bits, the entropy commitment, the art
    ///      identity, the lock timestamp, and this collection's chain/address.
    function _transmissionKey(
        bytes32 snapshot,
        uint64 entropyAnchorBlock_,
        uint64 firstSampleBlock,
        LockDerivation memory d
    ) private view returns (bytes32) {
        // Solidity zero-initializes memory structs; every field is assigned before encoding.
        // slither-disable-next-line uninitialized-local
        TransmissionKeyPreimage memory input;
        input.snapshot = snapshot;
        input.burnAddress = BURN_ADDRESS;
        input.historyContract = HISTORY_CONTRACT;
        input.historyCodehash = HISTORY_CODEHASH;
        input.historyWindow = HISTORY_WINDOW;
        input.entropyDelayBinding = ENTROPY_DELAY_BINDING;
        input.entropyAnchorBlock = entropyAnchorBlock_;
        input.entropyAnchorHash = d.entropyAnchorHash;
        input.firstSampleBlock = firstSampleBlock;
        input.entropySampleBits = d.entropySampleBits;
        input.entropyCommitment = d.entropyCommitment;
        input.renderKey = d.renderKey;
        input.lockedAt = d.lockedAt;
        input.chainId = block.chainid;
        input.collection = address(this);
        return keccak256(abi.encode(TRANSMISSION_KEY_DOMAIN_V1, input));
    }

    /// @dev Packed head opening index, lifetime opening count, and last pending token id (16 bits
    ///      each). An empty list has head == lifetime count and last id == 0.
    uint256 private _lockQueue;
    uint16[MAX_SOURCE_ID_DOMAIN] private _pendingLockQueue;
    /// @dev Per-token previous id, next id, and opening index (16 bits each). Id 0 terminates a
    ///      link; real source ids are 1..SOURCE_ID_MAX. Five nodes share each storage slot.
    uint48[MAX_SOURCE_ID_DOMAIN + 1] private _pendingLockLinks;

    /// @dev The single fresh word an opening writes: picks, future entropy anchor, OPEN state,
    ///      and render version. The window offset remains unresolved until the anchor is mined.
    function _openWord(SourceRead memory source) private view returns (uint256) {
        uint64 entropyAnchorBlock_ = uint64(block.number) + ENTROPY_ANCHOR_DELAY;
        return uint256(source.baseIndex) | (uint256(source.bgIndex) << _BG_SHIFT)
            | (uint256(entropyAnchorBlock_) << _ENTROPY_ANCHOR_SHIFT)
            | (uint256(uint8(TransmissionState.OPEN)) << _STATE_SHIFT)
            | (uint256(COLLECTION_RENDER_VERSION) << _RENDER_VERSION_SHIFT);
    }

    /// @dev Selects the sample-window start from the future anchor hash, token id, and source
    ///      snapshot. There are four possible starts; same-block transmissions may share one.
    function _entropyOffset(
        uint256 tokenId,
        bytes32 snapshot,
        uint64 entropyAnchorBlock_,
        bytes32 entropyAnchorHash_
    ) private view returns (uint64) {
        uint256 mixed = uint256(
            keccak256(
                abi.encode(
                    TARGET_OFFSET_DOMAIN_V1,
                    entropyAnchorHash_,
                    block.chainid,
                    address(this),
                    tokenId,
                    snapshot,
                    entropyAnchorBlock_
                )
            )
        );
        // Domain-separated keccak over the unknown future anchor hash, not a PRNG.
        // slither-disable-next-line weak-prng
        return MIN_ENTROPY_DELAY + uint64(mixed % ENTROPY_DELAY_SPREAD);
    }

    function _tryResolveSampleWindow(uint256 tokenId, uint256 word, uint64 entropyAnchorBlock_)
        private
        view
        returns (uint8 status, bytes32 entropyAnchorHash_, uint64 firstSampleBlock)
    {
        (status, entropyAnchorHash_) = _tryHistoryBlockHash(entropyAnchorBlock_);
        if (status != 0) return (status, bytes32(0), 0);
        bytes32 snapshot = _snapshotHash(tokenId, _snapshotOf(tokenId, word));
        firstSampleBlock = entropyAnchorBlock_
            + _entropyOffset(tokenId, snapshot, entropyAnchorBlock_, entropyAnchorHash_);
    }

    function _sampleWindowStatus(uint256 tokenId, uint256 word, TransmissionState state)
        private
        view
        returns (bool resolved, uint64 firstSampleBlock, uint64 finalSampleBlock)
    {
        uint64 anchorBlock = uint64(word >> _ENTROPY_ANCHOR_SHIFT);
        // slither-disable-next-line incorrect-equality
        if (state == TransmissionState.LOCKED) {
            firstSampleBlock =
                anchorBlock + uint8((word >> _SAMPLE_OFFSET_SHIFT) & _SAMPLE_OFFSET_MASK);
            return (true, firstSampleBlock, firstSampleBlock + ENTROPY_SAMPLE_COUNT - 1);
        }
        if (block.number <= anchorBlock || block.number - anchorBlock > HISTORY_WINDOW) {
            return (false, 0, 0);
        }
        (uint8 status,, uint64 first) = _tryResolveSampleWindow(tokenId, word, anchorBlock);
        if (status != 0) return (false, 0, 0);
        return (true, first, first + ENTROPY_SAMPLE_COUNT - 1);
    }

    /// @dev Non-reverting history read: 32-byte big-endian block number in, exactly 32 bytes out.
    ///      No caller may supply a hash.
    /// @return status 0 = ok, 1 = call failed or malformed, 2 = block no longer served.
    function _tryHistoryBlockHash(uint64 blockNumber)
        private
        view
        returns (uint8 status, bytes32 result)
    {
        // Recent hashes are already available through the EVM. Both routes return the same
        // canonical Ethereum header hash; this avoids 17 cold history SLOADs on a prompt lock.
        // The opcode itself returns zero outside the last 256 blocks (including current/future
        // blocks). Check each hash separately: a window may straddle that boundary.
        bytes32 nativeHash = blockhash(uint256(blockNumber));
        // slither-disable-next-line incorrect-equality
        if (nativeHash != bytes32(0)) return (0, nativeHash);

        // Older hashes (or an unavailable opcode answer) retain the full EIP-2935 window.
        // An unrecognized runtime is treated as no source, never as an answer.
        if (HISTORY_CONTRACT.codehash == HISTORY_CODEHASH) {
            // slither-disable-next-line low-level-calls
            (bool ok, bytes memory ret) =
                HISTORY_CONTRACT.staticcall(abi.encode(uint256(blockNumber)));
            if (!ok || ret.length != 32) {
                status = 1;
            } else {
                result = abi.decode(ret, (bytes32));
                // A zero value is never a usable canonical header hash. Production EIP-2935
                // reverts for an out-of-range lookup (caught above); mocks or an unexpected but
                // ABI-shaped response may still return zero, which fails closed here.
                // slither-disable-next-line incorrect-equality
                if (result != bytes32(0)) return (0, result);
                status = 2;
            }
        } else {
            status = 1;
        }

        return (status, bytes32(0));
    }

    function _artOf(uint256 word) private pure returns (ArtParams memory art) {
        art = ArtParams({
            baseIndex: uint16(word),
            bgIndex: uint16(word >> _BG_SHIFT),
            seed: uint64(word >> _SEED_SHIFT),
            profile: _profileOf(word),
            renderVersion: uint8(word >> _RENDER_VERSION_SHIFT)
        });
    }

    function _stateOf(uint256 word) private pure returns (TransmissionState) {
        return TransmissionState((word >> _STATE_SHIFT) & 3);
    }

    function _profileOf(uint256 word) private pure returns (uint8) {
        return uint8(((word >> _PROFILE_SHIFT) & 3) | (((word >> _PROFILE_HIGH_SHIFT) & 1) << 2));
    }

    /// @dev OPEN metadata carries a domain-separated logo-art seed, never the future-block seed or
    ///      LVL. Every input is fixed at opening, so the URI changes only on the LOCK metadata event.
    function _openTokenUri(uint256 tokenId, uint256 word) private view returns (string memory) {
        return _RENDERER.openTokenURI(
            tokenId, uint64(word >> _ENTROPY_ANCHOR_SHIFT), openArtSeed(tokenId)
        );
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

/// @title ERC-721 Metadata Update Extension
interface IERC4906 is IERC165, IERC721 {
    /// @dev This event emits when the metadata of a token is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFT.
    event MetadataUpdate(uint256 _tokenId);

    /// @dev This event emits when the metadata of a range of tokens is changed.
    /// So that the third-party platforms such as NFT market could
    /// timely update the images and related attributes of the NFTs.
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
}

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/solady/src/utils/SafeCastLib.sol

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

/// @notice Safe integer casting library that reverts on overflow.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
/// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000).
library SafeCastLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to cast to the target type due to overflow.
    error Overflow();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*          UNSIGNED INTEGER SAFE CASTING OPERATIONS          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a uint8. Reverts on overflow.
    function toUint8(uint256 x) internal pure returns (uint8) {
        if (x >= 1 << 8) _revertOverflow();
        return uint8(x);
    }

    /// @dev Casts `x` to a uint16. Reverts on overflow.
    function toUint16(uint256 x) internal pure returns (uint16) {
        if (x >= 1 << 16) _revertOverflow();
        return uint16(x);
    }

    /// @dev Casts `x` to a uint24. Reverts on overflow.
    function toUint24(uint256 x) internal pure returns (uint24) {
        if (x >= 1 << 24) _revertOverflow();
        return uint24(x);
    }

    /// @dev Casts `x` to a uint32. Reverts on overflow.
    function toUint32(uint256 x) internal pure returns (uint32) {
        if (x >= 1 << 32) _revertOverflow();
        return uint32(x);
    }

    /// @dev Casts `x` to a uint40. Reverts on overflow.
    function toUint40(uint256 x) internal pure returns (uint40) {
        if (x >= 1 << 40) _revertOverflow();
        return uint40(x);
    }

    /// @dev Casts `x` to a uint48. Reverts on overflow.
    function toUint48(uint256 x) internal pure returns (uint48) {
        if (x >= 1 << 48) _revertOverflow();
        return uint48(x);
    }

    /// @dev Casts `x` to a uint56. Reverts on overflow.
    function toUint56(uint256 x) internal pure returns (uint56) {
        if (x >= 1 << 56) _revertOverflow();
        return uint56(x);
    }

    /// @dev Casts `x` to a uint64. Reverts on overflow.
    function toUint64(uint256 x) internal pure returns (uint64) {
        if (x >= 1 << 64) _revertOverflow();
        return uint64(x);
    }

    /// @dev Casts `x` to a uint72. Reverts on overflow.
    function toUint72(uint256 x) internal pure returns (uint72) {
        if (x >= 1 << 72) _revertOverflow();
        return uint72(x);
    }

    /// @dev Casts `x` to a uint80. Reverts on overflow.
    function toUint80(uint256 x) internal pure returns (uint80) {
        if (x >= 1 << 80) _revertOverflow();
        return uint80(x);
    }

    /// @dev Casts `x` to a uint88. Reverts on overflow.
    function toUint88(uint256 x) internal pure returns (uint88) {
        if (x >= 1 << 88) _revertOverflow();
        return uint88(x);
    }

    /// @dev Casts `x` to a uint96. Reverts on overflow.
    function toUint96(uint256 x) internal pure returns (uint96) {
        if (x >= 1 << 96) _revertOverflow();
        return uint96(x);
    }

    /// @dev Casts `x` to a uint104. Reverts on overflow.
    function toUint104(uint256 x) internal pure returns (uint104) {
        if (x >= 1 << 104) _revertOverflow();
        return uint104(x);
    }

    /// @dev Casts `x` to a uint112. Reverts on overflow.
    function toUint112(uint256 x) internal pure returns (uint112) {
        if (x >= 1 << 112) _revertOverflow();
        return uint112(x);
    }

    /// @dev Casts `x` to a uint120. Reverts on overflow.
    function toUint120(uint256 x) internal pure returns (uint120) {
        if (x >= 1 << 120) _revertOverflow();
        return uint120(x);
    }

    /// @dev Casts `x` to a uint128. Reverts on overflow.
    function toUint128(uint256 x) internal pure returns (uint128) {
        if (x >= 1 << 128) _revertOverflow();
        return uint128(x);
    }

    /// @dev Casts `x` to a uint136. Reverts on overflow.
    function toUint136(uint256 x) internal pure returns (uint136) {
        if (x >= 1 << 136) _revertOverflow();
        return uint136(x);
    }

    /// @dev Casts `x` to a uint144. Reverts on overflow.
    function toUint144(uint256 x) internal pure returns (uint144) {
        if (x >= 1 << 144) _revertOverflow();
        return uint144(x);
    }

    /// @dev Casts `x` to a uint152. Reverts on overflow.
    function toUint152(uint256 x) internal pure returns (uint152) {
        if (x >= 1 << 152) _revertOverflow();
        return uint152(x);
    }

    /// @dev Casts `x` to a uint160. Reverts on overflow.
    function toUint160(uint256 x) internal pure returns (uint160) {
        if (x >= 1 << 160) _revertOverflow();
        return uint160(x);
    }

    /// @dev Casts `x` to a uint168. Reverts on overflow.
    function toUint168(uint256 x) internal pure returns (uint168) {
        if (x >= 1 << 168) _revertOverflow();
        return uint168(x);
    }

    /// @dev Casts `x` to a uint176. Reverts on overflow.
    function toUint176(uint256 x) internal pure returns (uint176) {
        if (x >= 1 << 176) _revertOverflow();
        return uint176(x);
    }

    /// @dev Casts `x` to a uint184. Reverts on overflow.
    function toUint184(uint256 x) internal pure returns (uint184) {
        if (x >= 1 << 184) _revertOverflow();
        return uint184(x);
    }

    /// @dev Casts `x` to a uint192. Reverts on overflow.
    function toUint192(uint256 x) internal pure returns (uint192) {
        if (x >= 1 << 192) _revertOverflow();
        return uint192(x);
    }

    /// @dev Casts `x` to a uint200. Reverts on overflow.
    function toUint200(uint256 x) internal pure returns (uint200) {
        if (x >= 1 << 200) _revertOverflow();
        return uint200(x);
    }

    /// @dev Casts `x` to a uint208. Reverts on overflow.
    function toUint208(uint256 x) internal pure returns (uint208) {
        if (x >= 1 << 208) _revertOverflow();
        return uint208(x);
    }

    /// @dev Casts `x` to a uint216. Reverts on overflow.
    function toUint216(uint256 x) internal pure returns (uint216) {
        if (x >= 1 << 216) _revertOverflow();
        return uint216(x);
    }

    /// @dev Casts `x` to a uint224. Reverts on overflow.
    function toUint224(uint256 x) internal pure returns (uint224) {
        if (x >= 1 << 224) _revertOverflow();
        return uint224(x);
    }

    /// @dev Casts `x` to a uint232. Reverts on overflow.
    function toUint232(uint256 x) internal pure returns (uint232) {
        if (x >= 1 << 232) _revertOverflow();
        return uint232(x);
    }

    /// @dev Casts `x` to a uint240. Reverts on overflow.
    function toUint240(uint256 x) internal pure returns (uint240) {
        if (x >= 1 << 240) _revertOverflow();
        return uint240(x);
    }

    /// @dev Casts `x` to a uint248. Reverts on overflow.
    function toUint248(uint256 x) internal pure returns (uint248) {
        if (x >= 1 << 248) _revertOverflow();
        return uint248(x);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*           SIGNED INTEGER SAFE CASTING OPERATIONS           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a int8. Reverts on overflow.
    function toInt8(int256 x) internal pure returns (int8) {
        unchecked {
            if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int16. Reverts on overflow.
    function toInt16(int256 x) internal pure returns (int16) {
        unchecked {
            if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int24. Reverts on overflow.
    function toInt24(int256 x) internal pure returns (int24) {
        unchecked {
            if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int32. Reverts on overflow.
    function toInt32(int256 x) internal pure returns (int32) {
        unchecked {
            if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int40. Reverts on overflow.
    function toInt40(int256 x) internal pure returns (int40) {
        unchecked {
            if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int48. Reverts on overflow.
    function toInt48(int256 x) internal pure returns (int48) {
        unchecked {
            if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int56. Reverts on overflow.
    function toInt56(int256 x) internal pure returns (int56) {
        unchecked {
            if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int64. Reverts on overflow.
    function toInt64(int256 x) internal pure returns (int64) {
        unchecked {
            if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int72. Reverts on overflow.
    function toInt72(int256 x) internal pure returns (int72) {
        unchecked {
            if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int80. Reverts on overflow.
    function toInt80(int256 x) internal pure returns (int80) {
        unchecked {
            if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int88. Reverts on overflow.
    function toInt88(int256 x) internal pure returns (int88) {
        unchecked {
            if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int96. Reverts on overflow.
    function toInt96(int256 x) internal pure returns (int96) {
        unchecked {
            if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int104. Reverts on overflow.
    function toInt104(int256 x) internal pure returns (int104) {
        unchecked {
            if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int112. Reverts on overflow.
    function toInt112(int256 x) internal pure returns (int112) {
        unchecked {
            if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int120. Reverts on overflow.
    function toInt120(int256 x) internal pure returns (int120) {
        unchecked {
            if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int128. Reverts on overflow.
    function toInt128(int256 x) internal pure returns (int128) {
        unchecked {
            if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int136. Reverts on overflow.
    function toInt136(int256 x) internal pure returns (int136) {
        unchecked {
            if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int144. Reverts on overflow.
    function toInt144(int256 x) internal pure returns (int144) {
        unchecked {
            if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int152. Reverts on overflow.
    function toInt152(int256 x) internal pure returns (int152) {
        unchecked {
            if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int160. Reverts on overflow.
    function toInt160(int256 x) internal pure returns (int160) {
        unchecked {
            if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int168. Reverts on overflow.
    function toInt168(int256 x) internal pure returns (int168) {
        unchecked {
            if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int176. Reverts on overflow.
    function toInt176(int256 x) internal pure returns (int176) {
        unchecked {
            if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int184. Reverts on overflow.
    function toInt184(int256 x) internal pure returns (int184) {
        unchecked {
            if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int192. Reverts on overflow.
    function toInt192(int256 x) internal pure returns (int192) {
        unchecked {
            if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int200. Reverts on overflow.
    function toInt200(int256 x) internal pure returns (int200) {
        unchecked {
            if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int208. Reverts on overflow.
    function toInt208(int256 x) internal pure returns (int208) {
        unchecked {
            if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int216. Reverts on overflow.
    function toInt216(int256 x) internal pure returns (int216) {
        unchecked {
            if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int224. Reverts on overflow.
    function toInt224(int256 x) internal pure returns (int224) {
        unchecked {
            if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int232. Reverts on overflow.
    function toInt232(int256 x) internal pure returns (int232) {
        unchecked {
            if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int240. Reverts on overflow.
    function toInt240(int256 x) internal pure returns (int240) {
        unchecked {
            if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x);
            _revertOverflow();
        }
    }

    /// @dev Casts `x` to a int248. Reverts on overflow.
    function toInt248(int256 x) internal pure returns (int248) {
        unchecked {
            if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x);
            _revertOverflow();
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*               OTHER SAFE CASTING OPERATIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Casts `x` to a int8. Reverts on overflow.
    function toInt8(uint256 x) internal pure returns (int8) {
        if (x >= 1 << 7) _revertOverflow();
        return int8(int256(x));
    }

    /// @dev Casts `x` to a int16. Reverts on overflow.
    function toInt16(uint256 x) internal pure returns (int16) {
        if (x >= 1 << 15) _revertOverflow();
        return int16(int256(x));
    }

    /// @dev Casts `x` to a int24. Reverts on overflow.
    function toInt24(uint256 x) internal pure returns (int24) {
        if (x >= 1 << 23) _revertOverflow();
        return int24(int256(x));
    }

    /// @dev Casts `x` to a int32. Reverts on overflow.
    function toInt32(uint256 x) internal pure returns (int32) {
        if (x >= 1 << 31) _revertOverflow();
        return int32(int256(x));
    }

    /// @dev Casts `x` to a int40. Reverts on overflow.
    function toInt40(uint256 x) internal pure returns (int40) {
        if (x >= 1 << 39) _revertOverflow();
        return int40(int256(x));
    }

    /// @dev Casts `x` to a int48. Reverts on overflow.
    function toInt48(uint256 x) internal pure returns (int48) {
        if (x >= 1 << 47) _revertOverflow();
        return int48(int256(x));
    }

    /// @dev Casts `x` to a int56. Reverts on overflow.
    function toInt56(uint256 x) internal pure returns (int56) {
        if (x >= 1 << 55) _revertOverflow();
        return int56(int256(x));
    }

    /// @dev Casts `x` to a int64. Reverts on overflow.
    function toInt64(uint256 x) internal pure returns (int64) {
        if (x >= 1 << 63) _revertOverflow();
        return int64(int256(x));
    }

    /// @dev Casts `x` to a int72. Reverts on overflow.
    function toInt72(uint256 x) internal pure returns (int72) {
        if (x >= 1 << 71) _revertOverflow();
        return int72(int256(x));
    }

    /// @dev Casts `x` to a int80. Reverts on overflow.
    function toInt80(uint256 x) internal pure returns (int80) {
        if (x >= 1 << 79) _revertOverflow();
        return int80(int256(x));
    }

    /// @dev Casts `x` to a int88. Reverts on overflow.
    function toInt88(uint256 x) internal pure returns (int88) {
        if (x >= 1 << 87) _revertOverflow();
        return int88(int256(x));
    }

    /// @dev Casts `x` to a int96. Reverts on overflow.
    function toInt96(uint256 x) internal pure returns (int96) {
        if (x >= 1 << 95) _revertOverflow();
        return int96(int256(x));
    }

    /// @dev Casts `x` to a int104. Reverts on overflow.
    function toInt104(uint256 x) internal pure returns (int104) {
        if (x >= 1 << 103) _revertOverflow();
        return int104(int256(x));
    }

    /// @dev Casts `x` to a int112. Reverts on overflow.
    function toInt112(uint256 x) internal pure returns (int112) {
        if (x >= 1 << 111) _revertOverflow();
        return int112(int256(x));
    }

    /// @dev Casts `x` to a int120. Reverts on overflow.
    function toInt120(uint256 x) internal pure returns (int120) {
        if (x >= 1 << 119) _revertOverflow();
        return int120(int256(x));
    }

    /// @dev Casts `x` to a int128. Reverts on overflow.
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) _revertOverflow();
        return int128(int256(x));
    }

    /// @dev Casts `x` to a int136. Reverts on overflow.
    function toInt136(uint256 x) internal pure returns (int136) {
        if (x >= 1 << 135) _revertOverflow();
        return int136(int256(x));
    }

    /// @dev Casts `x` to a int144. Reverts on overflow.
    function toInt144(uint256 x) internal pure returns (int144) {
        if (x >= 1 << 143) _revertOverflow();
        return int144(int256(x));
    }

    /// @dev Casts `x` to a int152. Reverts on overflow.
    function toInt152(uint256 x) internal pure returns (int152) {
        if (x >= 1 << 151) _revertOverflow();
        return int152(int256(x));
    }

    /// @dev Casts `x` to a int160. Reverts on overflow.
    function toInt160(uint256 x) internal pure returns (int160) {
        if (x >= 1 << 159) _revertOverflow();
        return int160(int256(x));
    }

    /// @dev Casts `x` to a int168. Reverts on overflow.
    function toInt168(uint256 x) internal pure returns (int168) {
        if (x >= 1 << 167) _revertOverflow();
        return int168(int256(x));
    }

    /// @dev Casts `x` to a int176. Reverts on overflow.
    function toInt176(uint256 x) internal pure returns (int176) {
        if (x >= 1 << 175) _revertOverflow();
        return int176(int256(x));
    }

    /// @dev Casts `x` to a int184. Reverts on overflow.
    function toInt184(uint256 x) internal pure returns (int184) {
        if (x >= 1 << 183) _revertOverflow();
        return int184(int256(x));
    }

    /// @dev Casts `x` to a int192. Reverts on overflow.
    function toInt192(uint256 x) internal pure returns (int192) {
        if (x >= 1 << 191) _revertOverflow();
        return int192(int256(x));
    }

    /// @dev Casts `x` to a int200. Reverts on overflow.
    function toInt200(uint256 x) internal pure returns (int200) {
        if (x >= 1 << 199) _revertOverflow();
        return int200(int256(x));
    }

    /// @dev Casts `x` to a int208. Reverts on overflow.
    function toInt208(uint256 x) internal pure returns (int208) {
        if (x >= 1 << 207) _revertOverflow();
        return int208(int256(x));
    }

    /// @dev Casts `x` to a int216. Reverts on overflow.
    function toInt216(uint256 x) internal pure returns (int216) {
        if (x >= 1 << 215) _revertOverflow();
        return int216(int256(x));
    }

    /// @dev Casts `x` to a int224. Reverts on overflow.
    function toInt224(uint256 x) internal pure returns (int224) {
        if (x >= 1 << 223) _revertOverflow();
        return int224(int256(x));
    }

    /// @dev Casts `x` to a int232. Reverts on overflow.
    function toInt232(uint256 x) internal pure returns (int232) {
        if (x >= 1 << 231) _revertOverflow();
        return int232(int256(x));
    }

    /// @dev Casts `x` to a int240. Reverts on overflow.
    function toInt240(uint256 x) internal pure returns (int240) {
        if (x >= 1 << 239) _revertOverflow();
        return int240(int256(x));
    }

    /// @dev Casts `x` to a int248. Reverts on overflow.
    function toInt248(uint256 x) internal pure returns (int248) {
        if (x >= 1 << 247) _revertOverflow();
        return int248(int256(x));
    }

    /// @dev Casts `x` to a int256. Reverts on overflow.
    function toInt256(uint256 x) internal pure returns (int256) {
        if (int256(x) >= 0) return int256(x);
        _revertOverflow();
    }

    /// @dev Casts `x` to a uint256. Reverts on overflow.
    function toUint256(int256 x) internal pure returns (uint256) {
        if (x >= 0) return uint256(x);
        _revertOverflow();
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function _revertOverflow() private pure {
        /// @solidity memory-safe-assembly
        assembly {
            // Store the function selector of `Overflow()`.
            mstore(0x00, 0x35278d12)
            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
    }
}

src/lib/AssetLib.sol

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

import { SafeCastLib } from "solady/utils/SafeCastLib.sol";

/// @title AssetLib
/// @notice Decoder for the shape-template/colorway storage model and home of the canonical
///         in-memory `Asset` view the renderer consumes. It decodes ONE shape record
///         (RLE2 or BITPACK → 1024 class IDs) plus ONE colorway record into a materialized
///         `Asset` — the logical asset the renderer reads directly.
///
/// @dev BYTE-EXACT RENDER: the materialized view's `pixels[p]` is the shape's class ID at p,
///      and `palette[classId]` is the colorway's RGB for that class — i.e. CLASS ID *IS* THE
///      PALETTE INDEX, exactly mirroring the TS `materializeColorway`. The renderer reads
///      `palette[uint8(pixels[p])]`. `protectedMask` is materialized as 0 (the renderer
///      recomputes structural-dark from RGB and never reads the stored mask on this path,
///      matching the TS materialization's all-false mask).
///
/// @dev Record byte layouts (big-endian) mirror the compiler's `serializeShape` /
///      `serializeColorway` (packages/compiler/src/asset-schema.ts) EXACTLY:
///
///        SHAPE record:
///          shapeId(2) kind(1) classCount(1,0⇒256) transparentClass(1) encoding(1)
///          payloadLen(2) payload(payloadLen)
///          RLE2 payload   : repeat [lenMinus1(1) classId(1)] until 1024 pixels.
///          BITPACK payload: 1024 row-major class IDs, bitsPerClass = max(1,ceilLog2(cc)),
///                           MSB-first within each byte.
///
///        COLORWAY record:
///          kind(1) colorwayId(2) shapeId(2) nameLen(1) name(N) paletteLen(1,0⇒256)
///          palette(3P)
///          bg add:    swapSourceLen(1) swapSrcClassIdx(Ssrc)
///          base add: transparentClass(1) swapTargetLen(1) swapTgtClassIdx(Stgt)
///                     swapForceLen(1) swapForceClassIdx(Sforce)
///                     anchorPick(1) faceDark(1) recolorFlags(1)
library AssetLib {
    uint256 internal constant PIXELS = 1024;

    /// @dev `anchorPick` sentinel: no same-shape-set source-color pick (auto).
    uint8 internal constant ANCHOR_PICK_NONE = 255;

    /// @dev In-memory decoded asset — the canonical materialized view both the renderer and the
    ///      NFT pick-validation consume. Produced by `decode(shape, colorway)`.
    struct Asset {
        uint8 kind; // 0=bg, 1=base
        uint16 paletteLen; // 1..256 (distinct-opaque pixel palette)
        int16 transparent; // palette index of the transparent entry, or -1 if none
        uint16 protectedMask; // bit i set => palette[i] is protected-dark
        uint8 anchorPick; // same-shape-set source-color pick, 255=none
        uint8 faceDark; // count of darkest target colors pinned dark, 0=none
        uint8 recolorFlags; // per-base tweak bitfield, 0=none
        string name; // ASCII [a-z0-9 ]
        uint24[] palette; // paletteLen entries, 24-bit RGB, luminance-sorted
        uint24[] swapSource; // source-swap palette (freq-ranked + luminance-sorted)
        uint24[] swapTarget; // target-swap palette (freq-ranked + luminance-sorted)
        uint24[] swapForce; // protected-dark colors forced to recolor as a swap target
        bytes pixels; // 1024 bytes: one 8-bit palette index per pixel
    }

    uint8 internal constant KIND_BG = 0;
    uint8 internal constant KIND_BASE = 1;
    uint8 internal constant ENCODING_RLE2 = 0;
    uint8 internal constant ENCODING_BITPACK = 1;
    /// @dev `transparentClass` sentinel meaning "no transparent class" (opaque shape).
    uint8 internal constant NO_TRANSPARENT_CLASS = 255;

    /// @dev Canonical base recolor-field bounds. Mirror the canonical TS `decode`: a sealed record
    ///      must carry only IN-RANGE recolor bytes, so a non-canonical record (which the renderer
    ///      would interpret unpredictably) is rejected at seal time. faceDark ≤ FACE_DARK_MAX;
    ///      recolorFlags ≤ RECOLOR_FLAGS_MAX (bits 0..6). anchorPick is intentionally unconstrained
    ///      (any byte 0..254 is a valid set-member pick, 255 = none). The former standalone
    ///      `recolorMode` byte was removed; MID_ANCHOR is now recolorFlags bit 1.
    uint8 internal constant FACE_DARK_MAX = 8;
    uint8 internal constant RECOLOR_FLAGS_MAX = 127;

    error BadKind(uint8 kind);
    error BadEncoding(uint8 encoding);
    error ShapeColorwayMismatch(uint16 shapeId, uint16 colorwayShapeId);
    /// @dev The colorway record's EMBEDDED colorwayId disagreed with the asset index entry's
    ///      colorwayId (doc P0 — render-pointer authentication). A repointed index entry that
    ///      lands on a different colorway record is rejected even before the storage-hash check.
    error ColorwayIdMismatch(uint16 entryColorwayId, uint16 recordColorwayId);
    error PixelCountMismatch(uint256 got);
    error ClassIdOutOfRange(uint256 classId, uint256 classCount);
    /// @dev A swap class index referenced a palette slot >= the colorway palette length
    ///      (doc seal rule "every swap class index < palette length"). HARD revert.
    error SwapClassIndexOutOfRange(uint256 classIndex, uint256 paletteLen);
    error TransparentMismatch(uint8 shapeTransparent, uint8 colorwayTransparent);
    /// @dev The shape record's EMBEDDED shapeId disagreed with its index position (doc P0 — a shape
    ///      index pointer must not be repointed to a different valid shape record).
    error ShapeIdMismatch(uint16 expectedShapeId, uint16 recordShapeId);
    /// @dev A shape/colorway record was NOT CANONICAL: it carried trailing bytes past the bytes the
    ///      decode actually consumes (a BITPACK payload longer than `ceil(1024*bits/8)`, an RLE2
    ///      payload with an odd trailing byte, or a colorway whose decoded fields end before its
    ///      record length). A sealed lib must contain only canonical records so the stored byte
    ///      stream the hash binds equals exactly what the decoder reads — no unauthenticated slack.
    error NonCanonicalRecord(uint256 consumed, uint256 recordLen);
    /// @dev A canonical base recolor field (faceDark=field 1 / recolorFlags=field 2) was out of its
    ///      valid range — see the `*_MAX` constants. Mirrors the canonical TS decoder's range checks.
    error RecolorFieldOutOfRange(uint8 field, uint8 value, uint8 max);
    /// @dev A shape record's EMBEDDED header field (classCount / transparentClass / encoding)
    ///      disagreed with the SHAPE INDEX entry's header for the same shapeId. The seal validates
    ///      colorways against the INDEX header while the renderer decodes from the RECORD header, so
    ///      a divergence between them could seal a library the renderer misreads (doc FIX 2).
    ///      `field`: 0=classCount, 1=transparentClass, 2=encoding.
    error ShapeHeaderMismatch(uint8 field, uint16 indexValue, uint16 recordValue);
    /// @dev The shape's `transparentClass` was neither the `255` no-transparent sentinel nor a REAL,
    ///      USED class: either it was `>= classCount` (a class id that can never appear, since every
    ///      pixel is `< classCount`) or it was `< classCount` but NO decoded pixel equals it. The
    ///      renderer treats `transparent >= 0` as a transparency/outline signal, so a shape that
    ///      advertises a transparent class no pixel can ever match is semantically invalid storage
    ///      the strict seal must reject (not merely internally self-consistent storage). `255` (opaque)
    ///      is always allowed. `used` is the offending value; `classCount` the shape's class count.
    error TransparentClassNotUsed(uint8 transparentClass, uint16 classCount);

    /// @notice Decode a shape record into its 1024 class IDs plus the shape header fields.
    /// @param shape The exact shape-record bytes (a `serializeShape` slice).
    /// @return kind 0=bg, 1=base.
    /// @return classCount distinct visible classes (1..256).
    /// @return transparentClass class ID of the transparent sentinel, or 255 for none.
    /// @return classIds 1024 row-major class IDs (each < classCount).
    function decodeShape(bytes memory shape)
        internal
        pure
        returns (uint8 kind, uint16 classCount, uint8 transparentClass, bytes memory classIds)
    {
        uint256 o;
        o += 2; // shapeId (validated by the caller against the colorway's shapeId)
        kind = uint8(shape[o++]);
        if (kind != KIND_BG && kind != KIND_BASE) revert BadKind(kind);
        // classCount: byte 0 ⇒ 256, else the byte (classCount is always ≥ 1).
        classCount = uint8(shape[o]) == 0 ? uint16(256) : uint16(uint8(shape[o]));
        o++;
        transparentClass = uint8(shape[o++]);
        uint8 encoding = uint8(shape[o++]);
        uint256 payloadLen = (uint256(uint8(shape[o])) << 8) | uint256(uint8(shape[o + 1]));
        o += 2;

        // CANONICAL record: header(8) + payloadLen must equal the record length exactly. This is a
        // pure ADDITION of a revert path for a NON-canonical record (trailing bytes the decode would
        // ignore) — every canonical record the compiler emits satisfies it, so the decoded class IDs
        // for any valid record are byte-for-byte unchanged.
        if (8 + payloadLen != shape.length) {
            revert NonCanonicalRecord(8 + payloadLen, shape.length);
        }

        if (encoding == ENCODING_RLE2) {
            classIds = _decodeRle2(shape, o, payloadLen);
        } else if (encoding == ENCODING_BITPACK) {
            classIds = _decodeBitpack(shape, o, classCount);
        } else {
            revert BadEncoding(encoding);
        }

        // Every class ID must be < classCount (doc seal rule).
        for (uint256 p; p < PIXELS; ++p) {
            uint256 c = uint8(classIds[p]);
            if (c >= classCount) revert ClassIdOutOfRange(c, classCount);
        }
    }

    /// @dev RLE2: repeat [lenMinus1, classId]; decoded run length = lenMinus1 + 1. Must
    ///      decode to EXACTLY 1024 pixels or revert.
    function _decodeRle2(bytes memory shape, uint256 start, uint256 payloadLen)
        private
        pure
        returns (bytes memory out)
    {
        out = new bytes(PIXELS);
        uint256 p;
        uint256 end = start + payloadLen;
        // Each run is two bytes [lenMinus1, classId]; stop when fewer than two remain
        // (k and k+1 must both be valid indices, i.e. k+2 <= end).
        for (uint256 k = start; k + 2 <= end; k += 2) {
            uint256 len = uint256(uint8(shape[k])) + 1;
            uint8 cls = uint8(shape[k + 1]);
            for (uint256 n; n < len; ++n) {
                if (p >= PIXELS) revert PixelCountMismatch(p + 1);
                out[p++] = bytes1(cls);
            }
        }
        if (p != PIXELS) revert PixelCountMismatch(p);
    }

    /// @dev BITPACK: 1024 row-major class IDs, `bitsPerClass(classCount)` bits each,
    ///      MSB-first within each byte (the compiler's explicit, tested bit order).
    function _decodeBitpack(bytes memory shape, uint256 start, uint16 classCount)
        private
        pure
        returns (bytes memory out)
    {
        out = new bytes(PIXELS);
        uint256 bits = _bitsPerClass(classCount);
        uint256 bitPos;
        for (uint256 p; p < PIXELS; ++p) {
            uint256 v;
            for (uint256 b; b < bits; ++b) {
                uint256 byteIdx = start + (bitPos >> 3);
                uint256 shift = 7 - (bitPos & 7);
                uint256 bit = (uint256(uint8(shape[byteIdx])) >> shift) & 1;
                v = (v << 1) | bit;
                ++bitPos;
            }
            out[p] = bytes1(SafeCastLib.toUint8(v));
        }
    }

    /// @dev bitsPerClass = max(1, ceilLog2(classCount)). Matches the TS `bitsPerClass`.
    function _bitsPerClass(uint16 classCount) private pure returns (uint256 bits) {
        if (classCount <= 1) return 1;
        bits = 0;
        uint256 n = uint256(classCount) - 1; // ceilLog2: smallest b with 2^b >= classCount
        while (n > 0) {
            n >>= 1;
            ++bits;
        }
        if (bits == 0) bits = 1;
    }

    /// @notice Seal-only fast shape validation: assert the shape record is well-formed WITHOUT
    ///         allocating/returning the 1024-byte class-id array. It runs the SAME checks
    ///         `decodeShape` enforces — valid kind, valid encoding, decodes to EXACTLY 1024 pixels,
    ///         and every class id < classCount — but FUSES the decode and the class-id range check
    ///         into a single pass and writes nothing to memory, roughly halving the per-shape seal
    ///         cost. It is intentionally SEPARATE from `decodeShape` so the parity-critical decode
    ///         the renderer/materializer depends on is left byte-for-byte unchanged.
    /// @param shape exact shape-record bytes.
    /// @param expectedShapeId the shape's index position; the record's EMBEDDED shapeId must equal it
    ///        (doc P0 — a shape index pointer cannot be repointed to a different valid shape record).
    /// @param idxClassCount the SHAPE INDEX entry's classCount (1..256); must equal the record's.
    /// @param idxTransparentClass the SHAPE INDEX entry's transparentClass byte; must equal the
    ///        record's transparentClass byte.
    /// @param idxEncoding the SHAPE INDEX entry's encoding byte; must equal the record's encoding.
    /// @dev FIX 2: the index header (classCount/transparentClass/encoding) is bound to the RECORD
    ///      header here. The seal validates colorways against the INDEX header (cheap, no record
    ///      decode) while the renderer decodes from the RECORD header — so binding the two closes the
    ///      gap where a mismatched index could seal a library the renderer then misreads.
    function validateShape(
        bytes memory shape,
        uint16 expectedShapeId,
        uint16 idxClassCount,
        uint8 idxTransparentClass,
        uint8 idxEncoding
    ) internal pure {
        uint256 o;
        uint16 recShapeId = (uint16(uint8(shape[0])) << 8) | uint16(uint8(shape[1]));
        if (recShapeId != expectedShapeId) revert ShapeIdMismatch(expectedShapeId, recShapeId);
        o += 2; // shapeId (validated above)
        uint8 kind = uint8(shape[o++]);
        if (kind != KIND_BG && kind != KIND_BASE) revert BadKind(kind);
        uint16 classCount = uint8(shape[o]) == 0 ? uint16(256) : uint16(uint8(shape[o]));
        o++;
        uint8 transparentClass = uint8(shape[o++]); // validated vs colorway in validateColorway
        uint8 encoding = uint8(shape[o++]);
        uint256 payloadLen = (uint256(uint8(shape[o])) << 8) | uint256(uint8(shape[o + 1]));
        o += 2;

        // FIX 2: the record header MUST equal the shape-index entry header (which the asset seal
        // validates colorways against). Without this, a mismatched index could seal a lib whose
        // renderer — decoding from the RECORD header — paints different bytes than were validated.
        if (classCount != idxClassCount) revert ShapeHeaderMismatch(0, idxClassCount, classCount);
        if (transparentClass != idxTransparentClass) {
            revert ShapeHeaderMismatch(1, idxTransparentClass, transparentClass);
        }
        if (encoding != idxEncoding) revert ShapeHeaderMismatch(2, idxEncoding, encoding);

        // The shape record must be CANONICAL: the header + payload account for the WHOLE record,
        // with no trailing bytes the decoder ignores (the storage hash would otherwise bind slack
        // the renderer never reads). header(8) + payloadLen == record length.
        if (8 + payloadLen != shape.length) {
            revert NonCanonicalRecord(8 + payloadLen, shape.length);
        }

        // The shape's transparentClass must be either the `255` no-transparent sentinel OR a real,
        // USED class: `< classCount` AND matched by at least one decoded pixel. A class `>= classCount`
        // can never be a pixel value (every pixel is `< classCount`), and a `< classCount` class no
        // pixel uses is a transparency/outline signal the renderer could honor for a shape that has no
        // transparent pixel — semantically invalid storage the strict seal rejects. The fused
        // validators below report whether `transparentClass` was actually seen among the pixels.
        bool transparentSeen;
        if (encoding == ENCODING_RLE2) {
            transparentSeen = _validateRle2(shape, o, payloadLen, classCount, transparentClass);
        } else if (encoding == ENCODING_BITPACK) {
            transparentSeen = _validateBitpack(shape, o, payloadLen, classCount, transparentClass);
        } else {
            revert BadEncoding(encoding);
        }
        // 255 (opaque) is always allowed; otherwise the transparent class must be a USED class.
        if (transparentClass != NO_TRANSPARENT_CLASS && !transparentSeen) {
            revert TransparentClassNotUsed(transparentClass, classCount);
        }
    }

    /// @dev RLE2 fused validate: walk runs, assert exactly 1024 pixels and every classId<classCount,
    ///      allocating nothing. Mirrors `_decodeRle2` + the class-id loop, and additionally REJECTS a
    ///      non-canonical odd trailing payload byte (a lone byte after the last [len,classId] run that
    ///      `_decodeRle2`'s `k+2<=end` loop would silently ignore). Returns whether any run's class id
    ///      equals `transparentClass` (used by `validateShape` to prove the transparent class is real).
    function _validateRle2(
        bytes memory shape,
        uint256 start,
        uint256 payloadLen,
        uint16 classCount,
        uint8 transparentClass
    ) private pure returns (bool transparentSeen) {
        // An RLE2 payload is a whole number of 2-byte runs; an odd length is non-canonical.
        if (payloadLen & 1 != 0) revert NonCanonicalRecord(payloadLen, shape.length);
        uint256 p;
        uint256 end = start + payloadLen;
        for (uint256 k = start; k + 2 <= end; k += 2) {
            uint256 len = uint256(uint8(shape[k])) + 1;
            uint256 cls = uint8(shape[k + 1]);
            if (cls >= classCount) revert ClassIdOutOfRange(cls, classCount);
            // A run with len >= 1 means at least one pixel takes class `cls`.
            if (cls == transparentClass) transparentSeen = true;
            p += len;
            if (p > PIXELS) revert PixelCountMismatch(p);
        }
        if (p != PIXELS) revert PixelCountMismatch(p);
    }

    /// @dev BITPACK fused validate: extract each `bits`-wide class id and assert <classCount,
    ///      allocating nothing. Same MSB-first bit order as `_decodeBitpack`, but pulls each field
    ///      with a single shift+mask off a rolling 16-bit window (no per-BIT inner loop), which is
    ///      where the bitpack-base seal cost lives. `bits` is at most 8 (classCount<=256), so a
    ///      window holding the current byte plus the next always covers one field.
    function _validateBitpack(
        bytes memory shape,
        uint256 start,
        uint256 payloadLen,
        uint16 classCount,
        uint8 transparentClass
    ) private pure returns (bool transparentSeen) {
        uint256 bits = _bitsPerClass(classCount);
        // The canonical BITPACK payload is EXACTLY ceil(1024*bits/8) bytes — the byte-rounded packing
        // the compiler emits. A longer payload carries trailing bytes the decoder never reads (the
        // `payloadLen` field would otherwise be ignored — doc FIX 4); reject it as non-canonical.
        uint256 expected = (PIXELS * bits + 7) / 8;
        if (payloadLen != expected) revert NonCanonicalRecord(payloadLen, expected);
        uint256 mask = (uint256(1) << bits) - 1;
        uint256 len = shape.length;
        uint256 bitPos;
        for (uint256 px; px < PIXELS; ++px) {
            uint256 byteIdx = start + (bitPos >> 3);
            uint256 bitOff = bitPos & 7; // bits already consumed in shape[byteIdx]
            // 16-bit window: current byte high, next byte low. The field of width `bits` starts
            // `bitOff` bits into the high byte; right-align it then mask. (bits<=8 ⇒ fits a window.)
            // The low byte may be one PAST the record on the final field; treat the missing byte as
            // 0 — it never contributes to the right-aligned field, matching `_decodeBitpack` which
            // only reads bits actually inside the payload.
            uint256 hi = uint256(uint8(shape[byteIdx])) << 8;
            uint256 lo = byteIdx + 1 < len ? uint256(uint8(shape[byteIdx + 1])) : 0;
            uint256 v = ((hi | lo) >> (16 - bitOff - bits)) & mask;
            if (v >= classCount) revert ClassIdOutOfRange(v, classCount);
            if (v == transparentClass) transparentSeen = true;
            bitPos += bits;
        }
    }

    /// @notice Materialize a shape + colorway into the logical `Asset` view
    ///         the renderer consumes (doc "Contract Architecture").
    /// @dev The view's `palette` is class-indexed and `pixels` are class IDs (class id ==
    ///      palette index). Swap arrays are reconstructed from the colorway's ordered class
    ///      indexes; ANY index >= palette length reverts `SwapClassIndexOutOfRange`.
    /// @param shape exact shape-record bytes.
    /// @param colorway exact colorway-record bytes.
    function decode(bytes memory shape, bytes memory colorway)
        internal
        pure
        returns (Asset memory a)
    {
        (uint8 shapeKind, uint16 classCount, uint8 shapeTransparent, bytes memory classIds) =
            decodeShape(shape);
        uint16 shapeId = (uint16(uint8(shape[0])) << 8) | uint16(uint8(shape[1]));

        a.kind = shapeKind;
        a.paletteLen = classCount;
        a.pixels = classIds;
        a.transparent =
            shapeTransparent == NO_TRANSPARENT_CLASS ? int16(-1) : int16(uint16(shapeTransparent));

        _decodeColorway(a, colorway, shapeId, classCount, shapeKind, shapeTransparent);
    }

    /// @notice Validate ONE colorway record against its shape's HEADER fields WITHOUT decoding the
    ///         shape's 1024-pixel payload — the seal's per-asset check. The full pixel decode +
    ///         classId-range check is already done once per shape by `decodeShape` in the shape
    ///         seal pass, so re-decoding it per asset (the dominant seal cost) is redundant. This
    ///         runs the SAME colorway checks `decode`/`_decodeColorway` do — kind tag matches the
    ///         shape kind, colorway shapeId matches, paletteLen == classCount (palette covers every
    ///         template class), base transparentClass matches the shape's, and every swap class
    ///         index < palette length — and additionally reports whether a background is OPAQUE.
    /// @param colorway exact colorway-record bytes.
    /// @param colorwayId the colorwayId from the asset index entry (must match the record's EMBEDDED
    ///        colorwayId — doc P0 render-pointer authentication).
    /// @param shapeId the shape id from the asset index (must match the colorway's).
    /// @param classCount the shape's class count from the shape index (palette must equal it).
    /// @param shapeKind the shape's kind from the shape index (0=bg, 1=base).
    /// @param shapeTransparent the shape's transparent class from the shape index (255=opaque).
    /// @return bgOpaque true iff this is a BACKGROUND colorway AND its shape is opaque (transparent
    ///         class == 255). For base it is meaningless and returned false.
    function validateColorway(
        bytes memory colorway,
        uint16 colorwayId,
        uint16 shapeId,
        uint16 classCount,
        uint8 shapeKind,
        uint8 shapeTransparent
    ) internal pure returns (bool bgOpaque) {
        uint256 o;
        uint8 cwKind = uint8(colorway[o++]);
        if (cwKind != shapeKind) revert BadKind(cwKind);
        // The record's EMBEDDED colorwayId MUST equal the asset entry's colorwayId. Without this an
        // index entry could be repointed (via its render pointer) onto a DIFFERENT same-shape
        // colorway record and still pass every other check — exactly the "minted != shown" gap.
        uint16 cwId = (uint16(uint8(colorway[o])) << 8) | uint16(uint8(colorway[o + 1]));
        o += 2;
        if (cwId != colorwayId) revert ColorwayIdMismatch(colorwayId, cwId);
        uint16 cwShapeId = (uint16(uint8(colorway[o])) << 8) | uint16(uint8(colorway[o + 1]));
        o += 2;
        if (cwShapeId != shapeId) revert ShapeColorwayMismatch(shapeId, cwShapeId);

        // skip name
        uint8 nameLen = uint8(colorway[o++]);
        o += nameLen;

        // palette length must cover every template class (paletteLen == classCount).
        uint16 P = uint8(colorway[o]) == 0 ? uint16(256) : uint16(uint8(colorway[o]));
        o++;
        if (P != classCount) revert ClassIdOutOfRange(P, classCount);
        o += uint256(P) * 3; // skip palette RGB triples

        if (shapeKind == KIND_BG) {
            o = _checkSwapInRange(colorway, o, P); // swapSource indexes
            bgOpaque = shapeTransparent == NO_TRANSPARENT_CLASS;
        } else {
            uint8 cwTransparent = uint8(colorway[o++]);
            if (cwTransparent != shapeTransparent) {
                revert TransparentMismatch(shapeTransparent, cwTransparent);
            }
            o = _checkSwapInRange(colorway, o, P); // swapTarget
            o = _checkSwapInRange(colorway, o, P); // swapForce
            // anchorPick(1) faceDark(1) recolorFlags(1). The renderer interprets these; a sealed
            // record must carry only CANONICAL in-range values (mirrors the canonical TS decoder), so
            // an out-of-range byte that the renderer would interpret unpredictably is rejected at seal
            // time rather than relied on never being uploaded.
            o = _checkRecolorFields(colorway, o);
            bgOpaque = false;
        }
        // CANONICAL: the colorway's decoded fields must account for the WHOLE record — no trailing
        // bytes (which the storage hash would bind but the decoder never reads). `o` is now PAST the
        // last consumed byte, so it must equal the record length exactly.
        if (o != colorway.length) revert NonCanonicalRecord(o, colorway.length);
    }

    /// @dev Range-check a length-prefixed swap class-index list at `o`: every index < `P`.
    ///      Returns the offset PAST the list (len byte + indexes).
    function _checkSwapInRange(bytes memory colorway, uint256 o, uint16 P)
        private
        pure
        returns (uint256 next)
    {
        uint8 len = uint8(colorway[o++]);
        for (uint256 i; i < len; ++i) {
            uint8 classIdx = uint8(colorway[o++]);
            if (classIdx >= P) revert SwapClassIndexOutOfRange(classIdx, P);
        }
        next = o;
    }

    /// @dev Validate the base recolor trailer at `o`: anchorPick(1) faceDark(1) recolorFlags(1).
    ///      faceDark/recolorFlags must be in their canonical ranges (mirror the canonical TS decoder);
    ///      anchorPick is unconstrained (0..254 a valid pick, 255 = none). Field indices in the
    ///      `RecolorFieldOutOfRange` error are preserved across the recolorMode removal: faceDark = 1,
    ///      recolorFlags = 2 (index 0 is now unused). Returns the offset past the 3 trailer bytes.
    ///      Split into its own frame to keep `validateColorway` under the (non-viaIR) stack-depth limit.
    function _checkRecolorFields(bytes memory colorway, uint256 o) private pure returns (uint256) {
        // o+0 is anchorPick (unconstrained).
        uint8 faceDark = uint8(colorway[o + 1]);
        if (faceDark > FACE_DARK_MAX) revert RecolorFieldOutOfRange(1, faceDark, FACE_DARK_MAX);
        uint8 recolorFlags = uint8(colorway[o + 2]);
        if (recolorFlags > RECOLOR_FLAGS_MAX) {
            revert RecolorFieldOutOfRange(2, recolorFlags, RECOLOR_FLAGS_MAX);
        }
        return o + 3;
    }

    /// @dev Decode the colorway record into `a` (palette, swap arrays, recolor fields). Kept
    ///      in its own frame so `decode` stays under the EVM stack-depth limit (non-viaIR).
    function _decodeColorway(
        Asset memory a,
        bytes memory colorway,
        uint16 shapeId,
        uint16 classCount,
        uint8 shapeKind,
        uint8 shapeTransparent
    ) private pure {
        uint256 o;
        // kind tag (must match the shape's kind).
        uint8 cwKind = uint8(colorway[o++]);
        if (cwKind != shapeKind) revert BadKind(cwKind);
        o += 2; // colorwayId (carried for the seal hash; not needed in the view)
        uint16 cwShapeId = (uint16(uint8(colorway[o])) << 8) | uint16(uint8(colorway[o + 1]));
        o += 2;
        if (cwShapeId != shapeId) revert ShapeColorwayMismatch(shapeId, cwShapeId);

        // name
        {
            uint8 nameLen = uint8(colorway[o++]);
            bytes memory nameBytes = new bytes(nameLen);
            for (uint256 i; i < nameLen; ++i) {
                nameBytes[i] = colorway[o++];
            }
            a.name = string(nameBytes);
        }

        // palette: paletteLen (0⇒256) then P × RGB24, indexed by class ID. The palette MUST
        // cover every template class (doc seal rule "palette covers its template classes"):
        // paletteLen == classCount.
        uint16 P = uint8(colorway[o]) == 0 ? uint16(256) : uint16(uint8(colorway[o]));
        o++;
        if (P != classCount) revert ClassIdOutOfRange(P, classCount);
        a.palette = new uint24[](P);
        for (uint256 i; i < P; ++i) {
            a.palette[i] = _readColor(colorway, o);
            o += 3;
        }

        if (shapeKind == KIND_BG) {
            // bg: swapSource only. swapTarget/swapForce/recolor fields are NOT stored for a
            // bg and stay at the Asset zero-defaults — exactly the bg logical
            // asset's renderer-consumed values (the bg is always the SOURCE layer).
            (a.swapSource, o) = _readSwap(colorway, o, a.palette);
        } else {
            // base: transparentClass, swapTarget, swapForce, recolor fields.
            uint8 cwTransparent = uint8(colorway[o++]);
            if (cwTransparent != shapeTransparent) {
                revert TransparentMismatch(shapeTransparent, cwTransparent);
            }
            (a.swapTarget, o) = _readSwap(colorway, o, a.palette);
            (a.swapForce, o) = _readSwap(colorway, o, a.palette);
            a.anchorPick = uint8(colorway[o++]);
            a.faceDark = uint8(colorway[o++]);
            a.recolorFlags = uint8(colorway[o++]);
        }
    }

    /// @dev Read a length-prefixed swap list of class indexes at `o` and reconstruct the
    ///      ordered `uint24[]` RGB array from `palette` (class index → palette[index]).
    ///      Reverts `SwapClassIndexOutOfRange` if any index >= palette length. Returns
    ///      the array AND the advanced offset (past the len byte + the indexes).
    function _readSwap(bytes memory colorway, uint256 o, uint24[] memory palette)
        private
        pure
        returns (uint24[] memory out, uint256 next)
    {
        uint256 P = palette.length;
        uint8 len = uint8(colorway[o++]);
        out = new uint24[](len);
        for (uint256 i; i < len; ++i) {
            uint8 classIdx = uint8(colorway[o++]);
            if (classIdx >= P) revert SwapClassIndexOutOfRange(classIdx, P);
            out[i] = palette[classIdx];
        }
        next = o;
    }

    /// @dev Read a 24-bit RGB color at offset `o` (3 bytes, big-endian R,G,B).
    function _readColor(bytes memory blob, uint256 o) private pure returns (uint24) {
        uint24 r = uint24(uint8(blob[o]));
        uint24 g = uint24(uint8(blob[o + 1]));
        uint24 b = uint24(uint8(blob[o + 2]));
        return (r << 16) | (g << 8) | b;
    }
}

src/lib/IPaletteAssets.sol

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

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

/// @title IPaletteAssets
/// @notice The MINIMAL read surface the renderer (and the NFT's pick validation) consume from the
///         asset library `PaletteAssets`. `base(i)`/`background(i)` return the materialized
///         `AssetLib.Asset` view the renderer reads directly; `numBase()`/`numBackgrounds()` bound
///         the valid pick ranges; `isSealed()` lets the renderer/NFT make "wired against a SEALED
///         library" a constructor invariant.
/// @dev Pure type abstraction over `PaletteAssets`'s stored shape/colorway bytes: the renderer reads
///      the library only through this interface, so it depends on the decoded `AssetLib.Asset` view,
///      not the on-chain storage layout.
interface IPaletteAssets {
    /// @notice Decoded base asset `i` (materialized `AssetLib.Asset` view).
    function base(uint256 i) external view returns (AssetLib.Asset memory);

    /// @notice Decoded background asset `i` (materialized `AssetLib.Asset` view).
    function background(uint256 i) external view returns (AssetLib.Asset memory);

    /// @notice Number of base assets.
    function numBase() external view returns (uint256);

    /// @notice Number of background assets.
    function numBackgrounds() external view returns (uint256);

    /// @notice Whether the library has been permanently sealed (a one-way latch after which no
    ///         asset bytes can ever change). Part of the read surface so the renderer/NFT can make
    ///         "wired against a SEALED library" a CONSTRUCTOR INVARIANT — turning the deploy-script
    ///         convention "seal before wiring" into something the contracts THEMSELVES enforce, so a
    ///         renderer/NFT can never be deployed against a still-mutable library (which would break
    ///         the audited immutability the "minted == shown" guarantee relies on).
    function isSealed() external view returns (bool);
}

src/zero/interfaces/IOnchain9mSource.sol

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

import { IPaletteAssets } from "../../lib/IPaletteAssets.sol";

/// @notice The pinned canonical 9m getters and transfers used by 0m//TX.
/// @dev 0m NEVER invokes a 9m administrative method. `safeTransferFrom` is declared only so the
///      holder-initiated ingress can be described and simulated; `Onchain0m` itself calls only
///      `transferFrom(address(this), BURN_ADDRESS, tokenId)` on a token it transiently owns.
interface IOnchain9mSource {
    function assets() external view returns (IPaletteAssets);

    function ownerOf(uint256 tokenId) external view returns (address);

    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    function transferFrom(address from, address to, uint256 tokenId) external;

    /// @return baseIndex bits 0..15 | bgIndex bits 16..31
    function tokenPicks(uint256 tokenId) external view returns (uint256);

    /// @return streakDay bits 0..15 | mintNumber bits 16..31 | mintedAt (uint64) bits 32..95
    function tokenMeta(uint256 tokenId) external view returns (uint256);

    /// @return Arbitrary raw callsign bytes, typically zero-padded text; all-zero means empty.
    function tokenUsername(uint256 tokenId) external view returns (bytes32);

    function totalMinted() external view returns (uint256);

    function maxSupply() external view returns (uint256);
}

src/zero/interfaces/IRgbPng32.sol

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

interface IRgbPng32 {
    function encode(bytes calldata rgb) external pure returns (bytes memory png);
}

src/zero/interfaces/IStaticGlitchSvg.sol

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

interface IStaticGlitchSvg {
    function render(bytes calldata png) external pure returns (string memory svgDocument);
}

src/zero/interfaces/IZeroAnimationRenderer.sol

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

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

interface IZeroAnimationRenderer {
    function templateStore() external view returns (IZeroHtmlTemplateStore);

    function render(
        bytes calldata signalRgb,
        bytes calldata echoRgb,
        uint64 seed,
        uint8 profile,
        bytes32 signalHash
    ) external view returns (string memory htmlDocument);

    function renderOpen(bytes calldata signalRgb, uint64 seed, bytes32 signalHash)
        external
        view
        returns (string memory htmlDocument);
}

src/zero/interfaces/IZeroGlitchKernel.sol

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

interface IZeroGlitchKernel {
    function renderVersion() external pure returns (uint8);
    function profileHash(uint8 profile) external pure returns (bytes32);
    function profileRoot() external pure returns (bytes32);
    function renderSpecHash() external pure returns (bytes32);

    function glitch(bytes calldata cleanRgb, uint64 seed, uint8 profile)
        external
        pure
        returns (bytes memory glitchedRgb);

    function glitchWithProgram(bytes calldata cleanRgb, uint64 seed, uint8 profile)
        external
        pure
        returns (bytes memory glitchedRgb, uint64 program);

    function glitchAnimationPairWithProgram(bytes calldata cleanRgb, uint64 seed, uint8 profile)
        external
        pure
        returns (bytes memory signalRgb, bytes memory echoRgb, uint64 program);
}

src/zero/interfaces/IZeroHtmlTemplateStore.sol

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

interface IZeroHtmlTemplateStore {
    function isSealed() external pure returns (bool);
    function templateHash() external view returns (bytes32);
    function templateLength() external view returns (uint256);

    function fragments()
        external
        view
        returns (
            bytes memory head,
            bytes memory afterRgb,
            bytes memory afterSeed,
            bytes memory afterProfile,
            bytes memory tail
        );
}

src/zero/interfaces/IZeroPaletteComposer.sol

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

import { IPaletteAssets } from "../../lib/IPaletteAssets.sol";
import { IOnchain9mSource } from "./IOnchain9mSource.sol";
import { IZeroGlitchKernel } from "./IZeroGlitchKernel.sol";

interface IZeroPaletteComposer {
    function assets() external view returns (IPaletteAssets);
    function sourceOnchain9m() external view returns (IOnchain9mSource);
    function sourceBindingHash() external view returns (bytes32);
    function kernel() external view returns (IZeroGlitchKernel);

    function glitchedRgb(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory rgb);

    function glitchedRgbWithMetadata(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory rgb, uint64 program, string memory baseName, string memory bgName);

    function glitchedAnimationRgb(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory signalRgb, bytes memory echoRgb);

    function glitchedAnimationRgbWithMetadata(
        uint256 baseIndex,
        uint256 bgIndex,
        uint64 seed,
        uint8 profile
    )
        external
        view
        returns (
            bytes memory signalRgb,
            bytes memory echoRgb,
            uint64 program,
            string memory baseName,
            string memory bgName
        );
}

src/zero/interfaces/IZeroStaticRenderer.sol

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

import { IPaletteAssets } from "../../lib/IPaletteAssets.sol";
import { IZeroPaletteComposer } from "./IZeroPaletteComposer.sol";
import { IZeroGlitchKernel } from "./IZeroGlitchKernel.sol";
import { IRgbPng32 } from "./IRgbPng32.sol";
import { IStaticGlitchSvg } from "./IStaticGlitchSvg.sol";
import { IZeroHtmlTemplateStore } from "./IZeroHtmlTemplateStore.sol";
import { IZeroAnimationRenderer } from "./IZeroAnimationRenderer.sol";

interface IZeroStaticRenderer {
    function assets() external view returns (IPaletteAssets);
    function composer() external view returns (IZeroPaletteComposer);
    function kernel() external view returns (IZeroGlitchKernel);
    function pngEncoder() external view returns (IRgbPng32);
    function svgRenderer() external view returns (IStaticGlitchSvg);
    function htmlTemplateStore() external view returns (IZeroHtmlTemplateStore);
    function animationRenderer() external view returns (IZeroAnimationRenderer);
    function renderVersion() external pure returns (uint8);
    function profileHash(uint8 profile) external view returns (bytes32);
    function templateHash() external view returns (bytes32);
    function cadence(uint64 seed) external pure returns (string memory name, uint8 burstFps);
    function openTokenURI(uint256 tokenId, uint64 entropyAnchorBlock, uint64 seed)
        external
        view
        returns (string memory);

    function rawRgb(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function signalRgb(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function echoRgb(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function animationStates(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory signalRgb_, bytes memory echoRgb_);
    function signalHash(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes32);
    function png(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function signalPng(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function echoPng(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (bytes memory);
    function svg(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function signalSvg(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function echoSvg(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function imageSvg(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function imageDataUri(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function signalDataUri(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function echoDataUri(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function animationHtml(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);
    function animationDataUri(uint256 baseIndex, uint256 bgIndex, uint64 seed, uint8 profile)
        external
        view
        returns (string memory);

    function tokenURI(
        uint256 tokenId,
        uint256 baseIndex,
        uint256 bgIndex,
        uint256 streakDay,
        uint256 mintNumber,
        uint256 mintedAt,
        bytes32 label,
        uint64 seed,
        uint8 profile
    ) external view returns (string memory);
}

src/zero/lib/Onchain9mSourceBinding.sol

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

import { IPaletteAssets } from "../../lib/IPaletteAssets.sol";
import { IOnchain9mSource } from "../interfaces/IOnchain9mSource.sol";

library Onchain9mSourceBinding {
    bytes32 internal constant BINDING_DOMAIN =
        keccak256("m1n7-807.!0m.source-onchain9m.binding.v1");
    bytes32 internal constant COMMITMENT_DOMAIN =
        keccak256("m1n7-807.!0m.source-onchain9m.commitment.v1");

    error SourceOnchain9mHasNoCode();
    error SourceAssetsHaveNoCode();
    error SourceAssetsNotSealed();
    error MissingSourceAssetRoot();

    struct Binding {
        uint256 chainId;
        address sourceOnchain9m;
        bytes32 sourceCodehash;
        IPaletteAssets assets;
        bytes32 assetsCodehash;
        bytes32 bindingHash;
    }

    function load(IOnchain9mSource source) internal view returns (Binding memory binding) {
        address sourceAddress = address(source);
        if (sourceAddress.code.length == 0) revert SourceOnchain9mHasNoCode();
        IPaletteAssets assets = source.assets();
        address assetsAddress = address(assets);
        if (assetsAddress.code.length == 0) revert SourceAssetsHaveNoCode();
        if (!assets.isSealed()) revert SourceAssetsNotSealed();

        binding.chainId = block.chainid;
        binding.sourceOnchain9m = sourceAddress;
        binding.sourceCodehash = sourceAddress.codehash;
        binding.assets = assets;
        binding.assetsCodehash = assetsAddress.codehash;
        binding.bindingHash = keccak256(
            abi.encode(
                BINDING_DOMAIN,
                binding.chainId,
                sourceAddress,
                binding.sourceCodehash,
                assetsAddress,
                binding.assetsCodehash
            )
        );
    }

    function requireAssets(IOnchain9mSource source) internal view returns (IPaletteAssets) {
        return load(source).assets;
    }

    function commitment(Binding memory binding, bytes32 assetRoot) internal pure returns (bytes32) {
        if (assetRoot == bytes32(0)) revert MissingSourceAssetRoot();
        return keccak256(abi.encode(COMMITMENT_DOMAIN, binding.bindingHash, assetRoot));
    }

    function configHash(
        bytes32 sourceCommitment,
        bytes32 renderSpecHash,
        bytes32 animationTemplateHash,
        bytes32 profileRoot,
        uint8 renderVersion
    ) internal pure returns (bytes32) {
        return keccak256(
            abi.encode(
                sourceCommitment, renderSpecHash, animationTemplateHash, profileRoot, renderVersion
            )
        );
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "runs": 25,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.