Skip to content
Verified contractExactMIT

GifsLoaderRenderer

Address0x1cacd3d9e78f94bbdd1c5ce285f60de736443722
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,246,767
Creation transaction
0x3659a8ad03…c42cc5e76a

src/GifsLoaderRenderer.sol

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

import {IAbxFieldRenderer} from "abx-contracts/src/uri/IAbxFieldRenderer.sol";
import {IAbxParams} from "abx-contracts/src/extensions/params/IAbxParams.sol";
import {IAbxDependencies} from "abx-contracts/src/extensions/dependencies/IAbxDependencies.sol";
import {IAbxOnChainMetadata} from "abx-contracts/src/extensions/onchain-metadata/IAbxOnChainMetadata.sol";
import {IAbxOnChainScript} from "abx-contracts/src/extensions/onchain-script/IAbxOnChainScript.sol";
import {IDependencyRegistryV0} from "abx-contracts/src/interfaces/IDependencyRegistryV0.sol";
import {LibString} from "solady/utils/LibString.sol";
import {Base64} from "solady/utils/Base64.sol";
import {GifsLoaderHtml as H} from "./GifsLoaderHtml.sol";

/// @notice AbxGenerator's reads this contract makes: its status (what `abx verify` asks of an
///         animation_url renderer) and the piecewise reads a document is built from.
interface IAbxGeneratorReads {
    function onChainStatus(address token)
        external
        view
        returns (uint8 branch, bool chainComplete, bytes32[] memory unresolvedRefs, bool urlOverBudget);
    function tokenDataJson(address token, uint256 tokenId) external view returns (string memory);
    function abxJs() external view returns (string memory);
    function gunzipScript() external view returns (string memory);
}

/// @notice The program index VesselDependencyRegistry keeps.
interface IGifsProgramIndex {
    function moduleOf(bytes32 core, uint256 g) external view returns (bool known, bytes32 module, bytes32 sample);
    function programModules(bytes32 core) external view returns (bytes32[] memory modules, bytes32[] memory samples);
}

/// @notice The pick GifsTraitsRenderer (the attributes field) makes from a seed.
interface IGifsPick {
    function pick(bytes32 seed) external view returns (uint256 form, uint256 generator);
}

/// @title GifsLoaderRenderer — a token's animation_url as a small on-chain page that loads its program
/// @notice The `animation_url` field renderer for gifs.shop projects. AbxGenerator puts the whole
///         program in the animation (the document is 300 KB+), so tokenURI outgrows what public RPCs
///         will execute. This page is about 3 KB. It carries:
///           - the token's coordinates, as AbxGenerator's `window.abxTokenData`;
///           - where the program is: the token's dependency registry, its dependency 0 ref (the
///             core) and the ref's chunk count, and the token's own generator module
///             and its chunk count, all read here at render time;
///           - the public RPCs to read it through, and this contract's address, whose `document`
///             rebuilds the token from the chain alone;
///           - the loader (abx/loader/loader.js), which reads the chunks with eth_call
///             getDependencyScript, gunzips them and runs the core, then the module.
///
///         The program is a core plus one module per generator, each
///         its own registry version, and the registry's index names each generator's module. The
///         token's generator is the pick of its project's attributes renderer (GifsTraitsRenderer),
///         the same pick tokenURI lists; the page names only the core and that one module. A
///         one-bundle program without an index gets a page that loads that bundle alone.
///
///         Two rebuild proofs, each a complete self-contained page, shaped exactly as AbxGenerator
///         builds a document (its token data, its abx.js, a gzip tag per dependency, its gunzip
///         bootstrap, the project's script), with only the core and one module inlined:
///           - `document(token, tokenId)`: the token, with its own seed;
///           - `generatorDocument(token, g)`: generator `g` of the project's program, drawn with the
///             sample seed the index stores, so every program is shown on-chain and runnable,
///             whether or not a token uses it yet.
///
///         One deployment serves every project and program version on its chain, because
///         everything token-specific is read from the token. Whatever is asked of it, it answers with
///         a page and never reverts: the collection surface, a token without a seed, a project
///         without a registry dependency and a generator the program doesn't have each get a plain
///         sentence. `page` is the same for every field; it is meant for `animation_url`.
///
///         The RPC list and the generator are the owner's to change (public URLs die over the
///         years), and by design they cannot be locked. Every URL must be https:// and unable to
///         leave its JSON string. Never put a keyed RPC URL here: the list is public.
contract GifsLoaderRenderer is IAbxFieldRenderer {
    string private constant CONTENT_TYPE = "text/html";
    bytes32 private constant SEED_KEY = "seed";
    bytes32 private constant F_ATTRIBUTES = "attributes";
    bytes32 private constant R_RENDERER = "renderer";
    uint256 private constant MAX_RPCS = 8;
    uint256 private constant MAX_RPC_BYTES = 200;
    /// @dev More chunks than this is not a program this page should try to fetch.
    uint256 private constant MAX_CHUNKS = 1024;
    /// @dev More project script chunks than this is not a gifs.shop stub.
    uint256 private constant MAX_SCRIPT_CHUNKS = 64;
    string private constant NL = hex"0a";
    /// @dev A JSON unicode escape for `<` (backslash, u003c), as AbxGenerator writes it.
    string private constant ESCAPED_LT = hex"5c7530303363";

    address public owner;
    /// @notice The address {transferOwnership} named, until it calls {acceptOwnership}.
    address public pendingOwner;
    /// @notice The AbxGenerator on this chain: its onChainStatus is passed on, and the documents use
    ///         its abx.js, gunzip bootstrap and token data.
    address public generator;
    string[] private _rpcs;

    event RpcsSet(string[] rpcs);
    event GeneratorSet(address indexed generator);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    error NotOwner();
    error ZeroOwner();
    error NotPendingOwner();
    error TooManyRpcs();
    error BadRpc(uint256 index);

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

    constructor(address owner_, address generator_, string[] memory rpcs_) {
        if (owner_ == address(0)) revert ZeroOwner();
        owner = owner_;
        emit OwnershipTransferred(address(0), owner_);
        generator = generator_;
        emit GeneratorSet(generator_);
        _setRpcs(rpcs_);
    }

    // ── owner ───────────────────────────────────────────────────────────────

    /// @notice Replace the RPC list. The page tries window.ethereum first, then these in order.
    function setRpcs(string[] calldata rpcs_) external onlyOwner {
        _setRpcs(rpcs_);
    }

    function setGenerator(address generator_) external onlyOwner {
        generator = generator_;
        emit GeneratorSet(generator_);
    }

    /// @notice Name the next owner; ownership moves only when it calls {acceptOwnership}, so a
    ///         mistyped address can't take the loader with it. Naming another replaces the pending one.
    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroOwner();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        delete pendingOwner;
    }

    function rpcs() external view returns (string[] memory) {
        return _rpcs;
    }

    // ── IAbxFieldRenderer ───────────────────────────────────────────────────

    /// @inheritdoc IAbxFieldRenderer
    function render(address token, uint256 tokenId, bytes32)
        external
        view
        returns (string memory contentType, bytes memory data)
    {
        return (CONTENT_TYPE, bytes(page(token, tokenId)));
    }

    /// @notice The page for a token: the loader page, or a plain one when there is nothing to load.
    function page(address token, uint256 tokenId) public view returns (string memory) {
        if (tokenId == type(uint256).max) return _plain(H.COLLECTION);
        (bool hasSeed, bytes32 seed) = _seed(token, tokenId);
        if (!hasSeed) return _plain(H.NO_SEED);
        (bool ok, address registry, bytes32 ref, uint256 chunks) = program(token);
        if (!ok) return _plain(H.NO_PROGRAM);
        (bytes32 module, uint256 moduleChunks) = _tokenModule(token, tokenId, seed, registry, ref);
        string memory head = string.concat(H.HEAD, _tokenData(token, LibString.toString(tokenId), seed), H.MID);
        string memory loader = _loaderData(registry, ref, chunks, module, moduleChunks);
        return string.concat(head, loader, H.OPEN, H.JS, H.TAIL);
    }

    /// @notice AbxGenerator's status for the token's program, as `abx verify` reads it from whatever
    ///         renderer animation_url points at (it calls onChainStatus on that address).
    ///         `chainComplete` is ABX's claim about where the program's bytes come from: every
    ///         dependency resolves to on-chain bytes, with no server, gateway or CDN in the graph. It
    ///         is not a claim about what the page does at runtime (AbxGenerator's natspec says so).
    ///         The page loads from exactly that graph, from the same registry, so the generator's
    ///         answer is passed on, with one narrowing: it is only complete if this page can load the
    ///         program itself. For a one-bundle program that is one registry dependency with a known
    ///         chunk count; for a split program, dependency 0 is a core with an index and the other
    ///         dependencies are exactly its modules, in index order, so ABX's document and this page
    ///         draw the same program. The generator's own branch, unresolved refs and URL budget pass
    ///         through unchanged. No generator, or a failing one, is (0, false, [], false).
    function onChainStatus(address token)
        external
        view
        returns (uint8 branch, bool chainComplete, bytes32[] memory unresolvedRefs, bool urlOverBudget)
    {
        unresolvedRefs = new bytes32[](0);
        if (generator.code.length == 0) return (0, false, unresolvedRefs, false);
        try IAbxGeneratorReads(generator).onChainStatus(token) returns (
            uint8 b, bool complete, bytes32[] memory unresolved, bool overBudget
        ) {
            bool loadable;
            try this.loadsWhatAbxDeclares(token) returns (bool yes) {
                loadable = yes;
            } catch {}
            return (b, complete && loadable, unresolved, overBudget);
        } catch {
            return (0, false, unresolvedRefs, false);
        }
    }

    /// @notice Whether this page loads the program the project declares to ABX: one registry
    ///         dependency it can read (a one-bundle program), or a core whose index names modules and
    ///         the project's dependencies 1… are exactly those modules, in index order. Used by
    ///         {onChainStatus}; it may revert on a token that isn't a token (that caller catches).
    function loadsWhatAbxDeclares(address token) external view returns (bool) {
        (bool ok, address registry, bytes32 ref,) = program(token);
        if (!ok) return false;
        uint256 count = IAbxDependencies(token).dependencyCount();
        bytes32[] memory modules = _programModules(registry, ref);
        if (modules.length == 0) return count == 1;
        uint256 next = 1;
        for (uint256 i; i < modules.length; ++i) {
            if (modules[i] == 0) continue;
            if (next >= count) return false;
            (IAbxDependencies.Resolution res, bytes32 dep) = IAbxDependencies(token).dependencyByIndex(next++);
            if (res != IAbxDependencies.Resolution.Registry || dep != modules[i]) return false;
        }
        return next == count;
    }

    /// @notice Where a token's program is: its registry, its dependency 0 ref and the ref's chunk
    ///         count. `ok` is false for anything the page can't load (no registry, no dependency,
    ///         an on-chain-address dependency, a ref the registry doesn't know).
    function program(address token)
        public
        view
        returns (bool ok, address registry, bytes32 ref, uint256 chunks)
    {
        bytes memory r;
        (ok, r) = _read(token, abi.encodeCall(IAbxDependencies.dependencyRegistry, ()), 32);
        if (!ok) return (false, address(0), 0, 0);
        registry = address(uint160(_word(r, 0)));
        if (registry.code.length == 0) return (false, address(0), 0, 0);

        (ok, r) = _read(token, abi.encodeCall(IAbxDependencies.dependencyCount, ()), 32);
        if (!ok || _word(r, 0) == 0) return (false, address(0), 0, 0);

        (ok, r) = _read(token, abi.encodeCall(IAbxDependencies.dependencyByIndex, (0)), 64);
        if (!ok || _word(r, 0) != uint256(IAbxDependencies.Resolution.Registry)) return (false, address(0), 0, 0);
        ref = bytes32(_word(r, 1));
        if (ref == 0) return (false, address(0), 0, 0);

        chunks = _chunkCount(registry, ref);
        if (chunks == 0) return (false, address(0), 0, 0);
        return (true, registry, ref, chunks);
    }

    /// @notice A token's whole program as its page loads it: the core (dependency 0) and the token's
    ///         generator module with their chunk counts. `module` is 0 (and `moduleChunks` 0) for a
    ///         generator the core draws, a program without an index, or anything the page can't resolve.
    function tokenProgram(address token, uint256 tokenId)
        external
        view
        returns (bool ok, address registry, bytes32 core, uint256 coreChunks, bytes32 module, uint256 moduleChunks)
    {
        (bool hasSeed, bytes32 seed) = _seed(token, tokenId);
        if (!hasSeed) return (false, address(0), 0, 0, 0, 0);
        (ok, registry, core, coreChunks) = program(token);
        if (!ok) return (false, address(0), 0, 0, 0, 0);
        (module, moduleChunks) = _tokenModule(token, tokenId, seed, registry, core);
    }

    // ── the rebuild proofs ──────────────────────────────────────────────────

    /// @notice A token's complete, self-contained document from the chain alone: the core and the
    ///         token's generator module inlined from the Vault, with AbxGenerator's token data, abx.js
    ///         and gunzip bootstrap and the project's script. Byte for byte what AbxGenerator builds
    ///         for the token when the project declares only those two dependencies. A plain page,
    ///         never a revert, when there is nothing to build.
    function document(address token, uint256 tokenId) external view returns (string memory) {
        (bool hasSeed, bytes32 seed) = _seed(token, tokenId);
        if (!hasSeed || tokenId == type(uint256).max) return _plain(H.NO_SEED);
        (bool ok, address registry, bytes32 ref, uint256 chunks) = program(token);
        if (!ok) return _plain(H.NO_PROGRAM);
        (bytes32 module, uint256 moduleChunks) = _tokenModule(token, tokenId, seed, registry, ref);
        if (_moduleMissing(token, tokenId, seed, registry, ref, module)) return _plain(H.NO_GENERATOR);
        string memory json;
        try IAbxGeneratorReads(generator).tokenDataJson(token, tokenId) returns (string memory j) {
            json = j;
        } catch {
            return _plain(H.NO_PROGRAM);
        }
        return _document(token, json, registry, ref, chunks, module, moduleChunks);
    }

    /// @notice Generator `g` (its index in the program, 0 = Squiggle) of the project's program,
    ///         as a complete, self-contained document: the core and g's module inlined from the Vault,
    ///         drawn with the sample seed the registry's index stores for it. The proof that every
    ///         generator is on-chain and runnable, minted or not. A `g` the program doesn't have, a
    ///         program without an index or a module that can't be read: a plain page, never a revert.
    function generatorDocument(address token, uint256 g) external view returns (string memory) {
        (bool ok, address registry, bytes32 ref, uint256 chunks) = program(token);
        if (!ok) return _plain(H.NO_PROGRAM);
        (bool rok, bytes memory r) = _read(registry, abi.encodeCall(IGifsProgramIndex.moduleOf, (ref, g)), 96);
        if (!rok || _word(r, 0) != 1) return _plain(H.NO_GENERATOR);
        bytes32 module = bytes32(_word(r, 1));
        bytes32 sample = bytes32(_word(r, 2));
        uint256 moduleChunks;
        if (module != 0) {
            moduleChunks = _chunkCount(registry, module);
            if (moduleChunks == 0) return _plain(H.NO_GENERATOR);
        }
        return _document(token, _tokenData(token, "sample", sample), registry, ref, chunks, module, moduleChunks);
    }

    /// @dev The document, or a plain page if any piece fails to read (a chunk that doesn't match
    ///      its keccak, a generator without abx.js): the assembly runs as a self-call so a revert
    ///      inside it is caught here.
    function _document(
        address token,
        string memory json,
        address registry,
        bytes32 ref,
        uint256 chunks,
        bytes32 module,
        uint256 moduleChunks
    ) private view returns (string memory) {
        try this.assemble(token, json, registry, ref, chunks, module, moduleChunks) returns (string memory doc) {
            return doc;
        } catch {
            return _plain(module == 0 ? H.NO_PROGRAM : H.NO_GENERATOR);
        }
    }

    /// @notice The document's assembly, AbxGenerator's template shape with two dependencies at most.
    ///         External only so {document} and {generatorDocument} can catch a failed read; it
    ///         reverts on one, and is of no use called directly.
    function assemble(
        address token,
        string calldata json,
        address registry,
        bytes32 ref,
        uint256 chunks,
        bytes32 module,
        uint256 moduleChunks
    ) external view returns (string memory) {
        string memory head = string.concat(_head(json), H.DOC_ABXJS_CLOSE, NL, _tags(registry, ref, chunks, module, moduleChunks));
        return string.concat(head, NL, _bootstrapTag(), H.DOC_BODY, _script(token), H.DOC_TAIL);
    }

    /// @dev The shell's head through abx.js: AbxGenerator's SHELL_HEAD, the token data with every `<`
    ///      escaped, SHELL_ABXJS_OPEN and its abx.js.
    function _head(string calldata json) private view returns (string memory) {
        return string.concat(H.HEAD, LibString.replace(json, "<", ESCAPED_LT), H.OPEN, IAbxGeneratorReads(generator).abxJs());
    }

    /// @dev The core's gzip tag, then the module's if there is one.
    function _tags(address registry, bytes32 ref, uint256 chunks, bytes32 module, uint256 moduleChunks)
        private
        view
        returns (string memory tags)
    {
        tags = _gzipTag(registry, ref, chunks);
        if (module != 0) tags = string.concat(tags, NL, _gzipTag(registry, module, moduleChunks));
    }

    /// @dev AbxGenerator's gunzip bootstrap, as it carries it: a base64 data-URI script.
    function _bootstrapTag() private view returns (string memory) {
        return string.concat(H.B64_TAG_OPEN, Base64.encode(bytes(IAbxGeneratorReads(generator).gunzipScript())), H.DATA_TAG_CLOSE);
    }

    // ── the page's parts ────────────────────────────────────────────────────

    /// @dev The seed, as GifsTraitsRenderer reads it: set, and not a hash commitment.
    function _seed(address token, uint256 tokenId) private view returns (bool, bytes32) {
        (bool ok, bytes memory r) = _read(token, abi.encodeCall(IAbxParams.tokenParam, (tokenId, SEED_KEY)), 96);
        if (!ok || _word(r, 1) != 0 || _word(r, 2) == 0) return (false, 0);
        return (true, bytes32(_word(r, 0)));
    }

    /// @dev The registry's chunk count for a ref (0 for an unknown ref or an absurd count).
    ///      getDependencyDetails' head is nine words; scriptCount is the last (static) one, so it is
    ///      read where it sits without decoding the strings.
    function _chunkCount(address registry, bytes32 ref) private view returns (uint256 n) {
        (bool ok, bytes memory r) = _read(registry, abi.encodeCall(IDependencyRegistryV0.getDependencyDetails, (ref)), 288);
        if (!ok) return 0;
        n = _word(r, 8);
        if (n > MAX_CHUNKS) return 0;
    }

    /// @dev The token's generator: the pick of the renderer its attributes field names (token scope
    ///      first, then the collection's), as ABX resolves a field. Nothing found: ok = false.
    function _generatorOf(address token, uint256 tokenId, bytes32 seed) private view returns (bool, uint256) {
        (bool ok, bytes memory r) = _read(token, abi.encodeCall(IAbxOnChainMetadata.tokenField, (tokenId, F_ATTRIBUTES)), 96);
        if (!ok || bytes32(_word(r, 0)) == 0) {
            (ok, r) = _read(token, abi.encodeCall(IAbxOnChainMetadata.contractField, (F_ATTRIBUTES)), 96);
        }
        // (bytes32 representation, bytes value): the value is abi.encode(renderer), one word
        if (!ok || bytes32(_word(r, 0)) != R_RENDERER || _word(r, 2) != 32 || r.length < 128) return (false, 0);
        uint256 w = _word(r, 3);
        if (w >> 160 != 0) return (false, 0);
        (ok, r) = _read(address(uint160(w)), abi.encodeCall(IGifsPick.pick, (seed)), 64);
        if (!ok) return (false, 0);
        return (true, _word(r, 1));
    }

    /// @dev The token's module and its chunk count, or (0, 0): a program without an index, a generator
    ///      the core draws, or a generator or module that can't be resolved.
    function _tokenModule(address token, uint256 tokenId, bytes32 seed, address registry, bytes32 ref)
        private
        view
        returns (bytes32 module, uint256 moduleChunks)
    {
        (bool ok, uint256 g) = _generatorOf(token, tokenId, seed);
        if (!ok) return (0, 0);
        bytes memory r;
        (ok, r) = _read(registry, abi.encodeCall(IGifsProgramIndex.moduleOf, (ref, g)), 96);
        if (!ok || _word(r, 0) != 1 || _word(r, 1) == 0) return (0, 0);
        module = bytes32(_word(r, 1));
        moduleChunks = _chunkCount(registry, module);
        if (moduleChunks == 0) return (0, 0);
    }

    /// @dev For a document: true when the token's program has an index but its generator's module
    ///      could not be resolved (the core alone would draw a "not loaded" sentence, not the art).
    function _moduleMissing(address token, uint256 tokenId, bytes32 seed, address registry, bytes32 ref, bytes32 module)
        private
        view
        returns (bool)
    {
        if (module != 0) return false;
        if (_programModules(registry, ref).length == 0) return false; // one bundle: the core is all
        (bool ok, uint256 g) = _generatorOf(token, tokenId, seed);
        if (!ok) return true;
        (bool rok, bytes memory r) = _read(registry, abi.encodeCall(IGifsProgramIndex.moduleOf, (ref, g)), 96);
        return !rok || _word(r, 0) != 1 || _word(r, 1) != 0; // known and drawn by the core is fine
    }

    /// @dev The index of `ref`'s program, or an empty list (no index, or a registry without one).
    function _programModules(address registry, bytes32 ref) private view returns (bytes32[] memory modules) {
        (bool ok, bytes memory r) = _read(registry, abi.encodeCall(IGifsProgramIndex.programModules, (ref)), 128);
        if (!ok) return modules;
        try this.decodeModules(r) returns (bytes32[] memory m) {
            return m;
        } catch {}
    }

    /// @notice Decodes programModules' answer. External only so a malformed one can be caught.
    function decodeModules(bytes calldata r) external pure returns (bytes32[] memory modules) {
        (modules,) = abi.decode(r, (bytes32[], bytes32[]));
    }

    /// @dev {"chainId":…,"contractAddress":"0x…","seed":"0x…","tokenId":"…"}, AbxGenerator's shape.
    function _tokenData(address token, string memory tokenId, bytes32 seed) private view returns (string memory) {
        string memory head = string.concat(
            '{"chainId":', LibString.toString(block.chainid), ',"contractAddress":"', LibString.toHexString(token)
        );
        return string.concat(head, '","seed":"', LibString.toHexString(uint256(seed), 32), '","tokenId":"', tokenId, '"}');
    }

    /// @dev {"registry":"0x…","ref":"0x…","chunks":…,"module":"0x…","moduleChunks":…,"loader":"0x…",
    ///      "rpcs":["…",…]}
    function _loaderData(address registry, bytes32 ref, uint256 chunks, bytes32 module, uint256 moduleChunks)
        private
        view
        returns (string memory)
    {
        string memory list;
        uint256 n = _rpcs.length;
        for (uint256 i; i < n; ++i) {
            list = string.concat(list, i == 0 ? '"' : ',"', _rpcs[i], '"');
        }
        string memory head = string.concat(
            '{"registry":"', LibString.toHexString(registry), '","ref":"', LibString.toHexString(uint256(ref), 32),
            '","chunks":', LibString.toString(chunks)
        );
        head = string.concat(
            head, ',"module":"', LibString.toHexString(uint256(module), 32), '","moduleChunks":', LibString.toString(moduleChunks)
        );
        return string.concat(head, ',"loader":"', LibString.toHexString(address(this)), '","rpcs":[', list, "]}");
    }

    /// @dev A registry dependency as AbxGenerator carries it: its chunks verbatim in one inert gzip
    ///      data-URI tag. Reverts if a chunk can't be read (the registry checks each keccak).
    function _gzipTag(address registry, bytes32 ref, uint256 count) private view returns (string memory) {
        bytes memory out = bytes(H.GZIP_TAG_OPEN);
        for (uint256 i; i < count; ++i) {
            out = bytes.concat(out, bytes(IDependencyRegistryV0(registry).getDependencyScript(ref, i)));
        }
        return string(bytes.concat(out, bytes(H.DATA_TAG_CLOSE)));
    }

    /// @dev The project's script chunks joined with "\n", with every `</script` (any case) escaped
    ///      to `<\/script`, as AbxGenerator inlines it.
    function _script(address token) private view returns (string memory) {
        uint256 n = IAbxOnChainScript(token).scriptChunkCount();
        if (n > MAX_SCRIPT_CHUNKS) n = MAX_SCRIPT_CHUNKS;
        bytes memory s;
        for (uint256 i; i < n; ++i) {
            s = i == 0 ? IAbxOnChainScript(token).scriptChunk(i) : bytes.concat(s, "\n", IAbxOnChainScript(token).scriptChunk(i));
        }
        bytes memory out;
        uint256 start;
        for (uint256 i; i + 8 <= s.length; ++i) {
            if (s[i] != "<" || s[i + 1] != "/") continue;
            bool word = true;
            bytes memory w = "script";
            for (uint256 k; k < 6; ++k) {
                if ((uint8(s[i + 2 + k]) | 0x20) != uint8(w[k])) {
                    word = false;
                    break;
                }
            }
            if (!word) continue;
            out = bytes.concat(out, _slice(s, start, i + 1), "\\");
            start = i + 1;
        }
        if (start == 0) return string(s);
        return string(bytes.concat(out, _slice(s, start, s.length)));
    }

    function _slice(bytes memory b, uint256 from, uint256 to) private pure returns (bytes memory out) {
        out = new bytes(to - from);
        for (uint256 i; i < out.length; ++i) out[i] = b[from + i];
    }

    function _plain(string memory message) private pure returns (string memory) {
        return string.concat(H.PLAIN_HEAD, message, H.PLAIN_TAIL);
    }

    // ── helpers ─────────────────────────────────────────────────────────────

    function _setRpcs(string[] memory rpcs_) private {
        if (rpcs_.length > MAX_RPCS) revert TooManyRpcs();
        delete _rpcs;
        for (uint256 i; i < rpcs_.length; ++i) {
            if (!_rpcOk(bytes(rpcs_[i]))) revert BadRpc(i);
            _rpcs.push(rpcs_[i]);
        }
        emit RpcsSet(rpcs_);
    }

    /// @dev https://, at most 200 bytes, printable ASCII without spaces, and none of " \ < > (so a
    ///      URL can't leave its JSON string or the script element). abx/loader/page.mjs rpcOk.
    function _rpcOk(bytes memory u) private pure returns (bool) {
        bytes memory scheme = "https://";
        if (u.length <= scheme.length || u.length > MAX_RPC_BYTES) return false;
        for (uint256 i; i < u.length; ++i) {
            bytes1 c = u[i];
            if (i < scheme.length && c != scheme[i]) return false;
            if (c < 0x21 || c > 0x7e || c == '"' || c == "\\" || c == "<" || c == ">") return false;
        }
        return true;
    }

    /// @dev A staticcall that succeeded and returned at least `minLength` bytes; anything else
    ///      (no code, a revert, a short answer) is `ok = false`, never a revert here.
    function _read(address target, bytes memory callData, uint256 minLength)
        private
        view
        returns (bool ok, bytes memory ret)
    {
        if (target.code.length == 0) return (false, ret);
        (ok, ret) = target.staticcall(callData);
        if (ret.length < minLength) ok = false;
    }

    /// @dev The `i`th 32-byte word of returned data (the caller has checked its length).
    function _word(bytes memory r, uint256 i) private pure returns (uint256 w) {
        assembly ("memory-safe") {
            w := mload(add(add(r, 0x20), mul(i, 0x20)))
        }
    }
}

dependencies/abx-contracts-3.0.0/src/extensions/dependencies/IAbxDependencies.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.28;

/// @title IAbxDependencies — Dependencies extension vocabulary (Register 2)
/// @notice The ordered **code** libraries a script needs (e.g. p5js at 1.0.0, as the ref
///         `"p5js"..."1.0.0"`). Ordered, with no "primary" event — index 0 = the runtime, by
///         generator convention. The registry pointer is **soft and non-validating**: never
///         enforced (if it vanished, the project still declares its needs), but
///         resolution-meaningful (disambiguates a name-and-version ref; a content-hash registry
///         makes resolution verifiable). Loaded assets (images, data on IPFS/Arweave) are
///         **params**, not dependencies.
interface IAbxDependencies {
    /// @notice How a dependency reference resolves.
    enum Resolution {
        Registry, // `ref` = a registry `name@version` (readable-ASCII bytes32)
        OnChain // `ref` = a contract address, left-aligned in bytes32
    }

    /// @notice The dependency at `index` was added or changed.
    event DependencyUpdated(uint256 index, Resolution resolution, bytes32 indexed ref);

    /// @notice The LAST dependency was removed (the list stays dense; order is load-bearing).
    event DependencyRemoved(uint256 index);

    /// @notice The resolving registry pointer was set (soft, non-validating).
    event DependencyRegistrySet(address indexed registry);

    /// @notice The dependency set is frozen permanently.
    event DependenciesLocked();

    /// @notice Number of declared dependencies.
    function dependencyCount() external view returns (uint256);

    /// @notice The dependency at `index`.
    function dependencyByIndex(uint256 index)
        external
        view
        returns (Resolution resolution, bytes32 ref);

    /// @notice The soft registry pointer (`address(0)` = none).
    function dependencyRegistry() external view returns (address);

    /// @notice Whether the dependency set is permanently frozen.
    function dependenciesLocked() external view returns (bool);
}

dependencies/abx-contracts-3.0.0/src/extensions/onchain-metadata/IAbxOnChainMetadata.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.28;

/// @title IAbxOnChainMetadata — On-Chain Metadata extension (Register 2)
/// @notice A generic on-chain metadata store: each `field` (the what: image/description/…)
///         holds ONE active `(representation, value)` — *how* it's carried (a protocol-
///         convention `bytes32` tag: "inline", "reader", "keccak256", "url", …) and the
///         payload — at per-token and contract-wide (collection) scopes, with a per-field
///         freeze. `value` rides each event, so the full set reconstructs from logs alone.
/// @dev The `bytes32` keys are opaque on-chain; field and representation meaning plus the
///      resolution rules are protocol convention, never baked into the contract. On-chain decoding
///      (e.g. decompression) is delegated to a separate
///      {IAbxOnChainReader} contract referenced from a field's `value` — see the "reader"
///      representation; the storage here never decodes anything.
interface IAbxOnChainMetadata {
    /// @notice A `(field, representation, value)` to set at initialize (single scope: one token
    ///         id, or the collection).
    /// @dev Declared on the INTERFACE rather than the mixin so {AbxMetadataLib} can name it without
    ///      importing the mixin that imports the library. Inherited types stay reachable through the
    ///      derived name, so every existing `IAbxOnChainMetadata.FieldInput` reference is unaffected.
    struct FieldInput {
        bytes32 field;
        bytes32 representation;
        bytes value;
    }

    /// @notice A `(tokenId, field, representation, value)` to set at initialize — the multi-token
    ///         form, carrying its own token id so one array can seed fields across many tokens
    ///         (a Series seeds its metadata-id slots this way). For a 1/1 the single-scope
    ///         `FieldInput` + `_initOnChainMetadata` is used instead.
    struct TokenFieldInput {
        uint256 tokenId;
        bytes32 field;
        bytes32 representation;
        bytes value;
    }

    event TokenFieldSet(
        uint256 indexed tokenId, bytes32 indexed field, bytes32 representation, bytes value
    );
    event TokenFieldLocked(uint256 indexed tokenId, bytes32 indexed field);
    event ContractFieldSet(bytes32 indexed field, bytes32 representation, bytes value);
    event ContractFieldLocked(bytes32 indexed field);

    /// @notice A token field's active representation + value (both empty if unset).
    function tokenField(uint256 tokenId, bytes32 field)
        external
        view
        returns (bytes32 representation, bytes memory value);

    /// @notice Whether a token's `field` is frozen.
    function tokenFieldLocked(uint256 tokenId, bytes32 field) external view returns (bool);

    /// @notice A collection field's active representation + value.
    function contractField(bytes32 field)
        external
        view
        returns (bytes32 representation, bytes memory value);

    /// @notice Whether a collection `field` is frozen.
    function contractFieldLocked(bytes32 field) external view returns (bool);
}

dependencies/abx-contracts-3.0.0/src/extensions/onchain-script/IAbxOnChainScript.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.28;

/// @title IAbxOnChainScript — On-Chain Script extension vocabulary (Register 2)
/// @notice A project's program stored on-chain in chunks, introspectably (not a co-opted param
///         key). Chunks are too large to log, so `ScriptUpdated` carries the changed `index` —
///         an indexer re-reads **just that chunk** (+ `scriptChunkCount()` for length), O(1),
///         never a full re-read. The storage mechanism (SSTORE2, raw, future stores) is the
///         implementation's; this is the on-chain form of a project's content, vs. an off-chain
///         `code` field pointer.
interface IAbxOnChainScript {
    /// @notice The chunk at `index` was written or removed — re-read just that chunk.
    event ScriptUpdated(uint256 index);

    /// @notice The script is frozen permanently; chunks are now immutable.
    event ScriptLocked();

    /// @notice Number of script chunks (concatenate `0..count-1` for the full program).
    function scriptChunkCount() external view returns (uint256);

    /// @notice One chunk's content, by index.
    function scriptChunk(uint256 index) external view returns (bytes memory);

    /// @notice Whether the script is permanently frozen.
    function scriptLocked() external view returns (bool);
}

dependencies/abx-contracts-3.0.0/src/extensions/params/IAbxParams.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.28;

/// @title IAbxParams — Params extension vocabulary (Register 2)
/// @notice On-chain metadata as `key → bytes` at two scopes (contract-wide and per-token).
///         `value` is one `bytes32`, and **`valueIsHash` tells the indexer how to read it**:
///         `false` → the literal; `true` → the keccak256 of the full value, read back via the
///         data view. A large value is **one blob, never multi-chunk** (bounded by the ~24 KB
///         SSTORE2 ceiling); content above that is a *pointer* param, not a bigger param.
///         Params hold **metadata, not behavior** — a capability belongs in its own extension.
///         Clearing is explicit: a value of `0` is a *valid value*; removing a key is its own
///         event, so "param is 0" and "param unset" never blur.
/// @notice Params are **enumerable on chain**: `tokenParamKeys` / `contractParamKeys` list a
///         scope's currently-set keys, so an on-chain consumer reads a token's whole param set
///         without knowing the keys in advance and without an indexer. Two rules bind consumers:
///         **order is unspecified** (insertion order, disturbed by removals — canonical
///         serialization sorts), and **`seed` is reserved and never listed** at either scope
///         (read it directly with `tokenParam(tokenId, "seed")`; it is a tokenData coordinate,
///         not an enumerated param). Everything else set is listed exactly once, and a cleared
///         key leaves.
/// @dev `updatedBy` (indexed) is the authorized actor who set the param — on-chain provenance
///      (can differ from the tx sender under delegation / hooks; under the Configurable Params
///      auth model, different actors set different params). Has a read surface → a real
///      ERC-165 id. Keys are readable-ASCII `bytes32` by convention (like fields).
interface IAbxParams {
    /// @notice A contract-scope param was set / changed.
    event ContractParamConfigured(
        bytes32 indexed key, bytes32 value, bool valueIsHash, address indexed updatedBy
    );

    /// @notice A token-scope param was set / changed.
    event TokenParamConfigured(
        uint256 indexed tokenId,
        bytes32 indexed key,
        bytes32 value,
        bool valueIsHash,
        address indexed updatedBy
    );

    /// @notice A contract-scope param was removed (distinct from being set to zero).
    event ContractParamCleared(bytes32 indexed key, address indexed updatedBy);

    /// @notice A token-scope param was removed (distinct from being set to zero).
    event TokenParamCleared(uint256 indexed tokenId, bytes32 indexed key, address indexed updatedBy);

    /// @notice A token param's active state. `isSet` distinguishes "0" from "unset".
    function tokenParam(uint256 tokenId, bytes32 key)
        external
        view
        returns (bytes32 value, bool valueIsHash, bool isSet);

    /// @notice A contract param's active state. `isSet` distinguishes "0" from "unset".
    function contractParam(bytes32 key)
        external
        view
        returns (bytes32 value, bool valueIsHash, bool isSet);

    /// @notice A large token-param's full content (empty bytes for literals / unset keys).
    ///         When set, `keccak256(returned bytes)` equals the evented `value`.
    function tokenParamData(uint256 tokenId, bytes32 key) external view returns (bytes memory);

    /// @notice A large contract-param's full content (empty bytes for literals / unset keys).
    function contractParamData(bytes32 key) external view returns (bytes memory);

    /// @notice Every token-scope key currently set for `tokenId`, `seed` excluded. Unspecified
    ///         order. The whole-set read an on-chain consumer makes in a single `eth_call`.
    function tokenParamKeys(uint256 tokenId) external view returns (bytes32[] memory);

    /// @notice A window on `tokenParamKeys` — the escape hatch past RPC response limits for a
    ///         project with many keys. Returns up to `count` keys from `start`, plus `total`
    ///         (the full list length); a `start` at or past the end returns empty, so a caller
    ///         can walk to exhaustion without a prior length read.
    function tokenParamKeysPaged(uint256 tokenId, uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory keys, uint256 total);

    /// @notice Every contract-scope key currently set, `seed` excluded. Unspecified order.
    function contractParamKeys() external view returns (bytes32[] memory);

    /// @notice A window on `contractParamKeys` — same semantics as `tokenParamKeysPaged`.
    function contractParamKeysPaged(uint256 start, uint256 count)
        external
        view
        returns (bytes32[] memory keys, uint256 total);
}

dependencies/abx-contracts-3.0.0/src/interfaces/IDependencyRegistryV0.sol

// SPDX-License-Identifier: LGPL-3.0-only
// Created By: Art Blocks Inc.
//
// Trimmed for ABX to the two load-bearing reads used by code projects from Art Blocks'
// IDependencyRegistryV0
// (github.com/ArtBlocks/artblocks-contracts, contracts/interfaces/v0.8.x/
// IDependencyRegistryV0.sol). Signatures are byte-identical to AB's — the hard
// compatibility rule: any registry ABX consumers read from speaks this shape.

pragma solidity 0.8.28;

interface IDependencyRegistryV0 {
    /**
     * @notice Returns script for dependency type `dependencyNameAndVersion` at script index `index`.
     * @param dependencyNameAndVersion Dependency type to be queried.
     * @param index Index of script to be queried.
     * @dev Chunks are stored gzip'd + base64'd; consumers append them verbatim into
     *      `data:text/javascript;base64,` URIs — zero transcoding at read.
     */
    function getDependencyScript(bytes32 dependencyNameAndVersion, uint256 index)
        external
        view
        returns (string memory);

    /**
     * @notice Returns details for a given dependency type `dependencyNameAndVersion`.
     * @param dependencyNameAndVersion Name and version of dependency (i.e. "name@version") used to identify dependency.
     * @return nameAndVersion String representation of `dependencyNameAndVersion`.
     * @return licenseType License type for dependency
     * @return preferredCDN Preferred CDN URL for dependency
     * @return additionalCDNCount Count of additional CDN URLs for dependency
     * @return preferredRepository Preferred repository URL for dependency
     * @return additionalRepositoryCount Count of additional repository URLs for dependency
     * @return dependencyWebsite Project website URL for dependency
     * @return availableOnChain Whether dependency is available on chain
     * @return scriptCount Count of on-chain scripts for dependency
     */
    function getDependencyDetails(bytes32 dependencyNameAndVersion)
        external
        view
        returns (
            string memory nameAndVersion,
            string memory licenseType,
            string memory preferredCDN,
            uint24 additionalCDNCount,
            string memory preferredRepository,
            uint24 additionalRepositoryCount,
            string memory dependencyWebsite,
            bool availableOnChain,
            uint24 scriptCount
        );
}

dependencies/abx-contracts-3.0.0/src/uri/IAbxFieldRenderer.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.28;

/// @title IAbxFieldRenderer — the `renderer` representation's target: computed fields
/// @notice Where an `IAbxOnChainReader` returns *stored* bytes, a field renderer returns
///         *computed* bytes — one field's value derived from chain state (the token's params,
///         owner, anything readable): an in-chain SVG from a seed, an on-chain trait array,
///         even a full HTML document. The on-chain twin of the render node's
///         `(params) → output`. A field opts in via the `renderer` representation
///         (`value = abi.encode(address fieldRenderer)`); the off-chain resolver dispatches it
///         with an `eth_call`, the on-chain metadata renderer (v2+) with a staticcall.
/// @dev Determinism is scoped to chain state: same state → same bytes. Stateless per read;
///      never confined to canonical deployments — any contract satisfying this interface, per
///      field, per project. Collection-surface reads (no token, e.g. `contractURI`) pass
///      `tokenId = type(uint256).max`.
interface IAbxFieldRenderer {
    /// @notice Compute `field`'s value for `(token, tokenId)`.
    /// @return contentType MIME of `data` (e.g. `image/svg+xml`, `application/json`, `text/html`).
    /// @return data the field's finished bytes.
    function render(address token, uint256 tokenId, bytes32 field)
        external
        view
        returns (string memory contentType, bytes memory data);
}

dependencies/solady-0.1.26/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.
            }
        }
    }
}

dependencies/solady-0.1.26/src/utils/LibBytes.sol

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

/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
    /// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
    /// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
    struct BytesStorage {
        bytes32 _spacer;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The constant returned when the `search` is not found in the bytes.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  BYTE STORAGE OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sets the value of the bytes storage `$` to `s`.
    function set(BytesStorage storage $, bytes memory s) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(s)
            let packed := or(0xff, shl(8, n))
            for { let i := 0 } 1 {} {
                if iszero(gt(n, 0xfe)) {
                    i := 0x1f
                    packed := or(n, shl(8, mload(add(s, i))))
                    if iszero(gt(n, i)) { break }
                }
                let o := add(s, 0x20)
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    sstore(add(p, shr(5, i)), mload(add(o, i)))
                    i := add(i, 0x20)
                    if iszero(lt(i, n)) { break }
                }
                break
            }
            sstore($.slot, packed)
        }
    }

    /// @dev Sets the value of the bytes storage `$` to `s`.
    function setCalldata(BytesStorage storage $, bytes calldata s) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let packed := or(0xff, shl(8, s.length))
            for { let i := 0 } 1 {} {
                if iszero(gt(s.length, 0xfe)) {
                    i := 0x1f
                    packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
                    if iszero(gt(s.length, i)) { break }
                }
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
                    i := add(i, 0x20)
                    if iszero(lt(i, s.length)) { break }
                }
                break
            }
            sstore($.slot, packed)
        }
    }

    /// @dev Sets the value of the bytes storage `$` to the empty bytes.
    function clear(BytesStorage storage $) internal {
        delete $._spacer;
    }

    /// @dev Returns whether the value stored is `$` is the empty bytes "".
    function isEmpty(BytesStorage storage $) internal view returns (bool) {
        return uint256($._spacer) & 0xff == uint256(0);
    }

    /// @dev Returns the length of the value stored in `$`.
    function length(BytesStorage storage $) internal view returns (uint256 result) {
        result = uint256($._spacer);
        /// @solidity memory-safe-assembly
        assembly {
            let n := and(0xff, result)
            result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
        }
    }

    /// @dev Returns the value stored in `$`.
    function get(BytesStorage storage $) internal view returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let o := add(result, 0x20)
            let packed := sload($.slot)
            let n := shr(8, packed)
            for { let i := 0 } 1 {} {
                if iszero(eq(or(packed, 0xff), packed)) {
                    mstore(o, packed)
                    n := and(0xff, packed)
                    i := 0x1f
                    if iszero(gt(n, i)) { break }
                }
                mstore(0x00, $.slot)
                for { let p := keccak256(0x00, 0x20) } 1 {} {
                    mstore(add(o, i), sload(add(p, shr(5, i))))
                    i := add(i, 0x20)
                    if iszero(lt(i, n)) { break }
                }
                break
            }
            mstore(result, n) // Store the length of the memory.
            mstore(add(o, n), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
        }
    }

    /// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
    function uint8At(BytesStorage storage $, uint256 i) internal view returns (uint8 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for { let packed := sload($.slot) } 1 {} {
                if iszero(eq(or(packed, 0xff), packed)) {
                    if iszero(gt(i, 0x1e)) {
                        result := byte(i, packed)
                        break
                    }
                    if iszero(gt(i, and(0xff, packed))) {
                        mstore(0x00, $.slot)
                        let j := sub(i, 0x1f)
                        result := byte(and(j, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, j))))
                    }
                    break
                }
                if iszero(gt(i, shr(8, packed))) {
                    mstore(0x00, $.slot)
                    result := byte(and(i, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, i))))
                }
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      BYTES OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
    function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let needleLen := mload(needle)
            let replacementLen := mload(replacement)
            let d := sub(result, subject) // Memory difference.
            let i := add(subject, 0x20) // Subject bytes pointer.
            mstore(0x00, add(i, mload(subject))) // End of subject.
            if iszero(gt(needleLen, mload(subject))) {
                let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
                let h := 0 // The hash of `needle`.
                if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
                let s := mload(add(needle, 0x20))
                for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
                    let t := mload(i)
                    // Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(i, needleLen), h)) {
                                mstore(add(i, d), t)
                                i := add(i, 1)
                                if iszero(lt(i, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        // Copy the `replacement` one word at a time.
                        for { let j := 0 } 1 {} {
                            mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
                            j := add(j, 0x20)
                            if iszero(lt(j, replacementLen)) { break }
                        }
                        d := sub(add(d, replacementLen), needleLen)
                        if needleLen {
                            i := add(i, needleLen)
                            if iszero(lt(i, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    mstore(add(i, d), t)
                    i := add(i, 1)
                    if iszero(lt(i, subjectSearchEnd)) { break }
                }
            }
            let end := mload(0x00)
            let n := add(sub(d, add(result, 0x20)), end)
            // Copy the rest of the bytes one word at a time.
            for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
            let o := add(i, d)
            mstore(o, 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(bytes memory subject, bytes memory needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0) // Initialize to `NOT_FOUND`.
            for { let subjectLen := mload(subject) } 1 {} {
                if iszero(mload(needle)) {
                    result := from
                    if iszero(gt(from, subjectLen)) { break }
                    result := subjectLen
                    break
                }
                let needleLen := mload(needle)
                let subjectStart := add(subject, 0x20)

                subject := add(subjectStart, from)
                let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
                let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
                let s := mload(add(needle, 0x20))

                if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }

                if iszero(lt(needleLen, 0x20)) {
                    for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
                        if iszero(shr(m, xor(mload(subject), s))) {
                            if eq(keccak256(subject, needleLen), h) {
                                result := sub(subject, subjectStart)
                                break
                            }
                        }
                        subject := add(subject, 1)
                        if iszero(lt(subject, end)) { break }
                    }
                    break
                }
                for {} 1 {} {
                    if iszero(shr(m, xor(mload(subject), s))) {
                        result := sub(subject, subjectStart)
                        break
                    }
                    subject := add(subject, 1)
                    if iszero(lt(subject, end)) { break }
                }
                break
            }
        }
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right, starting from `from`. Optimized for byte needles.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOfByte(bytes memory subject, bytes1 needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := not(0) // Initialize to `NOT_FOUND`.
            if gt(mload(subject), from) {
                let start := add(subject, 0x20)
                let end := add(start, mload(subject))
                let m := div(not(0), 255) // `0x0101 ... `.
                let h := mul(byte(0, needle), m) // Replicating needle mask.
                m := not(shl(7, m)) // `0x7f7f ... `.
                for { let i := add(start, from) } 1 {} {
                    let c := xor(mload(i), h) // Load 32-byte chunk and xor with mask.
                    c := not(or(or(add(and(c, m), m), c), m)) // Each needle byte will be `0x80`.
                    if c {
                        c := and(not(shr(shl(3, sub(end, i)), not(0))), c) // Truncate bytes past the end.
                        if c {
                            let r := shl(7, lt(0x8421084210842108cc6318c6db6d54be, c)) // Save bytecode.
                            r := or(shl(6, lt(0xffffffffffffffff, shr(r, c))), r)
                            // forgefmt: disable-next-item
                            result := add(sub(i, start), shr(3, xor(byte(and(0x1f, shr(byte(24,
                                mul(0x02040810204081, shr(r, c))), 0x8421084210842108cc6318c6db6d54be)),
                                0xc0c8c8d0c8e8d0d8c8e8e0e8d0d8e0f0c8d0e8d0e0e0d8f0d0d0e0d8f8f8f8f8), r)))
                            break
                        }
                    }
                    i := add(i, 0x20)
                    if iszero(lt(i, end)) { break }
                }
            }
        }
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right. Optimized for byte needles.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOfByte(bytes memory subject, bytes1 needle)
        internal
        pure
        returns (uint256 result)
    {
        return indexOfByte(subject, needle, 0);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
        return indexOf(subject, needle, 0);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
        internal
        pure
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                result := not(0) // Initialize to `NOT_FOUND`.
                let needleLen := mload(needle)
                if gt(needleLen, mload(subject)) { break }
                let w := result

                let fromMax := sub(mload(subject), needleLen)
                if iszero(gt(fromMax, from)) { from := fromMax }

                let end := add(add(subject, 0x20), w)
                subject := add(add(subject, 0x20), from)
                if iszero(gt(subject, end)) { break }
                // As this function is not too often used,
                // we shall simply use keccak256 for smaller bytecode size.
                for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
                    if eq(keccak256(subject, needleLen), h) {
                        result := sub(subject, add(end, 1))
                        break
                    }
                    subject := add(subject, w) // `sub(subject, 1)`.
                    if iszero(gt(subject, end)) { break }
                }
                break
            }
        }
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (uint256)
    {
        return lastIndexOf(subject, needle, type(uint256).max);
    }

    /// @dev Returns true if `needle` is found in `subject`, false otherwise.
    function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
        return indexOf(subject, needle) != NOT_FOUND;
    }

    /// @dev Returns whether `subject` starts with `needle`.
    function startsWith(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(needle)
            // Just using keccak256 directly is actually cheaper.
            let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
            result := lt(gt(n, mload(subject)), t)
        }
    }

    /// @dev Returns whether `subject` ends with `needle`.
    function endsWith(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(needle)
            let notInRange := gt(n, mload(subject))
            // `subject + 0x20 + max(subject.length - needle.length, 0)`.
            let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
            // Just using keccak256 directly is actually cheaper.
            result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
        }
    }

    /// @dev Returns `subject` repeated `times`.
    function repeat(bytes memory subject, uint256 times)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := mload(subject) // Subject length.
            if iszero(or(iszero(times), iszero(l))) {
                result := mload(0x40)
                subject := add(subject, 0x20)
                let o := add(result, 0x20)
                for {} 1 {} {
                    // Copy the `subject` one word at a time.
                    for { let j := 0 } 1 {} {
                        mstore(add(o, j), mload(add(subject, j)))
                        j := add(j, 0x20)
                        if iszero(lt(j, l)) { break }
                    }
                    o := add(o, l)
                    times := sub(times, 1)
                    if iszero(times) { break }
                }
                mstore(o, 0) // Zeroize the slot after the bytes.
                mstore(0x40, add(o, 0x20)) // Allocate memory.
                mstore(result, sub(o, add(result, 0x20))) // Store the length.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
    /// `start` and `end` are byte offsets.
    function slice(bytes memory subject, uint256 start, uint256 end)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := mload(subject) // Subject length.
            if iszero(gt(l, end)) { end := l }
            if iszero(gt(l, start)) { start := l }
            if lt(start, end) {
                result := mload(0x40)
                let n := sub(end, start)
                let i := add(subject, start)
                let w := not(0x1f)
                // Copy the `subject` one word at a time, backwards.
                for { let j := and(add(n, 0x1f), w) } 1 {} {
                    mstore(add(result, j), mload(add(i, j)))
                    j := add(j, w) // `sub(j, 0x20)`.
                    if iszero(j) { break }
                }
                let o := add(add(result, 0x20), n)
                mstore(o, 0) // Zeroize the slot after the bytes.
                mstore(0x40, add(o, 0x20)) // Allocate memory.
                mstore(result, n) // Store the length.
            }
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
    /// `start` is a byte offset.
    function slice(bytes memory subject, uint256 start)
        internal
        pure
        returns (bytes memory result)
    {
        result = slice(subject, start, type(uint256).max);
    }

    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
    /// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
    function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
            start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
            result.offset := add(subject.offset, start)
            result.length := mul(lt(start, end), sub(end, start))
        }
    }

    /// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
    /// `start` is a byte offset. Faster than Solidity's native slicing.
    function sliceCalldata(bytes calldata subject, uint256 start)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
            result.offset := add(subject.offset, start)
            result.length := mul(lt(start, subject.length), sub(subject.length, start))
        }
    }

    /// @dev Reduces the size of `subject` to `n`.
    /// If `n` is greater than the size of `subject`, this will be a no-op.
    function truncate(bytes memory subject, uint256 n)
        internal
        pure
        returns (bytes memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := subject
            mstore(mul(lt(n, mload(result)), result), n)
        }
    }

    /// @dev Returns a copy of `subject`, with the length reduced to `n`.
    /// If `n` is greater than the size of `subject`, this will be a no-op.
    function truncatedCalldata(bytes calldata subject, uint256 n)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result.offset := subject.offset
            result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
        }
    }

    /// @dev Returns all the indices of `needle` in `subject`.
    /// The indices are byte offsets.
    function indicesOf(bytes memory subject, bytes memory needle)
        internal
        pure
        returns (uint256[] memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let searchLen := mload(needle)
            if iszero(gt(searchLen, mload(subject))) {
                result := mload(0x40)
                let i := add(subject, 0x20)
                let o := add(result, 0x20)
                let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
                let h := 0 // The hash of `needle`.
                if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
                let s := mload(add(needle, 0x20))
                for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
                    let t := mload(i)
                    // Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
                    if iszero(shr(m, xor(t, s))) {
                        if h {
                            if iszero(eq(keccak256(i, searchLen), h)) {
                                i := add(i, 1)
                                if iszero(lt(i, subjectSearchEnd)) { break }
                                continue
                            }
                        }
                        mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
                        o := add(o, 0x20)
                        i := add(i, searchLen) // Advance `i` by `searchLen`.
                        if searchLen {
                            if iszero(lt(i, subjectSearchEnd)) { break }
                            continue
                        }
                    }
                    i := add(i, 1)
                    if iszero(lt(i, subjectSearchEnd)) { break }
                }
                mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
                // Allocate memory for result.
                // We allocate one more word, so this array can be recycled for {split}.
                mstore(0x40, add(o, 0x20))
            }
        }
    }

    /// @dev Returns an arrays of bytess based on the `delimiter` inside of the `subject` bytes.
    function split(bytes memory subject, bytes memory delimiter)
        internal
        pure
        returns (bytes[] memory result)
    {
        uint256[] memory indices = indicesOf(subject, delimiter);
        /// @solidity memory-safe-assembly
        assembly {
            let w := not(0x1f)
            let indexPtr := add(indices, 0x20)
            let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
            mstore(add(indicesEnd, w), mload(subject))
            mstore(indices, add(mload(indices), 1))
            for { let prevIndex := 0 } 1 {} {
                let index := mload(indexPtr)
                mstore(indexPtr, 0x60)
                if iszero(eq(index, prevIndex)) {
                    let element := mload(0x40)
                    let l := sub(index, prevIndex)
                    mstore(element, l) // Store the length of the element.
                    // Copy the `subject` one word at a time, backwards.
                    for { let o := and(add(l, 0x1f), w) } 1 {} {
                        mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
                        o := add(o, w) // `sub(o, 0x20)`.
                        if iszero(o) { break }
                    }
                    mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
                    // Allocate memory for the length and the bytes, rounded up to a multiple of 32.
                    mstore(0x40, add(element, and(add(l, 0x3f), w)))
                    mstore(indexPtr, element) // Store the `element` into the array.
                }
                prevIndex := add(index, mload(delimiter))
                indexPtr := add(indexPtr, 0x20)
                if iszero(lt(indexPtr, indicesEnd)) { break }
            }
            result := indices
            if iszero(mload(delimiter)) {
                result := add(indices, 0x20)
                mstore(result, sub(mload(indices), 2))
            }
        }
    }

    /// @dev Returns a concatenated bytes of `a` and `b`.
    /// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
    function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let w := not(0x1f)
            let aLen := mload(a)
            // Copy `a` one word at a time, backwards.
            for { let o := and(add(aLen, 0x20), w) } 1 {} {
                mstore(add(result, o), mload(add(a, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let bLen := mload(b)
            let output := add(result, aLen)
            // Copy `b` one word at a time, backwards.
            for { let o := and(add(bLen, 0x20), w) } 1 {} {
                mstore(add(output, o), mload(add(b, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            let totalLen := add(aLen, bLen)
            let last := add(add(result, 0x20), totalLen)
            mstore(last, 0) // Zeroize the slot after the bytes.
            mstore(result, totalLen) // Store the length.
            mstore(0x40, add(last, 0x20)) // Allocate memory.
        }
    }

    /// @dev Returns whether `a` equals `b`.
    function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
        }
    }

    /// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
    function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // These should be evaluated on compile time, as far as possible.
            let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
            let x := not(or(m, or(b, add(m, and(b, m)))))
            let r := shl(7, iszero(iszero(shr(128, x))))
            r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
                xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
        }
    }

    /// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
    /// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
    function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let aLen := mload(a)
            let bLen := mload(b)
            let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
            if n {
                for { let i := 0x20 } 1 {} {
                    let x := mload(add(a, i))
                    let y := mload(add(b, i))
                    if iszero(or(xor(x, y), eq(i, n))) {
                        i := add(i, 0x20)
                        continue
                    }
                    result := sub(gt(x, y), lt(x, y))
                    break
                }
            }
            // forgefmt: disable-next-item
            if iszero(result) {
                let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
                let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
                let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
                result := sub(gt(x, y), lt(x, y))
                if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
            }
        }
    }

    /// @dev Directly returns `a` without copying.
    function directReturn(bytes memory a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            // Assumes that the bytes does not start from the scratch space.
            let retStart := sub(a, 0x20)
            let retUnpaddedSize := add(mload(a), 0x40)
            // Right pad with zeroes. Just in case the bytes is produced
            // by a method that doesn't zero right pad.
            mstore(add(retStart, retUnpaddedSize), 0)
            mstore(retStart, 0x20) // Store the return offset.
            // End the transaction, returning the bytes.
            return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
        }
    }

    /// @dev Directly returns `a` with minimal copying.
    function directReturn(bytes[] memory a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(a) // `a.length`.
            let o := add(a, 0x20) // Start of elements in `a`.
            let u := a // Highest memory slot.
            let w := not(0x1f)
            for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
                let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
                let s := mload(c) // `a[i]`.
                let l := mload(s) // `a[i].length`.
                let r := and(l, 0x1f) // `a[i].length % 32`.
                let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
                // If `s` comes before `o`, or `s` is not zero right padded.
                if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
                    let m := mload(0x40)
                    mstore(m, l) // Copy `a[i].length`.
                    for {} 1 {} {
                        mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
                        z := add(z, w) // `sub(z, 0x20)`.
                        if iszero(z) { break }
                    }
                    let e := add(add(m, 0x20), l)
                    mstore(e, 0) // Zeroize the slot after the copied bytes.
                    mstore(0x40, add(e, 0x20)) // Allocate memory.
                    s := m
                }
                mstore(c, sub(s, o)) // Convert to calldata offset.
                let t := add(l, add(s, 0x20))
                if iszero(lt(t, u)) { u := t }
            }
            let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
            mstore(retStart, 0x20) // Store the return offset.
            return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
        }
    }

    /// @dev Returns the word at `offset`, without any bounds checks.
    function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(a, 0x20), offset))
        }
    }

    /// @dev Returns the word at `offset`, without any bounds checks.
    function loadCalldata(bytes calldata a, uint256 offset)
        internal
        pure
        returns (bytes32 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := calldataload(add(a.offset, offset))
        }
    }

    /// @dev Returns a slice representing a static struct in the calldata. Performs bounds checks.
    function staticStructInCalldata(bytes calldata a, uint256 offset)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := sub(a.length, 0x20)
            result.offset := add(a.offset, offset)
            result.length := sub(a.length, offset)
            if or(shr(64, or(l, a.offset)), gt(offset, l)) { revert(l, 0x00) }
        }
    }

    /// @dev Returns a slice representing a dynamic struct in the calldata. Performs bounds checks.
    function dynamicStructInCalldata(bytes calldata a, uint256 offset)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := sub(a.length, 0x20)
            let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
            result.offset := add(a.offset, s)
            result.length := sub(a.length, s)
            if or(shr(64, or(s, or(l, a.offset))), gt(offset, l)) { revert(l, 0x00) }
        }
    }

    /// @dev Returns bytes in calldata. Performs bounds checks.
    function bytesInCalldata(bytes calldata a, uint256 offset)
        internal
        pure
        returns (bytes calldata result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let l := sub(a.length, 0x20)
            let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
            result.offset := add(add(a.offset, s), 0x20)
            result.length := calldataload(add(a.offset, s))
            // forgefmt: disable-next-item
            if or(shr(64, or(result.length, or(s, or(l, a.offset)))),
                or(gt(add(s, result.length), l), gt(offset, l))) { revert(l, 0x00) }
        }
    }

    /// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
    function checkInCalldata(bytes calldata x, bytes calldata a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            if or(
                or(lt(x.offset, a.offset), gt(add(x.offset, x.length), add(a.length, a.offset))),
                shr(64, or(x.length, x.offset))
            ) { revert(0x00, 0x00) }
        }
    }

    /// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
    function checkInCalldata(bytes[] calldata x, bytes calldata a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            let e := sub(add(a.length, a.offset), 0x20)
            if or(lt(x.offset, a.offset), shr(64, x.offset)) { revert(0x00, 0x00) }
            for { let i := 0 } iszero(eq(x.length, i)) { i := add(i, 1) } {
                let o := calldataload(add(x.offset, shl(5, i)))
                let t := add(o, x.offset)
                let l := calldataload(t)
                if or(shr(64, or(l, o)), gt(add(t, l), e)) { revert(0x00, 0x00) }
            }
        }
    }

    /// @dev Returns empty calldata bytes. For silencing the compiler.
    function emptyCalldata() internal pure returns (bytes calldata result) {
        /// @solidity memory-safe-assembly
        assembly {
            result.length := 0
        }
    }

    /// @dev Returns the most significant 20 bytes as an address.
    function msbToAddress(bytes32 x) internal pure returns (address) {
        return address(bytes20(x));
    }

    /// @dev Returns the least significant 20 bytes as an address.
    function lsbToAddress(bytes32 x) internal pure returns (address) {
        return address(uint160(uint256(x)));
    }
}

dependencies/solady-0.1.26/src/utils/LibString.sol

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

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

/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Goated string storage struct that totally MOGs, no cap, fr.
    /// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
    /// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
    struct StringStorage {
        bytes32 _spacer;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The length of the output is too small to contain all the hex digits.
    error HexLengthInsufficient();

    /// @dev The length of the string is more than 32 bytes.
    error TooBigForSmallString();

    /// @dev The input string must be a 7-bit ASCII.
    error StringNot7BitASCII();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The constant returned when the `search` is not found in the string.
    uint256 internal constant NOT_FOUND = type(uint256).max;

    /// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;

    /// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;

    /// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
    uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;

    /// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
    uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;

    /// @dev Lookup for '0123456789'.
    uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;

    /// @dev Lookup for '0123456789abcdefABCDEF'.
    uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;

    /// @dev Lookup for '01234567'.
    uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;

    /// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
    uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;

    /// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
    uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;

    /// @dev Lookup for ' \t\n\r\x0b\x0c'.
    uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                 STRING STORAGE OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sets the value of the string storage `$` to `s`.
    function set(StringStorage storage $, string memory s) internal {
        LibBytes.set(bytesStorage($), bytes(s));
    }

    /// @dev Sets the value of the string storage `$` to `s`.
    function setCalldata(StringStorage storage $, string calldata s) internal {
        LibBytes.setCalldata(bytesStorage($), bytes(s));
    }

    /// @dev Sets the value of the string storage `$` to the empty string.
    function clear(StringStorage storage $) internal {
        delete $._spacer;
    }

    /// @dev Returns whether the value stored is `$` is the empty string "".
    function isEmpty(StringStorage storage $) internal view returns (bool) {
        return uint256($._spacer) & 0xff == uint256(0);
    }

    /// @dev Returns the length of the value stored in `$`.
    function length(StringStorage storage $) internal view returns (uint256) {
        return LibBytes.length(bytesStorage($));
    }

    /// @dev Returns the value stored in `$`.
    function get(StringStorage storage $) internal view returns (string memory) {
        return string(LibBytes.get(bytesStorage($)));
    }

    /// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
    function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
        return LibBytes.uint8At(bytesStorage($), i);
    }

    /// @dev Helper to cast `$` to a `BytesStorage`.
    function bytesStorage(StringStorage storage $)
        internal
        pure
        returns (LibBytes.BytesStorage storage casted)
    {
        /// @solidity memory-safe-assembly
        assembly {
            casted.slot := $.slot
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     DECIMAL OPERATIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(uint256 value) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            // The maximum value of a uint256 contains 78 digits (1 byte per digit), but
            // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
            // We will need 1 word for the trailing zeros padding, 1 word for the length,
            // and 3 words for a maximum of 78 digits.
            result := add(mload(0x40), 0x80)
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // Cache the end of the memory to calculate the length later.
            let w := not(0) // Tsk.
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let temp := value } 1 {} {
                result := add(result, w) // `sub(result, 1)`.
                // Store the character to the pointer.
                // The ASCII index of the '0' character is 48.
                mstore8(result, add(48, mod(temp, 10)))
                temp := div(temp, 10) // Keep dividing `temp` until zero.
                if iszero(temp) { break }
            }
            let n := sub(end, result)
            result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the base 10 decimal representation of `value`.
    function toString(int256 value) internal pure returns (string memory result) {
        if (value >= 0) return toString(uint256(value));
        unchecked {
            result = toString(~uint256(value) + 1);
        }
        /// @solidity memory-safe-assembly
        assembly {
            // We still have some spare memory space on the left,
            // as we have allocated 3 words (96 bytes) for up to 78 digits.
            let n := mload(result) // Load the string length.
            mstore(result, 0x2d) // Store the '-' character.
            result := sub(result, 1) // Move back the string pointer by a byte.
            mstore(result, add(n, 1)) // Update the string length.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   HEXADECIMAL OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `byteCount` bytes.
    /// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `byteCount * 2 + 2` bytes.
    /// Reverts if `byteCount` is too small for the output to contain all the digits.
    function toHexString(uint256 value, uint256 byteCount)
        internal
        pure
        returns (string memory result)
    {
        result = toHexStringNoPrefix(value, byteCount);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`,
    /// left-padded to an input length of `byteCount` bytes.
    /// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
    /// giving a total length of `byteCount * 2` bytes.
    /// Reverts if `byteCount` is too small for the output to contain all the digits.
    function toHexStringNoPrefix(uint256 value, uint256 byteCount)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
            // for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
            // We add 0x20 to the total and round down to a multiple of 0x20.
            // (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
            result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // Cache the end to calculate the length later.
            // Store "0123456789abcdef" in scratch space.
            mstore(0x0f, 0x30313233343536373839616263646566)

            let start := sub(result, add(byteCount, byteCount))
            let w := not(1) // Tsk.
            let temp := value
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for {} 1 {} {
                result := add(result, w) // `sub(result, 2)`.
                mstore8(add(result, 1), mload(and(temp, 15)))
                mstore8(result, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(xor(result, start)) { break }
            }
            if temp {
                mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
                revert(0x1c, 0x04)
            }
            let n := sub(end, result)
            result := sub(result, 0x20)
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
    /// As address are 20 bytes long, the output will left-padded to have
    /// a length of `20 * 2 + 2` bytes.
    function toHexString(uint256 value) internal pure returns (string memory result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x".
    /// The output excludes leading "0" from the `toHexString` output.
    /// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
    function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
            let n := add(mload(result), 2) // Compute the length.
            mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
            result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
            mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output excludes leading "0" from the `toHexStringNoPrefix` output.
    /// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
    function toMinimalHexStringNoPrefix(uint256 value)
        internal
        pure
        returns (string memory result)
    {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
            let n := mload(result) // Get the length.
            result := add(result, o) // Move the pointer, accounting for leading zero.
            mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is encoded using 2 hexadecimal digits per byte.
    /// As address are 20 bytes long, the output will left-padded to have
    /// a length of `20 * 2` bytes.
    function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
            // 0x02 bytes for the prefix, and 0x40 bytes for the digits.
            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
            result := add(mload(0x40), 0x80)
            mstore(0x40, add(result, 0x20)) // Allocate memory.
            mstore(result, 0) // Zeroize the slot after the string.

            let end := result // Cache the end to calculate the length later.
            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.

            let w := not(1) // Tsk.
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let temp := value } 1 {} {
                result := add(result, w) // `sub(result, 2)`.
                mstore8(add(result, 1), mload(and(temp, 15)))
                mstore8(result, mload(and(shr(4, temp), 15)))
                temp := shr(8, temp)
                if iszero(temp) { break }
            }
            let n := sub(end, result)
            result := sub(result, 0x20)
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
    /// and the alphabets are capitalized conditionally according to
    /// https://eips.ethereum.org/EIPS/eip-55
    function toHexStringChecksummed(address value) internal pure returns (string memory result) {
        result = toHexString(value);
        /// @solidity memory-safe-assembly
        assembly {
            let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
            let o := add(result, 0x22)
            let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
            let t := shl(240, 136) // `0b10001000 << 240`
            for { let i := 0 } 1 {} {
                mstore(add(i, i), mul(t, byte(i, hashed)))
                i := add(i, 1)
                if eq(i, 20) { break }
            }
            mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
            o := add(o, 0x20)
            mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
    function toHexString(address value) internal pure returns (string memory result) {
        result = toHexStringNoPrefix(value);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hexadecimal representation of `value`.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            // Allocate memory.
            // We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
            // 0x02 bytes for the prefix, and 0x28 bytes for the digits.
            // The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
            mstore(0x40, add(result, 0x80))
            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.

            result := add(result, 2)
            mstore(result, 40) // Store the length.
            let o := add(result, 0x20)
            mstore(add(o, 40), 0) // Zeroize the slot after the string.
            value := shl(96, value)
            // We write the string from rightmost digit to leftmost digit.
            // The following is essentially a do-while loop that also handles the zero case.
            for { let i := 0 } 1 {} {
                let p := add(o, add(i, i))
                let temp := byte(i, value)
                mstore8(add(p, 1), mload(and(temp, 15)))
                mstore8(p, mload(shr(4, temp)))
                i := add(i, 1)
                if eq(i, 20) { break }
            }
        }
    }

    /// @dev Returns the hex encoded string from the raw bytes.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexString(bytes memory raw) internal pure returns (string memory result) {
        result = toHexStringNoPrefix(raw);
        /// @solidity memory-safe-assembly
        assembly {
            let n := add(mload(result), 2) // Compute the length.
            mstore(result, 0x3078) // Store the "0x" prefix.
            result := sub(result, 2) // Move the pointer.
            mstore(result, n) // Store the length.
        }
    }

    /// @dev Returns the hex encoded string from the raw bytes.
    /// The output is encoded using 2 hexadecimal digits per byte.
    function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(raw)
            result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
            mstore(result, add(n, n)) // Store the length of the output.

            mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
            let o := add(result, 0x20)
            let end := add(raw, n)
            for {} iszero(eq(raw, end)) {} {
                raw := add(raw, 1)
                mstore8(add(o, 1), mload(and(mload(raw), 15)))
                mstore8(o, mload(and(shr(4, mload(raw)), 15)))
                o := add(o, 2)
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RUNE STRING OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the number of UTF characters in the string.
    function runeCount(string memory s) internal pure returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if mload(s) {
                mstore(0x00, div(not(0), 255))
                mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
                let o := add(s, 0x20)
                let end := add(o, mload(s))
                for { result := 1 } 1 { result := add(result, 1) } {
                    o := add(o, byte(0, mload(shr(250, mload(o)))))
                    if iszero(lt(o, end)) { break }
                }
            }
        }
    }

    /// @dev Returns if this string is a 7-bit ASCII string.
    /// (i.e. all characters codes are in [0..127])
    function is7BitASCII(string memory s) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 1
            let mask := shl(7, div(not(0), 255))
            let n := mload(s)
            if n {
                let o := add(s, 0x20)
                let end := add(o, n)
                let last := mload(end)
                mstore(end, 0)
                for {} 1 {} {
                    if and(mask, mload(o)) {
                        result := 0
                        break
                    }
                    o := add(o, 0x20)
                    if iszero(lt(o, end)) { break }
                }
                mstore(end, last)
            }
        }
    }

    /// @dev Returns if this string is a 7-bit ASCII string,
    /// AND all characters are in the `allowed` lookup.
    /// Note: If `s` is empty, returns true regardless of `allowed`.
    function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 1
            if mload(s) {
                let allowed_ := shr(128, shl(128, allowed))
                let o := add(s, 0x20)
                for { let end := add(o, mload(s)) } 1 {} {
                    result := and(result, shr(byte(0, mload(o)), allowed_))
                    o := add(o, 1)
                    if iszero(and(result, lt(o, end))) { break }
                }
            }
        }
    }

    /// @dev Converts the bytes in the 7-bit ASCII string `s` to
    /// an allowed lookup for use in `is7BitASCII(s, allowed)`.
    /// To save runtime gas, you can cache the result in an immutable variable.
    function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
        /// @solidity memory-safe-assembly
        assembly {
            if mload(s) {
                let o := add(s, 0x20)
                for { let end := add(o, mload(s)) } 1 {} {
                    result := or(result, shl(byte(0, mload(o)), 1))
                    o := add(o, 1)
                    if iszero(lt(o, end)) { break }
                }
                if shr(128, result) {
                    mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   BYTE STRING OPERATIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // For performance and bytecode compactness, byte string operations are restricted
    // to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
    // Usage of byte string operations on charsets with runes spanning two or more bytes
    // can lead to undefined behavior.

    /// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
    function replace(string memory subject, string memory needle, string memory replacement)
        internal
        pure
        returns (string memory)
    {
        return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(string memory subject, string memory needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.indexOf(bytes(subject), bytes(needle), from);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from left to right.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
        return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left, starting from `from`.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(string memory subject, string memory needle, uint256 from)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
    }

    /// @dev Returns the byte index of the first location of `needle` in `subject`,
    /// needleing from right to left.
    /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
    function lastIndexOf(string memory subject, string memory needle)
        internal
        pure
        returns (uint256)
    {
        return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
    }

    /// @dev Returns true if `needle` is found in `subject`, false otherwise.
    function contains(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.contains(bytes(subject), bytes(needle));
    }

    /// @dev Returns whether `subject` starts with `needle`.
    function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.startsWith(bytes(subject), bytes(needle));
    }

    /// @dev Returns whether `subject` ends with `needle`.
    function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
        return LibBytes.endsWith(bytes(subject), bytes(needle));
    }

    /// @dev Returns `subject` repeated `times`.
    function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
        return string(LibBytes.repeat(bytes(subject), times));
    }

    /// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
    /// `start` and `end` are byte offsets.
    function slice(string memory subject, uint256 start, uint256 end)
        internal
        pure
        returns (string memory)
    {
        return string(LibBytes.slice(bytes(subject), start, end));
    }

    /// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
    /// `start` is a byte offset.
    function slice(string memory subject, uint256 start) internal pure returns (string memory) {
        return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
    }

    /// @dev Returns all the indices of `needle` in `subject`.
    /// The indices are byte offsets.
    function indicesOf(string memory subject, string memory needle)
        internal
        pure
        returns (uint256[] memory)
    {
        return LibBytes.indicesOf(bytes(subject), bytes(needle));
    }

    /// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
    function split(string memory subject, string memory delimiter)
        internal
        pure
        returns (string[] memory result)
    {
        bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
        /// @solidity memory-safe-assembly
        assembly {
            result := a
        }
    }

    /// @dev Returns a concatenated string of `a` and `b`.
    /// Cheaper than `string.concat()` and does not de-align the free memory pointer.
    function concat(string memory a, string memory b) internal pure returns (string memory) {
        return string(LibBytes.concat(bytes(a), bytes(b)));
    }

    /// @dev Returns a copy of the string in either lowercase or UPPERCASE.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function toCase(string memory subject, bool toUpper)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(subject)
            if n {
                result := mload(0x40)
                let o := add(result, 0x20)
                let d := sub(subject, result)
                let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
                for { let end := add(o, n) } 1 {} {
                    let b := byte(0, mload(add(d, o)))
                    mstore8(o, xor(and(shr(b, flags), 0x20), b))
                    o := add(o, 1)
                    if eq(o, end) { break }
                }
                mstore(result, n) // Store the length.
                mstore(o, 0) // Zeroize the slot after the string.
                mstore(0x40, add(o, 0x20)) // Allocate memory.
            }
        }
    }

    /// @dev Returns a string from a small bytes32 string.
    /// `s` must be null-terminated, or behavior will be undefined.
    function fromSmallString(bytes32 s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let n := 0
            for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
            mstore(result, n) // Store the length.
            let o := add(result, 0x20)
            mstore(o, s) // Store the bytes of the string.
            mstore(add(o, n), 0) // Zeroize the slot after the string.
            mstore(0x40, add(result, 0x40)) // Allocate memory.
        }
    }

    /// @dev Returns the small string, with all bytes after the first null byte zeroized.
    function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
            mstore(0x00, s)
            mstore(result, 0x00)
            result := mload(0x00)
        }
    }

    /// @dev Returns the string as a normalized null-terminated small string.
    function toSmallString(string memory s) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(s)
            if iszero(lt(result, 33)) {
                mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
                revert(0x1c, 0x04)
            }
            result := shl(shl(3, sub(32, result)), mload(add(s, result)))
        }
    }

    /// @dev Returns a lowercased copy of the string.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function lower(string memory subject) internal pure returns (string memory result) {
        result = toCase(subject, false);
    }

    /// @dev Returns an UPPERCASED copy of the string.
    /// WARNING! This function is only compatible with 7-bit ASCII strings.
    function upper(string memory subject) internal pure returns (string memory result) {
        result = toCase(subject, true);
    }

    /// @dev Escapes the string to be used within HTML tags.
    function escapeHTML(string memory s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let end := add(s, mload(s))
            let o := add(result, 0x20)
            // Store the bytes of the packed offsets and strides into the scratch space.
            // `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
            mstore(0x1f, 0x900094)
            mstore(0x08, 0xc0000000a6ab)
            // Store "&quot;&amp;&#39;&lt;&gt;" into the scratch space.
            mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
            for {} iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                // Not in `["\"","'","&","<",">"]`.
                if iszero(and(shl(c, 1), 0x500000c400000000)) {
                    mstore8(o, c)
                    o := add(o, 1)
                    continue
                }
                let t := shr(248, mload(c))
                mstore(o, mload(and(t, 0x1f)))
                o := add(o, shr(5, t))
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
        }
    }

    /// @dev Escapes the string to be used within double-quotes in a JSON.
    /// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
    function escapeJSON(string memory s, bool addDoubleQuotes)
        internal
        pure
        returns (string memory result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            let o := add(result, 0x20)
            if addDoubleQuotes {
                mstore8(o, 34)
                o := add(1, o)
            }
            // Store "\\u0000" in scratch space.
            // Store "0123456789abcdef" in scratch space.
            // Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
            // into the scratch space.
            mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
            // Bitmask for detecting `["\"","\\"]`.
            let e := or(shl(0x22, 1), shl(0x5c, 1))
            for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                if iszero(lt(c, 0x20)) {
                    if iszero(and(shl(c, 1), e)) {
                        // Not in `["\"","\\"]`.
                        mstore8(o, c)
                        o := add(o, 1)
                        continue
                    }
                    mstore8(o, 0x5c) // "\\".
                    mstore8(add(o, 1), c)
                    o := add(o, 2)
                    continue
                }
                if iszero(and(shl(c, 1), 0x3700)) {
                    // Not in `["\b","\t","\n","\f","\d"]`.
                    mstore8(0x1d, mload(shr(4, c))) // Hex value.
                    mstore8(0x1e, mload(and(c, 15))) // Hex value.
                    mstore(o, mload(0x19)) // "\\u00XX".
                    o := add(o, 6)
                    continue
                }
                mstore8(o, 0x5c) // "\\".
                mstore8(add(o, 1), mload(add(c, 8)))
                o := add(o, 2)
            }
            if addDoubleQuotes {
                mstore8(o, 34)
                o := add(1, o)
            }
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
        }
    }

    /// @dev Escapes the string to be used within double-quotes in a JSON.
    function escapeJSON(string memory s) internal pure returns (string memory result) {
        result = escapeJSON(s, false);
    }

    /// @dev Encodes `s` so that it can be safely used in a URI,
    /// just like `encodeURIComponent` in JavaScript.
    /// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
    /// See: https://datatracker.ietf.org/doc/html/rfc2396
    /// See: https://datatracker.ietf.org/doc/html/rfc3986
    function encodeURIComponent(string memory s) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40)
            // Store "0123456789ABCDEF" in scratch space.
            // Uppercased to be consistent with JavaScript's implementation.
            mstore(0x0f, 0x30313233343536373839414243444546)
            let o := add(result, 0x20)
            for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
                s := add(s, 1)
                let c := and(mload(s), 0xff)
                // If not in `[0-9A-Z-a-z-_.!~*'()]`.
                if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
                    mstore8(o, 0x25) // '%'.
                    mstore8(add(o, 1), mload(and(shr(4, c), 15)))
                    mstore8(add(o, 2), mload(and(c, 15)))
                    o := add(o, 3)
                    continue
                }
                mstore8(o, c)
                o := add(o, 1)
            }
            mstore(result, sub(o, add(result, 0x20))) // Store the length.
            mstore(o, 0) // Zeroize the slot after the string.
            mstore(0x40, add(o, 0x20)) // Allocate memory.
        }
    }

    /// @dev Returns whether `a` equals `b`.
    function eq(string memory a, string memory b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
        }
    }

    /// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
    function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            // These should be evaluated on compile time, as far as possible.
            let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
            let x := not(or(m, or(b, add(m, and(b, m)))))
            let r := shl(7, iszero(iszero(shr(128, x))))
            r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
                xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
        }
    }

    /// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
    /// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
    function cmp(string memory a, string memory b) internal pure returns (int256) {
        return LibBytes.cmp(bytes(a), bytes(b));
    }

    /// @dev Packs a single string with its length into a single word.
    /// Returns `bytes32(0)` if the length is zero or greater than 31.
    function packOne(string memory a) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // We don't need to zero right pad the string,
            // since this is our own custom non-standard packing scheme.
            result :=
                mul(
                    // Load the length and the bytes.
                    mload(add(a, 0x1f)),
                    // `length != 0 && length < 32`. Abuses underflow.
                    // Assumes that the length is valid and within the block gas limit.
                    lt(sub(mload(a), 1), 0x1f)
                )
        }
    }

    /// @dev Unpacks a string packed using {packOne}.
    /// Returns the empty string if `packed` is `bytes32(0)`.
    /// If `packed` is not an output of {packOne}, the output behavior is undefined.
    function unpackOne(bytes32 packed) internal pure returns (string memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(0x40) // Grab the free memory pointer.
            mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
            mstore(result, 0) // Zeroize the length slot.
            mstore(add(result, 0x1f), packed) // Store the length and bytes.
            mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
        }
    }

    /// @dev Packs two strings with their lengths into a single word.
    /// Returns `bytes32(0)` if combined length is zero or greater than 30.
    function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            let aLen := mload(a)
            // We don't need to zero right pad the strings,
            // since this is our own custom non-standard packing scheme.
            result :=
                mul(
                    or( // Load the length and the bytes of `a` and `b`.
                    shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
                    // `totalLen != 0 && totalLen < 31`. Abuses underflow.
                    // Assumes that the lengths are valid and within the block gas limit.
                    lt(sub(add(aLen, mload(b)), 1), 0x1e)
                )
        }
    }

    /// @dev Unpacks strings packed using {packTwo}.
    /// Returns the empty strings if `packed` is `bytes32(0)`.
    /// If `packed` is not an output of {packTwo}, the output behavior is undefined.
    function unpackTwo(bytes32 packed)
        internal
        pure
        returns (string memory resultA, string memory resultB)
    {
        /// @solidity memory-safe-assembly
        assembly {
            resultA := mload(0x40) // Grab the free memory pointer.
            resultB := add(resultA, 0x40)
            // Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
            mstore(0x40, add(resultB, 0x40))
            // Zeroize the length slots.
            mstore(resultA, 0)
            mstore(resultB, 0)
            // Store the lengths and bytes.
            mstore(add(resultA, 0x1f), packed)
            mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
            // Right pad with zeroes.
            mstore(add(add(resultA, 0x20), mload(resultA)), 0)
            mstore(add(add(resultB, 0x20), mload(resultB)), 0)
        }
    }

    /// @dev Directly returns `a` without copying.
    function directReturn(string memory a) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            // Assumes that the string does not start from the scratch space.
            let retStart := sub(a, 0x20)
            let retUnpaddedSize := add(mload(a), 0x40)
            // Right pad with zeroes. Just in case the string is produced
            // by a method that doesn't zero right pad.
            mstore(add(retStart, retUnpaddedSize), 0)
            mstore(retStart, 0x20) // Store the return offset.
            // End the transaction, returning the string.
            return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
        }
    }
}

src/GifsLoaderHtml.sol

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

// GENERATED by abx/build.mjs from abx/loader/ (loader.js, page.mjs). Do not edit by hand.

/// @title GifsLoaderHtml — the loader page's fixed text and its minified loader
/// @notice GifsLoaderRenderer concatenates these around a token's values, exactly as
///         abx/loader/page.mjs does: HEAD tokenData MID loaderConfig OPEN JS TAIL, or
///         PLAIN_HEAD message PLAIN_TAIL. The DOC_ and _TAG_ parts are AbxGenerator's document shell,
///         for GifsLoaderRenderer.document and generatorDocument (documentPage).
library GifsLoaderHtml {
    string internal constant HEAD =
        "<!doctype html>\n<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<style>html,body{margin:0;padding:0;overflow:hidden}canvas{display:block}</style>\n<script>window.abxTokenData=";
    string internal constant MID =
        ";window.gifsLoader=";
    string internal constant OPEN =
        ";</script>\n<script>";
    string internal constant TAIL =
        "</script>\n</head><body></body></html>\n";
    string internal constant PLAIN_HEAD =
        "<!doctype html>\n<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<style>html,body{margin:0;height:100%;background:#fff;color:#555;font:14px/1.5 system-ui,sans-serif}body{display:flex;align-items:center;justify-content:center;text-align:center}p{margin:0;padding:16px}</style>\n</head><body><p>";
    string internal constant PLAIN_TAIL =
        "</p></body></html>\n";
    string internal constant COLLECTION =
        "gifs.shop: each token draws its own GIF from its seed, with a program stored on-chain.";
    string internal constant NO_SEED =
        "gifs.shop: this token has no seed yet.";
    string internal constant NO_PROGRAM =
        "gifs.shop: this project has no on-chain program to load.";
    string internal constant NO_GENERATOR =
        "gifs.shop: this program has no such generator.";
    string internal constant DOC_ABXJS_CLOSE =
        "</script>";
    string internal constant DOC_BODY =
        "\n</head><body>\n<script>\n";
    string internal constant DOC_TAIL =
        "\n</script>\n</body></html>";
    string internal constant GZIP_TAG_OPEN =
        "<script type=\"text/javascript+gzip\" src=\"data:text/javascript;base64,";
    string internal constant B64_TAG_OPEN =
        "<script src=\"data:text/javascript;base64,";
    string internal constant DATA_TAG_CLOSE =
        "\"></script>";
    string internal constant JS =
        "(()=>{const r=window.abxTokenData,o=window.gifsLoader,a=window.abx=window.abx||{};a.tokenData=r,a.__traits=null,a.__done=!1,a.traits=t=>{a.__traits=t;try{document.dispatchEvent(new CustomEvent(\"abx:traits\",{detail:t}))}catch{}return t},a.done=()=>{a.__done=!0;try{document.dispatchEvent(new CustomEvent(\"abx:done\"))}catch{}};const g=\"0x518cb3df\",f=t=>{const n=t<o.chunks?o.ref:o.module,e=t<o.chunks?t:t-o.chunks;return[{to:o.registry,data:g+n.slice(2)+e.toString(16).padStart(64,\"0\")},\"latest\"]},h=t=>({jsonrpc:\"2.0\",id:t,method:\"eth_call\",params:f(t)}),y=t=>{if(typeof t!=\"string\"||t.length<130)return null;const n=parseInt(t.slice(66,130),16);if(!(n>0)||t.length<130+2*n)return null;let e=\"\";for(let s=130;s<130+2*n;s+=2)e+=String.fromCharCode(parseInt(t.slice(s,s+2),16));return e},c=new Array(o.chunks+o.moduleChunks).fill(null),i=()=>c.map((t,n)=>t===null?n:-1).filter(t=>t>=0),d=(t,n)=>{const e=y(n);e!==null&&Number.isInteger(t)&&t>=0&&t<c.length&&(c[t]=e)};async function m(t,n){const e=new AbortController,s=setTimeout(()=>e.abort(),2e4);try{return await(await fetch(t,{method:\"POST\",headers:{\"content-type\":\"application/json\"},body:JSON.stringify(n),signal:e.signal})).json()}finally{clearTimeout(s)}}async function b(t){try{const n=await m(t,i().map(h));if(Array.isArray(n))for(const e of n)e&&d(e.id,e.result)}catch{}for(const n of i())try{const e=await m(t,h(n));e&&d(n,e.result)}catch{return}}async function k(t){if(parseInt(await t.request({method:\"eth_chainId\"}),16)===r.chainId)for(const n of i())d(n,await t.request({method:\"eth_call\",params:f(n)}))}function p(t){const n=document.createElement(\"p\");n.style.cssText=\"margin:0;padding:16px;font:14px/1.5 system-ui,sans-serif;color:#555;text-align:center\",n.textContent=\"gifs.shop #\"+r.tokenId+\": the art could not be loaded (\"+(t?String(t.message||t):\"no RPC answered\")+\"). It lives on-chain: document(\"+r.contractAddress+\", \"+r.tokenId+\") at \"+o.loader+\" on chain \"+r.chainId+\" rebuilds it.\";const e=()=>document.body.append(n);document.body?e():document.addEventListener(\"DOMContentLoaded\",e)}async function w(t){const n=atob(t.join(\"\")),e=new Uint8Array(n.length);for(let l=0;l<n.length;l++)e[l]=n.charCodeAt(l);const s=await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(\"gzip\"))).text(),u=document.createElement(\"script\");u.text=s,document.head.appendChild(u)}async function C(){if(window.ethereum)try{await k(window.ethereum)}catch{}for(const t of o.rpcs)i().length&&await b(t);if(i().length)return p(null);await w(c.slice(0,o.chunks)),o.moduleChunks&&await w(c.slice(o.chunks)),window.gifsSquiggles.render()}C().catch(p)})();";
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin-contracts-5.0.2/=dependencies/@openzeppelin-contracts-5.0.2/",
    "abx-contracts/=dependencies/abx-contracts-3.0.0/",
    "forge-std/=dependencies/forge-std-1.16.1/src/",
    "solady/=dependencies/solady-0.1.26/src/",
    "@openzeppelin/[email protected]/=dependencies/@openzeppelin-contracts-5.0.2/",
    "abx-contracts-3.0.0/=dependencies/abx-contracts-3.0.0/src/",
    "forge-std-1.16.1/=dependencies/forge-std-1.16.1/src/",
    "solady-0.1.26/=dependencies/solady-0.1.26/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.