Skip to content
Verified contractPartialMIT

OGPunkRenderer

Address0xdcd1f2a98cb720fd5ba9feca669f9474285f9610
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

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

src/evolution/renderers/OGPunkRenderer.sol

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

import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";
import {IEvolutionCollection, IEvolutionState, ISkeletonSource} from "../IEvolution.sol";
import {
    SkeletonAttribute,
    ArtState,
    SkeletonConfig,
    InvalidAddress,
    InvalidTokenId,
    InvalidCreditId,
    InvalidVisuals,
    InvalidSource
} from "../EvolutionTypes.sol";
import {PixelArtRenderer} from "./PixelArtRenderer.sol";
import {CreditPunkData} from "../sources/CreditPunkData.sol";

/// @notice Read-only evolution renderer. Existing Punk images/animation/traits are preserved.
contract OGPunkRenderer {
    struct Artwork {
        uint256 id;
        bool minted;
        uint32 source;
        uint256 item;
        uint24 credit;
        bool inVoid;
        uint8 backgroundId;
        uint8 renderMode;
    }
    address public immutable collection;
    address public immutable state;
    address public immutable voidContract;
    address public immutable credits;
    CreditPunkData public immutable dataSource;
    uint8 public constant skeletonId = 0;
    uint24 public constant VOID_BACKGROUND = 0xe3e5e4;

    constructor(address state_, address media_) {
        _code(state_);
        _code(media_);
        state = state_;
        collection = IEvolutionState(state_).collection();
        voidContract = IEvolutionState(state_).voidContract();
        credits = IEvolutionState(state_).credits();
        if (IEvolutionState(state_).renderEngines(1) != media_) revert InvalidAddress(media_);
        if (media().dataSource().credits() != credits) revert InvalidAddress(media_);
        dataSource = media().dataSource();
        if (address(dataSource) != IEvolutionState(state_).nativeSource()) revert InvalidAddress(media_);
    }

    function media() public view returns (PixelArtRenderer) {
        return PixelArtRenderer(IEvolutionState(state).renderEngines(1));
    }

    function supportedModes() public view returns (uint64) { return media().supportedModes(); }

    function readSkeleton(uint256 item) public view returns (bytes memory, uint24) {
        return dataSource.readSkeleton(item);
    }

    function getAttributes(uint256 item) external view returns (SkeletonAttribute[] memory) {
        return dataSource.getAttributes(item);
    }

    function validateSkeleton(uint256 item) external pure {
        if (item >= 10_000) revert InvalidTokenId(item);
    }

    function svg(uint256 id) external view returns (bytes memory) {
        (string memory img,) = _media(id);
        return Base64.decode(LibString.slice(img, 26));
    }

    function html(uint256 id) external view returns (bytes memory) {
        (, string memory anim) = _media(id);
        return bytes(anim).length == 0 ? new bytes(0) : Base64.decode(LibString.slice(anim, 22));
    }

    function _media(uint256 id) private view returns (string memory img, string memory anim) {
        ArtState memory a = IEvolutionState(state).getEffectiveArtState(id);
        if (a.config.skeletonId != 0) revert InvalidSource(a.config.skeletonId);
        if (a.config.renderMode > 63 || supportedModes() & (uint64(1) << a.config.renderMode) == 0)
            revert InvalidVisuals(a.config.backgroundId, a.config.renderMode);
        (bytes memory body,) = readSkeleton(a.skeletonTokenId);
        uint24 bg=IEvolutionState(state).backgroundColor(a.config.backgroundId);
        if(a.inVoid) (img,anim,)=media().artwork(body,bg,a.config.creditId,true,true);
        else (img,anim,)=media().artworkMode(body,24,24,bg,a.config.creditId,a.config.renderMode,true);
    }

    function tokenURI(uint256 id) external view returns (string memory) {
        if (id >= 10_000) revert InvalidTokenId(id);
        ArtState memory a = IEvolutionState(state).getEffectiveArtState(id);
        return _metadata(
            Artwork(
                id,
                true,
                a.config.skeletonId,
                a.skeletonTokenId,
                a.config.creditId,
                a.inVoid,
                a.config.backgroundId,
                a.config.renderMode
            )
        );
    }

    function previewArtwork(uint32 source, uint256 item, uint24 credit, bool inVoid)
        external
        view
        returns (string memory)
    {
        return _metadata(Artwork(0, false, source, item, credit, inVoid, 0, 0));
    }

    function previewCreditGrid(uint256 id) external view returns (bytes memory) {
        _validCredit(id);
        return dataSource.gridOf(id);
    }

    function _metadata(Artwork memory a) private view returns (string memory) {
        if (a.inVoid && a.credit != 0) revert InvalidCreditId(a.credit);
        if (!a.inVoid) _validCredit(a.credit);
        if (a.source != 0) revert InvalidSource(a.source);
        if (a.renderMode > 63 || supportedModes() & (uint64(1) << a.renderMode) == 0)
            revert InvalidVisuals(a.backgroundId, a.renderMode);
        (address adapter, string memory sourceName,) = IEvolutionState(state).sourceInfo(a.source);
        (bytes memory body,) = ISkeletonSource(adapter).readSkeleton(a.item);
        uint24 bg = IEvolutionState(state).backgroundColor(a.backgroundId);
        string memory image;string memory animation;string memory creditTraits;
        if(a.inVoid) (image,animation,creditTraits)=media().artwork(body,bg,a.credit,true,true);
        else (image,animation,creditTraits)=media().artworkMode(body,24,24,bg,a.credit,a.renderMode,true);

        // Only the legacy metadata label is source-specific. Pixels and native traits
        // always come through ISkeletonSource; adding a collection needs no new branch.
        string memory attrs =
            a.source == 0 ? string.concat('{"trait_type":"Punk ID","value":', LibString.toString(a.item), "}") : "";
        if (!a.inVoid) {
            attrs =
                _append(attrs, string.concat('{"trait_type":"Credit ID","value":', LibString.toString(a.credit), "}"));
        }
        string memory optional = _sourceTraits(adapter, a.item);
        if (bytes(optional).length != 0) attrs = _append(attrs, optional);
        if (!a.inVoid) attrs = string.concat(attrs, creditTraits); // legacy traits include their leading comma
        attrs = _append(attrs, _trait("Status", a.inVoid ? "Void" : "Circulating"));
        attrs = _append(attrs, _trait("Skeleton Source", sourceName));
        attrs = _append(attrs, _trait("Skeleton ID", LibString.toString(a.item)));
        attrs = _append(attrs, _trait("Source ID", LibString.toString(a.source)));
        attrs = _append(attrs, _trait("Skeleton Collection", sourceName));
        attrs = _append(attrs, _trait("Skeleton Token ID", LibString.toString(a.item)));
        attrs = _append(attrs, _trait("Background", a.inVoid ? "Void" : LibString.toString(a.backgroundId)));
        attrs = _append(attrs, _trait("Render Mode", a.inVoid ? "Void" : media().modeName(a.renderMode)));
        string memory description = a.inVoid
            ? "A colorless skeleton in the Void."
            : string.concat(
                a.source == 0
                    ? "Punk colors mutated by the onchain art of Credit #"
                    : "Skeleton colors mutated by the onchain art of Credit #",
                LibString.toString(a.credit),
                a.source == 0
                    ? ". Tap the animation to flip the original Punk blocks into Credit colors."
                    : ". Tap the animation to flip the original skeleton blocks into Credit colors."
            );
        string memory json = string.concat(
            '{"name":"',
            a.minted ? string.concat("CP #", LibString.toString(a.id)) : "COLOR PREVIEW",
            '","description":"',
            description,
            '","image":"',
            image,
            '"',
            a.inVoid ? "" : string.concat(',"animation_url":"', animation, '"'),
            ',"attributes":[',
            attrs,
            "]}"
        );
        return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
    }

    function _sourceTraits(address adapter, uint256 item) private view returns (string memory result) {
        try ISkeletonSource(adapter).getAttributes(item) returns (SkeletonAttribute[] memory attrs) {
            if (attrs.length > 32) return "";
            for (uint256 i; i < attrs.length; ++i) {
                if (
                    bytes(attrs[i].traitType).length > 64 || bytes(attrs[i].value).length > 128
                        || _reserved(attrs[i].traitType)
                ) return "";
                result = _append(result, _trait(attrs[i].traitType, attrs[i].value));
            }
        } catch {
            return "";
        }
    }

    function _reserved(string memory label) private pure returns (bool) {
        bytes32 h = keccak256(bytes(label));
        return h == keccak256("Punk ID") || h == keccak256("Original Punk ID") || h == keccak256("Credit ID")
            || h == keccak256("Credit Inked Cells") || h == keccak256("Credit Pigments")
            || h == keccak256("Credit Alignment") || h == keccak256("Status") || h == keccak256("Skeleton Source")
            || h == keccak256("Skeleton ID") || h == keccak256("Source ID") || h == keccak256("Revision")
            || h == keccak256("Rules Version");
    }

    function _trait(string memory key, string memory value) private pure returns (string memory) {
        return
            string.concat(
                '{"trait_type":"', LibString.escapeJSON(key), '","value":"', LibString.escapeJSON(value), '"}'
            );
    }

    function _append(string memory left, string memory right) private pure returns (string memory) {
        return bytes(left).length == 0 ? right : string.concat(left, ",", right);
    }

    function _validCredit(uint256 id) private pure {
        if (id == 0 || id > 122154) revert InvalidCreditId(id);
    }

    function _code(address addr) private view {
        if (addr.code.length == 0) revert InvalidAddress(addr);
    }
}

lib/solady/src/utils/Base64.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/solady/src/utils/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)));
    }
}

lib/solady/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 {} // Scan for '\0'.
             byte(n, s) { n := add(n, 1) } {}
            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 {} // Scan for '\0'.
             byte(result, s) { result := add(result, 1) } {}
            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))),
                    shr(shl(3, add(aLen, 1)), mload(add(b, 0x1f)))
                ),
                // `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)))
        }
    }
}

lib/solady/src/utils/SSTORE2.sol

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

/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The proxy initialization code.
    uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;

    /// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
    /// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
    bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
        0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;

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

    /// @dev Unable to deploy the storage contract.
    error DeploymentFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         WRITE LOGIC                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    function write(bytes memory data) internal returns (address pointer) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
            /**
             * ---------------------------------------------------+
             * Opcode | Mnemonic       | Stack     | Memory       |
             * ---------------------------------------------------|
             * 61 l   | PUSH2 l        | l         |              |
             * 80     | DUP1           | l l       |              |
             * 60 0xa | PUSH1 0xa      | 0xa l l   |              |
             * 3D     | RETURNDATASIZE | 0 0xa l l |              |
             * 39     | CODECOPY       | l         | [0..l): code |
             * 3D     | RETURNDATASIZE | 0 l       | [0..l): code |
             * F3     | RETURN         |           | [0..l): code |
             * 00     | STOP           |           |              |
             * ---------------------------------------------------+
             * @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
             * Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
             */
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create(0, add(data, 0x15), add(n, 0xb))
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract with `salt`
    /// and returns its normal CREATE2 deterministic address.
    function writeCounterfactual(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            // Deploy a new contract with the generated creation code.
            pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
            if iszero(pointer) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Writes `data` into the bytecode of a storage contract and returns its address.
    /// This uses the so-called "CREATE3" workflow,
    /// which means that `pointer` is agnostic to `data, and only depends on `salt`.
    function writeDeterministic(bytes memory data, bytes32 salt)
        internal
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
            let proxy := create2(0, 0x10, 0x10, salt)
            if iszero(proxy) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, proxy) // Store the proxy's address.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)

            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
            if iszero(
                mul( // The arguments of `mul` are evaluated last to first.
                    extcodesize(pointer),
                    call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
                )
            ) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    ADDRESS CALCULATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the initialization code hash of the storage contract for `data`.
    /// Used for mining vanity addresses with create2crunch.
    function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            // Do a out-of-gas revert if `n + 1` is more than 2 bytes.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
            mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
            hash := keccak256(add(data, 0x15), add(n, 0xb))
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
    function predictCounterfactualAddress(bytes memory data, bytes32 salt)
        internal
        view
        returns (address pointer)
    {
        pointer = predictCounterfactualAddress(data, salt, address(this));
    }

    /// @dev Returns the CREATE2 address of the storage contract for `data`
    /// deployed with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        bytes32 hash = initCodeHash(data);
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, hash)
            mstore(0x01, shl(96, deployer))
            mstore(0x15, salt)
            predicted := keccak256(0x00, 0x55)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x35, 0)
        }
    }

    /// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
    function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
        pointer = predictDeterministicAddress(salt, address(this));
    }

    /// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
    function predictDeterministicAddress(bytes32 salt, address deployer)
        internal
        pure
        returns (address pointer)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x00, deployer) // Store `deployer`.
            mstore8(0x0b, 0xff) // Store the prefix.
            mstore(0x20, salt) // Store the salt.
            mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.

            mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
            mstore(0x40, m) // Restore the free memory pointer.
            // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
            // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
            mstore(0x00, 0xd694)
            mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
            pointer := keccak256(0x1e, 0x17)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         READ LOGIC                         */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
    function read(address pointer) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
            extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
            mstore(data, n) // Store the length.
            mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
    function read(address pointer, uint256 start) internal view returns (bytes memory data) {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21))
            mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the data on `pointer` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `pointer` MUST be deployed via the SSTORE2 write functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `pointer` does not have any code.
    function read(address pointer, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory data)
    {
        /// @solidity memory-safe-assembly
        assembly {
            data := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
            if iszero(and(0xff, mload(add(data, d)))) {
                let n := sub(extcodesize(pointer), 0x01)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(data, d) // Store the length.
            mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
        }
    }
}

src/CreditedPunksRenderer.sol

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

import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";

import {ICryptoPunksData} from "./ICryptoPunksData.sol";
import {SvgRenderer} from "./SvgRenderer.sol";

interface ICreditData {
    function seedOf(uint256 tokenId) external view returns (bytes21);
    function timestampOf(uint256 tokenId) external view returns (uint64);
}

interface ICreditedPunksPairing {
    function creditOfToken(uint256 tokenId) external view returns (uint256);
    function punkOfToken(uint256 tokenId) external view returns (uint256);
}

/// @notice First, replaceable renderer for CREDITED PUNKS.
/// @dev Reads Credit seed/time and calls the original immutable art contract's raw SVG function.
///      The Credit tokenURI is never called. This renderer's art rule is A / FULL.
contract CreditedPunksRenderer {
    uint16 public constant MAX_SUPPLY = 10_000;
    uint24 public constant BACKGROUND = 0x708492;
    bytes4 private constant CREDIT_RAW_SVG_SELECTOR = 0x3931cef5;
    bytes private constant JSON_PREFIX = "data:application/json;base64,";
    bytes private constant SVG_PREFIX =
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" shape-rendering="crispEdges">';

    ICreditData public immutable credits;
    ICreditedPunksPairing public immutable collection;
    address public immutable creditArt;
    ICryptoPunksData public immutable punksData;

    error InvalidAddress();
    error InvalidTokenId();
    error InvalidPunk();
    error CreditArtFailed();
    error UnsupportedCreditSvg();

    constructor(address collection_, address credits_, address creditArt_, address punksData_) {
        if (collection_ == address(0) || credits_ == address(0) || creditArt_ == address(0) || punksData_ == address(0)) {
            revert InvalidAddress();
        }
        collection = ICreditedPunksPairing(collection_);
        credits = ICreditData(credits_);
        creditArt = creditArt_;
        punksData = ICryptoPunksData(punksData_);
    }

    function tokenURI(uint256 tokenId) external view returns (string memory) {
        uint256 creditId = collection.creditOfToken(tokenId);
        if (creditId == 0) revert InvalidTokenId();
        uint256 punkIdRaw = collection.punkOfToken(tokenId);
        if (punkIdRaw >= MAX_SUPPLY) revert InvalidPunk();
        uint16 punkId = uint16(punkIdRaw);
        bytes memory raw = punksData.punkImage(punkId);
        if (raw.length != 24 * 24 * 4) revert InvalidPunk();
        string memory originalPunkImage = SvgRenderer.renderImageDataURIWithBackground(raw, BACKGROUND);
        string memory creditSvg = _creditSvg(creditId);
        bytes memory grid = _gridFromSvg(bytes(creditSvg));
        bytes memory punkMask = new bytes(72);
        for (uint256 y; y < 24; ++y) {
            for (uint256 x; x < 24; ++x) {
                uint256 pixel = (y * 24 + x) * 4;
                if (raw[pixel + 3] == 0) continue;
                uint256 position = y * 24 + x;
                punkMask[position >> 3] = bytes1(uint8(punkMask[position >> 3]) | uint8(1 << (position & 7)));
                uint256 color = ((y / 3) * 8 + x / 3) * 3;
                raw[pixel] = grid[color];
                raw[pixel + 1] = grid[color + 1];
                raw[pixel + 2] = grid[color + 2];
            }
        }
        string memory image = SvgRenderer.renderImageDataURIWithBackground(raw, BACKGROUND);
        string memory animation = _animationDataURI(image, originalPunkImage, punkMask);
        string memory json = string.concat(
            '{"name":"CREDITED PUNKS #', LibString.toString(tokenId),
            '","description":"Punk colors mutated by the onchain art of Credit #', LibString.toString(creditId),
            '. Tap the animation to flip the original Punk blocks into Credit colors.","image":"',
            image, '","animation_url":"', animation,
            '","attributes":[{"trait_type":"Punk ID","value":', LibString.toString(punkId),
            '},{"trait_type":"Credit ID","value":', LibString.toString(creditId), '}',
            _punkAttributesJSON(punkId), _creditAttributesJSON(grid, bytes(creditSvg)), ']}'
        );
        return string.concat(string(JSON_PREFIX), Base64.encode(bytes(json)));
    }

    function previewCreditGrid(uint256 creditId) external view returns (bytes memory) {
        return _gridFromSvg(bytes(_creditSvg(creditId)));
    }

    function _creditSvg(uint256 creditId) private view returns (string memory) {
        bytes21 seed = credits.seedOf(creditId);
        uint64 timestamp = credits.timestampOf(creditId);
        (bool ok, bytes memory data) = creditArt.staticcall(
            abi.encodeWithSelector(CREDIT_RAW_SVG_SELECTOR, seed, timestamp)
        );
        if (!ok || data.length < 64) revert CreditArtFailed();
        return abi.decode(data, (string));
    }

    function _animationDataURI(
        string memory image, string memory originalPunkImage, bytes memory punkMask
    ) private pure returns (string memory) {
        string memory mask64 = Base64.encode(punkMask);
        bytes memory html = abi.encodePacked(
            "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>Credited Punk aligned block flip study</title><style>\nhtml,body{margin:0;width:100%;height:100%;overflow:hidden;background:#708492}\nbody{position:relative}\n#stage{position:absolute;left:0;top:0;width:24px;height:24px;perspective:900px;cursor:pointer;touch-action:manipulation}\n#stage:focus-visible{outline:2px solid #f",
            "ff;outline-offset:-2px}\n.tile{position:absolute;transform-style:preserve-3d;transform:rotateX(0deg);transition:transform 290ms cubic-bezier(.35,.1,.65,.9);transition-delay:var(--delay)}\n.tile.mutated{transform:rotateX(-180deg)}\n#stage.resetting .tile{transition:none}\n.face{position:absolute;inset:0;width:100%;height:100%;backface-visibility:hidden;image-rendering:pixelated}\n.face.back{transform:rotateX(180deg)}\n.still{position:absolute;inset:0;width:100%;h",
            "eight:100%;image-rendering:pixelated;pointer-events:none;z-index:2}\n.still[hidden]{display:none}\n</style></head><body><main id=\"stage\" role=\"button\" tabindex=\"0\" aria-label=\"Play color flip\" title=\"Tap to play or stop the color flip\"><img id=\"ogStill\" class=\"still\" hidden><img id=\"artStill\" class=\"still\"></main><script>\nconst originalURI='",
            originalPunkImage,
            "',finalURI='",
            image,
            "';\nconst mask=Uint8Array.from(atob('",
            mask64,
            "'),c=>c.charCodeAt(0));\nconst stage=document.getElementById('stage'),ogStill=document.getElementById('ogStill'),artStill=document.getElementById('artStill');\nfunction fitStage(){\n  const dpr=window.devicePixelRatio||1;\n  const unit=Math.max(1,Math.floor(Math.min(innerWidth,innerHeight)*dpr/24));\n  const physicalSize=unit*24;\n  stage.style.width=stage.style.height=physicalSize/dpr+'px';\n  stage.style.left=Math.round((innerWidth*dpr-physicalSize)/2)/dpr+'px';\n  stage.style.top=Math.round((innerHeight*dpr-physicalSize)/2)/dpr+'px';\n}\nfitStage();addEventListener('resize',fitStage);\nconst load=src=>new Promise((resolve,reject)=>{const image=new Image();image.onload=()=>resolve(image);image.onerror=reject;image.src=src});\nconst scratch=document.createElement('canvas');scratch.width=scratch.height=24;\nconst ctx=scratch.getContext('2d',{willReadFrequently:true});\nfunction cap",
            "ture(image){ctx.clearRect(0,0,24,24);ctx.drawImage(image,0,0,24,24);return ctx.getImageData(0,0,24,24).data}\nfunction face(pixels,tx,ty,back){\n  const canvas=document.createElement('canvas');canvas.width=canvas.height=3;\n  canvas.className='face '+(back?'back':'front');\n  const c=canvas.getContext('2d'),tile=c.createImageData(3,3);\n  for(let y=0;y<3;y++)for(let x=0;x<3;x++){\n    const source=((ty*3+y)*24+tx*3+x),target=(y*3+x)*4;\n    for(let k=0;k<4;k++)tile.data[target+k]=pixels[source*4+k];\n  }\n  c.putImageData(tile,0,0);return canvas;\n}\nlet tiles=[],playing=false,timer,settleTimer;\nfunction build(original,final){\n  for(let y=0;y<8;y++)for(let x=0;x<8;x++){\n    let o",
            "ccupied=false;\n    for(let py=0;py<3;py++)for(let px=0;px<3;px++){\n      const i=(y*3+py)*24+x*3+px;\n      if(mask[i>>3]&(1<<(i&7)))occupied=true;\n    }\n    if(!occupied)continue;\n    const tile=document.createElement('div');tile.className='tile mutated';tile.dataset.index=y*8+x;\n    tile.style.cssText=`left:${x*12.5}%;top:${y*12.5}%;width:12.5%;height:12.5%;--delay:${(y*8+x)*22}ms`;\n    tile.append(face(original,x,y,false),face(final,x,y,true));stage.appe",
            "nd(tile);tiles.push(tile);\n  }\n}\nfunction setMutated(value){for(const tile of tiles)tile.classList.toggle('mutated',value)}\nfunction flipToArt(){\n  if(!tiles.some(tile=>!tile.classList.contains('mutated'))){ogStill.hidden=true;artStill.hidden=false;return}\n  ogStill.hidden=true;setMutated(true);\n  clearTimeout(settleTimer);settleTimer=setTimeout(()=>artStill.hidden=false,1750);\n}\nfunction cycle(){\n  if(!playing)return;\n  clearTimeout(settleTimer)",
            ";artStill.hidden=true;ogStill.hidden=false;\n  stage.classList.add('resetting');\n  setMutated(false);\n  void stage.offsetWidth;\n  stage.classList.remove('resetting');\n  timer=setTimeout(()=>{if(!playing)return;flipToArt();\n    timer=setTimeout(cycle,4400);\n  },900);\n}\nfunction toggle(){\n  if(!tiles.length)return;\n  playing=!playing;clearTimeout(timer);\n  if(playing)cycle();else flipToArt();\n  stage.setAttribute('aria-label',playing?'Stop co",
            "lor flip':'Play color flip');\n}\nstage.addEventListener('click',e=>{if(e.button===0)toggle()});\nstage.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle()}});\nPromise.all([load(originalURI),load(finalURI)]).then(([a,b])=>{ogStill.src=originalURI;artStill.src=finalURI;build(capture(a),capture(b))});\n</script></body></html>\n"
        );
        return string.concat("data:text/html;base64,", Base64.encode(html));
    }

    function _punkAttributesJSON(uint16 punkId) private view returns (string memory) {
        try punksData.punkAttributes(punkId) returns (string memory text) {
            bytes memory raw = bytes(text);
            bytes memory json = "";
            uint256 start;
            uint256 attrIndex;
            while (start < raw.length) {
                while (start < raw.length && (raw[start] == 0x20 || raw[start] == 0x2c)) start++;
                uint256 end = start;
                while (end < raw.length && raw[end] != 0x2c) end++;
                uint256 trimmedEnd = end;
                while (trimmedEnd > start && raw[trimmedEnd - 1] == 0x20) trimmedEnd--;
                if (trimmedEnd > start) {
                    json = abi.encodePacked(
                        json, ',{"trait_type":"', attrIndex == 0 ? "Type" : "Attribute", '","value":"',
                        _escapeJson(_slice(raw, start, trimmedEnd - start)), '"}'
                    );
                    attrIndex++;
                }
                start = end + 1;
            }
            return string(json);
        } catch {
            return "";
        }
    }

    function _creditAttributesJSON(bytes memory grid, bytes memory svg) private pure returns (string memory) {
        uint256 inkedCells;
        uint256 pigmentCount;
        uint24[64] memory pigments;
        for (uint256 i; i < 64; ++i) {
            uint256 p = i * 3;
            uint24 color = (uint24(uint8(grid[p])) << 16) | (uint24(uint8(grid[p + 1])) << 8)
                | uint24(uint8(grid[p + 2]));
            if (color == 0xffffff) continue;
            inkedCells++;
            bool found;
            for (uint256 j; j < pigmentCount; ++j) {
                if (pigments[j] == color) { found = true; break; }
            }
            if (!found) pigments[pigmentCount++] = color;
        }
        uint256 frameStart = SVG_PREFIX.length + bytes('<rect width="320" height="320" fill="#ffffff"/>').length;
        (uint256 frameX, uint256 frameY,) = _readRect(svg, frameStart, true);
        return string.concat(
            ',{"display_type":"number","trait_type":"Credit Inked Cells","value":',
            LibString.toString(inkedCells),
            '},{"display_type":"number","trait_type":"Credit Pigments","value":',
            LibString.toString(pigmentCount),
            '},{"trait_type":"Credit Alignment","value":"',
            frameX == 80 && frameY == 80 ? "Centered" : "Shifted", '"}'
        );
    }

    function _slice(bytes memory data, uint256 start, uint256 len) private pure returns (bytes memory out) {
        out = new bytes(len);
        for (uint256 i; i < len; ++i) out[i] = data[start + i];
    }

    function _escapeJson(bytes memory value) private pure returns (bytes memory out) {
        out = "";
        for (uint256 i; i < value.length; ++i) {
            bytes1 c = value[i];
            if (c == 0x22 || c == 0x5c) out = abi.encodePacked(out, bytes1(0x5c), c);
            else if (uint8(c) >= 0x20) out = abi.encodePacked(out, c);
        }
    }

    function _gridFromSvg(bytes memory svg) private pure returns (bytes memory grid) {
        if (!_startsWith(svg, SVG_PREFIX)) revert UnsupportedCreditSvg();
        grid = new bytes(8 * 8 * 3);
        uint256 cursor = SVG_PREFIX.length;
        bytes memory whiteBackground = bytes('<rect width="320" height="320" fill="#ffffff"/>');
        if (!_match(svg, cursor, whiteBackground)) revert UnsupportedCreditSvg();
        cursor += whiteBackground.length;

        (uint256 frameX, uint256 frameY, uint24 frameColor) = _readRect(svg, cursor, true);
        if (frameColor != 0xffffff) revert UnsupportedCreditSvg();
        cursor += 63;
        for (uint256 i; i < 64; ++i) _writeColor(grid, i, 0xffffff);

        while (_match(svg, cursor, bytes('<rect x="'))) {
            (uint256 x, uint256 y, uint24 color) = _readRect(svg, cursor, false);
            uint256 gx = 8;
            uint256 gy = 8;
            for (uint256 row; row < 8; ++row) {
                uint256 cy = frameY + row * 20 + 10;
                if (cy >= y && cy < y + 20) { gy = row; break; }
            }
            for (uint256 col; col < 8; ++col) {
                uint256 cx = frameX + col * 20 + 10;
                if (cx >= x && cx < x + 20) { gx = col; break; }
            }
            if (gx < 8 && gy < 8) _writeColor(grid, gy * 8 + gx, color);
            cursor += 63;
        }
        if (!_match(svg, cursor, bytes("</svg>")) || cursor + 6 != svg.length) revert UnsupportedCreditSvg();
    }

    function _readRect(bytes memory svg, uint256 cursor, bool frame)
        private pure returns (uint256 x, uint256 y, uint24 color)
    {
        if (cursor + 63 > svg.length || !_match(svg, cursor, bytes('<rect x="'))
            || !_match(svg, cursor + 12, bytes('" y="'))
            || !_match(svg, cursor + 20, bytes('" width="'))
            || !_match(svg, cursor + 32, bytes('" height="'))
            || !_match(svg, cursor + 45, bytes('" fill="#'))
            || !_match(svg, cursor + 60, bytes('"/>'))
            || !_match(svg, cursor + 29, frame ? bytes("160") : bytes("020"))
            || !_match(svg, cursor + 42, frame ? bytes("160") : bytes("020"))
        ) revert UnsupportedCreditSvg();

        x = _readThreeDigits(svg, cursor + 9);
        y = _readThreeDigits(svg, cursor + 17);
        for (uint256 i; i < 6; ++i) {
            uint8 c = uint8(svg[cursor + 54 + i]);
            uint8 nibble;
            if (c >= 48 && c <= 57) nibble = c - 48;
            else if (c >= 97 && c <= 102) nibble = c - 87;
            else if (c >= 65 && c <= 70) nibble = c - 55;
            else revert UnsupportedCreditSvg();
            color = (color << 4) | nibble;
        }
    }

    function _readThreeDigits(bytes memory data, uint256 start) private pure returns (uint256 value) {
        for (uint256 i; i < 3; ++i) {
            uint8 c = uint8(data[start + i]);
            if (c < 48 || c > 57) revert UnsupportedCreditSvg();
            value = value * 10 + c - 48;
        }
    }

    function _writeColor(bytes memory grid, uint256 i, uint24 color) private pure {
        uint256 p = i * 3;
        grid[p] = bytes1(uint8(color >> 16));
        grid[p + 1] = bytes1(uint8(color >> 8));
        grid[p + 2] = bytes1(uint8(color));
    }

    function _startsWith(bytes memory data, bytes memory prefix) private pure returns (bool) {
        return _match(data, 0, prefix);
    }

    function _match(bytes memory data, uint256 start, bytes memory needle) private pure returns (bool) {
        if (start + needle.length > data.length) return false;
        for (uint256 i; i < needle.length; ++i) if (data[start + i] != needle[i]) return false;
        return true;
    }
}

src/ICryptoPunksData.sol

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

/// @notice Mainnet CryptoPunksData @ 0x16f5a35647d6f03d5d3da7b35409d65ba03af3b2
///         Returns raw 24x24 RGBA bytes (2304 bytes per Punk).
interface ICryptoPunksData {
    function punkAttributes(uint16 index) external view returns (string memory);
    function punkImage(uint16 index) external view returns (bytes memory);
}

src/SvgRenderer.sol

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

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

/// @title SvgRenderer
/// @notice Converts a 24x24 binary-alpha RGBA buffer (output of
///         ArchitectPixelModel) into a base64 SVG data URI using horizontal
///         run-length compression. Pixels with alpha=0 are skipped (no rect),
///         pixels with alpha=255 collapse adjacent same-color runs into one
///         <rect width="W"/>.
library SvgRenderer {
    error BadRgbaLength();

    /// Width / height in source pixels.
    uint256 internal constant DIM = 24;

    /// Worst-case payload sizing.
    /// - Max rects: 24 rows * 12 alternating runs/row ~ 288, but if every pixel
    ///   has different color, up to 576. Per rect ~ 50 bytes.
    /// - 576 * 60 + 200 = 34_760 bytes. We round up to 36_864.
    uint256 internal constant MAX_SVG_BYTES = 36_864;

    /// @notice Render an SVG document (NOT base64 encoded) for the given RGBA.
    function renderSvg(bytes memory rgba) internal pure returns (bytes memory svg) {
        return _renderSvg(rgba, false, 0);
    }

    /// @notice Render an SVG document with a fixed 24x24 background color.
    function renderSvgWithBackground(bytes memory rgba, uint24 backgroundColor)
        internal
        pure
        returns (bytes memory svg)
    {
        return _renderSvg(rgba, true, backgroundColor);
    }

    function _renderSvg(bytes memory rgba, bool hasBackground, uint24 backgroundColor)
        private
        pure
        returns (bytes memory svg)
    {
        if (rgba.length != DIM * DIM * 4) revert BadRgbaLength();

        // Pre-allocate output and use a cursor; we shrink before returning.
        svg = new bytes(MAX_SVG_BYTES);
        uint256 cursor = 0;

        cursor = _writeBytes(
            svg,
            cursor,
            bytes(
                '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" shape-rendering="crispEdges" style="image-rendering:pixelated">'
            )
        );

        if (hasBackground) {
            cursor = _writeBackgroundRect(svg, cursor, backgroundColor);
        }

        for (uint256 y = 0; y < DIM; ++y) {
            uint256 x = 0;
            while (x < DIM) {
                uint256 idx = (y * DIM + x) * 4;
                uint8 a = uint8(rgba[idx + 3]);

                if (a == 0) {
                    unchecked {
                        ++x;
                    }
                    continue;
                }

                bytes1 r = rgba[idx];
                bytes1 g = rgba[idx + 1];
                bytes1 b = rgba[idx + 2];

                // Find horizontal run of identical (r,g,b) opaque pixels.
                uint256 runEnd = x + 1;
                while (runEnd < DIM) {
                    uint256 nIdx = (y * DIM + runEnd) * 4;
                    if (uint8(rgba[nIdx + 3]) == 0 || rgba[nIdx] != r || rgba[nIdx + 1] != g || rgba[nIdx + 2] != b) {
                        break;
                    }
                    unchecked {
                        ++runEnd;
                    }
                }
                uint256 width = runEnd - x;

                cursor = _writeRect(svg, cursor, x, y, width, r, g, b);
                x = runEnd;
            }
        }

        cursor = _writeBytes(svg, cursor, bytes("</svg>"));

        // Truncate to actual length.
        assembly {
            mstore(svg, cursor)
        }
    }

    /// @notice Render an `<svg ...>` document and wrap as `data:image/svg+xml;base64,...`.
    function renderImageDataURI(bytes memory rgba) internal pure returns (string memory) {
        bytes memory svg = renderSvg(rgba);
        return string.concat("data:image/svg+xml;base64,", Base64.encode(svg));
    }

    /// @notice Render a background-backed SVG and wrap as `data:image/svg+xml;base64,...`.
    function renderImageDataURIWithBackground(bytes memory rgba, uint24 backgroundColor)
        internal
        pure
        returns (string memory)
    {
        bytes memory svg = renderSvgWithBackground(rgba, backgroundColor);
        return string.concat("data:image/svg+xml;base64,", Base64.encode(svg));
    }

    // ---------- internal writers ----------

    function _writeBackgroundRect(bytes memory buf, uint256 cursor, uint24 color) private pure returns (uint256) {
        // <rect width="24" height="24" fill="#RRGGBB"/>
        cursor = _writeBytes(buf, cursor, bytes('<rect width="24" height="24" fill="#'));
        cursor = _writeHexByte(buf, cursor, bytes1(uint8(color >> 16)));
        cursor = _writeHexByte(buf, cursor, bytes1(uint8(color >> 8)));
        cursor = _writeHexByte(buf, cursor, bytes1(uint8(color)));
        cursor = _writeBytes(buf, cursor, bytes('"/>'));
        return cursor;
    }

    function _writeRect(
        bytes memory buf,
        uint256 cursor,
        uint256 x,
        uint256 y,
        uint256 width,
        bytes1 r,
        bytes1 g,
        bytes1 b
    ) private pure returns (uint256) {
        // <rect x="X" y="Y" width="W" height="1" fill="#RRGGBB"/>
        cursor = _writeBytes(buf, cursor, bytes('<rect x="'));
        cursor = _writeUint(buf, cursor, x);
        cursor = _writeBytes(buf, cursor, bytes('" y="'));
        cursor = _writeUint(buf, cursor, y);
        cursor = _writeBytes(buf, cursor, bytes('" width="'));
        cursor = _writeUint(buf, cursor, width);
        cursor = _writeBytes(buf, cursor, bytes('" height="1" fill="#'));
        cursor = _writeHexByte(buf, cursor, r);
        cursor = _writeHexByte(buf, cursor, g);
        cursor = _writeHexByte(buf, cursor, b);
        cursor = _writeBytes(buf, cursor, bytes('"/>'));
        return cursor;
    }

    function _writeBytes(bytes memory buf, uint256 cursor, bytes memory data) private pure returns (uint256) {
        uint256 n = data.length;
        // Word-aligned copy via Cancun mcopy. Skips per-byte bounds checks.
        assembly {
            let dst := add(add(buf, 0x20), cursor)
            let src := add(data, 0x20)
            mcopy(dst, src, n)
        }
        return cursor + n;
    }

    function _writeUint(bytes memory buf, uint256 cursor, uint256 v) private pure returns (uint256) {
        // Values here are 0..24, so at most 2 digits. Use mstore8 directly.
        if (v == 0) {
            assembly { mstore8(add(add(buf, 0x20), cursor), 0x30) }
            return cursor + 1;
        }
        if (v < 10) {
            assembly { mstore8(add(add(buf, 0x20), cursor), add(v, 0x30)) }
            return cursor + 1;
        }
        // 2-digit (10..99): write tens then units.
        uint256 tens = v / 10;
        uint256 ones = v % 10;
        assembly {
            let p := add(add(buf, 0x20), cursor)
            mstore8(p, add(tens, 0x30))
            mstore8(add(p, 1), add(ones, 0x30))
        }
        return cursor + 2;
    }

    function _writeHexByte(bytes memory buf, uint256 cursor, bytes1 b) private pure returns (uint256) {
        uint8 v = uint8(b);
        uint8 hi = v >> 4;
        uint8 lo = v & 0x0f;
        // hi/lo nibble -> hex char (0..9 -> 0x30..0x39, 10..15 -> 0x61..0x66)
        uint8 hiC = hi < 10 ? uint8(48 + hi) : uint8(87 + hi);
        uint8 loC = lo < 10 ? uint8(48 + lo) : uint8(87 + lo);
        assembly {
            let p := add(add(buf, 0x20), cursor)
            mstore8(p, hiC)
            mstore8(add(p, 1), loC)
        }
        return cursor + 2;
    }
}

src/evolution/CreditArt.sol

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

import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";
import {ICreditData} from "../CreditedPunksRenderer.sol";

/// @dev Original raw-SVG parser and Credit traits. Does not query Credit ownerOf/tokenURI.
library CreditArt {
    error CreditArtFailed();
    error UnsupportedCreditSvg();
    bytes4 private constant CREDIT_RAW_SVG_SELECTOR = 0x3931cef5;
    bytes private constant SVG_PREFIX =
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" shape-rendering="crispEdges">';

    function read(address credits, address art, uint256 id)
        internal
        view
        returns (bytes memory grid, string memory attributes)
    {
        bytes memory svg = bytes(_creditSvg(credits, art, id));
        grid = _gridFromSvg(svg);
        attributes = _creditAttributesJSON(grid, svg);
    }

    function gridOf(address credits, address art, uint256 id) internal view returns (bytes memory) {
        return _gridFromSvg(bytes(_creditSvg(credits, art, id)));
    }

    function _creditSvg(address creditData, address creditArt, uint256 creditId) private view returns (string memory) {
        bytes21 seed = ICreditData(creditData).seedOf(creditId);
        uint64 timestamp = ICreditData(creditData).timestampOf(creditId);
        (bool ok, bytes memory data) =
            creditArt.staticcall(abi.encodeWithSelector(CREDIT_RAW_SVG_SELECTOR, seed, timestamp));
        if (!ok || data.length < 64) revert CreditArtFailed();
        return abi.decode(data, (string));
    }

    function _creditAttributesJSON(bytes memory grid, bytes memory svg) private pure returns (string memory) {
        uint256 inkedCells;
        uint256 pigmentCount;
        uint24[64] memory pigments;
        for (uint256 i; i < 64; ++i) {
            uint256 p = i * 3;
            uint24 color = (uint24(uint8(grid[p])) << 16) | (uint24(uint8(grid[p + 1])) << 8)
                | uint24(uint8(grid[p + 2]));
            if (color == 0xffffff) continue;
            inkedCells++;
            bool found;
            for (uint256 j; j < pigmentCount; ++j) {
                if (pigments[j] == color) { found = true; break; }
            }
            if (!found) pigments[pigmentCount++] = color;
        }
        uint256 frameStart = SVG_PREFIX.length + bytes('<rect width="320" height="320" fill="#ffffff"/>').length;
        (uint256 frameX, uint256 frameY,) = _readRect(svg, frameStart, true);
        return string.concat(
            ',{"display_type":"number","trait_type":"Credit Inked Cells","value":',
            LibString.toString(inkedCells),
            '},{"display_type":"number","trait_type":"Credit Pigments","value":',
            LibString.toString(pigmentCount),
            '},{"trait_type":"Credit Alignment","value":"',
            frameX == 80 && frameY == 80 ? "Centered" : "Shifted", '"}'
        );
    }

    function _gridFromSvg(bytes memory svg) private pure returns (bytes memory grid) {
        if (!_startsWith(svg, SVG_PREFIX)) revert UnsupportedCreditSvg();
        grid = new bytes(8 * 8 * 3);
        uint256 cursor = SVG_PREFIX.length;
        bytes memory whiteBackground = bytes('<rect width="320" height="320" fill="#ffffff"/>');
        if (!_match(svg, cursor, whiteBackground)) revert UnsupportedCreditSvg();
        cursor += whiteBackground.length;

        (uint256 frameX, uint256 frameY, uint24 frameColor) = _readRect(svg, cursor, true);
        if (frameColor != 0xffffff) revert UnsupportedCreditSvg();
        cursor += 63;
        for (uint256 i; i < 64; ++i) _writeColor(grid, i, 0xffffff);

        while (_match(svg, cursor, bytes('<rect x="'))) {
            (uint256 x, uint256 y, uint24 color) = _readRect(svg, cursor, false);
            uint256 gx = 8;
            uint256 gy = 8;
            for (uint256 row; row < 8; ++row) {
                uint256 cy = frameY + row * 20 + 10;
                if (cy >= y && cy < y + 20) { gy = row; break; }
            }
            for (uint256 col; col < 8; ++col) {
                uint256 cx = frameX + col * 20 + 10;
                if (cx >= x && cx < x + 20) { gx = col; break; }
            }
            if (gx < 8 && gy < 8) _writeColor(grid, gy * 8 + gx, color);
            cursor += 63;
        }
        if (!_match(svg, cursor, bytes("</svg>")) || cursor + 6 != svg.length) revert UnsupportedCreditSvg();
    }

    function _readRect(bytes memory svg, uint256 cursor, bool frame)
        private pure returns (uint256 x, uint256 y, uint24 color)
    {
        if (cursor + 63 > svg.length || !_match(svg, cursor, bytes('<rect x="'))
            || !_match(svg, cursor + 12, bytes('" y="'))
            || !_match(svg, cursor + 20, bytes('" width="'))
            || !_match(svg, cursor + 32, bytes('" height="'))
            || !_match(svg, cursor + 45, bytes('" fill="#'))
            || !_match(svg, cursor + 60, bytes('"/>'))
            || !_match(svg, cursor + 29, frame ? bytes("160") : bytes("020"))
            || !_match(svg, cursor + 42, frame ? bytes("160") : bytes("020"))
        ) revert UnsupportedCreditSvg();

        x = _readThreeDigits(svg, cursor + 9);
        y = _readThreeDigits(svg, cursor + 17);
        for (uint256 i; i < 6; ++i) {
            uint8 c = uint8(svg[cursor + 54 + i]);
            uint8 nibble;
            if (c >= 48 && c <= 57) nibble = c - 48;
            else if (c >= 97 && c <= 102) nibble = c - 87;
            else if (c >= 65 && c <= 70) nibble = c - 55;
            else revert UnsupportedCreditSvg();
            color = (color << 4) | nibble;
        }
    }

    function _readThreeDigits(bytes memory data, uint256 start) private pure returns (uint256 value) {
        for (uint256 i; i < 3; ++i) {
            uint8 c = uint8(data[start + i]);
            if (c < 48 || c > 57) revert UnsupportedCreditSvg();
            value = value * 10 + c - 48;
        }
    }

    function _writeColor(bytes memory grid, uint256 i, uint24 color) private pure {
        uint256 p = i * 3;
        grid[p] = bytes1(uint8(color >> 16));
        grid[p + 1] = bytes1(uint8(color >> 8));
        grid[p + 2] = bytes1(uint8(color));
    }

    function _startsWith(bytes memory data, bytes memory prefix) private pure returns (bool) {
        return _match(data, 0, prefix);
    }

    function _match(bytes memory data, uint256 start, bytes memory needle) private pure returns (bool) {
        if (start + needle.length > data.length) return false;
        for (uint256 i; i < needle.length; ++i) if (data[start + i] != needle[i]) return false;
        return true;
    }
}

src/evolution/EvolutionTypes.sol

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

enum EvolutionKind {
    DonorColor,
    FreeCredit,
    Redeem
}

struct ArtworkChange {
    uint256 tokenId;
    address ownerBefore;
    uint32 sourceId;
    uint256 sourceTokenId;
    uint24 creditBefore;
    uint24 creditAfter;
    bool inVoidBefore;
    bool inVoidAfter;
}

struct EvolutionQuote {
    EvolutionKind kind;
    address actor;
    ArtworkChange[] changes;
    uint256[] enteringVoid;
    uint256[] leavingVoid;
    uint24[] freedCredits;
    uint24 movedCreditId;
    uint24 newCreditId;
    uint24 historicalVoidCreditId;
}

struct SkeletonAttribute {
    string traitType;
    string value;
}

error InvalidAddress(address value);
error InvalidTokenId(uint256 tokenId);
error InvalidCreditId(uint256 creditId);
error NotReady();
error NotSoldOut();
error InvalidBatch(uint256 count);
error AlreadyBound();
error AlreadyActive();
error IncompatibleRenderer(address renderer);
error OnlyState();
error OnlyVoid();
error DuplicateToken(uint256 tokenId);
error WrongOwner(uint256 tokenId, address expected, address actual);
error InvalidActor(address actor);
error CreditOccupied(uint256 creditId);
error NotCreditOwner(uint256 creditId, address actor);
error CreditArtUnavailable(uint256 creditId);
error InvalidLedger(uint256 tokenId, uint256 creditId);
error InvalidSource(uint32 sourceId);
error InvalidSourceRegistration();
error InvalidPixels();
error UnexpectedTransfer();
error CustodyInvariant();

struct TokenConfig {
    bool initialized;
    uint24 creditId;
    uint8 skeletonId;
    uint24 skeletonTokenId;
    uint8 backgroundId;
    uint8 renderMode;
}

struct ArtState {
    TokenConfig config;
    uint256 skeletonTokenId;
    bool inVoid;
}

struct SkeletonConfig {
    address renderer;
    address sourceCollection;
    address eligibility;
    string collectionName;
    uint64 supportedModes;
    bool enabledForEquip;
}

error InvalidConfig();
error InvalidVisuals(uint8 backgroundId, uint8 renderMode);
error FeatureDisabled(uint8 feature);
error SkeletonUnauthorized(uint8 skeletonId, uint256 itemId, address actor);

src/evolution/IEvolution.sol

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

import {EvolutionQuote, SkeletonAttribute, ArtState, SkeletonConfig} from "./EvolutionTypes.sol";

interface IEvolutionCollection {
    function ownerOf(uint256 id) external view returns (address);
    function balanceOf(address holder) external view returns (uint256);
    function safeTransferFrom(address from, address to, uint256 id) external;
    function totalSupply() external view returns (uint256);
    function MAX_SUPPLY() external view returns (uint16);
    function creditOfToken(uint256 id) external view returns (uint256);
    function punkOfToken(uint256 id) external view returns (uint256);
    function creditUsed(uint256 id) external view returns (bool);
    function renderer() external view returns (address);
    function credits() external view returns (address);
}

/// @dev Native pixel-source ABI, used only by the current pixel rendering family.
/// Other renderer families are not required to provide a pixel buffer.
interface ISkeletonSource {
    function readSkeleton(uint256 itemId) external view returns (bytes memory bodyRGBA, uint24 backgroundRGB);
    function getAttributes(uint256 itemId) external view returns (SkeletonAttribute[] memory);
}

interface IEvolutionRenderer {
    function collection() external view returns (address);
    function state() external view returns (address);
    function voidContract() external view returns (address);
    function credits() external view returns (address);
    function tokenURI(uint256 tokenId) external view returns (string memory);
    function previewArtwork(uint32 sourceId, uint256 itemId, uint24 creditId, bool inVoid)
        external
        view
        returns (string memory);
    function previewCreditGrid(uint256 creditId) external view returns (bytes memory);
}

interface IEvolutionState {
    function getRawConfig(uint256 id) external view returns (uint64);
    function getPackedWord(uint256 word) external view returns (uint256);
    function creditOverride(uint256 id) external view returns (uint8);
    function creditOverrideWord(uint256 word) external view returns (uint256);
    function getEffectiveArtState(uint256 id) external view returns (ArtState memory);
    function getSkeletonConfig(uint8 id) external view returns (SkeletonConfig memory);
    function backgroundColor(uint8 id) external view returns (uint24);
    function collection() external view returns (address);
    function credits() external view returns (address);
    function voidContract() external view returns (address);
    function active() external view returns (bool);
    function paused() external view returns (bool);
    function enabledFeatures() external view returns (uint8);
    function assertRunning() external view;
    function nativeSource() external view returns (address);
    function setSkeletonRenderer(uint8 id, address renderer, uint64 enabledModes) external;
    function maxRenderMode() external view returns (uint8);
    function setRenderModeLimit(uint8 inclusiveMax) external;
    function renderEngines(uint8 family) external view returns (address);
    function setRenderEngine(uint8 family, address engine) external;
    function setSkeletonEligibility(uint8 id, address eligibility) external;
    function setSkeletonCC0(uint8 id, bool cc0) external;
    function isSkeletonCC0(uint8 id) external view returns (bool);
    function releaseReservedSkeleton(uint8 id) external;
    function colorStateOf(uint256 id) external view returns (bool initialized, uint24 creditId);
    function effectiveCreditOf(uint256 id) external view returns (uint24);
    function colorAvailable(uint256 id) external view returns (bool);
    function creditUsed(uint256 id) external view returns (bool);
    function creditsUsed(uint256[] calldata ids) external view returns (bool[] memory);
    function usedColorWord(uint256 word) external view returns (uint256);
    function skeletonOf(uint256 id) external view returns (uint32 sourceId, uint256 itemId);
    function sourceCount() external view returns (uint32);
    function sourceInfo(uint32 id) external view returns (address adapter, string memory name, bool enabled);
    function setSourceEnabled(uint32 id, bool enabled) external;
    function setupSkeleton(uint8 id, SkeletonConfig calldata config) external;
    function setFeatures(uint8 features) external;
    function registerBackground(uint8 id, uint24 color) external;
    function setVisuals(uint256 id, uint8 backgroundId, uint8 renderMode) external;
    function onSwapSkeleton(address actor, uint256 target, uint256 sacrifice, uint8 skeletonId, uint256 item, bytes calldata authData)
        external;
    function syncVoid(uint256 id) external returns (bool changed);
    function quoteRecolorFromDonor(address actor, uint256 target, uint256 donor)
        external
        view
        returns (EvolutionQuote memory);
    function quoteRecolorWithCredit(address actor, uint256 target, uint256 sacrifice, uint24 credit)
        external
        view
        returns (EvolutionQuote memory);
    function quoteRedeem(address actor, uint256 output, uint256 donor, uint256 sacrifice)
        external
        view
        returns (EvolutionQuote memory);
    function onRecolorFromDonor(address actor, uint256 target, uint256 donor) external;
    function onRecolorWithCredit(address actor, uint256 target, uint256 sacrifice, uint24 credit) external;
    function onRedeem(address actor, uint256 output, uint256 donor, uint256 sacrifice) external;
    function onVoidSync(uint256 id) external returns (bool changed);
}

interface IEvolutionVoid {
    function operationInProgress() external view returns (bool);
    function collection() external view returns (address);
    function state() external view returns (address);
    function recolorFromDonor(uint256 target, uint256 donor) external;
    function recolorWithCredit(uint256 target, uint256 sacrifice, uint24 credit) external;
    function swapSkeleton(uint256 target, uint256 sacrifice, uint8 skeletonId, uint256 item, bytes calldata authData) external;
    function redeem(uint256 output, uint256 donor, uint256 sacrifice) external;
    function syncUntracked(uint256 id) external returns (bool changed);
    function isInVoid(uint256 id) external view returns (bool);
    function voidCount() external view returns (uint256);
}

/// @dev Optional, separately reviewed delegation integration. No State or custody rights.
///      This is our adapter ABI, not a claim about the Warm registry's ABI.
interface ISkeletonEligibility {
    function canUse(address actor, address owner, address collection, uint256 itemId, bytes calldata authData)
        external
        view
        returns (bool);
}

/// @notice Family-neutral registration/media interface. SVG may wrap PNG layers,
/// vector paths or other content; no pixel dimensions or composition algorithm are imposed.
interface ISkeletonRenderer {
    function collection() external view returns (address);
    function state() external view returns (address);
    function skeletonId() external view returns (uint8);
    function supportedModes() external view returns (uint64);
    function validateSkeleton(uint256 itemId) external view;
    function svg(uint256 creditedPunkId) external view returns (bytes memory);
    function html(uint256 creditedPunkId) external view returns (bytes memory);
}

/// @notice Custom metadata endpoint addressed by the non-OG Core tokenURI.
/// @dev Returns raw JSON bytes containing media data URIs, not a Base64 JSON URI.
/// Independent PNG-layer/vector families can implement it without a pixel engine.
interface ICustomSkeletonRenderer is ISkeletonRenderer {
    function renderFamily() external pure returns (uint8);
    function tokenJSON(uint256 creditedPunkId) external view returns (bytes memory);
}

/// @notice Small, versioned family contract. 1 = native pixels, 2 = layered SVG effects.
/// Replacements must retain all previously advertised modes and the same calling ABI.
interface IRenderEngine {
    function renderFamily() external pure returns (uint8);
    function engineVersion() external pure returns (uint256);
    function supportedModes() external view returns (uint64);
    function modeName(uint8 mode) external view returns (string memory);
}

interface IPixelRenderEngine is IRenderEngine {
    function dataSource() external view returns (address);
}

interface ILayeredRenderEngine is IRenderEngine {
    /// @dev Only small effect markup crosses this boundary, never PNG/WebP payloads.
    /// Continues after the shared body/alpha-mask definitions and closes the SVG.
    function fragment(bytes calldata grid, uint24 background, uint16 width, uint16 height, uint8 mode)
        external view returns (bytes memory);
}

src/evolution/SkeletonPixels.sol

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

import {InvalidPixels} from "./EvolutionTypes.sol";

library SkeletonPixels {
    /// @dev Explicit bounds keep future sources from forcing unbounded rendering work.
    function alphaMask(bytes memory body, uint16 width, uint16 height) internal pure returns (bytes memory result) {
        if (width < 8 || height < 8 || width > 64 || height > 64 || body.length != uint256(width)*height*4) revert InvalidPixels();
        uint256 count=uint256(width)*height;
        result=new bytes((count+7)/8);
        bool occupied;
        for(uint256 i;i<count;++i) {
            if(body[i*4+3]!=0) { result[i>>3]|=bytes1(uint8(1<<(i&7))); occupied=true; }
        }
        if(!occupied) revert InvalidPixels();
    }

    function paint(bytes memory body,bytes memory grid,uint16 width,uint16 height) internal pure {
        if(grid.length!=192) revert InvalidPixels();
        for(uint256 y;y<height;++y) for(uint256 x;x<width;++x) {
            uint256 p=(y*width+x)*4;
            if(body[p+3]==0) continue;
            uint256 g=((y*8/height)*8+x*8/width)*3;
            body[p]=grid[g];body[p+1]=grid[g+1];body[p+2]=grid[g+2];
        }
    }

    function alphaMask(bytes memory body) internal pure returns (bytes memory result) {
        if (body.length != 2304) revert InvalidPixels();
        result = new bytes(72);
        bool occupied;
        for (uint256 i; i < 576; ++i) {
            if (body[i * 4 + 3] != 0) {
                result[i >> 3] |= bytes1(uint8(1 << (i & 7)));
                occupied = true;
            }
        }
        if (!occupied) revert InvalidPixels();
    }

    /// @dev Composite alpha onto the selected background only for SVG display.
    ///      The source body/mask and recolor retain their independent alpha.
    function flatten(bytes memory body, uint24 background) internal pure returns (bytes memory result) {
        result = new bytes(body.length);
        for (uint256 p; p < body.length; p += 4) {
            uint256 alpha = uint8(body[p + 3]);
            if (alpha == 0) continue;
            for (uint256 k; k < 3; ++k) {
                uint256 bg = uint8(background >> ((2 - k) * 8));
                result[p + k] = bytes1(uint8((uint8(body[p + k]) * alpha + bg * (255 - alpha) + 127) / 255));
            }
            result[p + 3] = 0xff;
        }
    }

    /// @dev One canonical body format for rendering and future skeleton selection.
    function mask(bytes memory body) internal pure returns (bytes memory result) {
        if (body.length != 2304) revert InvalidPixels();
        result = new bytes(72);
        bool occupied;
        for (uint256 i; i < 576; ++i) {
            uint256 p = i * 4;
            if (body[p + 3] == 0xff) {
                result[i >> 3] |= bytes1(uint8(1 << (i & 7)));
                occupied = true;
            } else if (body[p + 3] != 0 || body[p] != 0 || body[p + 1] != 0 || body[p + 2] != 0) {
                revert InvalidPixels();
            }
        }
        if (!occupied) revert InvalidPixels();
    }

    /// @dev Mutates only opaque body RGB; grid coordinates are never cropped/recentered.
    function paint(bytes memory body, bytes memory grid, bool inVoid) internal pure {
        for (uint256 i; i < 576; ++i) {
            uint256 p = i * 4;
            if (body[p + 3] == 0) continue;
            uint256 g = (((i / 24) / 3) * 8 + (i % 24) / 3) * 3;
            body[p] = inVoid ? bytes1(0x55) : grid[g];
            body[p + 1] = inVoid ? bytes1(0x55) : grid[g + 1];
            body[p + 2] = inVoid ? bytes1(0x55) : grid[g + 2];
        }
    }
}

src/evolution/renderers/PixelArtRenderer.sol

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

import {SvgRenderer} from "../../SvgRenderer.sol";
import {Base64} from "solady/utils/Base64.sol";
import {SkeletonPixels} from "../SkeletonPixels.sol";
import {PixelFlipbook} from "./lib/PixelFlipbook.sol";
import {SizedPixelSVG} from "./lib/SizedPixelSVG.sol";
import {SizedPixelCompositor} from "./lib/SizedPixelCompositor.sol";
import {PixelEffectCompositor} from "./PixelEffectCompositor.sol";
import {SVGRenderModes} from "./lib/SVGRenderModes.sol";
import {CreditPunkData} from "../sources/CreditPunkData.sol";
import {InvalidAddress, InvalidCreditId} from "../EvolutionTypes.sol";

/// @notice Shared native-size pixel engine (8..64 on each axis), with exact legacy 24x24 output.
/// Nine visual modes share the same Credit and native source dimensions.
/// @dev Does not store configs, perform transfers or call source tokenURI/SVG endpoints.
contract PixelArtRenderer {
    uint8 public constant renderFamily = 1;
    uint256 public constant engineVersion = 1;
    function supportedModes() external pure virtual returns (uint64) { return 511; }
    function modeName(uint8 mode) external pure virtual returns (string memory) { return SVGRenderModes.name(mode); }
    CreditPunkData public immutable dataSource;
    address public immutable animationTemplates;
    PixelEffectCompositor public immutable effects;
    uint24 public constant VOID_BACKGROUND = 0xe3e5e4;

    /// @dev Dependencies are deployed separately and may be reused by a replacement
    /// engine. Embedding their creation code here needlessly inflated this initcode.
    constructor(address palette_, address effects_, address templates_) {
        if (palette_.code.length == 0) revert InvalidAddress(palette_);
        if (effects_.code.length == 0) revert InvalidAddress(effects_);
        if (templates_.code.length <= 1) revert InvalidAddress(templates_);
        dataSource = CreditPunkData(palette_);
        animationTemplates = templates_;
        effects = PixelEffectCompositor(effects_);
    }

    function svg(bytes memory body, uint24 bg, uint24 credit) public view returns (bytes memory) {
        SkeletonPixels.alphaMask(body);
        SkeletonPixels.paint(body, dataSource.gridOf(credit), false);
        return SvgRenderer.renderSvgWithBackground(SkeletonPixels.flatten(body, bg), bg);
    }

    function artwork(bytes memory body, uint24 bg, uint24 credit, bool inVoid, bool nativePixels)
        public view returns (string memory image, string memory animation, string memory creditTraits)
    {
        bytes memory mask = nativePixels ? SkeletonPixels.mask(body) : SkeletonPixels.alphaMask(body);
        if (inVoid) {
            if (credit != 0) revert InvalidCreditId(credit);
            SkeletonPixels.paint(body, new bytes(0), true);
            return (SvgRenderer.renderImageDataURIWithBackground(body, VOID_BACKGROUND), "", "");
        }
        string memory original = SvgRenderer.renderImageDataURIWithBackground(
            nativePixels ? body : SkeletonPixels.flatten(body, bg), bg
        );
        bytes memory grid;
        (grid, creditTraits) = dataSource.read(credit);
        SkeletonPixels.paint(body, grid, false);
        image = SvgRenderer.renderImageDataURIWithBackground(nativePixels ? body : SkeletonPixels.flatten(body, bg), bg);
        animation = PixelFlipbook.render(animationTemplates, image, original, mask, bg, 24, 24);
    }

    function svgSized(bytes memory body, uint16 width, uint16 height, uint24 bg, uint24 credit)
        public view returns (bytes memory)
    {
        if (width==24 && height==24) return svg(body,bg,credit);
        (,bytes memory painted,)=SizedPixelCompositor.compose(body,dataSource.gridOf(credit),width,height,bg,false);
        return SizedPixelSVG.render(painted,width,height,bg);
    }

    function artworkSized(bytes memory body, uint16 width, uint16 height, uint24 bg, uint24 credit)
        public view returns (string memory image, string memory animation)
    {
        if (width==24 && height==24) { (image,animation,)=artwork(body,bg,credit,false,false); return(image,animation); }
        (bytes memory old,bytes memory painted,bytes memory mask)=SizedPixelCompositor.compose(body,dataSource.gridOf(credit),width,height,bg,true);
        string memory original=string.concat("data:image/svg+xml;base64,",
            Base64.encode(SizedPixelSVG.render(old,width,height,bg)));
        image=string.concat("data:image/svg+xml;base64,",
            Base64.encode(SizedPixelSVG.render(painted,width,height,bg)));
        animation=PixelFlipbook.render(animationTemplates,image,original,mask,bg,width,height);
    }

    function svgMode(bytes memory body,uint16 width,uint16 height,uint24 bg,uint24 credit,uint8 mode)
        external view returns(bytes memory)
    {
        if(mode==0) return svgSized(body,width,height,bg,credit);
        SVGRenderModes.name(mode);
        SkeletonPixels.alphaMask(body,width,height);
        if(mode==4) return SizedPixelSVG.renderInk(effects.paint(body,dataSource.gridOf(credit),width,height),width,height,bg);
        return effects.render(SizedPixelSVG.foreground(body,width,height),dataSource.gridOf(credit),width,height,bg,mode,false);
    }

    function artworkMode(bytes memory body,uint16 width,uint16 height,uint24 bg,uint24 credit,uint8 mode,bool nativePixels)
        external view returns(string memory image,string memory animation,string memory creditTraits)
    {
        if(mode==0) {
            if(width==24 && height==24) return artwork(body,bg,credit,false,nativePixels);
            (image,animation)=artworkSized(body,width,height,bg,credit);
            return(image,animation,"");
        }
        SVGRenderModes.name(mode);
        SkeletonPixels.alphaMask(body,width,height);
        bytes memory grid;
        (grid,creditTraits)=dataSource.read(credit);
        if(mode==4) {
            bytes memory ink=effects.paint(body,grid,width,height);
            image=string.concat("data:image/svg+xml;base64,",Base64.encode(SizedPixelSVG.renderInk(ink,width,height,bg)));
            string memory originalInk=string.concat("data:image/svg+xml;base64,",Base64.encode(SizedPixelSVG.renderInk(body,width,height,bg)));
            animation=PixelFlipbook.renderEffects(animationTemplates,image,originalInk,bg,width,height);
            return(image,animation,creditTraits);
        }
        bytes memory foreground=SizedPixelSVG.foreground(body,width,height);
        image=string.concat("data:image/svg+xml;base64,",Base64.encode(effects.render(foreground,grid,width,height,bg,mode,false)));
        string memory original=string.concat("data:image/svg+xml;base64,",Base64.encode(effects.render(foreground,grid,width,height,bg,mode,true)));
        animation=PixelFlipbook.renderEffects(animationTemplates,image,original,bg,width,height);
    }
}

src/evolution/renderers/PixelEffectCompositor.sol

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

import {SoftInkCompositor} from "./SoftInkCompositor.sol";
import {PixelModeSVG} from "./lib/PixelModeSVG.sol";

/// @notice Immutable, stateless helper reusable across PixelArtRenderer deployments.
/// Keeps growth room in the common engine without introducing another admin setting.
contract PixelEffectCompositor is SoftInkCompositor {
    function render(bytes memory foreground, bytes memory grid, uint16 width, uint16 height,
        uint24 background, uint8 mode, bool original) external pure returns (bytes memory)
    {
        return PixelModeSVG.render(foreground, grid, width, height, background, mode, original);
    }
}

src/evolution/renderers/SoftInkCompositor.sol

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

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

/// @notice Small stateless helper keeps the shared pixel engine below the EIP-170 code limit.
contract SoftInkCompositor {
    function paint(bytes memory body,bytes memory grid,uint16 width,uint16 height)
        external pure returns(bytes memory)
    { return SoftInkPixels.paint(body,grid,width,height); }
}

src/evolution/renderers/lib/DynamicBufferLibEx.sol

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

/// @notice DynamicBufferLib with reservePtr/commit extensions for zero-copy writes
/// @author Based on Solady DynamicBufferLib (vectorized)
/// @dev Extended with reserve/commit pattern for direct EXTCODECOPY into buffer
library DynamicBufferLibEx {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    struct DynamicBuffer {
        bytes data;
    }

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

    /// @dev Shorthand for `buffer.data.length`.
    function length(DynamicBuffer memory buffer) internal pure returns (uint256) {
        return buffer.data.length;
    }

    /// @dev Appends `data` to `buffer`.
    function p(DynamicBuffer memory buffer, bytes memory data) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = buffer;
        if (data.length == uint256(0)) return result;
        assembly ("memory-safe") {
            let w := not(0x1f)
            let bufData := mload(buffer)
            let bufDataLen := mload(bufData)
            let newBufDataLen := add(mload(data), bufDataLen)
            let prime := 1621250193422201
            let cap := mload(add(bufData, w))
            cap := mul(div(cap, prime), iszero(mod(cap, prime)))

            for {} iszero(lt(newBufDataLen, cap)) {} {
                let newCap := and(add(cap, add(or(cap, newBufDataLen), 0x20)), w)
                if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
                    mstore(add(bufData, w), mul(prime, newCap))
                    mstore(0x40, add(bufData, add(0x40, newCap)))
                    break
                }
                let newBufData := add(mload(0x40), 0x20)
                mstore(0x40, add(newBufData, add(0x40, newCap)))
                mstore(buffer, newBufData)
                for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
                    mstore(add(newBufData, o), mload(add(bufData, o)))
                    o := add(o, w)
                    if iszero(o) { break }
                }
                mstore(add(newBufData, w), mul(prime, newCap))
                bufData := newBufData
                break
            }
            for { let o := and(add(mload(data), 0x20), w) } 1 {} {
                mstore(add(add(bufData, bufDataLen), o), mload(add(data, o)))
                o := add(o, w)
                if iszero(o) { break }
            }
            mstore(add(add(bufData, 0x20), newBufDataLen), 0)
            mstore(bufData, newBufDataLen)
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    RESERVE/COMMIT EXTENSIONS               */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Reserve capacity for `size` additional logical bytes, return write pointer.
    ///      The allocator keeps one physical guard word after the logical capacity.
    ///      Together with the strict `newLen < cap` check, this lets streaming
    ///      writers use a final unaligned `mstore` without reserving 32 fake bytes.
    /// @param buffer The buffer to reserve in
    /// @param size Number of bytes to reserve
    /// @return ptr Pointer where caller can write `size` bytes
    function reservePtr(DynamicBuffer memory buffer, uint256 size) internal pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            let w := not(0x1f)
            let bufData := mload(buffer)
            let bufDataLen := mload(bufData)
            let newLen := add(bufDataLen, size)
            let prime := 1621250193422201
            let cap := mload(add(bufData, w))
            cap := mul(div(cap, prime), iszero(mod(cap, prime)))

            // Expand if needed
            for {} iszero(lt(newLen, cap)) {} {
                let newCap := and(add(cap, add(or(cap, newLen), 0x20)), w)
                if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
                    mstore(add(bufData, w), mul(prime, newCap))
                    mstore(0x40, add(bufData, add(0x40, newCap)))
                    break
                }
                let newBufData := add(mload(0x40), 0x20)
                mstore(0x40, add(newBufData, add(0x40, newCap)))
                mstore(buffer, newBufData)
                // Copy existing data (backwards, word by word)
                for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
                    mstore(add(newBufData, o), mload(add(bufData, o)))
                    o := add(o, w)
                    if iszero(o) { break }
                }
                // Copy length field (the loop above doesn't copy offset 0)
                mstore(newBufData, bufDataLen)
                mstore(add(newBufData, w), mul(prime, newCap))
                bufData := newBufData
                break
            }

            // Return write pointer: bufData + 32 (length slot) + current length
            ptr := add(add(bufData, 32), bufDataLen)
        }
    }

    /// @dev Commit `size` logical bytes that were written at the pointer from reservePtr.
    ///      The trailing zero-word write is covered by reservePtr's guard word.
    /// @param buffer The buffer to commit to
    /// @param size Number of bytes written
    function commit(DynamicBuffer memory buffer, uint256 size) internal pure {
        assembly ("memory-safe") {
            let bufData := mload(buffer)
            let bufDataLen := mload(bufData)
            let newLen := add(bufDataLen, size)
            mstore(bufData, newLen)
            mstore(add(add(bufData, 0x20), newLen), 0) // Zero word after buffer
        }
    }

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

    function _deallocate(DynamicBuffer memory result) private pure {
        assembly ("memory-safe") {
            mstore(0x40, result)
        }
    }
}

src/evolution/renderers/lib/PixelFlipbook.sol

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

import {SSTORE2} from "solady/utils/SSTORE2.sol";
import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";

library PixelFlipbook {
    /// @dev Effect geometry lives below native-pixel resolution. Its animation must
    /// capture the full SVG at display resolution, never resample it down to 24x24.
    function renderEffects(address templates,string memory image,string memory original,
        uint24 bg,uint16 width,uint16 height) internal view returns(string memory)
    {
        bytes[] memory p=abi.decode(SSTORE2.read(templates),(bytes[]));
        bytes memory html=abi.encodePacked(p[8],LibString.toHexStringNoPrefix(bg,3),p[9],
            "const W=",LibString.toString(width),",H=",LibString.toString(height),
            ",originalURI='",original,"',finalURI='",image,"';",p[10]);
        return string.concat("data:text/html;base64,",Base64.encode(html));
    }

    function render(address templates, string memory image, string memory original, bytes memory mask,
        uint24 bg, uint16 width, uint16 height) internal view returns (string memory)
    {
        bytes[] memory p = abi.decode(SSTORE2.read(templates), (bytes[]));
        bytes memory html;
        if (width == 24 && height == 24) {
            html = abi.encodePacked(p[0], LibString.toHexStringNoPrefix(bg, 3), p[1], original,
                p[2], image, p[3], Base64.encode(mask), p[4]);
        } else {
            html = abi.encodePacked(p[5], LibString.toHexStringNoPrefix(bg, 3), p[6],
                "const W=", LibString.toString(width), ",H=", LibString.toString(height),
                ",originalURI='", original, "',finalURI='", image, "',mask64='", Base64.encode(mask), "';", p[7]);
        }
        return string.concat("data:text/html;base64,", Base64.encode(html));
    }
}

src/evolution/renderers/lib/PixelModeSVG.sol

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

import {LibString} from "solady/utils/LibString.sol";
import {InvalidPixels,InvalidVisuals} from "../../EvolutionTypes.sol";
import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
import {SVGRenderModes} from "./SVGRenderModes.sol";

/// @dev SVG-only effects over native pixels. Exact pixel Ink uses SoftInkPixels instead.
library PixelModeSVG {
    using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;

    function render(bytes memory foreground,bytes memory grid,uint16 w,uint16 h,uint24 bg,uint8 mode,bool original)
        internal pure returns(bytes memory)
    {
        if(grid.length!=192) revert InvalidPixels();
        if(mode==4) revert InvalidVisuals(0,mode);
        DynamicBufferLibEx.DynamicBuffer memory out;
        uint256 first=out.reservePtr(foreground.length+16000);
        out.p(bytes(string.concat("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ",LibString.toString(w)," ",
            LibString.toString(h),"' width='100%' height='100%",
            "' shape-rendering='crispEdges'><defs><g id='body'>")));
        out.p(foreground);
        out.p(bytes("</g><mask id='m' mask-type='alpha' style='mask-type:alpha' maskUnits='userSpaceOnUse' x='0' y='0' width='100%' height='100%'><use href='#body'/></mask>"));
        out.p(bytes(SVGRenderModes.definitions(mode)));
        out.p(bytes(string.concat("</defs><rect width='100%' height='100%' fill='#",LibString.toHexStringNoPrefix(bg,3),"'/>")));
        if(mode==3) {
            out.p(bytes(string.concat("<use href='#body' filter='url(#cp-card-far)' transform='translate(",
                _shift(w,44)," ",_shift(h,37),")'/><use href='#body' filter='url(#cp-card-near)' transform='translate(",
                _shift(w,19)," ",_shift(h,17),")'/>")));
        }
        if(original) {
            out.p(bytes("<use href='#body'/>"));
            if(mode==2) out.p(bytes(SVGRenderModes.grid(w,h,false)));
            out.p(bytes("</svg>"));
            return _result(out,first);
        }
        out.p(bytes(string.concat("<g data-art='",SVGRenderModes.name(mode),"' mask='url(#m)'>")));
        if(mode>=5) {
            out.p(bytes("<svg viewBox='0 0 8 8' width='100%' height='100%' preserveAspectRatio='none'>"));
            for(uint256 i;i<64;++i) {
                uint24 color=_color(grid,i);
                string memory shift=mode==8 ? SVGRenderModes.blockOffset(i%8,i/8) : "";
                out.p(bytes(string.concat("<use href='#cp-block' x='",LibString.toString(i%8),"' y='",LibString.toString(i/8),
                    "' fill='#",LibString.toHexStringNoPrefix(color,3),"'",shift,"/>")));
            }
            out.p(bytes("</svg></g></svg>"));
            return _result(out,first);
        }
        if(mode==1) {
            out.p(bytes("<svg viewBox='0 0 8 8' width='100%' height='100%' preserveAspectRatio='none'><g filter='url(#cp-field)'>"));
        } else out.p(bytes("<g shape-rendering='crispEdges'>"));
        for(uint256 i;i<64;++i) {
            uint256 x=i%8;uint256 y=i/8;
            uint24 color=_color(grid,i);
            if(mode==1) {
                out.p(bytes(string.concat("<rect x='",LibString.toString(x),"' y='",LibString.toString(y),
                    "' width='1' height='1' fill='#",LibString.toHexStringNoPrefix(color,3),"'/>")));
            } else {
                uint256 left=(x*w+7)/8;uint256 top=(y*h+7)/8;
                out.p(bytes(string.concat("<rect x='",LibString.toString(left),"' y='",LibString.toString(top),
                    "' width='",LibString.toString(((x+1)*w+7)/8-left),"' height='",LibString.toString(((y+1)*h+7)/8-top),
                    "' fill='#",LibString.toHexStringNoPrefix(color,3),"'/>")));
            }
        }
        out.p(bytes(mode==1 ? "</g></svg>" : "</g>"));
        out.p(bytes("</g>"));
        if(mode==2) out.p(bytes(SVGRenderModes.grid(w,h,false)));
        out.p(bytes("</svg>"));
        return _result(out,first);
    }

    function _color(bytes memory grid,uint256 i) private pure returns(uint24) {
        uint256 p=i*3;
        return uint24(uint8(grid[p]))<<16|uint24(uint8(grid[p+1]))<<8|uint24(uint8(grid[p+2]));
    }

    function _shift(uint16 size,uint256 fraction) private pure returns(string memory) {
        uint256 millionths=uint256(size)*fraction*1_000_000/1262;
        uint256 decimals=millionths%1_000_000;
        return string.concat(LibString.toString(millionths/1_000_000),".",decimals<100_000?"0":"",
            decimals<10_000?"0":"",decimals<1_000?"0":"",decimals<100?"0":"",
            decimals<10?"0":"",LibString.toString(decimals));
    }

    function _result(DynamicBufferLibEx.DynamicBuffer memory out,uint256 first) private pure returns(bytes memory result) {
        result=out.data;uint256 end;
        assembly("memory-safe") { end:=add(result,32) }
        require(first==end,"Mode buffer relocated");
    }
}

src/evolution/renderers/lib/SVGRenderModes.sol

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

import {LibString} from "solady/utils/LibString.sol";
import {InvalidVisuals} from "../../EvolutionTypes.sol";

/// @dev Shared visual IDs; the same mode can have family-specific drawing rules.
library SVGRenderModes {
    function name(uint8 mode) internal pure returns(string memory) {
        if(mode==0) return "Flat";
        if(mode==1) return "Camo";
        if(mode==2) return "Grid";
        if(mode==3) return "Cardboard";
        if(mode==4) return "Ink";
        if(mode==5) return "Blocks1";
        if(mode==6) return "Blocks2";
        if(mode==7) return "Blocks3";
        if(mode==8) return "Blocks4";
        revert InvalidVisuals(0,mode);
    }

    function definitions(uint8 mode) internal pure returns(string memory) {
        name(mode);
        if(mode==1) return "<filter id='cp-field' x='-25%' y='-25%' width='150%' height='150%' color-interpolation-filters='sRGB'><feGaussianBlur stdDeviation='.27258'/></filter>";
        if(mode==3) return "<filter id='cp-card-far' x='-10%' y='-10%' width='120%' height='120%'><feFlood flood-color='#18323b' flood-opacity='.44'/><feComposite in2='SourceAlpha' operator='in'/></filter><filter id='cp-card-near' x='-10%' y='-10%' width='120%' height='120%'><feFlood flood-color='#d6e5dd' flood-opacity='.65'/><feComposite in2='SourceAlpha' operator='in'/></filter>";
        if(mode==4) return "<filter id='cp-ink' x='0' y='0' width='100%' height='100%' color-interpolation-filters='sRGB'><feColorMatrix type='matrix' values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  -0.59528 -2.00256 -0.20216 1.12 0'/></filter>";
        if(mode>=5) return blockDefinition(mode);
        return "";
    }

    /// @dev Tile markup is generated directly from research/svg-capabilities-2026-09-27/block_variants.py.
    function blockDefinition(uint8 mode) internal pure returns(string memory) {
        if(mode==5) return "<g id=\"cp-block\" shape-rendering=\"crispEdges\"><rect x=\"0.103\" y=\"0.125\" width=\"0.948\" height=\"0.948\" fill=\"#19292f\" opacity=\"0.14\"/><path d=\"M0.919 0.026L0.974 0.081V0.974L0.919 0.919Z\"/><path d=\"M0.919 0.026L0.974 0.081V0.974L0.919 0.919Z\" fill=\"#10202a\" opacity=\"0.18\"/><path d=\"M0.026 0.919H0.919L0.974 0.974H0.081Z\"/><path d=\"M0.026 0.919H0.919L0.974 0.974H0.081Z\" fill=\"#10202a\" opacity=\"0.14\"/><rect x=\"0.026\" y=\"0.026\" width=\"0.893\" height=\"0.893\" rx=\".07\"/><path d=\"M0.026 0.026H0.919L0.894 0.051H0.051Z\" fill=\"#fff\" opacity=\"0.36\"/><path d=\"M0.026 0.026V0.919H0.058V0.058H0.919V0.026Z\" fill=\"#fff\" opacity=\".27\"/><path d=\"M0.919 0.026V0.919H0.026V0.887H0.887V0.026Z\" fill=\"#14252c\" opacity=\".18\"/></g>";
        if(mode==6) return "<g id=\"cp-block\" shape-rendering=\"crispEdges\"><rect x=\"0.194\" y=\"0.236\" width=\"0.906\" height=\"0.906\" fill=\"#19292f\" opacity=\"0.22\"/><path d=\"M0.848 0.047L0.953 0.152V0.953L0.848 0.848Z\"/><path d=\"M0.848 0.047L0.953 0.152V0.953L0.848 0.848Z\" fill=\"#10202a\" opacity=\"0.31\"/><path d=\"M0.047 0.848H0.848L0.953 0.953H0.152Z\"/><path d=\"M0.047 0.848H0.848L0.953 0.953H0.152Z\" fill=\"#10202a\" opacity=\"0.2\"/><rect x=\"0.047\" y=\"0.047\" width=\"0.801\" height=\"0.801\"/><path d=\"M0.047 0.047H0.848L0.801 0.094H0.094Z\" fill=\"#fff\" opacity=\"0.17\"/></g>";
        if(mode==7) return "<g id=\"cp-block\" shape-rendering=\"crispEdges\"><rect x=\"0.338\" y=\"0.406\" width=\"0.8\" height=\"0.8\" fill=\"#19292f\" opacity=\"0.35\"/><path d=\"M0.73 0.1L0.9 0.27V0.9L0.73 0.73Z\"/><path d=\"M0.73 0.1L0.9 0.27V0.9L0.73 0.73Z\" fill=\"#10202a\" opacity=\"0.38\"/><path d=\"M0.1 0.73H0.73L0.9 0.9H0.27Z\"/><path d=\"M0.1 0.73H0.73L0.9 0.9H0.27Z\" fill=\"#10202a\" opacity=\"0.28\"/><rect x=\"0.1\" y=\"0.1\" width=\"0.63\" height=\"0.63\"/><path d=\"M0.1 0.1H0.73L0.653 0.177H0.177Z\" fill=\"#fff\" opacity=\"0.22\"/></g>";
        if(mode==8) return "<g id=\"cp-block\" shape-rendering=\"crispEdges\"><rect x=\"0.236\" y=\"0.282\" width=\"0.85\" height=\"0.85\" fill=\"#19292f\" opacity=\"0.33\"/><path d=\"M0.81 0.075L0.925 0.19V0.925L0.81 0.81Z\"/><path d=\"M0.81 0.075L0.925 0.19V0.925L0.81 0.81Z\" fill=\"#10202a\" opacity=\"0.3\"/><path d=\"M0.075 0.81H0.81L0.925 0.925H0.19Z\"/><path d=\"M0.075 0.81H0.81L0.925 0.925H0.19Z\" fill=\"#10202a\" opacity=\"0.21\"/><rect x=\"0.075\" y=\"0.075\" width=\"0.735\" height=\"0.735\"/><path d=\"M0.075 0.075H0.81L0.758 0.127H0.127Z\" fill=\"#fff\" opacity=\"0.23\"/></g>";
        revert InvalidVisuals(0,mode);
    }
    /// @dev Same two-axis offset formula as the approved Blocks4 visual source.
    function blockOffset(uint256 x,uint256 y) internal pure returns(string memory) {
        uint256 dx=(x*5+y*7)%3;
        uint256 dy=(x*7+y*5)%3;
        return string.concat(" transform='translate(",dx==0?"-.11":dx==1?"0":".11",
            " ",dy==0?"-.08":dy==1?"0":".08",")'");
    }
    function grid(uint16 w,uint16 h,bool pixelAligned) internal pure returns(string memory) {
        string memory path;
        for(uint256 k=1;k<8;++k) {
            string memory x=LibString.toString(pixelAligned?(k*w+7)/8:k);
            string memory y=LibString.toString(pixelAligned?(k*h+7)/8:k);
            if(pixelAligned) {x=string.concat(x,".5");y=string.concat(y,".5");}
            path=string.concat(path,"M",x," 0V",LibString.toString(pixelAligned?h:8),
                "M0 ",y,"H",LibString.toString(pixelAligned?w:8));
        }
        return string.concat("<svg viewBox='0 0 ",LibString.toString(pixelAligned?w:8)," ",
            LibString.toString(pixelAligned?h:8),"' width='100%' height='100%' preserveAspectRatio='none'>",
            "<path data-grid='8x8' d='",path,"' fill='none' stroke='#102932' stroke-opacity='.63' stroke-width='",
            pixelAligned?"1":".032","' shape-rendering='",pixelAligned?"crispEdges":"geometricPrecision","'/></svg>");
    }
}

src/evolution/renderers/lib/SizedPixelCompositor.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {InvalidPixels} from "../../EvolutionTypes.sol";

/// @dev One bounded pass: foreground mask, original and Credit colors over the selected background.
/// Alpha is used for compositing; fully transparent source RGB never becomes foreground.
library SizedPixelCompositor {
    function compose(bytes memory body,bytes memory grid,uint16 width,uint16 height,uint24 bg,bool withOriginal)
        internal pure returns(bytes memory original,bytes memory painted,bytes memory mask)
    {
        uint256 count=uint256(width)*height;
        if(width<8 || height<8 || width>64 || height>64 || body.length!=count*4 || grid.length!=192) revert InvalidPixels();
        original=new bytes(withOriginal?body.length:0);
        painted=new bytes(body.length);mask=new bytes((count+7)/8);
        bool occupied;
        assembly("memory-safe") {
            function blend(rgb,alpha,background) -> result {
                let inverse:=sub(255,alpha)
                let r:=div(add(add(mul(and(shr(16,rgb),255),alpha),mul(and(shr(16,background),255),inverse)),127),255)
                let g:=div(add(add(mul(and(shr(8,rgb),255),alpha),mul(and(shr(8,background),255),inverse)),127),255)
                let b:=div(add(add(mul(and(rgb,255),alpha),mul(and(background,255),inverse)),127),255)
                result:=or(or(shl(16,r),shl(8,g)),b)
            }
            function writePixel(ptr,rgb) {
                mstore8(ptr,shr(16,rgb))
                mstore8(add(ptr,1),shr(8,rgb))
                mstore8(add(ptr,2),rgb)
                mstore8(add(ptr,3),255)
            }
            let input:=add(body,32)
            let palette:=add(grid,32)
            let out:=add(painted,32)
            let old:=add(original,32)
            let bits:=add(mask,32)
            for {let i:=0} lt(i,count) {i:=add(i,1)} {
                let offset:=mul(i,4)
                let rgba:=shr(224,mload(add(input,offset)))
                let alpha:=and(rgba,255)
                if alpha {
                    occupied:=1
                    let bitPtr:=add(bits,shr(3,i))
                    mstore8(bitPtr,or(byte(0,mload(bitPtr)),shl(and(i,7),1)))
                    let cell:=add(mul(div(mul(div(i,width),8),height),8),div(mul(mod(i,width),8),width))
                    let color:=shr(232,mload(add(palette,mul(cell,3))))
                    let prior:=shr(8,rgba)
                    if lt(alpha,255) {color:=blend(color,alpha,bg) if withOriginal {prior:=blend(prior,alpha,bg)}}
                    writePixel(add(out,offset),color)
                    if withOriginal {writePixel(add(old,offset),prior)}
                }
            }
        }
        if(!occupied) revert InvalidPixels();
    }
}

src/evolution/renderers/lib/SizedPixelSVG.sol

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

import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
import {LibString} from "solady/utils/LibString.sol";

/// @dev Already flattened RGBA, validated by the engine. Merge equal-color horizontal runs.
library SizedPixelSVG {
    using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;

    function render(bytes memory rgba, uint16 width, uint16 height, uint24 bg) internal pure returns (bytes memory) {
        return _render(rgba,width,height,bg,false,true);
    }
    function foreground(bytes memory rgba,uint16 width,uint16 height) internal pure returns(bytes memory) {
        return _render(rgba,width,height,0,true,false);
    }
    function renderInk(bytes memory rgba,uint16 width,uint16 height,uint24 bg) internal pure returns(bytes memory) {
        return _render(rgba,width,height,bg,true,true);
    }
    function _render(bytes memory rgba,uint16 width,uint16 height,uint24 bg,bool transparent,bool hasBackground) private pure returns(bytes memory) {
        DynamicBufferLibEx.DynamicBuffer memory out;
        // Count visible color runs before allocating; then reclaim short formatting
        // temporaries without moving the output. Dense 64px sources otherwise pay
        // quadratic EVM memory expansion for thousands of dead temporary strings.
        uint256 runs;
        for(uint256 y;y<height;++y) {
            uint256 x;
            while(x<width) {
                uint256 p=(y*width+x)*4;
                if(rgba[p+3]==0) {++x;continue;}
                uint24 color=_color(rgba,p);bytes1 alpha=rgba[p+3];++runs;++x;
                while(x<width && rgba[(y*width+x)*4+3]!=0 && _color(rgba,(y*width+x)*4)==color
                    && (!transparent || rgba[(y*width+x)*4+3]==alpha)) ++x;
            }
        }
        uint256 first=out.reservePtr(512+runs*(transparent?112:80));
        out.p(bytes(string.concat('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ',
            LibString.toString(width), ' ', LibString.toString(height), '" width="', hasBackground?"100%":LibString.toString(width),
            '" height="', hasBackground?"100%":LibString.toString(height), '" shape-rendering="crispEdges">')));
        if(hasBackground) out.p(bytes(string.concat('<rect width="100%" height="100%" fill="#',LibString.toHexStringNoPrefix(bg,3),'"/>')));
        uint256 baseline;
        assembly("memory-safe") { baseline:=mload(0x40) }
        for (uint256 y; y < height; ++y) {
            uint256 x;
            while (x < width) {
                uint256 i = (y * width + x) * 4;
                if (rgba[i+3] == 0) { ++x; continue; }
                uint24 color = _color(rgba,i);
                uint256 end=x+1;
                while (end<width && rgba[(y*width+end)*4+3]!=0 && _color(rgba,(y*width+end)*4)==color
                    && (!transparent || rgba[(y*width+end)*4+3]==rgba[i+3])) ++end;
                out.p(bytes(string.concat('<rect x="',LibString.toString(x),'" y="',LibString.toString(y),
                    '" width="',LibString.toString(end-x),'" height="1" fill="#',LibString.toHexStringNoPrefix(color,3),'"')));
                if(transparent && rgba[i+3]!=0xff) {
                    uint256 opacity=uint256(uint8(rgba[i+3]))*1000000/255;
                    out.p(bytes(string.concat(' opacity="0.',opacity<100000?"0":"",opacity<10000?"0":"",LibString.toString(opacity),'"')));
                }
                out.p(bytes('/>'));
                x=end;
                assembly("memory-safe") { mstore(0x40,baseline) }
            }
        }
        out.p(bytes('</svg>'));
        bytes memory result=out.data;uint256 last;
        assembly("memory-safe") { last:=add(result,32) }
        require(first==last,"Pixel buffer relocated");
        return out.data;
    }

    function _color(bytes memory rgba,uint256 p) private pure returns(uint24) {
        return uint24(uint8(rgba[p]))<<16 | uint24(uint8(rgba[p+1]))<<8 | uint24(uint8(rgba[p+2]));
    }
}

src/evolution/renderers/lib/SoftInkPixels.sol

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

import {InvalidPixels} from "../../EvolutionTypes.sol";

/// @dev Exact native-pixel Soft 65 recipe: bilinear Credit sample, then 35/65 RGB mix.
library SoftInkPixels {
    struct Axis {
        uint256 lo;
        uint256 hi;
        uint256 weight;
        uint256 denominator;
    }

    function paint(bytes memory body, bytes memory grid, uint16 width, uint16 height)
        internal
        pure
        returns (bytes memory painted)
    {
        uint256 count = uint256(width) * height;
        if (width < 8 || height < 8 || width > 64 || height > 64 || body.length != count * 4 || grid.length != 192) {
            revert InvalidPixels();
        }
        painted = new bytes(body.length);
        // The axis mapping depends only on dimensions, not pixel color. Compute
        // each X once and each Y once, rather than allocating both for every pixel.
        Axis[] memory columns = new Axis[](width);
        for (uint256 x; x < width; ++x) {
            columns[x] = _axis(x, width);
        }
        bool occupied;
        // Dimensions are checked above (<=64); channels <=255, denominators <=128.
        // All arithmetic below is bounded, including weighted sums <=4,177,920.
        unchecked {
            for (uint256 y; y < height; ++y) {
                Axis memory row = _axis(y, height);
                for (uint256 x; x < width; ++x) {
                    uint256 p = (y * width + x) * 4;
                    uint256 rgba;
                    assembly ("memory-safe") { rgba := shr(224, mload(add(add(body, 32), p))) }
                    uint256 alpha = rgba & 255;
                    if (alpha == 0) continue;
                    occupied = true;
                    uint256 soft = _sample(grid, columns[x], row);
                    uint256 rgb;
                    for (uint256 channel; channel < 3; ++channel) {
                        uint256 shift = 16 - 8 * channel;
                        uint256 source = (rgba >> (24 - 8 * channel)) & 255;
                        uint256 credit = (soft >> shift) & 255;
                        rgb |= _roundEven(source * 35 + credit * 65, 100) << shift;
                    }
                    assembly ("memory-safe") {
                        let dest := add(add(painted, 32), p)
                        mstore8(dest, shr(16, rgb))
                        mstore8(add(dest, 1), shr(8, rgb))
                        mstore8(add(dest, 2), rgb)
                        mstore8(add(dest, 3), alpha)
                    }
                }
            }
        }
        if (!occupied) revert InvalidPixels();
    }

    function _axis(uint256 index, uint256 size) private pure returns (Axis memory a) {
        unchecked {
            a.denominator = 2 * size;
            uint256 numerator = (2 * index + 1) * 8;
            numerator = numerator <= size ? 0 : numerator - size;
            if (numerator >= 7 * a.denominator) numerator = 7 * a.denominator;
            a.lo = numerator / a.denominator;
            a.hi = a.lo < 7 ? a.lo + 1 : 7;
            a.weight = numerator % a.denominator;
        }
    }

    function _sample(bytes memory grid, Axis memory ax, Axis memory ay) private pure returns (uint256 rgb) {
        unchecked {
            uint256 c00 = _rgb(grid, ay.lo * 8 + ax.lo);
            uint256 c10 = _rgb(grid, ay.lo * 8 + ax.hi);
            uint256 c01 = _rgb(grid, ay.hi * 8 + ax.lo);
            uint256 c11 = _rgb(grid, ay.hi * 8 + ax.hi);
            uint256 w00 = (ax.denominator - ax.weight) * (ay.denominator - ay.weight);
            uint256 w10 = ax.weight * (ay.denominator - ay.weight);
            uint256 w01 = (ax.denominator - ax.weight) * ay.weight;
            uint256 w11 = ax.weight * ay.weight;
            uint256 denominator = ax.denominator * ay.denominator;
            for (uint256 channel; channel < 3; ++channel) {
                uint256 shift = 16 - 8 * channel;
                uint256 numerator =
                    ((c00 >> shift) & 255) * w00 + ((c10 >> shift) & 255) * w10 + ((c01 >> shift) & 255) * w01
                        + ((c11 >> shift) & 255) * w11;
                rgb |= _roundEven(numerator, denominator) << shift;
            }
        }
    }

    function _rgb(bytes memory grid, uint256 i) private pure returns (uint256 value) {
        assembly ("memory-safe") { value := shr(232, mload(add(add(grid, 32), mul(i, 3)))) }
    }

    function _roundEven(uint256 numerator, uint256 denominator) private pure returns (uint256 q) {
        unchecked {
            q = numerator / denominator;
            uint256 remainder = numerator % denominator;
            if (remainder * 2 > denominator || (remainder * 2 == denominator && q & 1 != 0)) ++q;
        }
    }
}

src/evolution/sources/CreditPunkData.sol

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

import {CreditArt} from "../CreditArt.sol";
import {ICryptoPunksData} from "../../ICryptoPunksData.sol";
import {ISkeletonSource} from "../IEvolution.sol";
import {SkeletonAttribute, InvalidAddress, InvalidTokenId, InvalidCreditId} from "../EvolutionTypes.sol";

/// @notice Immutable shared Credit palette and original Punk source; no owner or setters.
contract CreditPunkData is ISkeletonSource {
    ICryptoPunksData public immutable punksData;

    address public immutable credits;
    address public immutable creditArt;

    constructor(address credits_, address art_, address data) {
        if (credits_.code.length == 0) revert InvalidAddress(credits_);
        if (art_.code.length == 0) revert InvalidAddress(art_);
        credits = credits_;
        creditArt = art_;
        if (data.code.length == 0) revert InvalidAddress(data);
        punksData = ICryptoPunksData(data);
    }

    function gridOf(uint256 id) external view returns (bytes memory) {
        _validCredit(id);
        return CreditArt.gridOf(credits, creditArt, id);
    }

    function read(uint256 id) external view returns (bytes memory grid, string memory traits) {
        _validCredit(id);
        return CreditArt.read(credits, creditArt, id);
    }

    function _validCredit(uint256 id) private pure {
        if (id == 0 || id > 122154) revert InvalidCreditId(id);
    }

    function readSkeleton(uint256 id) external view returns (bytes memory bodyRGBA, uint24 backgroundRGB) {
        if (id >= 10_000) revert InvalidTokenId(id);
        return (punksData.punkImage(uint16(id)), 0x708492);
    }

    function getAttributes(uint256 id) external view returns (SkeletonAttribute[] memory attrs) {
        if (id >= 10_000) revert InvalidTokenId(id);
        bytes memory raw = bytes(punksData.punkAttributes(uint16(id)));
        require(raw.length <= 4096, "Attributes too long");
        attrs = new SkeletonAttribute[](32);
        uint256 start;
        uint256 count;
        while (start < raw.length) {
            while (start < raw.length && (raw[start] == 0x20 || raw[start] == 0x2c)) ++start;
            uint256 end = start;
            while (end < raw.length && raw[end] != 0x2c) ++end;
            uint256 trimmed = end;
            while (trimmed > start && raw[trimmed - 1] == 0x20) --trimmed;
            if (trimmed > start) {
                require(count < 32 && trimmed - start <= 128, "Invalid attributes");
                bytes memory value = new bytes(trimmed - start);
                for (uint256 i; i < value.length; ++i) {
                    value[i] = raw[start + i];
                }
                attrs[count] = SkeletonAttribute(count == 0 ? "Type" : "Attribute", string(value));
                ++count;
            }
            start = end + 1;
        }
        assembly { mstore(attrs, count) }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "ERC721A/=lib/ERC721A/contracts/",
    "erc721a/=lib/ERC721A/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "oz-upgradeable-v4/=node_modules/@openzeppelin/contracts-upgradeable/",
    "oz-v4/=node_modules/@openzeppelin/contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.