Skip to content
Verified contractExactMIT

GifsFixedPriceMinter

Address0xcaa7db6f6df2e60ff9b546865b63a3820e802854
Balance

0.032 ETH

 

Transactions

57

 

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,382,406
Creation transaction
0xdb2f50bc62…e4760cc053

src/GifsFixedPriceMinter.sol

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

import {Ownable} from "solady/auth/Ownable.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IAbxSequentialMint} from "abx-contracts/src/interfaces/IAbxSequentialMint.sol";
import {IAbxPrimaryPayee} from "abx-contracts/src/extensions/primary-payee/IAbxPrimaryPayee.sol";
import {GifsNameRenderer} from "./GifsNameRenderer.sol";

/// @title GifsFixedPriceMinter — the gifs.shop sale: a fixed price for anyone, free for the allowlist
/// @notice The project's External Minter (`abx set-minter <token> --minter <this>`), GifsMinter's
///         successor. Anyone mints 1 to {MAX_BATCH} tokens to any address by paying exactly
///         {price} per token; an allowlisted wallet mints the same way for free (and must send no
///         ETH), so the artist keeps a reserve. A {price} of 0 closes the paid sale: then only the
///         allowlist mints. The owner sets the price ({setPrice}) and keeps the list.
///
///         Proceeds stay here until {withdraw}, which anyone may call and which always sends the
///         whole balance to the token's own `primaryPayee()` (read fresh each time, so the token's
///         owner moves the payout with `abx set-primary-payee`, not here). Paying out apart from
///         the mint means a payee that can't take ETH never stops a sale, and nobody, the owner
///         included, can send the money anywhere else. Exact payment only: a price change between
///         a buyer's read and their transaction makes it revert rather than charge a new amount.
///
///         After each batch it asks the title renderer to number the new tokens within their
///         generators ({GifsNameRenderer.sync}), exactly as GifsMinter does: at most {SYNC_MAX}
///         tokens within {SYNC_GAS}, never failing the mint; titles are counted at read time
///         meanwhile. Each token minted emits the shared ABX minter vocabulary's `Purchase`, in
///         ETH, at the price that token paid (0 for the allowlist).
///
///         The token keeps its own rules: while it's paused it refuses this minter, its cap ends
///         the sale, and its owner can always mint directly. Setting another minter on the token
///         retires this one ({withdraw} still works after that). This minter's owner has a brake of
///         its own ({setPaused}); ownership can't be renounced while any wallet is still
///         allowlisted, and moves only by Solady's two-step handover.
contract GifsFixedPriceMinter is Ownable, ReentrancyGuard {
    using SafeTransferLib for address;

    /// @notice The most tokens one call mints.
    uint256 public constant MAX_BATCH = 40;
    /// @notice The most tokens one batch numbers: its own and up to 10 of a backlog when it mints 40.
    uint256 public constant SYNC_MAX = 50;
    /// @notice The most gas the per-batch numbering may use: {SYNC_MAX} tokens at ~95–107k each
    ///         (~5.4M), with room to spare, so a call that isn't starved always completes.
    uint256 public constant SYNC_GAS = 8_000_000;

    /// @notice The ABX project this minter sells.
    IAbxSequentialMint public immutable token;

    /// @notice The title renderer told about each batch (`address(0)`: none).
    GifsNameRenderer public titles;
    /// @notice What each token costs anyone not allowlisted, in wei (0: the paid sale is closed).
    uint256 public price;

    /// @notice Wallets that mint free.
    mapping(address wallet => bool) public allowed;
    /// @notice How many wallets are allowlisted.
    uint256 public allowedCount;
    /// @notice While true, nobody mints through this minter.
    bool public paused;

    /// @notice `wallet` was added to (`true`) or removed from the allowlist.
    event AllowedSet(address indexed wallet, bool allowed);
    /// @notice The title renderer told about each batch is now `titles`.
    event TitlesSet(address indexed titles);
    /// @notice The sale was paused (`true`) or resumed.
    event PausedSet(bool paused);
    /// @notice Each token now costs `price` wei (0: only the allowlist mints).
    event PriceSet(uint256 price);
    /// @notice `amount` wei went to the token's primary payee `payee`.
    event Withdrawn(address indexed payee, uint256 amount);
    /// @notice The per-batch numbering didn't run (out of its gas or reverted); titles are
    ///         counted at read time until a later {GifsNameRenderer.sync} catches up.
    event SyncSkipped(uint256 upTo);
    /// @notice One token (`tokenId`) minted to `to` at `buyer`'s call: ABX's minter spine event,
    ///         `paymentToken` 0 = ETH, `price` what that token paid.
    event Purchase(
        address indexed token,
        address indexed buyer,
        address indexed to,
        uint256 tokenId,
        address paymentToken,
        uint256 price
    );

    /// @notice The paid sale is closed ({price} is 0) and the caller isn't on the allowlist.
    error SaleClosed();
    /// @notice The ETH sent isn't exactly {price} × `quantity` (or isn't 0 for the allowlist).
    error WrongPayment();
    /// @notice `quantity` is 0 or above {MAX_BATCH}.
    error BadQuantity();
    /// @notice The recipient is the zero address.
    error NoRecipient();
    /// @notice The owner paused the sale.
    error SalePaused();
    /// @notice The token names no primary payee, so the proceeds have nowhere to go.
    error NoPrimaryPayee();
    /// @notice There's nothing to withdraw.
    error NothingToWithdraw();
    /// @notice Ownership can't be renounced while a wallet is still allowlisted.
    error StillAllowlisted();
    /// @notice The call didn't carry enough gas for the numbering to have a fair try.
    error OutOfGas();
    /// @notice A title renderer must be a contract (or `address(0)` for none).
    error NoCode();
    /// @notice Ownership moves by requestOwnershipHandover and completeOwnershipHandover only.
    error UseHandover();

    /// @param token_ The ABX project (a SeriesCode clone) this minter sells.
    /// @param owner_ Who sets the price and keeps the allowlist.
    /// @param allowlist The wallets that mint free from the start.
    /// @param titles_ The project's title renderer, numbered after each batch (`address(0)`: none).
    /// @param price_ What each token costs anyone else, in wei (0: only the allowlist mints).
    constructor(
        IAbxSequentialMint token_,
        address owner_,
        address[] memory allowlist,
        GifsNameRenderer titles_,
        uint256 price_
    ) {
        token = token_;
        _initializeOwner(owner_);
        for (uint256 i; i < allowlist.length; ++i) {
            _setAllowed(allowlist[i], true);
        }
        _setTitles(titles_);
        price = price_;
        emit PriceSet(price_);
    }

    // ── the sale ────────────────────────────────────────────────────────────────

    /// @notice Mint `quantity` tokens (1 to {MAX_BATCH}) to `to`. Send exactly {price} × `quantity`
    ///         wei, or nothing from an allowlisted wallet.
    /// @return tokenIds The ids minted, in order.
    function mint(address to, uint256 quantity) external payable nonReentrant returns (uint256[] memory tokenIds) {
        if (paused) revert SalePaused();
        if (quantity == 0 || quantity > MAX_BATCH) revert BadQuantity();
        if (to == address(0)) revert NoRecipient();
        uint256 each;
        if (!allowed[msg.sender]) {
            each = price;
            if (each == 0) revert SaleClosed();
        }
        if (msg.value != each * quantity) revert WrongPayment();

        IAbxSequentialMint t = token;
        tokenIds = new uint256[](quantity);
        for (uint256 i; i < quantity; ++i) {
            uint256 id = t.mint(to);
            tokenIds[i] = id;
            emit Purchase(address(t), msg.sender, to, id, address(0), each);
        }

        address n = address(titles);
        if (n != address(0)) {
            uint256 upTo = tokenIds[quantity - 1] + 1;
            // number at most SYNC_MAX past the stored mark, so a backlog is worked off a slice at
            // a time rather than asked for whole in a call that can never fit (sync stores nothing
            // when it runs out of gas)
            (bool read, bytes memory ret) = n.staticcall(abi.encodeWithSignature("synced(address)", address(t)));
            if (read && ret.length >= 32) {
                uint256 from = abi.decode(ret, (uint256));
                if (from < upTo && upTo - from > SYNC_MAX) upTo = from + SYNC_MAX;
            }
            // a plain call that ignores the return data, so no answer from the renderer (a revert,
            // too little data) can fail the mint
            bytes memory data = abi.encodeCall(GifsNameRenderer.sync, (address(t), upTo));
            bool ok;
            assembly ("memory-safe") {
                ok := call(SYNC_GAS, n, 0, add(data, 0x20), mload(data), 0, 0)
            }
            if (!ok) {
                // under 1/63 of SYNC_GAS left means the call was starved by the caller's gas limit
                // rather than run out of its own budget: revert, so a gas estimate can't settle on
                // a limit that always skips the numbering
                if (gasleft() < SYNC_GAS / 63) revert OutOfGas();
                emit SyncSkipped(upTo);
            }
        }
    }

    /// @notice Send everything the sale has taken to the token's primary payee. Anyone may call it;
    ///         the money only ever goes to that one address.
    /// @return amount The wei sent.
    function withdraw() external nonReentrant returns (uint256 amount) {
        address payee = IAbxPrimaryPayee(address(token)).primaryPayee();
        if (payee == address(0)) revert NoPrimaryPayee();
        amount = address(this).balance;
        if (amount == 0) revert NothingToWithdraw();
        payee.safeTransferETH(amount);
        emit Withdrawn(payee, amount);
    }

    // ── the owner's ─────────────────────────────────────────────────────────────

    /// @notice Set what each token costs anyone not allowlisted, in wei (0 closes the paid sale).
    function setPrice(uint256 price_) external onlyOwner {
        price = price_;
        emit PriceSet(price_);
    }

    /// @notice Add (`true`) or remove (`false`) a wallet from the allowlist.
    function setAllowed(address wallet, bool on) external onlyOwner {
        _setAllowed(wallet, on);
    }

    /// @notice Stop (`true`) or resume the sale through this minter.
    function setPaused(bool on) external onlyOwner {
        paused = on;
        emit PausedSet(on);
    }

    /// @notice Renouncing is refused while any wallet is allowlisted: remove every wallet first
    ///         (and retire this minter on the token, `setMinter(0)`), then renounce. {withdraw}
    ///         needs no owner, so nothing taken can be stranded by renouncing.
    function renounceOwnership() public payable override onlyOwner {
        if (allowedCount != 0) revert StillAllowlisted();
        super.renounceOwnership();
    }

    /// @notice A one-step transfer is refused: the new owner calls requestOwnershipHandover, then
    ///         the owner completeOwnershipHandover within 48 hours.
    function transferOwnership(address) public payable override onlyOwner {
        revert UseHandover();
    }

    /// @notice Point the per-batch numbering at another title renderer (`address(0)`: none).
    function setTitles(GifsNameRenderer titles_) external onlyOwner {
        _setTitles(titles_);
    }

    function _setTitles(GifsNameRenderer titles_) private {
        if (address(titles_) != address(0) && address(titles_).code.length == 0) revert NoCode();
        titles = titles_;
        emit TitlesSet(address(titles_));
    }

    function _setAllowed(address wallet, bool on) private {
        if (allowed[wallet] == on) return;
        allowed[wallet] = on;
        if (on) ++allowedCount;
        else --allowedCount;
        emit AllowedSet(wallet, on);
    }
}

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/extensions/primary-payee/IAbxPrimaryPayee.sol

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

/// @title IAbxPrimaryPayee — Primary Payee extension vocabulary (Register 2)
/// @notice A **single** primary-sale payout destination, readable by any minter (external or
///         included). Topology-independent — the minter reads `primaryPayee()` to know where
///         proceeds go; multi-party splits are handled by pointing this at a splitter contract.
/// @dev Distinct from royalty (secondary). Projects that never sell can omit the extension (or
///      leave the payee `address(0)` = none). Has a read function → a real (non-zero) ERC-165 id.
interface IAbxPrimaryPayee {
    /// @notice The primary-sale payout address changed (`address(0)` = none).
    event PrimaryPayeeChanged(address indexed account);

    /// @notice The current primary-sale payout destination (`address(0)` = none).
    function primaryPayee() external view returns (address);
}

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

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

/// @title IAbxSequentialMint — the canonical mint primitive an external minter targets
/// @notice The entire coupling between a minter and a sequentially-minted ABX token is this one
///         call. Token ids issue strictly in order (`0,1,2,…` — the natural supply count); the
///         caller never chooses an id (a token's metadata *is* its token id). It returns the id
///         just minted, so a minter can report exactly what it sold (in its own events) and
///         compose — without trusting `totalSupply()` (burns move it) or a contract-specific
///         cursor.
/// @dev A **capability interface, not an extension** — no version, no beacon signal — but it *is*
///      ERC-165-advertised, so a minter (or tooling) can verify a target is mintable
///      (`IERC165(token).supportsInterface(type(IAbxSequentialMint).interfaceId)`) before
///      configuring a sale, turning a would-be raw revert into a clear, up-front error. The
///      one-shot, owner-only 1/1 ({OneOfOneImage}) deliberately does **not** implement it: a
///      fixed-price minter targets open, sequential drops (a 1/1 is pre-minted and sold on the
///      secondary market). How a minter *uses* this — price, allocation, ETH vs ERC-20, sale
///      events — is a separate sale-contract concern; see the maintained minting documentation.
interface IAbxSequentialMint {
    /// @notice Mint the next sequential token to `to`.
    /// @param to Recipient of the freshly minted token.
    /// @return tokenId The id just minted (the pre-mint issuance cursor).
    function mint(address to) external returns (uint256 tokenId);
}

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/auth/Ownable.sol

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

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

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

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

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

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

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

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

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

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

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

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

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
        }
        _;
    }
}

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

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

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

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

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

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

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

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` does not implement `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented :=
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

src/GifsNameRenderer.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 {LibString} from "solady/utils/LibString.sol";
import {GifsTraitsRenderer} from "./GifsTraitsRenderer.sol";

interface ICollectionName {
    function name() external view returns (string memory);
}

/// @notice The issuance cursor every ABX series exposes (SeriesCode): ids below it are minted.
interface ISeriesCursor {
    function nextTokenId() external view returns (uint256);
}

/// @title GifsNameRenderer — a token's title, "<Generator> #<n>", numbered within its generator
/// @notice The `name` field renderer for the gifs.shop project (set at collection scope with the
///         renderer representation). A token is titled by its generator and its place among that
///         generator's tokens, in mint order: the first token the Stamp generator draws is
///         "Stamp #1", the second "Stamp #2", whatever their token ids. The generator is the one
///         the token's attributes name: the index from the traits renderer's `pick`, the name read
///         from the head of that renderer's own attributes, so the title and the Generator
///         attribute can't disagree, whichever build the traits renderer came from.
///
///         The numbers are written down once, in token-id order, by {sync}: anyone may call it
///         (the sale's minter does, after every batch), and it only reads what the token has
///         settled (a minted id and its seed), so the numbers are a function of the chain and
///         can't be steered. Until a token has been synced its number is counted at read time,
///         from the stored counts plus the tokens minted since, so a title is right either way;
///         past {LIVE_COUNT_LIMIT} unsynced tokens it isn't counted (the read would cost more gas
///         than a public RPC allows) and the token gets the fallback title until {sync} catches up.
///
///         A token without a settled seed (none, or a hashed one) and the collection surface get
///         ABX's own fallback, "<collection name> #<id>"; {sync} waits at such a token, since
///         numbering past it would fix the order before its seed is known. A traits renderer that
///         reverts or runs past {ATTRIBUTES_GAS} for a seed gets the fallback too. One deployment
///         serves any project, keyed by token address. {render} never reverts for a token or seed
///         (only for a call starved of gas, which reverts rather than answer wrong).
contract GifsNameRenderer is IAbxFieldRenderer {
    error UnsupportedField();
    /// @notice The call didn't carry enough gas to read the generator's name.
    error OutOfGas();

    /// @notice Tokens `from`…`to - 1` of `token` were numbered.
    event Synced(address indexed token, uint256 from, uint256 to);

    string private constant CONTENT_TYPE = "text/plain";
    bytes32 private constant F_NAME = "name";
    bytes32 private constant SEED_KEY = "seed";
    /// @dev Every attributes list the traits renderer gives starts with the Generator.
    bytes private constant GENERATOR_HEAD = '[{"trait_type":"Generator","value":"';

    /// @notice The most gas one read of the traits renderer's attributes may use (about 8x the
    ///         worst seed measured).
    uint256 public constant ATTRIBUTES_GAS = 2_000_000;
    /// @notice The most unsynced tokens a title read counts through before giving the fallback.
    uint256 public constant LIVE_COUNT_LIMIT = 100;

    /// @notice The traits renderer whose pick names the generator (the project's attributes field).
    GifsTraitsRenderer public immutable traits;

    /// @notice Per token contract: ids below this have their number stored.
    mapping(address token => uint256) public synced;
    /// @notice Per token contract and generator: how many of its tokens are numbered so far.
    mapping(address token => mapping(uint256 generator => uint256)) public generatorCount;
    /// @dev Per token contract: each id's number, eight 32-bit numbers to a word (id >> 3).
    mapping(address token => mapping(uint256 word => uint256)) private _numbers;

    constructor(GifsTraitsRenderer traits_) {
        traits = traits_;
    }

    // ── numbering ───────────────────────────────────────────────────────────────

    /// @notice Number `token`'s minted ids in order, up to (not including) `upTo` or the mint
    ///         cursor, whichever is lower. Stops early at a minted token whose seed isn't settled.
    /// @return The new {synced} mark.
    function sync(address token, uint256 upTo) public returns (uint256) {
        uint256 from = synced[token];
        uint256 end = _minted(token);
        if (upTo < end) end = upTo;
        if (from >= end) return from;

        mapping(uint256 => uint256) storage counts = generatorCount[token];
        mapping(uint256 => uint256) storage numbers = _numbers[token];
        uint256 wordIndex = from >> 3;
        uint256 word = numbers[wordIndex];
        uint256 id = from;
        for (; id < end; ++id) {
            (bool seeded, uint256 generator) = _generatorOf(token, id);
            if (!seeded) break;
            uint256 n = ++counts[generator];
            if (id >> 3 != wordIndex) {
                numbers[wordIndex] = word;
                wordIndex = id >> 3;
                word = numbers[wordIndex];
            }
            word |= (n & 0xffffffff) << ((id & 7) << 5);
        }
        if (id == from) return from;
        numbers[wordIndex] = word;
        synced[token] = id;
        emit Synced(token, from, id);
        return id;
    }

    /// @notice Token `tokenId`'s number within its generator, from 1; 0 for a token that isn't
    ///         minted, has no settled seed, or sits more than {LIVE_COUNT_LIMIT} past the synced
    ///         mark. Stored once synced, counted from the stored counts before that.
    function numberOf(address token, uint256 tokenId) public view returns (uint256) {
        uint256 from = synced[token];
        if (tokenId < from) return (_numbers[token][tokenId >> 3] >> ((tokenId & 7) << 5)) & 0xffffffff;
        if (tokenId >= _minted(token) || tokenId - from > LIVE_COUNT_LIMIT) return 0;
        (bool seeded, uint256 generator) = _generatorOf(token, tokenId);
        if (!seeded) return 0;
        uint256 n = generatorCount[token][generator] + 1;
        for (uint256 id = from; id < tokenId; ++id) {
            (bool s, uint256 g) = _generatorOf(token, id);
            if (s && g == generator) ++n;
        }
        return n;
    }

    // ── the title ───────────────────────────────────────────────────────────────

    /// @inheritdoc IAbxFieldRenderer
    function render(address token, uint256 tokenId, bytes32 field)
        external
        view
        returns (string memory contentType, bytes memory data)
    {
        if (field != F_NAME) revert UnsupportedField();
        // try/catch doesn't catch a call to an address with no code
        if (token.code.length == 0) return (CONTENT_TYPE, bytes(string.concat(" #", LibString.toString(tokenId))));
        if (tokenId != type(uint256).max) {
            try IAbxParams(token).tokenParam(tokenId, SEED_KEY) returns (bytes32 seed, bool isHash, bool isSet) {
                if (isSet && !isHash) {
                    uint256 n = numberOf(token, tokenId);
                    string memory generator = generatorName(seed);
                    if (n != 0 && bytes(generator).length != 0) return (CONTENT_TYPE, bytes(title(generator, n)));
                }
            } catch {}
        }
        return (CONTENT_TYPE, bytes(_fallback(token, tokenId)));
    }

    /// @notice A title: the generator's name, " #", its number.
    function title(string memory generator, uint256 number) public pure returns (string memory) {
        return string.concat(generator, " #", LibString.toString(number));
    }

    /// @notice The name of the generator a seed picks, as the traits renderer's Generator
    ///         attribute gives it ("" if its attributes don't start with one, or the read reverts
    ///         or runs past {ATTRIBUTES_GAS}).
    function generatorName(bytes32 seed) public view returns (string memory) {
        bytes memory a;
        try traits.attributes{gas: ATTRIBUTES_GAS}(seed) returns (string memory s) {
            a = bytes(s);
        } catch {
            // starved by the caller's gas rather than out of its own budget: revert, don't answer
            if (gasleft() < ATTRIBUTES_GAS / 63) revert OutOfGas();
            return "";
        }
        bytes memory head = GENERATOR_HEAD;
        if (a.length <= head.length) return "";
        for (uint256 i; i < head.length; ++i) {
            if (a[i] != head[i]) return "";
        }
        uint256 end = head.length;
        while (end < a.length && a[end] != '"') ++end;
        if (end == a.length) return "";
        return string(LibString.slice(string(a), head.length, end));
    }

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

    /// @dev The generator a minted token's settled seed picks; false without one.
    function _generatorOf(address token, uint256 tokenId) private view returns (bool, uint256) {
        try IAbxParams(token).tokenParam(tokenId, SEED_KEY) returns (bytes32 seed, bool isHash, bool isSet) {
            if (!isSet || isHash) return (false, 0);
            (, uint256 generator) = traits.pick(seed);
            return (true, generator);
        } catch {
            return (false, 0);
        }
    }

    /// @dev How many ids `token` has minted (its cursor); 0 for anything that doesn't say.
    function _minted(address token) private view returns (uint256) {
        if (token.code.length == 0) return 0;
        try ISeriesCursor(token).nextTokenId() returns (uint256 next) {
            return next;
        } catch {
            return 0;
        }
    }

    /// @dev ABX's own title for a token with no field: "<collection name> #<id>".
    function _fallback(address token, uint256 tokenId) private view returns (string memory) {
        string memory collection;
        try ICollectionName(token).name() returns (string memory n) {
            collection = n;
        } catch {}
        return string.concat(collection, " #", LibString.toString(tokenId));
    }
}

src/GifsTraitsRenderer.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 {GifsTraitsTables as T} from "./GifsTraitsTables.sol";

/// @title GifsTraitsRenderer — a token's attributes, computed on-chain from its seed
/// @notice The `attributes` field renderer for the gifs.shop project: marketplaces read traits from
///         tokenURI with no resolver and no off-chain step. First the program's live pick
///         (live.mjs pickScene), the same arithmetic on the same bytes. The token is always the
///         art, so no hash function is involved:
///
///           base  = the seed's own base, read from its bytes as the squiggle script reads them:
///                   fuzzy, pipe, slinky, bold, ribbed, else plain
///           form  = base, except a plain seed is Lofi when seed mod LOFI_SPLIT < LOFI_OF_PLAIN
///           gen   = (seed div LOFI_SPLIT) mod W, walked against the tier weights of the generators
///                   that give that form and take the seed (on ribbed, under their grey rule), in
///                   registry order, W being their total weight; none at all sends it to Lofi
///
///         Then the generator's own traits, rolled from the seed's bytes by its trait data
///         (traits-spec.mjs): this contract is one interpreter for the data's kinds and rules, and
///         the data itself sits in trait packs (GifsTraitPack, generated by abx/trait-packs.mjs),
///         pinned by code hash in the constructor. A generator added later is a data change.
///
///         It reports the attributes exactly as the program's liveTraits gives them (render.mjs):
///         Generator, Form and Tier, then the generator's shown traits in the data's order, true as
///         "Yes", false and none left out. (The program's own abx.traits call reports the same list
///         without Generator.) The tables are generated from the mill (GifsTraitsTables.sol), and
///         abx/dist/traits-fixture.json pins the result to Node's. Stateless, view-only, never
///         reverts for any seed, and a token without a seed has no attributes. As a backstop
///         {render} reads them through a bounded self-call ({ATTRIBUTES_GAS}): should a later
///         data build ever trip the interpreter, that token loses its attributes, not its tokenURI.
contract GifsTraitsRenderer is IAbxFieldRenderer {
    error UnsupportedField();
    error WrongPacks();
    /// @notice The call didn't carry enough gas to read the attributes.
    error OutOfGas();

    /// @notice The most gas {render}'s read of a seed's attributes may use (about 8x the worst
    ///         seed measured).
    uint256 public constant ATTRIBUTES_GAS = 2_000_000;

    string private constant CONTENT_TYPE = "application/json";
    bytes32 private constant F_ATTRIBUTES = "attributes";
    bytes32 private constant SEED_KEY = "seed";

    // the forms, in FORMS order (generators.mjs); the bases are the first six, in BASES order
    uint256 private constant PLAIN = 0;
    uint256 private constant PIPE = 1;
    uint256 private constant SLINKY = 2;
    uint256 private constant BOLD = 3;
    uint256 private constant RIBBED = 4;
    uint256 private constant FUZZY = 5;
    uint256 private constant LOFI = 6;

    // a value: one of the generator's strings, or one of these (abx/trait-packs.mjs)
    uint256 private constant NONE = 0xff;
    uint256 private constant TRUE = 0xfe;
    uint256 private constant FALSE = 0xfd;
    uint256 private constant COMPUTED = 0xfc;

    // kinds
    uint256 private constant LOOKUP = 1;
    uint256 private constant LOOKUP2 = 2;
    uint256 private constant MOD = 3;
    uint256 private constant MOD2 = 4;
    uint256 private constant DERIVED = 5;
    uint256 private constant DRAWS = 6;
    uint256 private constant SLOT = 7;
    uint256 private constant REPEAT = 8;
    uint256 private constant PRICE = 9;
    uint256 private constant HUES = 10;

    address private immutable _pack0;
    address private immutable _pack1;
    address private immutable _pack2;
    address private immutable _pack3;

    /// @param packList The deployed GifsTraitPack contracts, in order; each must hold exactly the data
    ///        this build generated (GifsTraitsTables PACK_HASH_<i>).
    constructor(address[] memory packList) {
        if (packList.length != T.PACK_COUNT || packList.length > 4) revert WrongPacks();
        for (uint256 i; i < packList.length; ++i) {
            if (packList[i].codehash != T.packHash(i)) revert WrongPacks();
        }
        _pack0 = packList.length > 0 ? packList[0] : address(0);
        _pack1 = packList.length > 1 ? packList[1] : address(0);
        _pack2 = packList.length > 2 ? packList[2] : address(0);
        _pack3 = packList.length > 3 ? packList[3] : address(0);
    }

    /// @notice The trait packs this renderer reads, in order.
    function packs() external view returns (address[] memory out) {
        out = new address[](T.PACK_COUNT);
        for (uint256 i; i < out.length; ++i) {
            out[i] = _packAt(i);
        }
    }

    /// @inheritdoc IAbxFieldRenderer
    function render(address token, uint256 tokenId, bytes32 field)
        external
        view
        returns (string memory contentType, bytes memory data)
    {
        if (field != F_ATTRIBUTES) revert UnsupportedField();
        if (tokenId == type(uint256).max) return (CONTENT_TYPE, bytes("[]"));
        (bytes32 seed, bool isHash, bool isSet) = IAbxParams(token).tokenParam(tokenId, SEED_KEY);
        if (!isSet || isHash) return (CONTENT_TYPE, bytes("[]"));
        try this.attributes{gas: ATTRIBUTES_GAS}(seed) returns (string memory a) {
            return (CONTENT_TYPE, bytes(a));
        } catch {
            // starved by the caller's gas rather than out of its own budget: revert, don't answer
            if (gasleft() < ATTRIBUTES_GAS / 63) revert OutOfGas();
            return (CONTENT_TYPE, bytes("[]"));
        }
    }

    /// @notice A seed's attributes: [{Generator}, {Form}, {Tier}, then the generator's traits].
    function attributes(bytes32 seed) public view returns (string memory) {
        (uint256 form, uint256 generator) = pick(seed);
        return string.concat(
            '[{"trait_type":"Generator","value":"',
            T.sceneName(generator),
            '"},{"trait_type":"Form","value":"',
            T.formName(form),
            '"},{"trait_type":"Tier","value":"',
            T.tierName(uint8(T.TIER_OF[generator])),
            '"}',
            string(traits(seed, generator)),
            "]"
        );
    }

    /// @notice The form index (FORMS order) and generator index (registry order) a seed picks.
    function pick(bytes32 seed) public pure returns (uint256 form, uint256 generator) {
        uint256 v = uint256(seed);
        uint256 grey = uint8(seed[25]);
        uint256 base = nativeBase(seed);
        form = base == PLAIN && v % T.LOFI_SPLIT < T.LOFI_OF_PLAIN ? LOFI : base;
        uint256 total = _poolWeight(form, grey);
        if (total == 0) {
            form = LOFI;
            total = _poolWeight(form, grey);
        }
        // Lofi's generators take every seed (the build refuses anything else), so total > 0
        uint256 at = (v / T.LOFI_SPLIT) % total;
        bytes memory gens = T.formGenerators(form);
        uint256 cum;
        for (uint256 i; i < gens.length; ++i) {
            uint256 g = uint8(gens[i]);
            if (!_takes(g, form, grey)) continue;
            cum += _tierWeight(g);
            if (at < cum) return (form, g);
        }
        // unreachable: at < total
        return (form, uint8(gens[gens.length - 1]));
    }

    /// @notice The seed's own base, as the squiggle script decides it (squiggle.mjs nativeBase):
    ///         fuzzy is pipe without slinky, pipe is pipe and slinky, then slinky, bold, ribbed
    ///         (segmented), else plain. In FORMS order: plain 0, pipe 1, slinky 2, bold 3, ribbed 4,
    ///         fuzzy 5.
    function nativeBase(bytes32 seed) public pure returns (uint256) {
        bool slinky = uint8(seed[31]) < T.SLINKY_BELOW;
        bool pipe = uint8(seed[22]) < T.PIPE_BELOW;
        if (pipe && !slinky) return FUZZY;
        if (slinky && pipe) return PIPE;
        if (slinky) return SLINKY;
        if (uint8(seed[23]) < T.BOLD_BELOW) return BOLD;
        if (uint8(seed[24]) < T.SEGMENTED_BELOW) return RIBBED;
        return PLAIN;
    }

    /// @notice A generator's own traits for a seed, as the attributes list continues them: each
    ///         `,{"trait_type":…,"value":…}`, in the trait data's order. Empty for a generator with
    ///         no traits.
    function traits(bytes32 seed, uint256 generator) public view returns (bytes memory out) {
        if (generator >= T.GENERATOR_COUNT) return out;
        uint256 at = generator * 5;
        bytes memory index = T.TRAIT_INDEX;
        uint256 packIndex = uint8(index[at]);
        uint256 offset = (uint256(uint8(index[at + 1])) << 8) | uint8(index[at + 2]);
        uint256 length = (uint256(uint8(index[at + 3])) << 8) | uint8(index[at + 4]);
        if (length == 0) return out;
        bytes memory p = new bytes(length);
        address pack = _packAt(packIndex);
        assembly {
            extcodecopy(pack, add(p, 0x20), add(offset, 1), length)
        }
        return _run(p, seed, nativeBase(seed));
    }

    // ------------------------------------------------------------------------------------------------
    // The interpreter. `p` is one generator's program (abx/trait-packs.mjs has its layout); it was
    // generated by the build and pinned by code hash, so it is read without bounds checks.

    /// @dev Where the interpreter is: the program, the read position, the generator's strings, and
    ///      every trait's value so far (with the text of each computed one).
    struct Run {
        bytes p;
        uint256 at;
        bytes32 seed;
        uint256 base;
        uint256[] strAt;
        uint256[] vals;
        bytes[] text;
    }

    /// @dev A draws trait: where its bytes, names and weights are, and how many names it has.
    struct Draw {
        uint256 bytesAt;
        uint256 namesAt;
        uint256 weightsAt;
        uint256 n;
    }

    function _run(bytes memory p, bytes32 seed, uint256 base) internal pure returns (bytes memory out) {
        Run memory r = Run(p, 0, seed, base, new uint256[](0), new uint256[](0), new bytes[](0));
        uint256 n = _u8(r);
        r.strAt = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            r.strAt[i] = r.at;
            r.at += 1 + uint8(p[r.at]);
        }
        n = _u8(r);
        r.vals = new uint256[](n);
        r.text = new bytes[](n);
        for (uint256 i; i < n; ++i) {
            uint256 kind = _u8(r);
            uint256 key = _u8(r);
            uint256 x = _roll(r, kind & 0x7f, i);
            r.vals[i] = x;
            x = _rules(r, x, i);
            r.vals[i] = x;
            if (kind & 0x80 != 0 || x == NONE || x == FALSE) continue;
            out = abi.encodePacked(
                out,
                ',{"trait_type":"',
                _str(r, key),
                '","value":"',
                x == TRUE ? bytes("Yes") : x == COMPUTED ? r.text[i] : _str(r, x),
                '"}'
            );
        }
    }

    /// @dev The trait's roll by its kind. A computed value's text goes to r.text[i].
    function _roll(Run memory r, uint256 kind, uint256 i) private pure returns (uint256 x) {
        if (kind == LOOKUP || kind == LOOKUP2) {
            uint256 v = kind == LOOKUP ? _byte(r, _u8(r)) : _pairAt(r);
            uint256 n = _u8(r);
            uint256 width = kind == LOOKUP ? 1 : 2;
            uint256 row = n - 1;
            for (uint256 j; j + 1 < n; ++j) {
                uint256 bound = width == 1 ? uint8(r.p[r.at + j]) : _u16At(r, r.at + 2 * j);
                if (v < bound) {
                    row = j;
                    break;
                }
            }
            r.at += (n - 1) * width;
            x = uint8(r.p[r.at + row]);
            r.at += n;
        } else if (kind == MOD || kind == MOD2) {
            uint256 v = kind == MOD ? _byte(r, _u8(r)) : _pairAt(r);
            uint256 n = _u8(r);
            x = uint8(r.p[r.at + v % n]);
            r.at += n;
        } else if (kind == DERIVED) {
            uint256 from = r.vals[_u8(r)];
            uint256 n = _u8(r);
            x = NONE;
            for (uint256 j; j < n; ++j) {
                uint256 fv = _u8(r);
                uint256 tag = _u8(r);
                uint256 y = _u8(r);
                if (x == NONE && fv == from) x = tag == 0 ? y : r.vals[y];
            }
        } else if (kind == DRAWS) {
            x = _draws(r, i);
        } else if (kind == SLOT) {
            x = _slot(r, i);
        } else if (kind == REPEAT) {
            uint256 n = 13 + (8 * _byte(r, 26) + 254) / 255;
            x = FALSE;
            for (uint256 j; j + 1 < n; ++j) {
                if (_byte(r, j) == _byte(r, j + 1)) return TRUE;
            }
        } else if (kind == PRICE) {
            x = _price(r, i);
        } else if (kind == HUES) {
            x = _hues(r, i);
        } else {
            x = NONE;
        }
    }

    /// @dev Draws without repeats (exploded's roles and margins): the k-th draw reads its own byte
    ///      and takes from the names left, by weight; the value lists the names in alphabetical order.
    function _draws(Run memory r, uint256 i) private pure returns (uint256) {
        Draw memory d;
        uint256 k = _u8(r);
        d.bytesAt = r.at;
        r.at += k;
        d.n = _u8(r);
        d.namesAt = r.at;
        r.at += d.n;
        // 0 when unweighted: a program never has its weights at 0, where its string count is
        d.weightsAt = _u8(r) != 0 ? r.at : 0;
        if (d.weightsAt != 0) r.at += d.n;
        uint256 count = _drawCount(r);
        if (count > k) count = k;
        if (count > d.n) count = d.n;
        uint256 none = _u8(r);
        uint256 orderAt = r.at;
        r.at += d.n;
        if (count == 0) return none;
        r.text[i] = _names(r, d, orderAt, _drawn(r, d, count));
        return COMPUTED;
    }

    /// @dev The names taken (a bit per name), in alphabetical order, joined with ", ".
    function _names(Run memory r, Draw memory d, uint256 orderAt, uint256 taken)
        private
        pure
        returns (bytes memory text)
    {
        for (uint256 j; j < d.n; ++j) {
            uint256 name = uint8(r.p[orderAt + j]);
            if (taken & (1 << name) == 0) continue;
            bytes memory s = _str(r, uint8(r.p[d.namesAt + name]));
            text = text.length == 0 ? s : abi.encodePacked(text, ", ", s);
        }
    }

    /// @dev How many names a draws trait takes: fixed, or by a trait above.
    function _drawCount(Run memory r) private pure returns (uint256 count) {
        uint256 countTrait = _u8(r);
        if (countTrait == 0xff) return _u8(r);
        uint256 m = _u8(r);
        for (uint256 j; j < m; ++j) {
            uint256 fv = _u8(r);
            uint256 c = _u8(r);
            if (r.vals[countTrait] == fv) count = c;
        }
    }

    /// @dev The names drawn, as a bit per name: each draw x = floor(dec · weight left / 256), then
    ///      the first name not yet taken whose running weight passes x.
    function _drawn(Run memory r, Draw memory d, uint256 count) private pure returns (uint256 taken) {
        uint256 left;
        for (uint256 j; j < d.n; ++j) {
            left += _weight(r, d, j);
        }
        for (uint256 q; q < count; ++q) {
            uint256 x = (_byte(r, uint8(r.p[d.bytesAt + q])) * left) / 256;
            uint256 j;
            for (; j < d.n; ++j) {
                if (taken & (1 << j) != 0) continue;
                uint256 w = _weight(r, d, j);
                if (x < w) break;
                x -= w;
            }
            taken |= 1 << j;
            left -= _weight(r, d, j);
        }
    }

    function _weight(Run memory r, Draw memory d, uint256 j) private pure returns (uint256) {
        return d.weightsAt == 0 ? 1 : uint8(r.p[d.weightsAt + j]);
    }

    /// @dev Slot's three reels (FORMULAS.slotSymbols): the common symbol dec[7] mod 4, the other
    ///      (common + 1 + dec[8] mod 3) mod 4; PAIR puts the other on reel dec[11] mod 3.
    function _slot(Run memory r, uint256 i) private pure returns (uint256) {
        uint256 outcome = r.vals[_u8(r)];
        uint256 outcomesAt = r.at;
        uint256 symbolsAt = r.at + 5;
        r.at += 11;
        uint256 common = _byte(r, 7) % 4;
        uint256 other = (common + 1 + (_byte(r, 8) % 3)) % 4;
        uint256[3] memory reels;
        if (outcome == uint8(r.p[outcomesAt])) {
            reels = [common, common, common];
            reels[_byte(r, 11) % 3] = other;
        } else if (outcome == uint8(r.p[outcomesAt + 1])) {
            reels = [common, common, common];
        } else if (outcome == uint8(r.p[outcomesAt + 2])) {
            reels = [uint256(4), 4, 4];
        } else if (outcome == uint8(r.p[outcomesAt + 3])) {
            reels = [uint256(5), 5, 5];
        } else if (outcome == uint8(r.p[outcomesAt + 4])) {
            uint256 third;
            while (third == common || third == other) ++third;
            reels = [common, other, third];
        } else {
            return NONE;
        }
        r.text[i] = abi.encodePacked(
            _str(r, uint8(r.p[symbolsAt + reels[0]])),
            ", ",
            _str(r, uint8(r.p[symbolsAt + reels[1]])),
            ", ",
            _str(r, uint8(r.p[symbolsAt + reels[2]]))
        );
        return COMPUTED;
    }

    /// @dev Auction's price (FORMULAS.auctionPrice): within the bidding style's tenths [low, high],
    ///      evenly by the byte pair, printed "12.3".
    function _price(Run memory r, uint256 i) private pure returns (uint256 x) {
        uint256 v = _pairAt(r);
        uint256 bidding = r.vals[_u8(r)];
        uint256 n = _u8(r);
        x = NONE;
        for (uint256 j; j < n; ++j) {
            uint256 fv = _u8(r);
            uint256 low = _u16At(r, r.at);
            uint256 high = _u16At(r, r.at + 2);
            r.at += 4;
            if (x != NONE || fv != bidding || high < low) continue;
            uint256 tenths = low + (v * (high - low + 1)) / 65536;
            r.text[i] = abi.encodePacked(_decimal(tenths / 10), ".", _decimal(tenths % 10));
            x = COMPUTED;
        }
    }

    /// @dev The machine's colours for the squiggle (FORMULAS.hueCount, hueBins in traits-spec.mjs):
    ///      the hue slots the stroke passes through, plus the base's finishing colours.
    function _hues(Run memory r, uint256 i) private pure returns (uint256) {
        uint256 hues = _u8(r);
        uint256 grey = _u8(r);
        uint256 extra = uint8(r.p[r.at + r.base]);
        r.at += 6;
        if (r.base == RIBBED) hues = grey;
        uint256 c = (10 + (8 * _byte(r, 26) + 254) / 255) * (r.base == FUZZY ? 1001 : 201) - 1;
        uint256 s = _byte(r, 29);
        uint256 spread = _byte(r, 28);
        uint256 num = spread < 3 ? (2 * c + s) * hues : (c * 17 + s * (85 + 3 * spread)) * hues;
        uint256 den = spread < 3 ? 255 : (85 + 3 * spread) * 255;
        // reversed: ceil((2num - den) / 2den); else floor((2num + den) / 2den). 2num > den always.
        uint256 last = _byte(r, 30) < 128 ? (2 * num - den + 2 * den - 1) / (2 * den) : (2 * num + den) / (2 * den);
        uint256 first = (2 * s * hues + 255) / 510;
        uint256 count = last + 1 > first ? last + 1 - first : 0;
        if (count > hues) count = hues;
        r.text[i] = _decimal(count + extra);
        return COMPUTED;
    }

    /// @dev The trait's rules, in order: the first that applies sets the value.
    function _rules(Run memory r, uint256 x, uint256 i) private pure returns (uint256) {
        uint256 n = _u8(r);
        bool done;
        for (uint256 k; k < n; ++k) {
            if (_u8(r) == 1) {
                bool ok = _conds(r);
                uint256 then = _u8(r);
                if (!done && ok) {
                    x = then;
                    done = true;
                }
            } else {
                (uint256 y, bool applies) = _avoid(r, x, done);
                if (applies) {
                    x = y;
                    done = true;
                }
            }
        }
        if (done && x != COMPUTED) r.text[i] = "";
        return x;
    }

    /// @dev Whether every test of an `if` holds.
    function _conds(Run memory r) private pure returns (bool ok) {
        uint256 n = _u8(r);
        ok = true;
        for (uint256 c; c < n; ++c) {
            uint256 test = _u8(r);
            if (test == 1 || test == 2) {
                uint256 v = r.vals[_u8(r)];
                uint256 m = _u8(r);
                bool hit;
                for (uint256 j; j < m; ++j) {
                    if (uint8(r.p[r.at + j]) == v) hit = true;
                }
                r.at += m;
                if (hit != (test == 1)) ok = false;
            } else if (test == 3) {
                if ((_u8(r) >> r.base) & 1 == 0) ok = false;
            } else {
                uint256 b = _byte(r, _u8(r));
                uint256 bound = _u16At(r, r.at);
                r.at += 2;
                if ((b < bound) != (test == 4)) ok = false;
            }
        }
    }

    /// @dev An avoid rule: when the value clashes, step along the trait's own list until one doesn't
    ///      (the roll standing if none passes). `applies` is false when the value didn't clash, so the
    ///      rules after it are still read.
    function _avoid(Run memory r, uint256 x, bool done) private pure returns (uint256, bool applies) {
        uint256 step = _u8(r);
        uint256 n = _u8(r);
        uint256 listAt = r.at;
        r.at += n;
        uint256 k = _u8(r);
        uint256 avoidAt = r.at;
        // skip past the rule: each avoided trait, and its clash table if it has one
        for (uint256 a; a < k; ++a) {
            r.at += 1;
            if (_u8(r) == 1) {
                uint256 m = _u8(r);
                for (uint256 j; j < m; ++j) {
                    r.at += 1;
                    r.at += 1 + uint8(r.p[r.at]);
                }
            }
        }
        if (done || !_clashes(r, avoidAt, k, x)) return (x, false);
        uint256 y = x;
        for (uint256 q; q < n && _clashes(r, avoidAt, k, y); ++q) {
            uint256 ix = n;
            for (uint256 j; j < n; ++j) {
                if (uint8(r.p[listAt + j]) == y) {
                    ix = j;
                    break;
                }
            }
            // y is always on the list (it came from it); off it, JS's indexOf is -1
            y = uint8(r.p[listAt + (ix == n ? step + n - 1 : ix + step) % n]);
        }
        return (_clashes(r, avoidAt, k, y) ? x : y, true);
    }

    /// @dev Whether `y` clashes with any of the avoided traits (avoid rule at `at`, k traits).
    function _clashes(Run memory r, uint256 at, uint256 k, uint256 y) private pure returns (bool) {
        for (uint256 a; a < k; ++a) {
            uint256 other = r.vals[uint8(r.p[at])];
            uint256 mode = uint8(r.p[at + 1]);
            at += 2;
            if (mode == 0) {
                if (y == other) return true;
                continue;
            }
            uint256 m = uint8(r.p[at]);
            at += 1;
            for (uint256 j; j < m; ++j) {
                uint256 key = uint8(r.p[at]);
                uint256 c = uint8(r.p[at + 1]);
                if (key == other) {
                    for (uint256 z; z < c; ++z) {
                        if (uint8(r.p[at + 2 + z]) == y) return true;
                    }
                }
                at += 2 + c;
            }
        }
        return false;
    }

    // ------------------------------------------------------------------------------------------------

    function _u8(Run memory r) private pure returns (uint256 v) {
        v = uint8(r.p[r.at]);
        r.at += 1;
    }

    function _u16At(Run memory r, uint256 at) private pure returns (uint256) {
        return (uint256(uint8(r.p[at])) << 8) | uint8(r.p[at + 1]);
    }

    function _byte(Run memory r, uint256 i) private pure returns (uint256) {
        return uint8(r.seed[i % 32]);
    }

    /// @dev Reads u8 hi, u8 lo and gives dec[hi]·256 + dec[lo].
    function _pairAt(Run memory r) private pure returns (uint256) {
        uint256 hi = _u8(r);
        uint256 lo = _u8(r);
        return (_byte(r, hi) << 8) | _byte(r, lo);
    }

    /// @dev String i of the generator's strings (already escaped for JSON).
    function _str(Run memory r, uint256 i) private pure returns (bytes memory s) {
        if (i >= r.strAt.length) return s;
        uint256 at = r.strAt[i];
        uint256 len = uint8(r.p[at]);
        s = new bytes(len);
        bytes memory p = r.p;
        // word by word (no MCOPY: the default profile is paris); s is the newest allocation, so
        // the last word's spill lands in free memory
        assembly {
            let from := add(add(p, 0x21), at)
            let to := add(s, 0x20)
            for { let o := 0 } lt(o, len) { o := add(o, 0x20) } { mstore(add(to, o), mload(add(from, o))) }
        }
    }

    function _decimal(uint256 v) private pure returns (bytes memory s) {
        uint256 len = 1;
        for (uint256 t = v; t >= 10; t /= 10) ++len;
        s = new bytes(len);
        for (uint256 j = len; j > 0; --j) {
            s[j - 1] = bytes1(uint8(48 + (v % 10)));
            v /= 10;
        }
    }

    function _packAt(uint256 i) private view returns (address) {
        if (i == 0) return _pack0;
        if (i == 1) return _pack1;
        if (i == 2) return _pack2;
        if (i == 3) return _pack3;
        return address(0);
    }

    /// @dev Whether a generator that gives `form` takes the seed: only ribbed has rules, on the grey.
    function _takes(uint256 generator, uint256 form, uint256 grey) private pure returns (bool) {
        if (form != RIBBED) return true;
        uint256 rule = uint8(T.RIBBED_RULE[generator]);
        if (rule == 1) return grey >= T.RIBBED_LIGHT_FROM;
        if (rule == 2) return grey <= T.RIBBED_DARK_TO;
        return true;
    }

    /// @dev The total tier weight of the generators that give `form` and take the seed.
    function _poolWeight(uint256 form, uint256 grey) private pure returns (uint256 total) {
        bytes memory gens = T.formGenerators(form);
        for (uint256 i; i < gens.length; ++i) {
            if (_takes(uint8(gens[i]), form, grey)) total += _tierWeight(uint8(gens[i]));
        }
    }

    function _tierWeight(uint256 generator) private pure returns (uint256) {
        uint256 tier = uint8(T.TIER_OF[generator]);
        return (uint256(uint8(T.TIER_WEIGHTS[tier * 2])) << 8) | uint8(T.TIER_WEIGHTS[tier * 2 + 1]);
    }
}

src/GifsTraitsTables.sol

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

// GENERATED by abx/build.mjs from tools/squiggle-mill/generators.mjs. Do not edit: rebuild.
// 100 generators, 7 forms.

/// @title GifsTraitsTables — the live pick's tables (FORMS, LOFI_ODDS, TIERS, the registry, the script's thresholds)
library GifsTraitsTables {
    uint256 internal constant GENERATOR_COUNT = 100;
    uint256 internal constant FORM_COUNT = 7;

    /// @dev The script's base traits, each "byte below this": slinky dec[31], pipe dec[22], bold
    ///      dec[23], segmented dec[24] (squiggle.mjs traits()).
    uint256 internal constant SLINKY_BELOW = 35;
    uint256 internal constant PIPE_BELOW = 32;
    uint256 internal constant BOLD_BELOW = 15;
    uint256 internal constant SEGMENTED_BELOW = 30;

    /// @dev LOFI_ODDS: a plain token is Lofi when the seed mod LOFI_SPLIT is below LOFI_OF_PLAIN.
    uint256 internal constant LOFI_SPLIT = 161;
    uint256 internal constant LOFI_OF_PLAIN = 97;

    /// @dev The ribbed rules on the grey, dec[25]: light (1) takes grey >= RIBBED_LIGHT_FROM, dark (2)
    ///      takes grey <= RIBBED_DARK_TO (generators.mjs RULES).
    uint256 internal constant RIBBED_LIGHT_FROM = 127;
    uint256 internal constant RIBBED_DARK_TO = 200;

    /// @dev Each generator's ribbed rule, in registry order: 0 every ribbed token, 1 light, 2 dark.
    bytes internal constant RIBBED_RULE = hex"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

    /// @dev TIERS weights in TIERS order (classic, rare, epic, legendary, unicorn), two bytes each.
    bytes internal constant TIER_WEIGHTS = hex"00c80064003200190001";

    /// @dev Each generator's tier index, in registry order.
    bytes internal constant TIER_OF = hex"04030302020302020102010203020303030203010102000200020002010003030101000000010000000200030002020200020200020001000102010001010100010300030000000302010300040404040404000304040001000001010001020101020101";

    /// @dev The trait packs (GifsTraitPacks.sol, deployed as GifsTraitPack): how many, and each one's
    ///      code hash, which the renderer checks in its constructor.
    uint256 internal constant PACK_COUNT = 1;
    bytes32 internal constant PACK_HASH_0 = 0xd4dbc96d64a8c205d0bfa33eb75d0baa7ecfdc574c1d42c58476307ed3b3b396;

    function packHash(uint256 i) internal pure returns (bytes32) {
        if (i == 0) return PACK_HASH_0;
        return 0;
    }

    /// @dev Each generator's trait program, in registry order: u8 pack, u16 offset, u16 length (a
    ///      length of 0: no traits).
    bytes internal constant TRAIT_INDEX = hex"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007700007700720000e9002d000000000000011600a80001be00a4000262010900036b01450004b0017100062100820006a300d800077b018700090200a10009a300d6000a7900c7000b40019d000cdd0126000e0300cc000ecf010f000fde00e90010c700cb00119200e4001276022a0014a001530015f300ff0016f20156001848013f00198700cb001a5202f3001d45007a001dbf00c1001e800101001f81013b0020bc008400214001c400230400fa0023fe007900247700dd00255400cb00261f0112002731010c00283d00ba0028f7008500297c00b0002a2c00c0002aec0191002c7d0118002d95012b002ec00085002f4501f400313900c00031f9009d00329600c400335a011200346c012b00359700f300368a011a0037a4013a0038de00ac00398a0131003abb00da003b9501ec003d810060003de10062003e43004c003e8f0061003ef00060003f500055003fa500ff0040a4019a00423e005000428e003a0042c8027300453b015e00469901a100483a012900496300e8004a4b00bf004b0a010b004c150172004d8700e0004e670219005080016f0051ef02090053f800c50054bd017c";

    /// @dev The generators that give plain, in registry order.
    bytes internal constant FORM_0 = hex"00010203040607080e0f101112131b1d1e1f202324262728292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e6063";
    /// @dev The generators that give pipe, in registry order.
    bytes internal constant FORM_1 = hex"00010203040607080e0f101112131b1d1e1f2023242627292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e6063";
    /// @dev The generators that give slinky, in registry order.
    bytes internal constant FORM_2 = hex"00010203040607080e0f101112131b1d1e1f202324262728292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e6063";
    /// @dev The generators that give bold, in registry order.
    bytes internal constant FORM_3 = hex"00010203040607080e0f101112131b1d1e1f202324262728292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e63";
    /// @dev The generators that give ribbed, in registry order.
    bytes internal constant FORM_4 = hex"00010203040607080e0f101112131b1d1e1f202324262728292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e6063";
    /// @dev The generators that give fuzzy, in registry order.
    bytes internal constant FORM_5 = hex"00010203040607080e0f101112131b1d1e1f202324262728292a2b2c2d303233353738393a3b3c3d3f4244454647484a4c4d4e4f5051535455585a5b5d5e6063";
    /// @dev The generators that give lofi, in registry order.
    bytes internal constant FORM_6 = hex"05090a0b0c0d1415161718191a1c2122252e2f3134363e404143494b525657595c5f6162";

    function formGenerators(uint256 form) internal pure returns (bytes memory) {
        if (form == 0) return FORM_0;
        if (form == 1) return FORM_1;
        if (form == 2) return FORM_2;
        if (form == 3) return FORM_3;
        if (form == 4) return FORM_4;
        if (form == 5) return FORM_5;
        if (form == 6) return FORM_6;
        revert("no such form");
    }

    function formName(uint256 form) internal pure returns (string memory) {
        string[7] memory names = ["Normal", "Pipe", "Slinky", "Bold", "Ribbed", "Fuzzy", "Lofi"];
        return names[form];
    }

    function tierName(uint256 tier) internal pure returns (string memory) {
        string[5] memory names = ["Classic", "Rare", "Epic", "Legendary", "Unicorn"];
        return names[tier];
    }

    function sceneName(uint256 generator) internal pure returns (string memory) {
        string[100] memory names = [
            "Squiggle",
            "Party",
            "Vessel",
            "Glitch",
            "Outline",
            "Wave",
            "Segments",
            "Pour",
            "Ink",
            "Flatline",
            "Heartbeat",
            "Morph",
            "Prototype",
            "Reflection",
            "Crt",
            "Plotter",
            "Embroidery",
            "Comet",
            "Balloon",
            "Coaster",
            "Skywriter",
            "River",
            "Lightning",
            "Chrome",
            "Card",
            "Fuse",
            "Slot",
            "Graffiti",
            "Claw",
            "Snowglobe",
            "Museum",
            "Auction",
            "Stamp",
            "Sign",
            "Vending",
            "Printer",
            "Catch",
            "Xray",
            "Magic",
            "Candles",
            "Pinata",
            "Spec",
            "Stick",
            "Pixelsort",
            "Echo",
            "Decode",
            "Screensaver",
            "Helix",
            "Browser",
            "Ferro",
            "Paintbynumbers",
            "Waterslide",
            "Sketch",
            "Polygraph",
            "Bungee",
            "Fireworks",
            "Quantize",
            "Wrap",
            "Blast",
            "DJ",
            "Glow",
            "Afterimage",
            "Sort",
            "Cake",
            "Mutation",
            "Recursive",
            "Screenprint",
            "Kintsugi",
            "Yoyo",
            "Heart",
            "Snowcone",
            "Race",
            "Cube",
            "Barber",
            "Lightpaint",
            "Latte",
            "Cleaner",
            "Electrician",
            "Beltop",
            "Fitter",
            "Crane",
            "Hoist",
            "Jumbotron",
            "Scroll",
            "Repairman",
            "Tuner",
            "Lava",
            "Firehose",
            "Billboard",
            "Weather",
            "Forge",
            "Tattoo",
            "Handheld",
            "Fetch",
            "Jack",
            "Autograph",
            "Straw",
            "Crop",
            "Rink",
            "Puzzle"
        ];
        return names[generator];
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "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.