Skip to content
Verified contractPartialMIT

UsualSuspectsRendererV2

Address0x7433ef50246ccb7530ce84651bbc88db1dd0bca8
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.17

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.17+commit.8df45f5f
Language
solidity
Optimization
Yes, 200 runs
EVM version
london
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,397,802
Creation transaction
0x0ac288a9da…5032df040e

src/renderers/UsualSuspectsRendererV2.sol

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

import {IUsualSuspectsData} from "../interfaces/IUsualSuspectsData.sol";
import {TusBinaryReader} from "../libraries/TusBinaryReader.sol";
import {TusBulkSvgAssembler} from "../libraries/TusBulkSvgAssembler.sol";
import {TusCatalog} from "../libraries/TusCatalog.sol";
import {TusMetadata} from "../libraries/TusMetadata.sol";
import {TusSvgAssembler} from "../libraries/TusSvgAssembler.sol";
import {UsualSuspectsRenderer} from "./UsualSuspectsRenderer.sol";
import {UsualSuspectsSvgTransform} from "./UsualSuspectsSvgTransform.sol";

/// @title UsualSuspectsRendererV2
/// @notice Renders corrected SVGs and canonical metadata using the original TUS1 archive.
/// @author berny0x
contract UsualSuspectsRendererV2 is UsualSuspectsRenderer {
    bytes32 private constant _ARCHIVE_HASH = 0x1f0774dab0341ba3c067241c97a0cfd4f34cf6d08eaab17a4dfc0216b8a27792;
    uint256 private constant _MAX_SVG_BYTES = 200_000;
    uint256 private constant _MAX_JSON_BYTES = 4 * ((_MAX_SVG_BYTES + 2) / 3) + TusMetadata.MAX_ATTRIBUTES_BYTES + 512;

    /// @notice Immutable code that corrects the SVG assembled from the existing archive.
    UsualSuspectsSvgTransform public immutable svgTransform;

    error InvalidSvgTransform();
    error SvgOutputTooLarge();

    /// @notice Binds the verified original archive and SVG transformation logic.
    /// @param data The existing canonical TUS1 data reader.
    /// @param transform The deployed compatibility transform.
    constructor(IUsualSuspectsData data, UsualSuspectsSvgTransform transform) UsualSuspectsRenderer(data) {
        if (data.dataHash() != _ARCHIVE_HASH) revert InvalidCollectionData();
        if (address(transform).code.length == 0) revert InvalidSvgTransform();
        svgTransform = transform;
    }

    /// @inheritdoc UsualSuspectsRenderer
    function renderSvg(uint256 artworkId) external view override returns (string memory) {
        (bytes memory originalSvg,) = _readScene(artworkId, false);
        return string(_transform(originalSvg));
    }

    /// @inheritdoc UsualSuspectsRenderer
    function tokenURI(uint256 tokenId, uint256 artworkId, bool revealed)
        external
        view
        override
        returns (string memory)
    {
        if (revealed && artworkId == 0) revert TusCatalog.InvalidPreset();
        (bytes memory originalSvg, bytes memory attributesJson) = _readScene(revealed ? artworkId : 0, true);
        return TusMetadata.tokenURI(tokenId, _transform(originalSvg), attributesJson, revealed, _MAX_JSON_BYTES);
    }

    function _transform(bytes memory originalSvg) private view returns (bytes memory svg) {
        svg = svgTransform.transform(originalSvg);
        if (svg.length == 0 || svg.length > _MAX_SVG_BYTES) revert SvgOutputTooLarge();
    }

    function _readScene(uint256 artworkId, bool includeAttributes)
        private
        view
        returns (bytes memory originalSvg, bytes memory attributesJson)
    {
        originalSvg = new bytes(TusSvgAssembler.MAX_SVG_BYTES);
        attributesJson = new bytes(includeAttributes ? TusMetadata.MAX_ATTRIBUTES_BYTES : 0);
        uint256 scratch;
        assembly ("memory-safe") {
            scratch := mload(0x40)
        }

        TusCatalog.Context memory catalog = TusCatalog.open(_data, _layout);
        TusCatalog.Selection memory selection = TusCatalog.select(catalog, artworkId);
        TusBulkSvgAssembler.FragmentData memory fragments = TusBulkSvgAssembler.open(_data, _layout);
        bytes memory assembledSvg = TusBulkSvgAssembler.assemble(catalog, selection, fragments);
        TusBinaryReader.copy(assembledSvg, 0, originalSvg, 0, assembledSvg.length);

        if (includeAttributes) {
            bytes memory traits = TusMetadata.attributes(catalog, selection, fragments);
            TusBinaryReader.copy(traits, 0, attributesJson, 0, traits.length);
            assembly ("memory-safe") {
                mstore(attributesJson, mload(traits))
            }
        }

        // The scene and trait buffers precede scratch. The catalog, assembly
        // buffers and decoder cache are dead before the transform and Base64.
        assembly ("memory-safe") {
            mstore(originalSvg, mload(assembledSvg))
            mstore(0x40, scratch)
        }
    }
}

lib/seadrop/lib/openzeppelin-contracts/contracts/utils/Base64.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

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

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

pragma solidity ^0.8.0;

import "./math/Math.sol";

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

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

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

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

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

src/interfaces/IUsualSuspectsData.sol

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

/// @title IUsualSuspectsData
/// @notice Provides bounded access to an immutable TUS1 archive.
/// @author berny0x
interface IUsualSuspectsData {
    /// @notice Returns the SHA-256 commitment to the complete logical archive.
    /// @return The archive SHA-256 digest, excluding physical shard sentinels.
    function dataHash() external view returns (bytes32);

    /// @notice Returns the archive length, excluding physical shard sentinels.
    /// @return The number of logical archive bytes.
    function dataLength() external view returns (uint256);

    /// @notice Reads a bounded range, including ranges crossing shard boundaries.
    /// @param offset The logical archive byte offset.
    /// @param length The number of bytes to return.
    /// @return The exact archive bytes in the requested range.
    function read(uint256 offset, uint256 length) external view returns (bytes memory);
}

src/interfaces/IUsualSuspectsRenderer.sol

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

/// @title IUsualSuspectsRenderer
/// @notice Separates ERC721 ownership and allocation from SVG and metadata assembly.
/// @author berny0x
interface IUsualSuspectsRenderer {
    /// @notice Identifies the archive encoding accepted by this renderer.
    /// @return The TUS1 format identifier.
    function sourceFormat() external view returns (bytes4);

    /// @notice Returns the immutable archive reader used by this renderer.
    /// @return The collection data contract address.
    function collectionData() external view returns (address);

    /// @notice Returns the SHA-256 commitment to the canonical archive.
    /// @return The archive SHA-256 digest.
    function dataHash() external view returns (bytes32);

    /// @notice Assembles the SVG for an artwork or the common Unrevealed scene.
    /// @param artworkId The one-based artwork ID, or zero for Unrevealed.
    /// @return The complete self-contained SVG document.
    function renderSvg(uint256 artworkId) external view returns (string memory);

    /// @notice Builds token metadata without taking ownership of token allocation.
    /// @param tokenId The NFT token ID used in the display name.
    /// @param artworkId The one-based resolved artwork ID when revealed.
    /// @param revealed Whether final artwork and trait values are visible.
    /// @return The Base64 JSON data URI containing the SVG image and twelve traits.
    function tokenURI(uint256 tokenId, uint256 artworkId, bool revealed) external view returns (string memory);
}

src/libraries/TusBase64.sol

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

/// @title TusBase64
/// @notice Encodes large SVG metadata in 24-byte input blocks.
/// @author berny0x
library TusBase64 {
    /// @notice Encodes a byte string with standard Base64 padding.
    /// @param data The exact input bytes.
    /// @return output The Base64 ASCII bytes.
    function encode(bytes memory data) internal pure returns (bytes memory output) {
        uint256 encodedLength = 4 * ((data.length + 2) / 3);
        output = new bytes(encodedLength);
        assembly ("memory-safe") {
            // A sextet is at most 63. Adding a bias sets its byte's high bit
            // at the threshold without carrying into an adjacent byte.
            function atLeast(digits, threshold) -> mask {
                let ones := 0x0101010101010101010101010101010101010101010101010101010101010101
                let highBits := 0x8080808080808080808080808080808080808080808080808080808080808080
                mask := shr(7, and(add(digits, mul(sub(128, threshold), ones)), highBits))
            }

            function encodeBlock(input) -> encoded {
                // Expand the low 24 bytes into eight four-byte lanes, inserting
                // one zero before each triple by successively splitting groups.
                let lanes :=
                    or(
                        and(input, 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff),
                        shl(32, and(input, 0x0000000000000000ffffffffffffffffffffffff000000000000000000000000))
                    )
                lanes := or(
                    and(lanes, 0x00000000000000000000ffffffffffff00000000000000000000ffffffffffff),
                    shl(16, and(lanes, 0x00000000ffffffffffff00000000000000000000ffffffffffff000000000000))
                )
                lanes := or(
                    and(lanes, 0x0000000000ffffff0000000000ffffff0000000000ffffff0000000000ffffff),
                    shl(8, and(lanes, 0x0000ffffff0000000000ffffff0000000000ffffff0000000000ffffff000000))
                )

                // Separate the four Base64 digits of each triple into individual bytes.
                let digits := and(shl(6, lanes), 0x3f0000003f0000003f0000003f0000003f0000003f0000003f0000003f000000)
                digits := or(
                    digits,
                    and(shl(4, lanes), 0x003f0000003f0000003f0000003f0000003f0000003f0000003f0000003f0000)
                )
                digits := or(
                    digits,
                    and(shl(2, lanes), 0x00003f0000003f0000003f0000003f0000003f0000003f0000003f0000003f00)
                )
                digits := or(digits, and(lanes, 0x0000003f0000003f0000003f0000003f0000003f0000003f0000003f0000003f))

                // Start with 'A' and adjust the alphabet at 'a', '0', '+', and '/'.
                encoded := add(digits, 0x4141414141414141414141414141414141414141414141414141414141414141)
                encoded := add(encoded, mul(6, atLeast(digits, 26)))
                encoded := sub(encoded, mul(75, atLeast(digits, 52)))
                encoded := sub(encoded, mul(15, atLeast(digits, 62)))
                encoded := add(encoded, mul(3, atLeast(digits, 63)))
            }

            let length := mload(data)
            let tailLength := mod(length, 24)
            let fullEnd := add(data, sub(length, tailLength))
            let outputStart := add(output, 32)
            let destination := outputStart
            // Each read ends at its block's last byte and stays in the input allocation.
            for { let cursor := add(data, 24) } iszero(gt(cursor, fullEnd)) { cursor := add(cursor, 24) } {
                mstore(destination, encodeBlock(mload(cursor)))
                destination := add(destination, 32)
            }
            if tailLength {
                let tail := shl(mul(sub(24, tailLength), 8), mload(add(data, length)))
                let outputEnd := add(outputStart, encodedLength)
                let paddingBits := mul(sub(32, sub(outputEnd, destination)), 8)
                mstore(destination, shl(paddingBits, shr(paddingBits, encodeBlock(tail))))
                switch mod(tailLength, 3)
                case 1 {
                    mstore8(sub(outputEnd, 2), 0x3d)
                    mstore8(sub(outputEnd, 1), 0x3d)
                }
                case 2 { mstore8(sub(outputEnd, 1), 0x3d) }
            }
        }
    }
}

src/libraries/TusBinaryReader.sol

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

/// @title TusBinaryReader
/// @notice Reads bounded unsigned big-endian integers and copies exact byte ranges.
/// @author berny0x
library TusBinaryReader {
    error BinaryReadOutOfBounds();

    function readUint16(bytes memory data, uint256 offset) internal pure returns (uint16 value) {
        _checkRange(data.length, offset, 2);
        assembly {
            value := shr(240, mload(add(add(data, 0x20), offset)))
        }
    }

    function readUint32(bytes memory data, uint256 offset) internal pure returns (uint32 value) {
        _checkRange(data.length, offset, 4);
        assembly {
            value := shr(224, mload(add(add(data, 0x20), offset)))
        }
    }

    function readUint64(bytes memory data, uint256 offset) internal pure returns (uint64 value) {
        _checkRange(data.length, offset, 8);
        assembly {
            value := shr(192, mload(add(add(data, 0x20), offset)))
        }
    }

    function readBytes4(bytes memory data, uint256 offset) internal pure returns (bytes4 value) {
        _checkRange(data.length, offset, 4);
        assembly {
            value := mload(add(add(data, 0x20), offset))
        }
    }

    /// @notice Copies a nonoverlapping byte range without modifying surrounding bytes.
    /// @dev Source and destination must not overlap. Internal callers own both buffers.
    function copy(
        bytes memory source,
        uint256 sourceOffset,
        bytes memory destination,
        uint256 destinationOffset,
        uint256 length
    ) internal pure {
        _checkRange(source.length, sourceOffset, length);
        _checkRange(destination.length, destinationOffset, length);
        assembly {
            let sourcePointer := add(add(source, 0x20), sourceOffset)
            let destinationPointer := add(add(destination, 0x20), destinationOffset)
            let fullLength := and(length, not(31))
            for { let cursor := 0 } lt(cursor, fullLength) { cursor := add(cursor, 32) } {
                mstore(add(destinationPointer, cursor), mload(add(sourcePointer, cursor)))
            }
            let remainder := and(length, 31)
            if remainder {
                let remainingBits := mul(sub(32, remainder), 8)
                let mask := sub(shl(remainingBits, 1), 1)
                let target := add(destinationPointer, fullLength)
                mstore(target, or(and(mload(target), mask), and(mload(add(sourcePointer, fullLength)), not(mask))))
            }
        }
    }

    function _checkRange(uint256 size, uint256 offset, uint256 length) private pure {
        if (offset > size || length > size - offset) revert BinaryReadOutOfBounds();
    }
}

src/libraries/TusBuffer.sol

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

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

/// @title TusBuffer
/// @notice Joins bounded selected fragments with one final allocation.
/// @author berny0x
library TusBuffer {
    error OutputTooLarge();

    /// @notice Copies selected pieces once, preserving their exact bytes and order.
    /// @param pieces The selected byte fragments.
    /// @param count The number of populated entries, bounded by the array length.
    /// @param maximum The maximum permitted concatenated byte length.
    /// @return output The exact concatenation of the populated fragments.
    function join(bytes[] memory pieces, uint256 count, uint256 maximum) internal pure returns (bytes memory output) {
        if (count > pieces.length) revert OutputTooLarge();
        uint256 length;
        for (uint256 index; index < count; ++index) {
            if (pieces[index].length > maximum - length) revert OutputTooLarge();
            length += pieces[index].length;
        }
        output = new bytes(length);
        uint256 cursor;
        for (uint256 index; index < count; ++index) {
            bytes memory piece = pieces[index];
            TusBinaryReader.copy(piece, 0, output, cursor, piece.length);
            cursor += piece.length;
        }
    }
}

src/libraries/TusBulkSvgAssembler.sol

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

import {IUsualSuspectsData} from "../interfaces/IUsualSuspectsData.sol";
import {TusBinaryReader} from "./TusBinaryReader.sol";
import {TusCatalog} from "./TusCatalog.sol";
import {TusSvgAssembler} from "./TusSvgAssembler.sol";

/// @title TusBulkSvgAssembler
/// @notice Assembles original artwork with one read of the TUF1 fragment section.
/// @dev Uses the same fragment and preset order as the original renderer.
/// @author berny0x
library TusBulkSvgAssembler {
    bytes32 private constant _ARCHIVE_HASH = 0x1f0774dab0341ba3c067241c97a0cfd4f34cf6d08eaab17a4dfc0216b8a27792;
    uint256 private constant _ARCHIVE_LENGTH = 396_250;
    bytes4 private constant _TUS1 = "TUS1";
    bytes4 private constant _TUF1 = "TUF1";
    uint256 private constant _TUF1_HEADER_LENGTH = 32;

    struct Table {
        uint256 count;
        uint256 offsets;
        uint256 dataStart;
        uint256 dataEnd;
    }

    struct FragmentData {
        bytes contents;
        Table strings;
        Table templates;
        Table programs;
    }

    error UnexpectedArchive();
    error InvalidFragmentSection();
    error InvalidRange();
    error InvalidInstruction();

    /// @notice Assembles the exact original SVG without adding storage.
    /// @param data Verified immutable reader for the complete frozen archive.
    /// @param artworkId Artwork ID, or zero for Unrevealed.
    /// @return svg The bounded original SVG bytes.
    function assemble(IUsualSuspectsData data, uint256 artworkId) internal view returns (bytes memory svg) {
        uint256 layout = _layout(data);
        TusCatalog.Context memory catalog = TusCatalog.open(data, layout);
        TusCatalog.Selection memory selection = TusCatalog.select(catalog, artworkId);
        return assemble(data, layout, catalog, selection);
    }

    /// @notice Assembles an artwork selected from a validated archive layout.
    /// @param data The immutable canonical data reader.
    /// @param layout The section offsets and lengths validated by the renderer.
    /// @param catalog The catalog opened against that layout.
    /// @param selection The ordered assets resolved for this artwork.
    /// @return svg The exact original SVG bytes.
    function assemble(
        IUsualSuspectsData data,
        uint256 layout,
        TusCatalog.Context memory catalog,
        TusCatalog.Selection memory selection
    ) internal view returns (bytes memory svg) {
        return assemble(catalog, selection, open(data, layout));
    }

    /// @notice Loads the original fragment section for both artwork and trait names.
    /// @param data The immutable canonical data reader.
    /// @param layout The section offsets and lengths validated by the renderer.
    /// @return fragments The in-memory TUF1 section and validated table layout.
    function open(IUsualSuspectsData data, uint256 layout) internal view returns (FragmentData memory fragments) {
        (uint256 offset, uint256 length) = TusCatalog.section(layout, 0);
        return _open(data.read(offset, length));
    }

    /// @notice Decodes a short trait name from a loaded fragment section.
    /// @param fragments The in-memory TUF1 section.
    /// @param index The trait name fragment index.
    /// @return name The exact UTF-8 name, bounded to 256 bytes.
    function decodeName(FragmentData memory fragments, uint256 index) internal pure returns (bytes memory name) {
        name = new bytes(256 + 32);
        uint256 length = _append(fragments, index, name, 0);
        assembly ("memory-safe") {
            mstore(name, length)
        }
    }

    function _layout(IUsualSuspectsData data) private view returns (uint256 layout) {
        if (data.dataLength() != _ARCHIVE_LENGTH || data.dataHash() != _ARCHIVE_HASH) revert UnexpectedArchive();
        bytes memory header = data.read(0, 40);
        if (
            TusBinaryReader.readBytes4(header, 0) != _TUS1 || TusBinaryReader.readUint16(header, 4) != 1
                || TusBinaryReader.readUint16(header, 6) != 0
        ) revert UnexpectedArchive();
        uint256 cursor = 40;
        for (uint256 index; index < 4; ++index) {
            uint256 offset = TusBinaryReader.readUint32(header, 8 + index * 8);
            uint256 length = TusBinaryReader.readUint32(header, 12 + index * 8);
            if (offset != cursor || length == 0 || length > _ARCHIVE_LENGTH - cursor) revert UnexpectedArchive();
            layout |= offset << ((7 - index * 2) * 32);
            layout |= length << ((6 - index * 2) * 32);
            cursor += length;
        }
        if (cursor != _ARCHIVE_LENGTH) revert UnexpectedArchive();
    }

    function _open(bytes memory contents) private pure returns (FragmentData memory fragments) {
        uint256 length = contents.length;
        if (
            length < _TUF1_HEADER_LENGTH || TusBinaryReader.readBytes4(contents, 0) != _TUF1
                || TusBinaryReader.readUint16(contents, 10) != 0 || TusBinaryReader.readUint32(contents, 28) != length
        ) revert InvalidFragmentSection();
        uint256 strings = TusBinaryReader.readUint16(contents, 4);
        uint256 templates = TusBinaryReader.readUint16(contents, 6);
        uint256 programs = TusBinaryReader.readUint16(contents, 8);
        uint256 stringData = TusBinaryReader.readUint32(contents, 12);
        uint256 templateOffsets = TusBinaryReader.readUint32(contents, 16);
        uint256 templateData = templateOffsets + 4 * (templates + 1);
        uint256 programOffsets = TusBinaryReader.readUint32(contents, 20);
        uint256 programData = TusBinaryReader.readUint32(contents, 24);
        if (
            stringData != _TUF1_HEADER_LENGTH + 4 * (strings + 1) || stringData > templateOffsets
                || templateData > programOffsets || programData != programOffsets + 4 * (programs + 1)
                || programData > length
        ) revert InvalidFragmentSection();
        fragments.contents = contents;
        fragments.strings = Table(strings, _TUF1_HEADER_LENGTH, stringData, templateOffsets);
        fragments.templates = Table(templates, templateOffsets, templateData, programOffsets);
        fragments.programs = Table(programs, programOffsets, programData, length);
    }

    /// @notice Assembles a selected artwork from an already loaded fragment section.
    /// @param catalog The original catalog.
    /// @param selection The ordered assets resolved for the artwork.
    /// @param fragments The in-memory TUF1 section.
    /// @return svg The exact original SVG bytes.
    function assemble(
        TusCatalog.Context memory catalog,
        TusCatalog.Selection memory selection,
        FragmentData memory fragments
    ) internal pure returns (bytes memory svg) {
        bytes memory bitmap = new bytes(catalog.bitmapBytes);
        uint32 requested;
        uint8 composition;
        uint16[16] memory bodies;
        for (uint256 index; index < selection.count; ++index) {
            TusCatalog.Asset memory asset = TusCatalog.asset(catalog, selection.assets[index]);
            bodies[index] = asset.body;
            requested |= asset.animations;
            if (composition == 0) composition = asset.composition;
            for (uint256 position; position < bitmap.length; ++position) {
                bitmap[position] |= catalog.catalog[asset.bitmapOffset + position];
            }
        }

        // A trailing partial word can write at most 31 bytes beyond the logical bound.
        svg = new bytes(TusSvgAssembler.MAX_SVG_BYTES + 32);
        uint256 written = _append(fragments, catalog.roots[composition == 3 ? 8 : composition], svg, 0);
        written = _append(fragments, catalog.roots[4], svg, written);
        for (uint256 index; index < catalog.glyphCount; ++index) {
            if (uint8(bitmap[index / 8]) & (uint256(1) << (index % 8)) != 0) {
                written = _append(fragments, TusCatalog.glyph(catalog, index), svg, written);
            }
        }
        written = _append(fragments, catalog.roots[5], svg, written);
        uint16[] memory sequence = TusCatalog.animations(catalog, requested);
        if (requested != 0) {
            written = _append(fragments, catalog.roots[6], svg, written);
            for (uint256 index; index < sequence.length; ++index) {
                written = _append(fragments, sequence[index], svg, written);
            }
            written = _append(fragments, catalog.roots[7], svg, written);
        }
        for (uint256 index; index < selection.count; ++index) {
            written = _append(fragments, bodies[index], svg, written);
        }
        written = _append(fragments, catalog.roots[3], svg, written);
        assembly ("memory-safe") {
            mstore(svg, written)
        }
    }

    function _append(FragmentData memory fragments, uint256 index, bytes memory svg, uint256 written)
        private
        pure
        returns (uint256)
    {
        bytes memory contents = fragments.contents;
        (uint256 programStart, uint256 programEnd) = _range(contents, fragments.programs, index);
        Table memory strings = fragments.strings;
        Table memory templates = fragments.templates;
        uint256 capacity = svg.length - 32;
        bytes4 errorSelector = InvalidInstruction.selector;
        assembly ("memory-safe") {
            function fail(selector) {
                mstore(0, selector)
                revert(0, 4)
            }

            // These reads end at the final requested byte, inside the validated
            // section, even at the end of a program or string table.
            function readUint16(pointer) -> value {
                value := and(mload(sub(pointer, 30)), 0xffff)
            }

            function lookup(base, table, item, selector) -> first, end {
                if iszero(lt(item, mload(table))) { fail(selector) }
                let offset := add(add(base, mload(add(table, 32))), shl(2, item))
                let pair := and(mload(sub(offset, 24)), 0xffffffffffffffff)
                let dataStart := add(base, mload(add(table, 64)))
                first := add(dataStart, shr(32, pair))
                end := add(dataStart, and(pair, 0xffffffff))
                if or(gt(first, end), gt(end, add(base, mload(add(table, 96))))) { fail(selector) }
            }

            function appendString(base, table, reference, destination, limit, selector) -> next {
                let first, end := lookup(base, table, readUint16(reference), selector)
                let length := sub(end, first)
                next := add(destination, length)
                if gt(next, limit) { fail(selector) }
                let complete := and(length, not(31))
                for { let cursor := 0 } lt(cursor, complete) { cursor := add(cursor, 32) } {
                    mstore(add(destination, cursor), mload(add(first, cursor)))
                }
                let tail := and(length, 31)
                if tail {
                    mstore(add(destination, complete), shl(shl(3, sub(32, tail)), mload(sub(end, 32))))
                }
            }

            let base := add(contents, 32)
            let cursor := add(base, programStart)
            let end := add(base, programEnd)
            let output := add(svg, 32)
            let limit := add(output, capacity)
            let destination := add(output, written)
            for {} lt(cursor, end) {} {
                if lt(sub(end, cursor), 2) { fail(errorSelector) }
                let first, templateEnd := lookup(base, templates, readUint16(cursor), errorSelector)
                if lt(sub(templateEnd, first), 3) { fail(errorSelector) }
                let arity := and(mload(sub(first, 31)), 0xff)
                let parameterBytes := shl(1, arity)
                cursor := add(cursor, 2)
                if or(
                    iszero(eq(sub(templateEnd, first), add(3, parameterBytes))),
                    gt(parameterBytes, sub(end, cursor))
                ) {
                    fail(errorSelector)
                }
                destination := appendString(base, strings, add(first, 1), destination, limit, errorSelector)
                for { let parameter := 0 } lt(parameter, parameterBytes) { parameter := add(parameter, 2) } {
                    destination := appendString(base, strings, cursor, destination, limit, errorSelector)
                    destination := appendString(
                        base,
                        strings,
                        add(add(first, 3), parameter),
                        destination,
                        limit,
                        errorSelector
                    )
                    cursor := add(cursor, 2)
                }
            }
            written := sub(destination, output)
        }
        return written;
    }

    function _range(bytes memory contents, Table memory table, uint256 index)
        private
        pure
        returns (uint256 start, uint256 stop)
    {
        if (index >= table.count) revert InvalidRange();
        uint256 position = table.offsets + index * 4;
        start = table.dataStart + TusBinaryReader.readUint32(contents, position);
        stop = table.dataStart + TusBinaryReader.readUint32(contents, position + 4);
        if (start > stop || stop > table.dataEnd) revert InvalidRange();
    }
}

src/libraries/TusCatalog.sol

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

import {IUsualSuspectsData} from "../interfaces/IUsualSuspectsData.sol";
import {TusBinaryReader} from "./TusBinaryReader.sol";

/// @title TusCatalog
/// @notice Reads bounded TUC1, TUL1 and TUP1 records without changing artwork geometry.
/// @author berny0x
library TusCatalog {
    uint16 internal constant NONE = type(uint16).max;
    uint256 private constant _POOL_HEADER_BYTES = 292;
    uint256 private constant _CATEGORY_COUNT = 12;

    struct Context {
        IUsualSuspectsData data;
        bytes catalog;
        bytes pools;
        uint256 presetOffset;
        uint256 artworkCount;
        uint256 assetCount;
        uint256 glyphCount;
        uint256 animationCount;
        uint256 combinationCount;
        uint256 bitmapBytes;
        uint256 assetBytes;
        uint256 assetOffset;
        uint256 rootCount;
        uint256 glyphOffset;
        uint256 animationOffset;
        uint256 combinationOffset;
        uint256 sequenceOffset;
        uint16 unrevealed;
        uint16[4] bases;
        uint16[9] roots;
    }

    struct Asset {
        uint8 pool;
        uint8 category;
        uint8 composition;
        uint16 name;
        uint16 body;
        uint32 animations;
        uint256 bitmapOffset;
    }

    struct Selection {
        uint8 kind;
        uint16[12] slots;
        uint16[16] assets;
        uint256 count;
    }

    error InvalidCatalog();
    error InvalidPools();
    error InvalidPreset();
    error InvalidAsset();
    error UnknownAnimationCombination();

    /// @notice Opens bounded tables whose immutable archive layout was validated by the renderer.
    /// @param data The immutable logical archive reader.
    /// @param layout Eight packed u32 section offsets and lengths, in archive order.
    /// @return context The per-call catalog and pool tables with validated header offsets.
    function open(IUsualSuspectsData data, uint256 layout) internal view returns (Context memory context) {
        context.data = data;
        (uint256 offset, uint256 length) = section(layout, 1);
        if (length < 72 || length > 65_536) revert InvalidCatalog();
        context.catalog = data.read(offset, length);
        (offset, length) = section(layout, 2);
        if (length < _POOL_HEADER_BYTES || length > 16_384) revert InvalidPools();
        context.pools = data.read(offset, length);
        (offset, length) = section(layout, 3);
        if (length != 44_448) revert InvalidPreset();
        context.presetOffset = offset;
        bytes memory header = data.read(offset, 8);
        if (TusBinaryReader.readBytes4(header, 0) != bytes4("TUP1")) revert InvalidPreset();
        context.artworkCount = TusBinaryReader.readUint32(header, 4);
        if (context.artworkCount != 5555) revert InvalidPreset();
        _openCatalog(context);
        if (TusBinaryReader.readBytes4(context.pools, 0) != bytes4("TUL1")) revert InvalidPools();
    }

    /// @notice Extracts an archive-relative section offset and length.
    /// @param layout The packed eight-u32 archive layout.
    /// @param index The section index, from zero through three.
    /// @return offset The logical archive offset.
    /// @return length The section byte length.
    function section(uint256 layout, uint256 index) internal pure returns (uint256 offset, uint256 length) {
        if (index > 3) revert InvalidCatalog();
        offset = uint32(layout >> ((7 - index * 2) * 32));
        length = uint32(layout >> ((6 - index * 2) * 32));
    }

    /// @notice Checks fixed catalog references, bases, canonical pools and animation indexes at construction.
    /// @param context The opened immutable catalog.
    /// @param fragmentCount The fragment dictionary capacity.
    function validate(Context memory context, uint256 fragmentCount) internal pure {
        for (uint256 index; index < context.rootCount; ++index) {
            if (context.roots[index] >= fragmentCount) revert InvalidCatalog();
        }
        for (uint256 index; index < context.assetCount; ++index) {
            Asset memory entry = asset(context, uint16(index));
            if (entry.name >= fragmentCount || entry.body >= fragmentCount) revert InvalidCatalog();
        }
        Asset memory placeholder = asset(context, context.unrevealed);
        if (placeholder.pool != 4 || placeholder.category != 12) revert InvalidCatalog();
        for (uint256 index; index < 4; ++index) {
            if (context.bases[index] == NONE) continue;
            Asset memory base = asset(context, context.bases[index]);
            uint256 category = index == 0 ? 4 : index == 1 ? 3 : index == 2 ? 5 : 7;
            if (base.pool != 5 || base.category != category) revert InvalidCatalog();
        }
        for (uint256 index; index < context.glyphCount; ++index) {
            if (glyph(context, index) >= fragmentCount) revert InvalidCatalog();
        }
        for (uint256 index; index < context.animationCount; ++index) {
            if (TusBinaryReader.readUint16(context.catalog, context.animationOffset + index * 2) >= fragmentCount) {
                revert InvalidCatalog();
            }
        }
        _validateCombinations(context);
        _validatePools(context);
    }

    /// @notice Resolves a single preset and its exact ordered shared-base/body selections.
    /// @param context The opened catalog.
    /// @param artworkId The one-based record, or zero for the common placeholder.
    /// @return selected The final body order and the twelve category identities.
    function select(Context memory context, uint256 artworkId) internal view returns (Selection memory selected) {
        if (artworkId == 0) {
            selected.kind = 4;
            selected.assets[0] = context.unrevealed;
            selected.count = 1;
            return selected;
        }
        if (artworkId > context.artworkCount) revert InvalidPreset();
        bytes memory record = context.data.read(context.presetOffset + 8 + (artworkId - 1) * 8, 8);
        uint256 word = TusBinaryReader.readUint64(record, 0);
        selected.kind = uint8(word & 3);
        word >>= 2;
        if (selected.kind == 3) {
            if (word >= NONE) revert InvalidPreset();
            Asset memory unique = asset(context, uint16(word));
            if (unique.pool != 3 || unique.category != 12) revert InvalidPreset();
            selected.assets[0] = uint16(word);
            selected.count = 1;
            return selected;
        }
        for (uint256 category; category < _CATEGORY_COUNT; ++category) {
            uint256 descriptor = 4 + (uint256(selected.kind) * _CATEGORY_COUNT + category) * 8;
            uint256 count = TusBinaryReader.readUint16(context.pools, descriptor + 4);
            uint256 width = uint8(context.pools[descriptor + 6]);
            uint256 local = word & ((uint256(1) << width) - 1);
            if (local >= count) revert InvalidPreset();
            word >>= width;
            uint256 offset = _POOL_HEADER_BYTES + TusBinaryReader.readUint32(context.pools, descriptor) + local * 2;
            selected.slots[category] = TusBinaryReader.readUint16(context.pools, offset);
        }
        if (word != 0) revert InvalidPreset();
        for (uint256 position; position < _CATEGORY_COUNT; ++position) {
            // Paint Accessory last; presets retain their permanent sampling order.
            uint256 category = position == 0 ? 0 : position == 11 ? 1 : position + 1;
            _selectCategory(context, selected, category);
        }
    }

    /// @notice Reads a validated fixed-width asset record.
    /// @param context The opened catalog.
    /// @param index The global asset index, excluding the synthetic None sentinel.
    /// @return entry The exact pool, category and fragment references.
    function asset(Context memory context, uint16 index) internal pure returns (Asset memory entry) {
        if (index >= context.assetCount) revert InvalidAsset();
        uint256 offset = context.assetOffset + uint256(index) * context.assetBytes;
        bytes memory catalog = context.catalog;
        entry.pool = uint8(catalog[offset]);
        entry.category = uint8(catalog[offset + 1]);
        entry.composition = uint8(catalog[offset + 2]);
        entry.name = TusBinaryReader.readUint16(catalog, offset + 4);
        entry.body = TusBinaryReader.readUint16(catalog, offset + 6);
        entry.animations = TusBinaryReader.readUint32(catalog, offset + 8);
        entry.bitmapOffset = offset + 12;
        if (
            entry.pool > 5 || entry.category > 12 || entry.composition > (context.rootCount == 9 ? 3 : 2)
                || catalog[offset + 3] != 0 || uint256(entry.animations) >> context.animationCount != 0
        ) revert InvalidAsset();
        uint256 remainder = context.glyphCount % 8;
        if (remainder != 0 && uint8(catalog[entry.bitmapOffset + context.bitmapBytes - 1]) >> remainder != 0) {
            revert InvalidAsset();
        }
    }

    /// @notice Reads the fragment containing one canonical glyph definition.
    /// @param context The opened catalog.
    /// @param index The contiguous glyph index.
    /// @return The glyph fragment index.
    function glyph(Context memory context, uint256 index) internal pure returns (uint16) {
        if (index >= context.glyphCount) revert InvalidCatalog();
        return TusBinaryReader.readUint16(context.catalog, context.glyphOffset + index * 2);
    }

    /// @notice Resolves a precompiled animation union without inventing CSS order.
    /// @param context The opened catalog.
    /// @param mask The union requested by selected bodies and shared bases.
    /// @return sequence The exact dependency-ordered CSS fragment indexes.
    function animations(Context memory context, uint32 mask) internal pure returns (uint16[] memory sequence) {
        uint256 low;
        uint256 high = context.combinationCount;
        while (low < high) {
            uint256 middle = (low + high) / 2;
            uint256 requested = TusBinaryReader.readUint32(context.catalog, context.combinationOffset + middle * 8);
            if (requested < mask) low = middle + 1;
            else high = middle;
        }
        if (
            low == context.combinationCount
                || TusBinaryReader.readUint32(context.catalog, context.combinationOffset + low * 8) != mask
        ) revert UnknownAnimationCombination();
        uint256 offset = context.sequenceOffset
            + TusBinaryReader.readUint32(context.catalog, context.combinationOffset + low * 8 + 4);
        uint256 count = TusBinaryReader.readUint16(context.catalog, offset);
        if (count > context.animationCount) revert InvalidCatalog();
        sequence = new uint16[](count);
        uint256 included;
        for (uint256 index; index < count; ++index) {
            uint16 fragment = TusBinaryReader.readUint16(context.catalog, offset + 2 + index * 2);
            uint256 bit = _animationBit(context, fragment);
            if (included & bit != 0) revert InvalidCatalog();
            included |= bit;
            sequence[index] = fragment;
        }
        if (included & mask != mask || (mask == 0 && count != 0)) revert InvalidCatalog();
    }

    function _openCatalog(Context memory context) private pure {
        bytes memory catalog = context.catalog;
        uint256 version = TusBinaryReader.readUint16(catalog, 4);
        if (
            TusBinaryReader.readBytes4(catalog, 0) != bytes4("TUC1") || (version != 1 && version != 2)
                || TusBinaryReader.readUint16(catalog, 6) > 3 || TusBinaryReader.readUint16(catalog, 18) != 0
                || TusBinaryReader.readUint16(catalog, 20) != 58 || TusBinaryReader.readUint16(catalog, 22) != 58
        ) revert InvalidCatalog();
        context.rootCount = version == 1 ? 8 : 9;
        context.assetOffset = version == 1 ? 72 : 74;
        if (catalog.length < context.assetOffset) revert InvalidCatalog();
        context.assetCount = TusBinaryReader.readUint16(catalog, 8);
        context.glyphCount = TusBinaryReader.readUint16(catalog, 10);
        context.animationCount = TusBinaryReader.readUint16(catalog, 12);
        context.combinationCount = TusBinaryReader.readUint16(catalog, 14);
        context.unrevealed = TusBinaryReader.readUint16(catalog, 16);
        if (
            context.assetCount == 0 || context.assetCount > 512 || context.glyphCount == 0 || context.glyphCount > 512
                || context.animationCount > 32 || context.combinationCount == 0 || context.combinationCount > 1024
                || context.unrevealed >= context.assetCount
        ) revert InvalidCatalog();
        context.bitmapBytes = (context.glyphCount + 7) / 8;
        context.assetBytes = 12 + context.bitmapBytes;
        for (uint256 index; index < 4; ++index) {
            context.bases[index] = TusBinaryReader.readUint16(catalog, 24 + index * 2);
        }
        for (uint256 index; index < context.rootCount; ++index) {
            context.roots[index] = TusBinaryReader.readUint16(catalog, 32 + index * 2);
        }
        uint256 offsetsStart = 32 + context.rootCount * 2;
        context.glyphOffset = TusBinaryReader.readUint32(catalog, offsetsStart + 4);
        context.animationOffset = TusBinaryReader.readUint32(catalog, offsetsStart + 8);
        context.combinationOffset = TusBinaryReader.readUint32(catalog, offsetsStart + 12);
        context.sequenceOffset = TusBinaryReader.readUint32(catalog, offsetsStart + 16);
        if (
            TusBinaryReader.readUint32(catalog, offsetsStart) != context.assetOffset
                || context.glyphOffset != context.assetOffset + context.assetCount * context.assetBytes
                || context.animationOffset != context.glyphOffset + context.glyphCount * 2
                || context.combinationOffset != context.animationOffset + context.animationCount * 2
                || context.sequenceOffset != context.combinationOffset + context.combinationCount * 8
                || context.sequenceOffset > catalog.length
                || TusBinaryReader.readUint32(catalog, offsetsStart + 20) != catalog.length
        ) revert InvalidCatalog();
    }

    function _validatePools(Context memory context) private pure {
        uint256 cursor = _POOL_HEADER_BYTES;
        uint256 totalWidth;
        for (uint256 descriptor; descriptor < 36; ++descriptor) {
            uint256 offset = 4 + descriptor * 8;
            uint256 count = TusBinaryReader.readUint16(context.pools, offset + 4);
            uint256 width = uint8(context.pools[offset + 6]);
            uint256 expectedWidth;
            if (count == 0 || count > context.assetCount + 1) revert InvalidPools();
            for (uint256 value = count - 1; value != 0; value >>= 1) {
                ++expectedWidth;
            }
            if (
                width != expectedWidth || context.pools[offset + 7] != 0
                    || _POOL_HEADER_BYTES + TusBinaryReader.readUint32(context.pools, offset) != cursor
                    || cursor + count * 2 > context.pools.length
            ) revert InvalidPools();
            for (uint256 index; index < count; ++index) {
                uint16 candidate = TusBinaryReader.readUint16(context.pools, cursor + index * 2);
                if (candidate == NONE) {
                    if (index != 0) revert InvalidPools();
                } else {
                    Asset memory entry = asset(context, candidate);
                    if (entry.category != descriptor % 12 || (entry.pool != 0 && entry.pool != descriptor / 12)) {
                        revert InvalidPools();
                    }
                }
                for (uint256 previous; previous < index; ++previous) {
                    if (candidate == TusBinaryReader.readUint16(context.pools, cursor + previous * 2)) {
                        revert InvalidPools();
                    }
                }
            }
            cursor += count * 2;
            totalWidth += width;
            if (descriptor % 12 == 11) {
                if (totalWidth > 62) revert InvalidPools();
                totalWidth = 0;
            }
        }
        if (cursor != context.pools.length) revert InvalidPools();
    }

    function _validateCombinations(Context memory context) private pure {
        uint256 cursor = context.sequenceOffset;
        uint256 previous;
        for (uint256 index; index < context.combinationCount; ++index) {
            uint256 offset = context.combinationOffset + index * 8;
            uint256 mask = TusBinaryReader.readUint32(context.catalog, offset);
            if (
                (index == 0 ? mask != 0 : mask <= previous) || mask >> context.animationCount != 0
                    || TusBinaryReader.readUint32(context.catalog, offset + 4) != cursor - context.sequenceOffset
            ) revert InvalidCatalog();
            uint256 count = TusBinaryReader.readUint16(context.catalog, cursor);
            if (count > context.animationCount || (mask == 0 && count != 0)) revert InvalidCatalog();
            cursor += 2 + count * 2;
            if (cursor > context.catalog.length) revert InvalidCatalog();
            previous = mask;
        }
        if (cursor != context.catalog.length) revert InvalidCatalog();
    }

    function _selectCategory(Context memory context, Selection memory selected, uint256 category) private pure {
        uint16 index = selected.slots[category];
        if (index == NONE) return;
        Asset memory entry = asset(context, index);
        if (entry.category != category || (entry.pool != 0 && entry.pool != selected.kind)) revert InvalidPreset();
        uint256 baseIndex = category == 4 ? 0 : category == 3 ? 1 : category == 5 ? 2 : category == 7 ? 3 : 4;
        bool useBase = selected.kind == 0 || (selected.kind == 1 && category != 4 && entry.pool == 0);
        if (baseIndex < 4 && useBase && context.bases[baseIndex] != NONE) {
            selected.assets[selected.count++] = context.bases[baseIndex];
        }
        selected.assets[selected.count++] = index;
    }

    function _animationBit(Context memory context, uint16 fragment) private pure returns (uint256) {
        for (uint256 index; index < context.animationCount; ++index) {
            if (TusBinaryReader.readUint16(context.catalog, context.animationOffset + index * 2) == fragment) {
                return uint256(1) << index;
            }
        }
        revert InvalidCatalog();
    }
}

src/libraries/TusFragmentDecoder.sol

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

import {IUsualSuspectsData} from "../interfaces/IUsualSuspectsData.sol";
import {TusBinaryReader} from "./TusBinaryReader.sol";

/// @title TusFragmentDecoder
/// @notice Expands selected TUF1 programs with exact literal and parameter bytes.
/// @author berny0x
library TusFragmentDecoder {
    uint256 private constant _MAX_FRAGMENT_BYTES = 128 * 1024;
    uint256 private constant _MAX_PROGRAM_BYTES = 128 * 1024;

    struct Context {
        IUsualSuspectsData data;
        uint256 sectionOffset;
        uint256 sectionLength;
        uint256 stringCount;
        uint256 templateCount;
        uint256 fragmentCount;
        uint256 stringDataOffset;
        uint256 templateDataOffset;
        uint256 programDataOffset;
        uint256 stringDataLength;
        uint256 templateDataLength;
        uint256 programDataLength;
        bytes stringOffsets;
        bytes templateOffsets;
        bytes fragmentOffsets;
        bytes[] strings;
        bytes[] templates;
    }

    error InvalidFragmentHeader();
    error InvalidOffsets();
    error InvalidFragmentIndex();
    error InvalidTemplate();
    error InvalidStringIndex();
    error TruncatedProgram();
    error FragmentTooLarge();

    /// @notice Opens TUF1 with bounded index tables; validate() checks their global ordering once.
    /// @param data Immutable archive reader whose commitment was approved at deployment.
    /// @param sectionOffset Logical archive offset of TUF1.
    /// @param sectionLength Exact TUF1 section length.
    /// @return context Per-render tables and lazy caches; reuse for every selected fragment.
    function open(IUsualSuspectsData data, uint256 sectionOffset, uint256 sectionLength)
        internal
        view
        returns (Context memory context)
    {
        uint256 archiveLength = data.dataLength();
        if (sectionLength < 32 || sectionOffset > archiveLength || sectionLength > archiveLength - sectionOffset) {
            revert InvalidFragmentHeader();
        }
        bytes memory header = data.read(sectionOffset, 32);
        if (
            TusBinaryReader.readBytes4(header, 0) != 0x54554631 || TusBinaryReader.readUint16(header, 10) != 0
                || TusBinaryReader.readUint32(header, 28) != sectionLength
        ) revert InvalidFragmentHeader();
        context.data = data;
        context.sectionOffset = sectionOffset;
        context.sectionLength = sectionLength;
        context.stringCount = TusBinaryReader.readUint16(header, 4);
        context.templateCount = TusBinaryReader.readUint16(header, 6);
        context.fragmentCount = TusBinaryReader.readUint16(header, 8);
        context.stringDataOffset = TusBinaryReader.readUint32(header, 12);
        uint256 templateOffsetsOffset = TusBinaryReader.readUint32(header, 16);
        uint256 fragmentOffsetsOffset = TusBinaryReader.readUint32(header, 20);
        context.templateDataOffset = templateOffsetsOffset + 4 * (context.templateCount + 1);
        context.programDataOffset = TusBinaryReader.readUint32(header, 24);
        if (
            context.stringDataOffset != 32 + 4 * (context.stringCount + 1)
                || context.stringDataOffset > templateOffsetsOffset
                || context.templateDataOffset > fragmentOffsetsOffset
                || context.programDataOffset != fragmentOffsetsOffset + 4 * (context.fragmentCount + 1)
                || context.programDataOffset > sectionLength
        ) revert InvalidOffsets();
        context.stringOffsets = data.read(sectionOffset + 32, 4 * (context.stringCount + 1));
        context.templateOffsets = data.read(sectionOffset + templateOffsetsOffset, 4 * (context.templateCount + 1));
        context.fragmentOffsets = data.read(sectionOffset + fragmentOffsetsOffset, 4 * (context.fragmentCount + 1));
        context.stringDataLength = templateOffsetsOffset - context.stringDataOffset;
        context.templateDataLength = fragmentOffsetsOffset - context.templateDataOffset;
        context.programDataLength = sectionLength - context.programDataOffset;
        _validateEndpoints(context.stringOffsets, context.stringDataLength);
        _validateEndpoints(context.templateOffsets, context.templateDataLength);
        _validateEndpoints(context.fragmentOffsets, context.programDataLength);
        context.strings = new bytes[](context.stringCount);
        context.templates = new bytes[](context.templateCount);
    }

    /// @notice Validates global index ordering once before activating an immutable archive.
    /// @param context An opened context whose immutable data is bound to the renderer.
    /// @dev Selected ranges remain independently checked by decode(), including after this gate.
    function validate(Context memory context) internal pure {
        _validateOffsets(context.stringOffsets, context.stringDataLength);
        _validateOffsets(context.templateOffsets, context.templateDataLength);
        _validateOffsets(context.fragmentOffsets, context.programDataLength);
    }

    /// @notice Expands one selected fragment with bounded, linear output copies.
    /// @param context Open section context; selected strings/templates are cached in memory.
    /// @param fragmentIndex Zero-based fragment index, below context.fragmentCount.
    /// @return output Exact UTF-8 bytes, bounded to 128 KiB per fragment.
    function decode(Context memory context, uint256 fragmentIndex) internal view returns (bytes memory output) {
        if (fragmentIndex >= context.fragmentCount) revert InvalidFragmentIndex();
        (uint256 start, uint256 programLength) =
            _range(context.fragmentOffsets, fragmentIndex, context.programDataLength);
        if (programLength > _MAX_PROGRAM_BYTES) revert FragmentTooLarge();
        bytes memory program =
            context.data.read(context.sectionOffset + context.programDataOffset + start, programLength);
        uint256 length = _expandedLength(context, program);
        output = new bytes(length);
        uint256 cursor;
        uint256 written;
        while (cursor < program.length) {
            bytes memory template = _template(context, TusBinaryReader.readUint16(program, cursor));
            cursor += 2;
            uint256 arity = uint8(template[0]);
            bytes memory piece = _string(context, TusBinaryReader.readUint16(template, 1));
            TusBinaryReader.copy(piece, 0, output, written, piece.length);
            written += piece.length;
            for (uint256 index; index < arity; ++index) {
                piece = _string(context, TusBinaryReader.readUint16(program, cursor));
                cursor += 2;
                TusBinaryReader.copy(piece, 0, output, written, piece.length);
                written += piece.length;
                piece = _string(context, TusBinaryReader.readUint16(template, 3 + index * 2));
                TusBinaryReader.copy(piece, 0, output, written, piece.length);
                written += piece.length;
            }
        }
    }

    function _expandedLength(Context memory context, bytes memory program) private view returns (uint256 length) {
        uint256 cursor;
        while (cursor < program.length) {
            if (program.length - cursor < 2) revert TruncatedProgram();
            bytes memory template = _template(context, TusBinaryReader.readUint16(program, cursor));
            uint256 arity = uint8(template[0]);
            cursor += 2;
            if (arity * 2 > program.length - cursor) revert TruncatedProgram();
            length += _string(context, TusBinaryReader.readUint16(template, 1)).length;
            for (uint256 index; index < arity; ++index) {
                length += _string(context, TusBinaryReader.readUint16(program, cursor)).length;
                cursor += 2;
                length += _string(context, TusBinaryReader.readUint16(template, 3 + index * 2)).length;
            }
            if (length > _MAX_FRAGMENT_BYTES) revert FragmentTooLarge();
        }
    }

    function _template(Context memory context, uint256 index) private view returns (bytes memory template) {
        if (index >= context.templateCount) revert InvalidTemplate();
        template = context.templates[index];
        if (template.length != 0) return template;
        (uint256 start, uint256 length) = _range(context.templateOffsets, index, context.templateDataLength);
        if (length < 3 || length > 513) revert InvalidTemplate();
        template = context.data.read(context.sectionOffset + context.templateDataOffset + start, length);
        uint256 arity = uint8(template[0]);
        if (template.length != 1 + 2 * (arity + 1)) revert InvalidTemplate();
        context.templates[index] = template;
    }

    function _string(Context memory context, uint256 index) private view returns (bytes memory value) {
        if (index >= context.stringCount) revert InvalidStringIndex();
        value = context.strings[index];
        if (value.length != 0) return value;
        (uint256 start, uint256 length) = _range(context.stringOffsets, index, context.stringDataLength);
        if (length > _MAX_FRAGMENT_BYTES) revert FragmentTooLarge();
        if (length == 0) return value;
        value = context.data.read(context.sectionOffset + context.stringDataOffset + start, length);
        context.strings[index] = value;
    }

    function _range(bytes memory offsets, uint256 index, uint256 dataLength)
        private
        pure
        returns (uint256 start, uint256 length)
    {
        start = TusBinaryReader.readUint32(offsets, 4 * index);
        uint256 end = TusBinaryReader.readUint32(offsets, 4 * (index + 1));
        if (start > end || end > dataLength) revert InvalidOffsets();
        length = end - start;
    }

    function _validateEndpoints(bytes memory offsets, uint256 dataLength) private pure {
        if (
            TusBinaryReader.readUint32(offsets, 0) != 0
                || TusBinaryReader.readUint32(offsets, offsets.length - 4) != dataLength
        ) revert InvalidOffsets();
    }

    function _validateOffsets(bytes memory offsets, uint256 dataLength) private pure {
        bytes4 errorSelector = InvalidOffsets.selector;
        // open() supplies compact u32 tables. Validate each transition without
        // repeating dynamic-array range checks for every one of the 9,240 entries.
        assembly {
            let size := mload(offsets)
            if or(lt(size, 4), and(size, 3)) {
                mstore(0, errorSelector)
                revert(0, 4)
            }
            let start := add(offsets, 0x20)
            if shr(224, mload(start)) {
                mstore(0, errorSelector)
                revert(0, 4)
            }
            let end := add(start, size)
            let previous := 0
            for { let cursor := add(start, 4) } lt(cursor, end) { cursor := add(cursor, 4) } {
                let current := shr(224, mload(cursor))
                if or(lt(current, previous), gt(current, dataLength)) {
                    mstore(0, errorSelector)
                    revert(0, 4)
                }
                previous := current
            }
            if iszero(eq(previous, dataLength)) {
                mstore(0, errorSelector)
                revert(0, 4)
            }
        }
    }
}

src/libraries/TusMetadata.sol

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

import {Base64} from "../../lib/seadrop/lib/openzeppelin-contracts/contracts/utils/Base64.sol";
import {Strings} from "../../lib/seadrop/lib/openzeppelin-contracts/contracts/utils/Strings.sol";
import {TusCatalog} from "./TusCatalog.sol";
import {TusFragmentDecoder} from "./TusFragmentDecoder.sol";
import {TusBuffer} from "./TusBuffer.sol";
import {TusBase64} from "./TusBase64.sol";
import {TusBulkSvgAssembler} from "./TusBulkSvgAssembler.sol";

/// @title TusMetadata
/// @notice Applies the uniform twelve-trait publication policy and escapes JSON without altering UTF-8.
/// @author berny0x
library TusMetadata {
    string private constant _REVEALED_DESCRIPTION =
        "A lineup of 5,555 glyph characters on Ethereum. Artwork, traits and animations are stored onchain and rendered directly as SVG.";
    string private constant _UNREVEALED_DESCRIPTION =
        "An unrevealed suspect from The Usual Suspects. Its twelve traits will be revealed after minting closes.";
    string private constant _DATA_URI_PREFIX = "data:application/json;base64,";
    bytes16 private constant _HEX = "0123456789abcdef";
    uint256 private constant _MAX_NAME_BYTES = 256;
    uint256 private constant _MAX_METADATA_BYTES = 160_000;
    uint256 internal constant MAX_ATTRIBUTES_BYTES = 22_000;

    struct Trait {
        uint16 fragment;
        bytes value;
    }

    error InvalidTraitName();

    /// @notice Serializes one exact SVG and twelve ordered string-valued attributes.
    /// @param tokenId The NFT token ID used only in the display name.
    /// @param svg The already assembled, bounded complete SVG document.
    /// @param attributesJson The already serialized twelve-attribute JSON array.
    /// @param revealed Whether final artwork and final traits are visible.
    /// @return The Base64 JSON token URI, including the exact SVG image data URI.
    function tokenURI(uint256 tokenId, bytes memory svg, bytes memory attributesJson, bool revealed)
        internal
        pure
        returns (string memory)
    {
        bytes memory json = _json(tokenId, bytes(Base64.encode(svg)), attributesJson, revealed, _MAX_METADATA_BYTES);
        return string.concat(_DATA_URI_PREFIX, Base64.encode(json));
    }

    /// @notice Serializes metadata with the calling renderer's bounded JSON size.
    /// @param tokenId The NFT token ID used in the display name.
    /// @param svg The complete SVG image bytes.
    /// @param attributesJson The serialized twelve-attribute JSON array.
    /// @param revealed Whether final artwork and trait values are visible.
    /// @param maximumJsonBytes The maximum unencoded JSON length, including the Base64 image.
    /// @return The Base64 JSON data URI containing the SVG image.
    function tokenURI(
        uint256 tokenId,
        bytes memory svg,
        bytes memory attributesJson,
        bool revealed,
        uint256 maximumJsonBytes
    ) internal pure returns (string memory) {
        bytes memory json = _json(tokenId, TusBase64.encode(svg), attributesJson, revealed, maximumJsonBytes);
        return string.concat(_DATA_URI_PREFIX, string(TusBase64.encode(json)));
    }

    function _json(
        uint256 tokenId,
        bytes memory encodedSvg,
        bytes memory attributesJson,
        bool revealed,
        uint256 maximumJsonBytes
    ) private pure returns (bytes memory) {
        bytes[] memory pieces = new bytes[](7);
        pieces[0] = abi.encodePacked('{"name":"Suspect #', Strings.toString(tokenId), '","description":"');
        pieces[1] = bytes(revealed ? _REVEALED_DESCRIPTION : _UNREVEALED_DESCRIPTION);
        pieces[2] = bytes('","image":"data:image/svg+xml;base64,');
        pieces[3] = encodedSvg;
        pieces[4] = bytes('","external_url":"https://theusualsuspects.xyz","attributes":');
        pieces[5] = attributesJson;
        pieces[6] = bytes("}");
        return TusBuffer.join(pieces, 7, maximumJsonBytes);
    }

    /// @notice Escapes all JSON control bytes and preserves the original non-ASCII UTF-8 bytes.
    /// @param value A catalog trait name of at most 256 UTF-8 bytes.
    /// @return output The escaped string contents, without surrounding JSON quotes.
    function escape(bytes memory value) internal pure returns (bytes memory output) {
        if (value.length > _MAX_NAME_BYTES) revert InvalidTraitName();
        uint256 length;
        for (uint256 index; index < value.length; ++index) {
            uint8 character = uint8(value[index]);
            length += character < 32 ? 6 : character == 34 || character == 92 ? 2 : 1;
        }
        output = new bytes(length);
        uint256 cursor;
        for (uint256 index; index < value.length; ++index) {
            uint8 character = uint8(value[index]);
            if (character < 32) {
                output[cursor++] = "\\";
                output[cursor++] = "u";
                output[cursor++] = "0";
                output[cursor++] = "0";
                output[cursor++] = _HEX[character >> 4];
                output[cursor++] = _HEX[character & 15];
            } else {
                if (character == 34 || character == 92) output[cursor++] = "\\";
                output[cursor++] = value[index];
            }
        }
    }

    /// @notice Builds the uniform attribute array while the selected decoder cache remains live.
    /// @param catalog The immutable catalog.
    /// @param selected The selected scene and original category identities.
    /// @param fragments The same decoder cache used for SVG assembly.
    /// @return The complete twelve-attribute JSON array, bounded to MAX_ATTRIBUTES_BYTES.
    function attributes(
        TusCatalog.Context memory catalog,
        TusCatalog.Selection memory selected,
        TusFragmentDecoder.Context memory fragments
    ) internal view returns (bytes memory) {
        Trait[12] memory traits = _traits(catalog, selected);
        uint16 last = TusCatalog.NONE;
        bytes memory name;
        for (uint256 position; position < traits.length; ++position) {
            uint16 index = traits[position].fragment;
            if (index == TusCatalog.NONE) continue;
            if (index != last) name = TusFragmentDecoder.decode(fragments, index);
            traits[position].value = name;
            last = index;
        }
        return _encodeTraits(traits);
    }

    /// @notice Builds the same attributes from the fragment section loaded for artwork assembly.
    /// @param catalog The immutable catalog.
    /// @param selected The selected scene and original category identities.
    /// @param fragments The already loaded TUF1 fragment section.
    /// @return The complete twelve-attribute JSON array.
    function attributes(
        TusCatalog.Context memory catalog,
        TusCatalog.Selection memory selected,
        TusBulkSvgAssembler.FragmentData memory fragments
    ) internal pure returns (bytes memory) {
        Trait[12] memory traits = _traits(catalog, selected);
        uint16 last = TusCatalog.NONE;
        bytes memory name;
        for (uint256 position; position < traits.length; ++position) {
            uint16 index = traits[position].fragment;
            if (index == TusCatalog.NONE) continue;
            if (index != last) name = TusBulkSvgAssembler.decodeName(fragments, index);
            traits[position].value = name;
            last = index;
        }
        return _encodeTraits(traits);
    }

    function _traits(TusCatalog.Context memory catalog, TusCatalog.Selection memory selected)
        private
        pure
        returns (Trait[12] memory traits)
    {
        uint16 uniqueName = selected.kind == 3 ? TusCatalog.asset(catalog, selected.assets[0]).name : TusCatalog.NONE;
        for (uint256 position; position < traits.length; ++position) {
            uint256 category = position == 0 ? 0 : position == 11 ? 1 : position + 1;
            uint16 fragment = TusCatalog.NONE;
            bytes memory value;
            if (selected.kind == 4) {
                value = bytes("Unrevealed");
            } else if (selected.kind == 3) {
                fragment = uniqueName;
            } else if (selected.kind == 2 && category != 4) {
                value = bytes(category == 10 ? "Bagger" : "Bagged");
            } else if (selected.slots[category] == TusCatalog.NONE) {
                value = bytes(selected.kind == 1 ? "Masked" : "None");
            } else {
                fragment = TusCatalog.asset(catalog, selected.slots[category]).name;
            }
            traits[position] = Trait(fragment, value);
        }
    }

    function _encodeTraits(Trait[12] memory traits) private pure returns (bytes memory) {
        bytes[] memory pieces = new bytes[](14);
        pieces[0] = bytes("[");
        for (uint256 position; position < traits.length; ++position) {
            pieces[position + 1] = abi.encodePacked(
                position == 0 ? '{"trait_type":"' : ',{"trait_type":"',
                _key(position),
                '","value":"',
                escape(traits[position].value),
                '"}'
            );
        }
        pieces[13] = bytes("]");
        return TusBuffer.join(pieces, 14, MAX_ATTRIBUTES_BYTES);
    }

    function _key(uint256 position) private pure returns (string memory) {
        if (position == 0) return "Backdrop";
        if (position == 1) return "Head";
        if (position == 2) return "Expression";
        if (position == 3) return "Eyes";
        if (position == 4) return "Nose";
        if (position == 5) return "Ear Accessory";
        if (position == 6) return "Facial Hair";
        if (position == 7) return "Mouth";
        if (position == 8) return "Chin";
        if (position == 9) return "Neck";
        if (position == 10) return "Ear Tip";
        return "Accessory";
    }
}

src/libraries/TusSvgAssembler.sol

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

import {TusCatalog} from "./TusCatalog.sol";
import {TusFragmentDecoder} from "./TusFragmentDecoder.sol";
import {TusBuffer} from "./TusBuffer.sol";

/// @title TusSvgAssembler
/// @notice Copies selected glyphs, dependency-ordered CSS and authored bodies into the exact final SVG.
/// @author berny0x
library TusSvgAssembler {
    // The committed snapshot's largest complete SVG is 91,995 bytes. The small
    // allowance does not permit collection-wide expansion during a token read.
    uint256 internal constant MAX_SVG_BYTES = 100_000;

    /// @notice Assembles a complete scene without parsing or rewriting its XML.
    /// @param catalog The validated immutable catalog tables.
    /// @param selected The ordered shared bases and authored bodies.
    /// @param fragments The per-call decoder cache, reusable for trait names.
    /// @return The exact UTF-8 SVG bytes, bounded by MAX_SVG_BYTES.
    function assemble(
        TusCatalog.Context memory catalog,
        TusCatalog.Selection memory selected,
        TusFragmentDecoder.Context memory fragments
    ) internal view returns (bytes memory) {
        bytes memory bitmap = new bytes(catalog.bitmapBytes);
        uint32 requested;
        uint8 composition;
        uint16[16] memory bodies;
        for (uint256 index; index < selected.count; ++index) {
            TusCatalog.Asset memory entry = TusCatalog.asset(catalog, selected.assets[index]);
            bodies[index] = entry.body;
            requested |= entry.animations;
            if (composition == 0) composition = entry.composition;
            for (uint256 byteIndex; byteIndex < bitmap.length; ++byteIndex) {
                bitmap[byteIndex] |= catalog.catalog[entry.bitmapOffset + byteIndex];
            }
        }
        uint16[] memory sequence = TusCatalog.animations(catalog, requested);
        bytes[] memory pieces = new bytes[](catalog.glyphCount + catalog.animationCount + 24);
        uint256 count;
        pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[composition == 3 ? 8 : composition]);
        pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[4]);
        for (uint256 index; index < catalog.glyphCount; ++index) {
            if (uint8(bitmap[index / 8]) & (uint256(1) << (index % 8)) != 0) {
                pieces[count++] = TusFragmentDecoder.decode(fragments, TusCatalog.glyph(catalog, index));
            }
        }
        pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[5]);
        if (requested != 0) {
            pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[6]);
            for (uint256 index; index < sequence.length; ++index) {
                pieces[count++] = TusFragmentDecoder.decode(fragments, sequence[index]);
            }
            pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[7]);
        }
        for (uint256 index; index < selected.count; ++index) {
            pieces[count++] = TusFragmentDecoder.decode(fragments, bodies[index]);
        }
        pieces[count++] = TusFragmentDecoder.decode(fragments, catalog.roots[3]);
        return TusBuffer.join(pieces, count, MAX_SVG_BYTES);
    }
}

src/libraries/TusSvgDocument.sol

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

/// @title TusSvgDocument
/// @notice Indexes the bounded XML subset used by the frozen collection SVGs.
/// @dev Nodes are one-based. Text, including entities, stays in the original byte ranges.
/// @author berny0x
library TusSvgDocument {
    uint256 private constant _MAX_BYTES = 100_000;
    uint256 private constant _MAX_NODES = 1024;
    uint256 private constant _MAX_DEPTH = 32;
    uint256 private constant _FIELD_MASK = 0xffffff;

    // Each node packs nine 24-bit fields, from its start offset in the low
    // bits through the parser's last-child index in the high bits.
    struct Document {
        bytes source;
        uint256[] nodes;
        uint256 count;
    }

    error InvalidSvgDocument();
    error InvalidSvgAttribute();

    /// @notice Indexes elements and their source offsets in a single SVG document.
    /// @param source The SVG bytes from the canonical archive.
    /// @return document The source and its packed, one-based element index.
    function parse(bytes memory source) internal pure returns (Document memory document) {
        return _parse(source, false);
    }

    /// @notice Indexes an SVG from the pinned, validated collection archive.
    /// @dev Its exporter never writes a literal greater-than character inside
    /// quoted attributes. Callers must pin the archive before using this path.
    /// @param source The SVG bytes assembled from that pinned archive.
    /// @return document The source and its packed, one-based element index.
    function parseFrozen(bytes memory source) internal pure returns (Document memory document) {
        return _parse(source, true);
    }

    function _parse(bytes memory source, bool frozen) private pure returns (Document memory document) {
        if (source.length == 0 || source.length > _MAX_BYTES) revert InvalidSvgDocument();

        uint256[] memory nodes = new uint256[](_MAX_NODES + 1);
        uint256 count;
        bytes4 invalidSelector = InvalidSvgDocument.selector;
        assembly ("memory-safe") {
            function fail(selector) {
                mstore(0, selector)
                revert(0, 4)
            }

            function at(base, offset) -> character {
                character := byte(and(offset, 31), mload(add(base, and(offset, not(31)))))
            }

            function isSpace(character) -> result {
                result := or(or(eq(character, 32), eq(character, 9)), or(eq(character, 10), eq(character, 13)))
            }

            function isName(character) -> result {
                result := or(
                    or(lt(sub(or(character, 32), 97), 26), lt(sub(character, 48), 10)),
                    or(or(eq(character, 45), eq(character, 46)), or(eq(character, 58), eq(character, 95)))
                )
            }

            function zeroBytes(word) -> mask {
                let lowerBits := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
                // Adding 0x7f to the low seven bits sets the high bit of any
                // nonzero lane without carrying into an adjacent lane.
                mask := not(or(or(add(and(word, lowerBits), lowerBits), word), lowerBits))
            }

            function firstMarkedByte(mask) -> offset {
                if iszero(shr(128, mask)) {
                    mask := shl(128, mask)
                    offset := 16
                }
                if iszero(shr(192, mask)) {
                    mask := shl(64, mask)
                    offset := add(offset, 8)
                }
                if iszero(shr(224, mask)) {
                    mask := shl(32, mask)
                    offset := add(offset, 4)
                }
                if iszero(shr(240, mask)) {
                    mask := shl(16, mask)
                    offset := add(offset, 2)
                }
                if iszero(shr(248, mask)) {
                    offset := add(offset, 1)
                }
            }

            function boundedWord(base, position, limit) -> word, size {
                size := sub(limit, position)
                if iszero(lt(size, 32)) {
                    word := mload(add(base, position))
                    size := 32
                    leave
                }
                // Read the last full word ending at the limit. Align the
                // remaining bytes to the left and leave zero bytes on the right.
                word := shl(shl(3, sub(32, size)), mload(sub(add(base, limit), 32)))
            }

            function findByte(base, position, limit, character) -> found {
                let needle := mul(character, 0x0101010101010101010101010101010101010101010101010101010101010101)
                for {} lt(position, limit) {} {
                    if eq(at(base, position), character) {
                        found := position
                        leave
                    }
                    let word, size := boundedWord(base, position, limit)
                    let mask := zeroBytes(xor(word, needle))
                    if mask {
                        found := add(position, firstMarkedByte(mask))
                        leave
                    }
                    position := add(position, size)
                }
                found := limit
            }

            function nameEnd(base, position, limit, selector) -> found {
                let first := position
                for {} lt(position, limit) {} {
                    if iszero(isName(at(base, position))) { break }
                    position := add(position, 1)
                }
                if or(eq(position, first), gt(sub(position, first), 32)) { fail(selector) }
                found := position
            }

            function tagEnd(base, position, limit, selector) -> found {
                for {} lt(position, limit) {} {
                    let word, size := boundedWord(base, position, limit)
                    let quotes :=
                        or(
                            zeroBytes(xor(word, 0x2222222222222222222222222222222222222222222222222222222222222222)),
                            zeroBytes(xor(word, 0x2727272727272727272727272727272727272727272727272727272727272727))
                        )
                    let angles :=
                        or(
                            zeroBytes(xor(word, 0x3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e3e)),
                            zeroBytes(xor(word, 0x3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c3c))
                        )
                    let delimiters := or(quotes, angles)
                    switch delimiters
                    case 0 { position := add(position, size) }
                    default {
                        let offset := firstMarkedByte(delimiters)
                        let character := byte(offset, word)
                        position := add(add(position, offset), 1)
                        if eq(character, 62) {
                            found := position
                            leave
                        }
                        if eq(character, 60) { fail(selector) }
                        position := findByte(base, position, limit, character)
                        if eq(position, limit) { fail(selector) }
                        position := add(position, 1)
                    }
                }
                fail(selector)
            }

            function slot(table, node) -> pointer {
                pointer := add(table, shl(5, node))
            }

            function field(packed, shift) -> value {
                value := and(shr(shift, packed), 0xffffff)
            }

            function setField(packed, shift, value) -> updated {
                updated := or(and(packed, not(shl(shift, 0xffffff))), shl(shift, value))
            }

            let base := add(source, 32)
            let length := mload(source)
            let table := add(nodes, 32)
            let maximum := sub(mload(nodes), 1)
            let active := 0
            let depth := 0
            let position := 0

            for {} lt(position, length) {} {
                let opening := findByte(base, position, length, 60)
                if iszero(active) {
                    for {} lt(position, opening) { position := add(position, 1) } {
                        if iszero(isSpace(at(base, position))) { fail(invalidSelector) }
                    }
                }
                if eq(opening, length) { break }
                if iszero(lt(add(opening, 1), length)) { fail(invalidSelector) }

                let nameStart := add(opening, 1)
                switch at(base, nameStart)
                case 47 {
                    if iszero(active) { fail(invalidSelector) }
                    nameStart := add(nameStart, 1)
                    let afterName := nameEnd(base, nameStart, length, invalidSelector)
                    let packed := mload(slot(table, active))
                    let originalStart := add(field(packed, 0), 1)
                    let nameSize := sub(afterName, nameStart)
                    if iszero(eq(nameSize, sub(field(packed, 168), originalStart))) { fail(invalidSelector) }
                    let mask := sub(shl(shl(3, nameSize), 1), 1)
                    let original := mload(sub(add(add(base, originalStart), nameSize), 32))
                    let closing := mload(sub(add(base, afterName), 32))
                    if and(xor(original, closing), mask) { fail(invalidSelector) }

                    position := afterName
                    for {} lt(position, length) {} {
                        if iszero(isSpace(at(base, position))) { break }
                        position := add(position, 1)
                    }
                    if eq(position, length) { fail(invalidSelector) }
                    if iszero(eq(at(base, position), 62)) { fail(invalidSelector) }
                    position := add(position, 1)
                    mstore(slot(table, active), or(or(packed, shl(48, opening)), shl(72, position)))
                    active := field(packed, 96)
                    depth := sub(depth, 1)
                }
                case 33 { fail(invalidSelector) }
                case 63 { fail(invalidSelector) }
                default {
                    let afterName := nameEnd(base, nameStart, length, invalidSelector)
                    switch frozen
                    case 1 {
                        let greater := findByte(base, afterName, length, 62)
                        if eq(greater, length) { fail(invalidSelector) }
                        position := add(greater, 1)
                    }
                    default { position := tagEnd(base, afterName, length, invalidSelector) }
                    if eq(count, maximum) { fail(invalidSelector) }
                    if iszero(active) {
                        if or(count, iszero(eq(sub(afterName, nameStart), 3))) { fail(invalidSelector) }
                        if iszero(eq(and(mload(sub(add(base, afterName), 32)), 0xffffff), 0x737667)) {
                            fail(invalidSelector)
                        }
                    }
                    count := add(count, 1)
                    let packed := or(or(opening, shl(24, position)), or(shl(96, active), shl(168, afterName)))

                    if active {
                        let parentSlot := slot(table, active)
                        let parentNode := mload(parentSlot)
                        let previous := field(parentNode, 192)
                        switch previous
                        case 0 { parentNode := setField(parentNode, 120, count) }
                        default {
                            let previousSlot := slot(table, previous)
                            mstore(previousSlot, setField(mload(previousSlot), 144, count))
                        }
                        mstore(parentSlot, setField(parentNode, 192, count))
                    }
                    switch eq(at(base, sub(position, 2)), 47)
                    case 1 { packed := or(or(packed, shl(48, position)), shl(72, position)) }
                    default {
                        depth := add(depth, 1)
                        if gt(depth, _MAX_DEPTH) { fail(invalidSelector) }
                        active := count
                    }
                    mstore(slot(table, count), packed)
                }
            }

            if or(active, iszero(count)) { fail(invalidSelector) }
            mstore(nodes, add(count, 1))
        }
        document = Document({source: source, nodes: nodes, count: count});
    }

    function start(Document memory document, uint256 node) internal pure returns (uint256) {
        return document.nodes[node] & _FIELD_MASK;
    }

    function openEnd(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 24) & _FIELD_MASK;
    }

    function closeStart(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 48) & _FIELD_MASK;
    }

    function end(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 72) & _FIELD_MASK;
    }

    function parent(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 96) & _FIELD_MASK;
    }

    function firstChild(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 120) & _FIELD_MASK;
    }

    function nextSibling(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 144) & _FIELD_MASK;
    }

    function attributesStart(Document memory document, uint256 node) internal pure returns (uint256) {
        return (document.nodes[node] >> 168) & _FIELD_MASK;
    }

    function isTag(Document memory document, uint256 node, bytes memory name) internal pure returns (bool) {
        if (node == 0) return false;
        uint256 nameStart = start(document, node) + 1;
        return name.length == attributesStart(document, node) - nameStart && matches(document.source, nameStart, name);
    }

    /// @notice Finds an attribute's exact value range, excluding quotes.
    function attribute(Document memory document, uint256 node, bytes memory name)
        internal
        pure
        returns (uint256 offset, uint256 length)
    {
        uint256 cursor = attributesStart(document, node);
        uint256 tagEnd = openEnd(document, node);
        while (cursor < tagEnd) {
            uint256 keyStart;
            uint256 keyLength;
            (cursor, keyStart, keyLength, offset, length) = nextAttribute(document, cursor, tagEnd);
            if (keyLength == 0) break;
            if (keyLength == name.length && matches(document.source, keyStart, name)) return (offset, length);
        }
        return (0, 0);
    }

    /// @notice Advances one attribute or returns a zero key length at the tag terminator.
    /// @param document The parsed document.
    /// @param cursor Start at attributesStart or the previous returned next offset.
    /// @param tagEnd The tag's exclusive opening boundary.
    /// @return next Offset immediately after the attribute's closing quote.
    /// @return keyStart First source byte of the attribute name.
    /// @return keyLength Attribute name length, or zero at the tag terminator.
    /// @return valueStart First source byte of the attribute value.
    /// @return valueLength Attribute value length.
    function nextAttribute(Document memory document, uint256 cursor, uint256 tagEnd)
        internal
        pure
        returns (uint256 next, uint256 keyStart, uint256 keyLength, uint256 valueStart, uint256 valueLength)
    {
        bytes memory source = document.source;
        if (cursor > tagEnd || tagEnd > source.length) revert InvalidSvgAttribute();
        bytes4 invalidSelector = InvalidSvgAttribute.selector;

        assembly ("memory-safe") {
            function fail(selector) {
                mstore(0, selector)
                revert(0, 4)
            }

            function at(base, offset) -> character {
                character := byte(and(offset, 31), mload(add(base, and(offset, not(31)))))
            }

            function isSpace(character) -> result {
                result := or(or(eq(character, 32), eq(character, 9)), or(eq(character, 10), eq(character, 13)))
            }

            function skipSpace(base, position, limit) -> found {
                for {} lt(position, limit) {} {
                    if iszero(isSpace(at(base, position))) { break }
                    position := add(position, 1)
                }
                found := position
            }

            function findQuote(base, position, limit, quote) -> found {
                let ones := 0x0101010101010101010101010101010101010101010101010101010101010101
                let lowerBits := 0x7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f
                let needle := mul(quote, ones)
                for {} lt(position, limit) {} {
                    let size := sub(limit, position)
                    let word := 0
                    switch lt(size, 32)
                    case 0 {
                        size := 32
                        word := mload(add(base, position))
                    }
                    default { word := shl(shl(3, sub(32, size)), mload(sub(add(base, limit), 32))) }
                    word := xor(word, needle)
                    let mask := not(or(or(add(and(word, lowerBits), lowerBits), word), lowerBits))
                    if mask {
                        // Skip an empty half of the marked word at each step.
                        found := position
                        if iszero(shr(128, mask)) {
                            mask := shl(128, mask)
                            found := add(found, 16)
                        }
                        if iszero(shr(192, mask)) {
                            mask := shl(64, mask)
                            found := add(found, 8)
                        }
                        if iszero(shr(224, mask)) {
                            mask := shl(32, mask)
                            found := add(found, 4)
                        }
                        if iszero(shr(240, mask)) {
                            mask := shl(16, mask)
                            found := add(found, 2)
                        }
                        if iszero(shr(248, mask)) { found := add(found, 1) }
                        leave
                    }
                    position := add(position, size)
                }
                found := limit
            }

            let base := add(source, 32)
            let position := skipSpace(base, cursor, tagEnd)
            next := tagEnd
            if lt(position, tagEnd) {
                let first := at(base, position)
                if iszero(or(eq(first, 47), eq(first, 62))) {
                    keyStart := position
                    for {} lt(position, tagEnd) {} {
                        let character := at(base, position)
                        if or(eq(character, 61), isSpace(character)) { break }
                        position := add(position, 1)
                    }
                    keyLength := sub(position, keyStart)
                    position := skipSpace(base, position, tagEnd)
                    if or(iszero(keyLength), eq(position, tagEnd)) { fail(invalidSelector) }
                    if iszero(eq(at(base, position), 61)) { fail(invalidSelector) }
                    position := skipSpace(base, add(position, 1), tagEnd)
                    if eq(position, tagEnd) { fail(invalidSelector) }
                    let quote := at(base, position)
                    if iszero(or(eq(quote, 34), eq(quote, 39))) { fail(invalidSelector) }
                    valueStart := add(position, 1)
                    position := findQuote(base, valueStart, tagEnd, quote)
                    if eq(position, tagEnd) { fail(invalidSelector) }
                    valueLength := sub(position, valueStart)
                    next := add(position, 1)
                }
            }
        }
    }

    /// @notice Compares a literal with the source range at the given byte offset.
    function matches(bytes memory source, uint256 offset, bytes memory value) internal pure returns (bool same) {
        uint256 length = value.length;
        if (offset > source.length || length > source.length - offset) return false;
        assembly ("memory-safe") {
            same := 1
            let sourcePointer := add(add(source, 32), offset)
            let valuePointer := add(value, 32)
            let full := and(length, not(31))
            for { let cursor := 0 } lt(cursor, full) { cursor := add(cursor, 32) } {
                if iszero(eq(mload(add(sourcePointer, cursor)), mload(add(valuePointer, cursor)))) {
                    same := 0
                    break
                }
            }
            let tail := and(length, 31)
            if and(same, iszero(iszero(tail))) {
                let mask := sub(shl(shl(3, tail), 1), 1)
                same := iszero(
                    and(
                        xor(mload(sub(add(sourcePointer, length), 32)), mload(sub(add(valuePointer, length), 32))),
                        mask
                    )
                )
            }
        }
    }
}

src/libraries/TusSvgEffects.sol

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

import {TusSvgDocument} from "./TusSvgDocument.sol";
import {TusSvgOutput} from "./TusSvgOutput.sol";

/// @title TusSvgEffects
/// @notice Serializes merged onchain artwork with browser-compatible filter and composition effects.
/// @author berny0x
library TusSvgEffects {
    using TusSvgDocument for TusSvgDocument.Document;
    using TusSvgOutput for TusSvgOutput.Buffer;

    uint256 private constant _MAX_SVG_BYTES = 200_000;
    uint256 private constant _DIRTY = 1;
    uint256 private constant _OMIT = 2;
    uint256 private constant _DETACH = 4;
    uint256 private constant _SPLIT = 8;
    uint256 private constant _SHARED_PATH = 16;
    uint256 private constant _THREE_D = 1;
    uint256 private constant _GLITCHED = 2;

    bytes private constant _FEATURE_STYLE =
        "<style>@supports (font:-apple-system-body){svg{shape-rendering:auto}}</style>";
    bytes private constant _BLACK_MATRIX_PREFIX = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ";
    bytes16 private constant _HEX = "0123456789ABCDEF";

    // The three red-derived and two blue-derived sRGB channels of the frozen 3D
    // matrices. Input is one 8-bit sRGB channel. Each row is R,G,B,G,B.
    bytes private constant _THREE_D_COLORS =
        hex"0000000000000000000001000001010100000101020000020202000002020300000202030000030304000003030401000403050101040405010104040601010505060101050507010106050801010606080101070609010107070a010108080a010108080b010109090c01010a090d02010a0a0d02010b0b0e02020c0b0f02020c0c1002020d0d1002020e0d1102020e0e1202020f0f130302100f1303021010140302111115030312111603031212160303131317030314131804031514190403151519040316151a040317161b040417171b050418171c050419181d050419191e05041a191e05051b1a1f06051b1b2006051c1b2106051d1c2106051d1d2207051e1d2307061f1e2407061f1f240706201f2508062120260807212127080722212708072322280907232329090724232a090825242a0a0825252b0a0826252c0a0827262d0a0927272d0b0928272e0b0929282f0b0a29292f0c0a2a29300c0a2b2a310c0a2c2b320d0b2c2b320d0b2d2c330d0b2e2d340e0c2e2d350e0c2f2e350e0c302f360e0c302f370f0d3130380f0d3231380f0d323139100e33323a100e34333b100e34333b110e35343c110f36353d110f36353e120f37363e121038373f1210383740121039384113103a394113113a394213113b3a4314113c3b4414123c3b4414123d3c4515123e3d4615123e3d4615133f3e471613403f481613413f491614414049171442414a171443414b171443424c171544434c181545434d181545444e181646454f191647454f191647465019164847511a174947521a174948521a174a49531b184b49541b184b4a551b184c4b551b184d4b561c194d4c571c194e4d581c194f4d581d1a4f4e591d1a504f5a1d1a514f5a1e1a51505b1e1b52515c1e1b53515d1f1b53525d1f1c54535e1f1c55535f201c555460201c565560201d575561201d585662211d585763211e595763211e5a5864221e5a5965221e5b5966221f5c5a66231f5c5b67231f5d5b6823205e5c6924205e5d6924205f5d6a2420605e6b2421605f6c2521615f6c252162606d252262616e262263616e262264626f2622646370272365637127236664712723666572282467657328246866742824686774282469677529256a687629256a697729256b69772a266c6a782a266d6b792a266d6b7a2b276e6c7a2b276f6d7b2b276f6d7c2c27706e7d2c28716f7d2c28716f7e2d2872707f2d297371802d297371802d297472812e297573822e2a7573822e2a7674832f2a7775842f2b7775852f2b787685302b797786302b797787302c7a7888312c7b7988312c7b7989312d7c7a8a312d7d7b8b322d7d7b8b322d7e7c8c322e7f7d8d332e7f7d8e332e807e8e332f817f8f342f817f90342f828091342f83819135308481923530848293353085839435318683943631868495363187859636318885963732888697373289879837328a879938338a889938338b899a38338c899b39338c8a9c39348d8b9c39348e8b9d3a348e8c9e3a358f8d9f3a35908d9f3a35908ea03b35918fa13b36928fa23b369290a23c369391a33c379491a43c379492a53d379592a53d379693a63d389694a73e389794a83e389895a83e399996a93e399996aa3f399a97aa3f399b98ab3f3a9b98ac403a9c99ad403a9d9aad403b9d9aae413b9e9baf413b9f9cb0413b9f9cb0423ca09db1423ca19eb2423ca19eb3423da29fb3433da3a0b4433da3a0b5433da4a1b6443ea5a2b6443ea5a2b7443ea6a3b8453fa7a4b9453fa7a4b9453fa8a5";

    struct Paint {
        uint256 channel;
        bytes suffix;
        bytes textFilter;
    }

    struct Context {
        TusSvgDocument.Document document;
        TusSvgOutput.Buffer output;
        bytes paths;
        uint256[] ranges;
        uint256[] sharedPaths;
        uint256[] flags;
        bytes32[] filterIds;
        uint256[] filterActions;
        uint256 filterCount;
        bytes32[] scopedIds;
        uint256 scopedCount;
        uint256 mode;
        bytes colors;
    }

    error InvalidScene();

    /// @notice Applies the gallery's filter and composition changes to the bounded original scene.
    /// @param document Parsed SVG, with unchanged source spans.
    /// @param paths Concatenated merged path data from the original geometry.
    /// @param ranges Per-node offsets in the low 32 bits and byte lengths in bits 32–63.
    /// @return svg A complete animated SVG document.
    function render(TusSvgDocument.Document memory document, bytes memory paths, uint256[] memory ranges)
        internal
        pure
        returns (bytes memory svg)
    {
        if (document.count == 0 || ranges.length <= document.count || !document.isTag(1, "svg")) {
            revert InvalidScene();
        }
        Context memory context;
        context.document = document;
        context.output = TusSvgOutput.allocate(_MAX_SVG_BYTES);
        context.paths = paths;
        context.ranges = ranges;
        context.flags = new uint256[](document.count + 1);
        context.filterIds = new bytes32[](document.count);
        context.filterActions = new uint256[](document.count);

        if (_attributeEquals(document, 1, "style", "filter:url(#dealers-composition-a3d)")) {
            context.mode = _THREE_D;
            context.colors = _THREE_D_COLORS;
        } else if (_attributeEquals(document, 1, "style", "filter:url(#dealers-composition-glitched)")) {
            context.mode = _GLITCHED;
        }
        if (context.mode != 0) {
            context.scopedIds = new bytes32[](document.count);
            context.sharedPaths = new uint256[](document.count + 1);
        }
        _prepare(context);
        Paint memory original;
        _open(context, 1, original, false, context.mode != 0);
        context.output.append(_FEATURE_STYLE);
        if (context.mode == 0) {
            _children(context, 1, original);
        } else {
            _metadata(context, original);
            if (context.mode == _THREE_D) _threeD(context, original);
            else _glitched(context, original);
            _copy(context, document.closeStart(1), document.end(1));
        }
        return context.output.finish();
    }

    function _prepare(Context memory context) private pure {
        TusSvgDocument.Document memory document = context.document;
        bool art;
        uint256 node = 2;
        while (node <= document.count) {
            if (document.parent(node) == 1) art = !_isMetadata(document, node);
            if (art && context.mode != 0) {
                if (context.mode == _THREE_D && _isSolidBackdrop(document, node)) {
                    context.flags[node] = _OMIT;
                    node = _after(document, node);
                    continue;
                }
                uint256 shared = _sharedPath(document, node);
                if (shared != 0) {
                    context.sharedPaths[node] = shared;
                    context.flags[node] |= _SHARED_PATH;
                } else if (_mayHave(document, node, "id=", 3)) {
                    (uint256 start, uint256 size) = document.attribute(node, "id");
                    if (size != 0) context.scopedIds[context.scopedCount++] = _hash(document.source, start, size);
                }
            }
            if (document.isTag(node, "filter")) _prepareFilter(context, node);
            node = context.ranges[node] == 0 ? node + 1 : _after(document, node);
        }

        if (context.filterCount != 0) {
            node = 2;
            while (node <= document.count) {
                if (_mayHave(document, node, "filter=", 7)) {
                    uint256 action = _filterAction(context, node);
                    if (action != 0) context.flags[node] |= action;
                }
                node =
                    (context.ranges[node] == 0 && context.flags[node] & _OMIT == 0) ? node + 1 : _after(document, node);
            }
        }
        for (node = document.count; node > 1; --node) {
            if (context.flags[node] != 0 || context.ranges[node] != 0) {
                context.flags[document.parent(node)] |= _DIRTY;
            }
        }
    }

    function _prepareFilter(Context memory context, uint256 filter) private pure {
        TusSvgDocument.Document memory document = context.document;
        uint256 last;
        uint256 colorMatrix;
        for (uint256 child = document.firstChild(filter); child != 0; child = document.nextSibling(child)) {
            last = child;
            if (document.isTag(child, "feColorMatrix") && !_attributeEquals(document, child, "in", "SourceAlpha")) {
                colorMatrix = child;
            }
        }
        if (last == 0) return;
        uint256 action;
        if (document.isTag(last, "feMerge")) {
            uint256 lastMerge;
            for (uint256 child = document.firstChild(last); child != 0; child = document.nextSibling(child)) {
                lastMerge = child;
            }
            if (lastMerge == 0 || !_attributeEquals(document, lastMerge, "in", "SourceGraphic")) return;
            context.flags[lastMerge] |= _OMIT;
            action = _SPLIT;
        } else if (document.isTag(last, "feBlend") && _attributeEquals(document, last, "in", "SourceGraphic")) {
            action = _isBlackMatrix(document, colorMatrix) ? _DETACH : _SPLIT;
            if (action == _SPLIT) context.flags[last] |= _OMIT;
        }
        if (action == 0) return;
        (uint256 start, uint256 size) = document.attribute(filter, "id");
        if (size == 0) return;
        context.filterIds[context.filterCount] = _hash(document.source, start, size);
        context.filterActions[context.filterCount++] = action;
    }

    function _filterAction(Context memory context, uint256 node) private pure returns (uint256) {
        (uint256 start, uint256 size) = context.document.attribute(node, "filter");
        bytes memory source = context.document.source;
        if (size < 7 || !TusSvgDocument.matches(source, start, "url(#") || source[start + size - 1] != ")") {
            return 0;
        }
        bytes32 id = _hash(source, start + 5, size - 6);
        for (uint256 index; index < context.filterCount; ++index) {
            if (context.filterIds[index] == id) return context.filterActions[index];
        }
        return 0;
    }

    function _isBlackMatrix(TusSvgDocument.Document memory document, uint256 node) private pure returns (bool) {
        if (node == 0) return false;
        (uint256 start, uint256 size) = document.attribute(node, "values");
        uint256 end = start + size;
        while (start < end && uint8(document.source[start]) <= 32) ++start;
        return end - start >= _BLACK_MATRIX_PREFIX.length
            && TusSvgDocument.matches(document.source, start, _BLACK_MATRIX_PREFIX);
    }

    function _isSolidBackdrop(TusSvgDocument.Document memory document, uint256 node) private pure returns (bool) {
        if (
            !document.isTag(node, "rect") || !_attributeEquals(document, node, "width", "58")
                || !_attributeEquals(document, node, "height", "58")
        ) return false;
        (uint256 start, uint256 size) = document.attribute(node, "fill");
        return size != 0 && document.source[start] == "#";
    }

    function _sharedPath(TusSvgDocument.Document memory document, uint256 node) private pure returns (uint256 range) {
        if (!document.isTag(node, "path")) return 0;
        uint256 end = document.openEnd(node);
        if (document.end(node) != end) return 0;
        uint256 cursor = document.attributesStart(node);
        while (true) {
            (uint256 next, uint256 key, uint256 keySize, uint256 value, uint256 size) =
                document.nextAttribute(cursor, end);
            if (keySize == 0) return range;
            cursor = next;
            bytes32 name = _key(document.source, key, keySize);
            if (name == bytes32("d") && size >= 80) range = value | (size << 32);
            else if (name != bytes32("fill-rule") && name != bytes32("data-line-join")) return 0;
        }
    }

    function _after(TusSvgDocument.Document memory document, uint256 node) private pure returns (uint256) {
        while (node != 1) {
            uint256 sibling = document.nextSibling(node);
            if (sibling != 0) return sibling;
            node = document.parent(node);
        }
        return document.count + 1;
    }

    function _isMetadata(TusSvgDocument.Document memory document, uint256 node) private pure returns (bool) {
        return document.isTag(node, "defs") || document.isTag(node, "style");
    }

    function _metadata(Context memory context, Paint memory original) private pure {
        TusSvgDocument.Document memory document = context.document;
        for (uint256 node = document.firstChild(1); node != 0; node = document.nextSibling(node)) {
            if (_isMetadata(document, node)) _emit(context, node, original);
        }
    }

    function _art(Context memory context, Paint memory paint) private pure {
        TusSvgDocument.Document memory document = context.document;
        for (uint256 node = document.firstChild(1); node != 0; node = document.nextSibling(node)) {
            if (!_isMetadata(document, node)) _emit(context, node, paint);
        }
    }

    function _threeD(Context memory context, Paint memory original) private pure {
        Paint memory red = Paint(1, "-3d0", "tus-3d-tint-0");
        Paint memory blue = Paint(2, "-3d1", "tus-3d-tint-1");
        context.output.append("<defs>");
        _paths(context);
        _textTint(context, red, ".487 0 0 0 0 .06 0 0 0 0 .05 0 0 0 0");
        _textTint(context, blue, "0 0 0 0 0 0 0 .392 0 0 0 0 .377 0 0");
        context.output.append('</defs><rect width="58" height="58" fill="#0D0D00"/>');
        context.output.append('<g transform="translate(1.16 1.16)" style="mix-blend-mode:screen">');
        _art(context, red);
        context.output.append('</g><g transform="translate(-1.16 -1.16)" style="mix-blend-mode:screen">');
        _art(context, blue);
        context.output.append('</g><g style="mix-blend-mode:screen">');
        _art(context, original);
        context.output.append("</g>");
    }

    function _glitched(Context memory context, Paint memory original) private pure {
        context.output.append("<defs>");
        _paths(context);
        _glitchChannel(context, Paint(3, "-gl0", "tus-glitch-tint-0"), "1 0 0 0 0 0 0 0 0 0 0 0 0 0 0");
        _glitchChannel(context, Paint(4, "-gl1", "tus-glitch-tint-1"), "0 0 0 0 0 0 1 0 0 0 0 0 0 0 0");
        _glitchChannel(context, Paint(5, "-gl2", "tus-glitch-tint-2"), "0 0 0 0 0 0 0 0 0 0 0 0 1 0 0");
        context.output
            .append(
                '<clipPath id="tus-glitch-band-0"><rect x="0" y="13" width="58" height="2"/></clipPath>'
                '<clipPath id="tus-glitch-band-1"><rect x="0" y="28" width="58" height="4"/></clipPath>'
                '<clipPath id="tus-glitch-band-2"><rect x="0" y="42" width="58" height="2.5"/></clipPath></defs><g>'
            );
        _art(context, original);
        context.output.append('</g><g style="isolation:isolate">');
        _glitchLayer(context, 0, "0 0;.9 .2;-.7 -.15;0 0;1.2 .1;-.5 -.2;0 0;-1.1 .15;.6 -.1;-.8 .2;.5 -.15;0 0;0 0");
        _glitchLayer(context, 1, "0 0;0 0;.4 0;0 0;-.4 0;0 0;0 0;.4 0;0 0;-.4 0;0 0;0 0;0 0");
        _glitchLayer(context, 2, "0 0;-.9 -.2;.7 .15;0 0;-1.2 -.1;.5 .2;0 0;1.1 -.15;-.6 .1;.8 -.2;-.5 .15;0 0;0 0");
        context.output.append("</g>");
    }

    function _glitchChannel(Context memory context, Paint memory paint, bytes memory matrix) private pure {
        _textTint(context, paint, matrix);
        context.output.append('<g id="tus-glitch-ch');
        context.output.appendUint(paint.channel - 3);
        context.output.append('">');
        _art(context, paint);
        context.output.append("</g>");
    }

    function _glitchLayer(Context memory context, uint256 channel, bytes memory offsets) private pure {
        context.output.append(channel == 0 ? bytes("<g>") : bytes('<g style="mix-blend-mode:screen">'));
        _glitchAnimation(context.output, offsets, true);
        _glitchBand(context.output, channel, 0, "0 0;2.4 0;-1.8 0;0 0;1.4 0;-2.6 0;0 0;-2 0;1.5 0;-2.8 0;1.2 0;0 0;0 0");
        _glitchBand(context.output, channel, 1, "0 0;-1.6 0;2.2 0;0 0;-2.8 0;1.8 0;0 0;2.6 0;-1.4 0;2 0;-2.4 0;0 0;0 0");
        _glitchBand(context.output, channel, 2, "0 0;1 0;-2.4 0;0 0;2.6 0;-1.2 0;0 0;-1.8 0;2.8 0;-1.2 0;2 0;0 0;0 0");
        context.output.append("</g>");
    }

    function _glitchBand(TusSvgOutput.Buffer memory output, uint256 channel, uint256 band, bytes memory offsets)
        private
        pure
    {
        output.append('<g opacity="0">');
        _glitchAnimation(output, "0;1;1;0;1;1;0;1;1;1;1;0;0", false);
        output.append("<g>");
        _glitchAnimation(output, offsets, true);
        output.append('<use href="#tus-glitch-ch');
        output.appendUint(channel);
        output.append('" clip-path="url(#tus-glitch-band-');
        output.appendUint(band);
        output.append(')"/></g></g>');
    }

    function _glitchAnimation(TusSvgOutput.Buffer memory output, bytes memory values, bool transform) private pure {
        output.append(
            transform
                ? bytes('<animateTransform attributeName="transform" type="translate" values="')
                : bytes('<animate attributeName="opacity" values="')
        );
        output.append(values);
        output.append(
            '" keyTimes="0;.18;.194;.208;.22;.237;.249;.57;.585;.603;.617;.635;1"'
            ' dur="8.3s" repeatCount="indefinite" calcMode="discrete"/>'
        );
    }

    function _textTint(Context memory context, Paint memory paint, bytes memory matrix) private pure {
        context.output.append('<filter id="');
        context.output.append(paint.textFilter);
        context.output.append('"><feColorMatrix type="matrix" values="');
        context.output.append(matrix);
        context.output.append(' 0 0 0 1 0"/></filter>');
    }

    function _paths(Context memory context) private pure {
        for (uint256 node = 2; node <= context.document.count; ++node) {
            uint256 range = context.ranges[node];
            bytes memory data = context.paths;
            if (range == 0) {
                range = context.sharedPaths[node];
                if (range == 0) continue;
                data = context.document.source;
            }
            context.output.append('<path id="tus-path-');
            context.output.appendUint(node);
            context.output.append('" d="');
            context.output.appendSlice(data, uint32(range), uint32(range >> 32));
            context.output.append('"/>');
        }
    }

    function _emit(Context memory context, uint256 node, Paint memory paint) private pure {
        uint256 flags = context.flags[node];
        if (flags & _OMIT != 0) return;
        if (paint.channel == 0 && flags == 0 && context.ranges[node] == 0) {
            _copy(context, context.document.start(node), context.document.end(node));
            return;
        }
        _emitOnce(context, node, paint, flags & _DETACH != 0);
        if (flags & _SPLIT != 0) _emitOnce(context, node, paint, true);
    }

    function _emitOnce(Context memory context, uint256 node, Paint memory paint, bool detach) private pure {
        _open(context, node, paint, detach, false);
        uint256 range = context.ranges[node];
        if (range == 0) {
            _children(context, node, paint);
            return;
        }
        if (context.mode == 0) {
            context.output.append('<path d="');
            context.output.appendSlice(context.paths, uint32(range), uint32(range >> 32));
        } else {
            context.output.append('<use href="#tus-path-');
            context.output.appendUint(node);
        }
        context.output.append('"/>');
        _copy(context, context.document.closeStart(node), context.document.end(node));
    }

    function _children(Context memory context, uint256 node, Paint memory paint) private pure {
        TusSvgDocument.Document memory document = context.document;
        uint256 cursor = document.openEnd(node);
        for (uint256 child = document.firstChild(node); child != 0; child = document.nextSibling(child)) {
            _copy(context, cursor, document.start(child));
            _emit(context, child, paint);
            cursor = document.end(child);
        }
        _copy(context, cursor, document.end(node));
    }

    function _open(Context memory context, uint256 node, Paint memory paint, bool detach, bool dropStyle) private pure {
        TusSvgDocument.Document memory document = context.document;
        uint256 end = document.openEnd(node);
        bool share = context.flags[node] & _SHARED_PATH != 0;
        bool textTint = paint.channel != 0 && document.isTag(node, "text");
        uint256 cursor = document.attributesStart(node);
        if ((!textTint && cursor + 1 == end) || (paint.channel == 0 && !detach && !dropStyle && !share)) {
            _copy(context, document.start(node), end);
            return;
        }
        if (share) {
            context.output.append('<use href="#tus-path-');
            context.output.appendUint(node);
            context.output.appendByte('"');
        } else {
            _copy(context, document.start(node), cursor);
        }
        while (true) {
            (uint256 next, uint256 key, uint256 keySize, uint256 value, uint256 size) =
                document.nextAttribute(cursor, end);
            if (keySize == 0) break;
            cursor = next;
            bytes memory source = document.source;
            bytes32 name = _key(source, key, keySize);
            if ((detach || textTint) && name == bytes32("filter")) continue;
            if (dropStyle && name == bytes32("style")) continue;
            if (share && name == bytes32("d")) continue;
            context.output.appendByte(" ");
            _copy(context, key, value);
            if (paint.channel == 0) _copy(context, value, value + size);
            else _paintAttribute(context, paint, name, value, size);
            context.output.appendByte(source[value - 1]);
        }
        if (textTint) {
            context.output.append(' filter="url(#');
            context.output.append(paint.textFilter);
            context.output.append(')"');
        }
        context.output.append(document.end(node) == end ? bytes("/>") : bytes(">"));
    }

    function _paintAttribute(Context memory context, Paint memory paint, bytes32 name, uint256 value, uint256 size)
        private
        pure
    {
        bytes memory source = context.document.source;
        if (name == bytes32("id")) {
            _copy(context, value, value + size);
            context.output.append(paint.suffix);
            return;
        }
        if (
            size == 7 && source[value] == "#"
                && (name == bytes32("fill") || name == bytes32("stroke") || name == bytes32("flood-color"))
                && _paintColor(context, paint.channel, value)
        ) return;

        if (name == bytes32("href") || name == bytes32("xlink:href")) {
            _copy(context, value, value + size);
            if (size > 1 && source[value] == "#" && _isScoped(context, value + 1, size - 1)) {
                context.output.append(paint.suffix);
            }
            return;
        }
        // These are the URL-bearing attribute names in the frozen archive.
        if (
            name == bytes32("filter") || name == bytes32("clip-path") || name == bytes32("style")
                || name == bytes32("fill") || name == bytes32("mask")
        ) {
            _paintUrls(context, paint.suffix, value, size);
            return;
        }
        _copy(context, value, value + size);
    }

    function _paintUrls(Context memory context, bytes memory suffix, uint256 start, uint256 size) private pure {
        bytes memory source = context.document.source;
        uint256 end = start + size;
        uint256 cursor = start;
        while (cursor + 6 < end) {
            if (source[cursor] != "u" || !TusSvgDocument.matches(source, cursor, "url(#")) {
                ++cursor;
                continue;
            }
            uint256 referenceStart = cursor + 5;
            cursor = referenceStart;
            while (cursor < end && source[cursor] != ")") ++cursor;
            if (cursor < end && _isScoped(context, referenceStart, cursor - referenceStart)) {
                _copy(context, start, cursor);
                context.output.append(suffix);
                start = cursor;
            }
            ++cursor;
        }
        _copy(context, start, end);
    }

    function _isScoped(Context memory context, uint256 start, uint256 size) private pure returns (bool) {
        if (size >= 6 && TusSvgDocument.matches(context.document.source, start, "glyph-")) return false;
        bytes32 id = _hash(context.document.source, start, size);
        for (uint256 index; index < context.scopedCount; ++index) {
            if (context.scopedIds[index] == id) return true;
        }
        return false;
    }

    function _paintColor(Context memory context, uint256 channel, uint256 start) private pure returns (bool) {
        bytes memory source = context.document.source;
        uint256 red = _hex(source[start + 1]) * 16 + _hex(source[start + 2]);
        uint256 green = _hex(source[start + 3]) * 16 + _hex(source[start + 4]);
        uint256 blue = _hex(source[start + 5]) * 16 + _hex(source[start + 6]);
        // 256 is the sentinel for a non-hex character.
        if (red > 255 || green > 255 || blue > 255) return false;
        if (channel == 1) {
            uint256 row = red * 5;
            red = uint8(context.colors[row]);
            green = uint8(context.colors[row + 1]);
            blue = uint8(context.colors[row + 2]);
        } else if (channel == 2) {
            uint256 row = blue * 5;
            red = 0;
            green = uint8(context.colors[row + 3]);
            blue = uint8(context.colors[row + 4]);
        } else {
            if (channel != 3) red = 0;
            if (channel != 4) green = 0;
            if (channel != 5) blue = 0;
        }
        uint256 packed = (35 << 48) | (_hexPair(red) << 32) | (_hexPair(green) << 16) | _hexPair(blue);
        bytes memory color = new bytes(7);
        assembly ("memory-safe") {
            mstore(add(color, 32), shl(200, packed))
        }
        context.output.append(color);
        return true;
    }

    function _hex(bytes1 character) private pure returns (uint256) {
        uint256 value = uint8(character);
        if (value >= 48 && value <= 57) return value - 48;
        value |= 32;
        if (value >= 97 && value <= 102) return value - 87;
        return 256;
    }

    function _hexPair(uint256 value) private pure returns (uint256) {
        return (uint256(uint8(_HEX[value >> 4])) << 8) | uint8(_HEX[value & 15]);
    }

    function _copy(Context memory context, uint256 start, uint256 end) private pure {
        if (end != start) context.output.appendSlice(context.document.source, start, end - start);
    }

    function _attributeEquals(
        TusSvgDocument.Document memory document,
        uint256 node,
        bytes memory attribute,
        bytes memory value
    ) private pure returns (bool) {
        (uint256 start, uint256 size) = document.attribute(node, attribute);
        return _equal(document.source, start, size, value);
    }

    function _equal(bytes memory source, uint256 start, uint256 size, bytes memory value) private pure returns (bool) {
        return size == value.length && TusSvgDocument.matches(source, start, value);
    }

    function _hash(bytes memory source, uint256 start, uint256 size) private pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            digest := keccak256(add(add(source, 32), start), size)
        }
    }

    function _key(bytes memory source, uint256 start, uint256 size) private pure returns (bytes32 key) {
        if (size <= 32) {
            assembly ("memory-safe") {
                key := shl(shl(3, sub(32, size)), mload(sub(add(add(add(source, 32), start), size), 32)))
            }
        }
    }

    /// @dev Fast negative check for the frozen export's id= and filter= spellings.
    /// The document parser still validates positive matches as XML attributes.
    function _mayHave(TusSvgDocument.Document memory document, uint256 node, bytes32 marker, uint256 size)
        private
        pure
        returns (bool found)
    {
        uint256 start = document.attributesStart(node);
        uint256 end = document.openEnd(node);
        bytes memory source = document.source;
        if (size > end - start) return false;
        assembly ("memory-safe") {
            function firstByte(mask) -> offset {
                if iszero(shr(128, mask)) {
                    mask := shl(128, mask)
                    offset := 16
                }
                if iszero(shr(192, mask)) {
                    mask := shl(64, mask)
                    offset := add(offset, 8)
                }
                if iszero(shr(224, mask)) {
                    mask := shl(32, mask)
                    offset := add(offset, 4)
                }
                if iszero(shr(240, mask)) {
                    mask := shl(16, mask)
                    offset := add(offset, 2)
                }
                if iszero(shr(248, mask)) { offset := add(offset, 1) }
            }

            let ones := 0x0101010101010101010101010101010101010101010101010101010101010101
            let high := 0x8080808080808080808080808080808080808080808080808080808080808080
            let mask := sub(shl(shl(3, size), 1), 1)
            let expected := shr(shl(3, sub(32, size)), marker)
            let needle := mul(byte(0, marker), ones)
            let base := add(source, 32)
            let limit := add(base, end)
            let last := sub(limit, size)
            for { let cursor := add(base, start) } iszero(gt(cursor, last)) { cursor := add(cursor, 32) } {
                let word
                let remaining := sub(limit, cursor)
                switch lt(remaining, 32)
                case 0 { word := mload(cursor) }
                default { word := shl(shl(3, sub(32, remaining)), mload(sub(limit, 32))) }
                let difference := xor(word, needle)
                let matches := and(and(sub(difference, ones), not(difference)), high)
                for {} matches {} {
                    let offset := firstByte(matches)
                    let candidate := add(cursor, offset)
                    if gt(candidate, last) { break }
                    if eq(and(mload(sub(add(candidate, size), 32)), mask), expected) {
                        found := 1
                        break
                    }
                    matches := and(matches, not(shr(shl(3, offset), shl(255, 1))))
                }
                if found { break }
            }
        }
    }
}

src/libraries/TusSvgGeometry.sol

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

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

/// @title TusSvgGeometry
/// @notice Merges eligible painted glyph groups into compact SVG path geometry.
/// @dev Bounds are for the hash-bound TUS1 artwork. Group paint and its own transform remain on the group.
/// @author berny0x
library TusSvgGeometry {
    uint256 private constant _MAX_GLYPH_ID = 511;
    uint256 private constant _MAX_SOURCE_PATH = 2_048;
    uint256 private constant _MAX_MERGED_BYTES = 131_072;
    uint256 private constant _FIELD_MASK = type(uint32).max;
    uint256 private constant _GROUP = 1 << 160;
    uint256 private constant _CANDIDATE = 1 << 161;
    int256 private constant _UNIT = 1e12;
    int256 private constant _OUTPUT_UNIT = 1e20;

    struct Matrix {
        int256 a;
        int256 b;
        int256 c;
        int256 d;
        int256 e;
        int256 f;
    }

    struct Path {
        bytes commands;
        bytes arities;
        bytes coordinates;
        uint256 commandCount;
        uint256 coordinateCount;
        uint256 relative;
    }

    struct RelativePath {
        Matrix linear;
        Path head;
        bytes suffix;
    }

    struct Scene {
        uint256[] members;
        uint256[] cache;
        bytes paths;
        uint256[] ranges;
        uint256 written;
    }

    error InvalidGeometry();
    error GeometryLimitExceeded();

    /// @notice Writes one path per eligible group and leaves all other nodes untouched.
    /// @param document The canonical original SVG document.
    /// @return paths The bounded concatenation of compact SVG paths.
    /// @return ranges Each group's offset in the low 32 bits and length in the next 32 bits.
    function merge(TusSvgDocument.Document memory document)
        internal
        pure
        returns (bytes memory paths, uint256[] memory ranges)
    {
        Scene memory scene;
        scene.members = _members(document);
        scene.cache = new uint256[](document.count + 1);
        scene.paths = new bytes(_MAX_MERGED_BYTES + 32);
        scene.ranges = new uint256[](document.count + 1);
        _visit(document, scene, 1);
        paths = scene.paths;
        ranges = scene.ranges;
        uint256 written = scene.written;
        if (written > _MAX_MERGED_BYTES) revert GeometryLimitExceeded();
        assembly ("memory-safe") {
            mstore(paths, written)
        }
    }

    function _members(TusSvgDocument.Document memory document) private pure returns (uint256[] memory members) {
        uint256[] memory atlas = new uint256[](_MAX_GLYPH_ID + 1);
        for (uint256 node = 2; node <= document.count; ++node) {
            if (_kind(document, node) != 3) continue;
            (uint256 id, uint256 length) = TusSvgDocument.attribute(document, node, "id");
            if (length < 7 || !TusSvgDocument.matches(document.source, id, "glyph-")) continue;
            (uint256 offset, uint256 size) = TusSvgDocument.attribute(document, node, "d");
            uint256 glyphId = _glyphId(document.source, id + 6, id + length);
            atlas[glyphId] = offset | (size << 32) | (node << 128);
        }

        members = new uint256[](document.count + 1);
        for (uint256 node = document.count; node > 1; --node) {
            uint256 kind = _kind(document, node);
            if (kind == 1) {
                for (
                    uint256 child = TusSvgDocument.firstChild(document, node);
                    child != 0;
                    child = TusSvgDocument.nextSibling(document, child)
                ) {
                    if (members[child] & ~_CANDIDATE == 0) {
                        kind = 0;
                        break;
                    }
                }
            }
            if (kind != 0 && kind <= 3) {
                uint256 member = _member(document, atlas, node, kind);
                members[node] = kind == 1 ? member | _CANDIDATE : member;
            }
        }
    }

    function _member(TusSvgDocument.Document memory document, uint256[] memory atlas, uint256 node, uint256 kind)
        private
        pure
        returns (uint256 member)
    {
        bytes memory source = document.source;
        uint256 cursor = TusSvgDocument.attributesStart(document, node);
        uint256 tagEnd = TusSvgDocument.openEnd(document, node);
        if (kind == 2) {
            uint256 canonical = _canonicalUse(source, cursor, tagEnd, atlas);
            if (canonical != 0) return canonical;
        }
        uint256 transform;
        uint256 href;
        uint256 xlinkHref;
        while (cursor < tagEnd) {
            (uint256 next, uint256 name, uint256 length, uint256 value, uint256 size) =
                TusSvgDocument.nextAttribute(document, cursor, tagEnd);
            if (length == 0) break;
            cursor = next;
            if (_equals(source, name, length, "transform")) {
                if (size != 0) transform = (value << 64) | (size << 96);
            } else if (_equals(source, name, length, "stroke-width") || _equals(source, name, length, "xmlns")) {
                continue;
            } else if (length > 6 && TusSvgDocument.matches(source, name, "xmlns:")) {
                continue;
            } else if (kind == 2 && _equals(source, name, length, "href")) {
                if (size != 0) href = value | (size << 32);
            } else if (kind == 2 && _equals(source, name, length, "xlink:href")) {
                if (size != 0) xlinkHref = value | (size << 32);
            } else if (kind == 3 && _equals(source, name, length, "d")) {
                member = value | (size << 32);
            } else if (kind != 3 || !_equals(source, name, length, "fill-rule")) {
                return 0;
            }
        }

        if (kind == 1) return _GROUP | transform;
        if (kind == 2) {
            if (href == 0) href = xlinkHref;
            uint256 begin = href & _FIELD_MASK;
            uint256 size = (href >> 32) & _FIELD_MASK;
            if (size < 8 || !TusSvgDocument.matches(source, begin, "#glyph-")) return 0;
            member = atlas[_glyphId(source, begin + 7, begin + size)];
        }
        if ((member >> 32) & _FIELD_MASK == 0) return 0;
        return member | transform;
    }

    function _visit(TusSvgDocument.Document memory document, Scene memory scene, uint256 node) private pure {
        for (
            uint256 child = TusSvgDocument.firstChild(document, node);
            child != 0;
            child = TusSvgDocument.nextSibling(document, child)
        ) {
            if (scene.members[child] & _CANDIDATE != 0 && TusSvgDocument.firstChild(document, child) != 0) {
                (, uint256 fillLength) = TusSvgDocument.attribute(document, child, "fill");
                if (fillLength != 0) {
                    uint256 begin = scene.written;
                    _collect(document, scene, child, Matrix(_UNIT, 0, 0, _UNIT, 0, 0));
                    if (scene.written != begin) {
                        scene.ranges[child] = begin | ((scene.written - begin) << 32);
                        continue;
                    }
                }
            }
            if (_kind(document, child) != 4) {
                _visit(document, scene, child);
            }
        }
    }

    function _collect(TusSvgDocument.Document memory document, Scene memory scene, uint256 node, Matrix memory parent)
        private
        pure
    {
        for (
            uint256 child = TusSvgDocument.firstChild(document, node);
            child != 0;
            child = TusSvgDocument.nextSibling(document, child)
        ) {
            uint256 member = scene.members[child];
            uint256 transform = (member >> 64) & _FIELD_MASK;
            Matrix memory matrix =
                transform == 0 ? parent : _transform(document.source, transform, (member >> 96) & _FIELD_MASK, parent);
            if (member & _GROUP != 0) {
                _collect(document, scene, child, matrix);
                continue;
            }
            uint256 definition = (member >> 128) & _FIELD_MASK;
            uint256[] memory cache = scene.cache;
            uint256 cached = definition == 0 ? 0 : cache[definition];
            Path memory path;
            if (cached == 0) {
                path = _readPath(document.source, member & _FIELD_MASK, (member >> 32) & _FIELD_MASK);
                if (definition != 0) {
                    assembly ("memory-safe") {
                        cached := path
                    }
                    cache[definition] = cached;
                }
            } else {
                assembly ("memory-safe") {
                    path := cached
                }
            }
            scene.written = definition == 0
                ? _appendPath(scene.paths, scene.written, path, matrix)
                : _appendAtlasPath(scene.paths, scene.written, path, matrix);
        }
    }

    function _appendAtlasPath(bytes memory output, uint256 written, Path memory path, Matrix memory matrix)
        private
        pure
        returns (uint256)
    {
        uint256 pointer = path.relative;
        RelativePath memory relative;
        if (pointer == 0) {
            relative = _relativePath(path, matrix);
            assembly ("memory-safe") {
                pointer := relative
            }
            path.relative = pointer;
        } else {
            assembly ("memory-safe") {
                relative := pointer
            }
        }
        Matrix memory linear = relative.linear;
        bytes memory suffix = relative.suffix;
        if (
            suffix.length == 0 || linear.a != matrix.a || linear.b != matrix.b || linear.c != matrix.c
                || linear.d != matrix.d || _hasTie(path, matrix)
        ) {
            return _appendPath(output, written, path, matrix);
        }

        written = _appendPath(output, written, relative.head, matrix);
        if (suffix.length + 31 > output.length - written) revert GeometryLimitExceeded();
        assembly ("memory-safe") {
            let source := add(suffix, 32)
            let destination := add(add(output, 32), written)
            let size := mload(suffix)
            for { let cursor := 0 } lt(cursor, size) { cursor := add(cursor, 32) } {
                mstore(add(destination, cursor), mload(add(source, cursor)))
            }
            written := add(written, size)
        }
        return written;
    }

    /// @dev Integral output-grid differences preserve every rounded coordinate across
    /// placements of the same glyph. An exact midpoint can round differently across zero.
    function _relativePath(Path memory path, Matrix memory matrix) private pure returns (RelativePath memory relative) {
        if (path.commandCount < 2 || path.commands[0] != "M") return relative;
        Matrix memory linear = Matrix(matrix.a, matrix.b, matrix.c, matrix.d, 0, 0);
        Path memory tail;
        tail.commandCount = path.commandCount - 1;
        tail.commands = new bytes(tail.commandCount);
        tail.arities = new bytes(tail.commandCount);
        tail.coordinates = new bytes(8 * path.coordinateCount + 32);
        (int256 x, int256 y) = _pairAt(path.coordinates, 0);
        int256 startX = x;
        int256 startY = y;
        uint256 coordinate = 2;
        for (uint256 i = 1; i < path.commandCount; ++i) {
            bytes1 command = path.commands[i];
            uint256 arity = uint8(path.arities[i]);
            tail.commands[i - 1] = bytes1(uint8(command) + 32);
            tail.arities[i - 1] = path.arities[i];
            if (command == "Z") {
                x = startX;
                y = startY;
                continue;
            }
            int256 nextX;
            int256 nextY;
            for (uint256 j = 0; j < arity; j += 2) {
                (nextX, nextY) = _pairAt(path.coordinates, coordinate);
                coordinate += 2;
                int256 dx = nextX - x;
                int256 dy = nextY - y;
                if (
                    (linear.a * dx + linear.c * dy) % _OUTPUT_UNIT != 0
                        || (linear.b * dx + linear.d * dy) % _OUTPUT_UNIT != 0
                ) return relative;
                _appendCoordinate(tail, dx);
                _appendCoordinate(tail, dy);
            }
            x = nextX;
            y = nextY;
            if (command == "M") {
                startX = x;
                startY = y;
            }
        }
        relative.linear = linear;
        relative.head = Path(path.commands, path.arities, path.coordinates, 1, 2, 0);
        relative.suffix = new bytes(tail.commandCount + 13 * tail.coordinateCount + 32);
        bytes memory suffix = relative.suffix;
        uint256 size = _appendPath(suffix, 0, tail, linear);
        assembly ("memory-safe") {
            mstore(suffix, size)
        }
    }

    function _hasTie(Path memory path, Matrix memory matrix) private pure returns (bool) {
        (int256 x, int256 y) = _pairAt(path.coordinates, 0);
        int256 scaledX = (matrix.a * x + matrix.c * y + matrix.e * _UNIT) % _OUTPUT_UNIT;
        int256 scaledY = (matrix.b * x + matrix.d * y + matrix.f * _UNIT) % _OUTPUT_UNIT;
        int256 half = _OUTPUT_UNIT / 2;
        return scaledX == half || scaledX == -half || scaledY == half || scaledY == -half;
    }

    function _pairAt(bytes memory coordinates, uint256 index) private pure returns (int256 x, int256 y) {
        assembly ("memory-safe") {
            let pointer := add(add(coordinates, 32), shl(3, index))
            x := sar(192, mload(pointer))
            y := sar(192, mload(add(pointer, 8)))
        }
    }

    function _readPath(bytes memory source, uint256 cursor, uint256 size) private pure returns (Path memory path) {
        if (size > _MAX_SOURCE_PATH) revert GeometryLimitExceeded();
        path.commands = new bytes(size);
        path.arities = new bytes(size);
        path.coordinates = new bytes(8 * (size + 2) + 24);
        uint256 end = cursor + size;
        bytes1 command;
        int256 x;
        int256 y;
        while (cursor < end) {
            cursor = _skip(source, cursor, end);
            if (cursor == end) break;
            bytes1 character = source[cursor];
            if (character >= "A" && character <= "Z") {
                command = character;
                ++cursor;
            }

            bytes1 outputCommand = command;
            uint256 arity;
            if (command == "M" || command == "L") {
                arity = 2;
            } else if (command == "H" || command == "V") {
                arity = 2;
                outputCommand = "L";
            } else if (command == "C") {
                arity = 6;
            } else if (command == "Q") {
                arity = 4;
            } else if (command == "Z" && character == "Z") {
                path.commands[path.commandCount++] = command;
                continue;
            } else {
                revert InvalidGeometry();
            }

            if (path.coordinateCount + arity > size + 2) revert GeometryLimitExceeded();
            path.commands[path.commandCount] = outputCommand;
            path.arities[path.commandCount++] = bytes1(uint8(arity));
            if (command == "H" || command == "V") {
                if (command == "H") (x, cursor) = _number(source, cursor, end);
                else (y, cursor) = _number(source, cursor, end);
                _appendCoordinate(path, x);
                _appendCoordinate(path, y);
            } else {
                for (uint256 i = 0; i < arity; i += 2) {
                    (x, cursor) = _number(source, cursor, end);
                    (y, cursor) = _number(source, cursor, end);
                    _appendCoordinate(path, x);
                    _appendCoordinate(path, y);
                }
            }
            if (command == "M") command = "L";
        }
    }

    function _appendCoordinate(Path memory path, int256 value) private pure {
        bytes memory coordinates = path.coordinates;
        uint256 index = path.coordinateCount++;
        assembly ("memory-safe") {
            mstore(add(add(coordinates, 32), shl(3, index)), shl(192, value))
        }
    }

    function _appendPath(bytes memory output, uint256 written, Path memory path, Matrix memory matrix)
        private
        pure
        returns (uint256 endOffset)
    {
        // Each coordinate is bounded to six integer digits, a sign, a decimal and four fractional digits.
        if (path.commandCount + 13 * path.coordinateCount > output.length - written) revert GeometryLimitExceeded();
        bytes memory commands = path.commands;
        bytes memory arities = path.arities;
        bytes memory coordinates = path.coordinates;
        uint256 count = path.commandCount;
        bytes4 errorSelector = GeometryLimitExceeded.selector;
        assembly ("memory-safe") {
            function writeNumber(cursor, value, selector) -> next {
                let negative := slt(value, 0)
                if negative { value := sub(0, value) }
                // Matrix and input coordinates each have 12 decimals. Round to four.
                value := div(add(value, 50000000000000000000), 100000000000000000000)
                if iszero(lt(value, 10000000000)) {
                    mstore(0, selector)
                    revert(0, 4)
                }
                if and(negative, iszero(iszero(value))) {
                    mstore8(cursor, 45)
                    cursor := add(cursor, 1)
                }
                let integer := div(value, 10000)
                if iszero(lt(integer, 10)) {
                    let divisor := 10
                    for {} iszero(lt(integer, mul(divisor, 10))) {} { divisor := mul(divisor, 10) }
                    for {} gt(divisor, 1) { divisor := div(divisor, 10) } {
                        mstore8(cursor, add(48, div(integer, divisor)))
                        cursor := add(cursor, 1)
                        integer := mod(integer, divisor)
                    }
                }
                mstore8(cursor, add(48, integer))
                cursor := add(cursor, 1)
                let fraction := mod(value, 10000)
                if fraction {
                    mstore8(cursor, 46)
                    cursor := add(cursor, 1)
                    for { let divisor := 1000 } fraction { divisor := div(divisor, 10) } {
                        mstore8(cursor, add(48, div(fraction, divisor)))
                        cursor := add(cursor, 1)
                        fraction := mod(fraction, divisor)
                    }
                }
                next := cursor
            }

            let start := add(output, 32)
            let destination := add(start, written)
            let coordinate := add(coordinates, 32)
            let a := mload(matrix)
            let b := mload(add(matrix, 32))
            let c := mload(add(matrix, 64))
            let d := mload(add(matrix, 96))
            let e := mul(mload(add(matrix, 128)), 1000000000000)
            let f := mul(mload(add(matrix, 160)), 1000000000000)
            for { let index := 0 } lt(index, count) { index := add(index, 1) } {
                mstore8(destination, mload(add(add(commands, 1), index)))
                destination := add(destination, 1)
                let arity := and(mload(add(add(arities, 1), index)), 0xff)
                let commandEnd := add(coordinate, shl(3, arity))
                for {} lt(coordinate, commandEnd) {} {
                    let x := sar(192, mload(coordinate))
                    let y := sar(192, mload(add(coordinate, 8)))
                    destination := writeNumber(destination, add(add(mul(a, x), mul(c, y)), e), errorSelector)
                    mstore8(destination, 32)
                    destination := writeNumber(add(destination, 1), add(add(mul(b, x), mul(d, y)), f), errorSelector)
                    coordinate := add(coordinate, 16)
                    if lt(coordinate, commandEnd) {
                        mstore8(destination, 32)
                        destination := add(destination, 1)
                    }
                }
            }
            endOffset := sub(destination, start)
        }
    }

    function _transform(bytes memory source, uint256 cursor, uint256 size, Matrix memory parent)
        private
        pure
        returns (Matrix memory result)
    {
        result = Matrix(parent.a, parent.b, parent.c, parent.d, parent.e, parent.f);
        uint256 end = cursor + size;
        if (_canonicalTransform(source, cursor, end, result)) return result;
        while (cursor < end) {
            cursor = _skip(source, cursor, end);
            if (cursor == end) break;
            if (end - cursor >= 10 && TusSvgDocument.matches(source, cursor, "translate(")) {
                int256 x;
                int256 y;
                (x, cursor) = _number(source, cursor + 10, end);
                cursor = _skip(source, cursor, end);
                if (cursor < end && source[cursor] != ")") (y, cursor) = _number(source, cursor, end);
                result.e += (result.a * x + result.c * y) / _UNIT;
                result.f += (result.b * x + result.d * y) / _UNIT;
            } else if (end - cursor >= 6 && TusSvgDocument.matches(source, cursor, "scale(")) {
                int256 x;
                int256 y;
                (x, cursor) = _number(source, cursor + 6, end);
                cursor = _skip(source, cursor, end);
                y = x;
                if (cursor < end && source[cursor] != ")") (y, cursor) = _number(source, cursor, end);
                result.a = result.a * x / _UNIT;
                result.b = result.b * x / _UNIT;
                result.c = result.c * y / _UNIT;
                result.d = result.d * y / _UNIT;
            } else if (end - cursor >= 7 && TusSvgDocument.matches(source, cursor, "matrix(")) {
                Matrix memory value;
                (value.a, cursor) = _number(source, cursor + 7, end);
                (value.b, cursor) = _number(source, cursor, end);
                (value.c, cursor) = _number(source, cursor, end);
                (value.d, cursor) = _number(source, cursor, end);
                (value.e, cursor) = _number(source, cursor, end);
                (value.f, cursor) = _number(source, cursor, end);
                result = _multiply(result, value);
            } else {
                revert InvalidGeometry();
            }
            cursor = _skip(source, cursor, end);
            if (cursor == end || source[cursor++] != ")") revert InvalidGeometry();
        }
    }

    /// @dev The archive serializes glyph placements with nine translation and
    /// twelve scale decimals. Parse these digit lanes in parallel, with a generic
    /// transform fallback for other valid forms.
    function _canonicalTransform(bytes memory source, uint256 cursor, uint256 end, Matrix memory matrix)
        private
        pure
        returns (bool recognized)
    {
        if (end - cursor < 62) return false;
        int256 x;
        int256 y;
        int256 scaleX;
        int256 scaleY;
        assembly ("memory-safe") {
            function at(pointer) -> character {
                character := and(mload(sub(pointer, 31)), 0xff)
            }

            function scalar(pointer, limit, width) -> value, next, ok {
                if gt(add(pointer, add(width, 2)), limit) { leave }
                let negative := eq(at(pointer), 45)
                pointer := add(pointer, negative)
                let whole := 0
                let first := pointer
                for {} lt(pointer, limit) { pointer := add(pointer, 1) } {
                    let digit := sub(at(pointer), 48)
                    if iszero(lt(digit, 10)) { break }
                    whole := add(mul(whole, 10), digit)
                    if gt(whole, 1000000) { leave }
                }
                if or(eq(first, pointer), iszero(lt(pointer, limit))) { leave }
                if iszero(eq(at(pointer), 46)) { leave }
                next := add(add(pointer, 1), width)
                if gt(next, limit) { leave }

                let mask := sub(shl(shl(3, width), 1), 1)
                let ascii := or(and(mload(sub(next, 32)), mask), and(0x30303030303030303030303030303030, not(mask)))
                if iszero(eq(and(ascii, 0xf0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0), 0x30303030303030303030303030303030)) {
                    leave
                }
                let digits := and(ascii, 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f)
                if and(add(digits, 0x06060606060606060606060606060606), 0x10101010101010101010101010101010) {
                    leave
                }
                digits := add(
                    mul(shr(8, and(digits, 0xff00ff00ff00ff00ff00ff00ff00ff00)), 10),
                    and(digits, 0x00ff00ff00ff00ff00ff00ff00ff00ff)
                )
                digits := add(
                    mul(shr(16, and(digits, 0xffff0000ffff0000ffff0000ffff0000)), 100),
                    and(digits, 0x0000ffff0000ffff0000ffff0000ffff)
                )
                digits := add(
                    mul(shr(32, and(digits, 0xffffffff00000000ffffffff00000000)), 10000),
                    and(digits, 0x00000000ffffffff00000000ffffffff)
                )
                digits := add(mul(shr(64, digits), 100000000), and(digits, 0xffffffffffffffff))
                value := add(mul(whole, 1000000000000), mul(digits, exp(10, sub(12, width))))
                if negative { value := sub(0, value) }
                ok := 1
            }

            function placement(pointer, limit) -> tx, ty, sx, sy, ok {
                if iszero(eq(and(mload(sub(pointer, 22)), 0xffffffffffffffffffff), 0x7472616e736c61746528)) { leave }
                let position := 0
                let valid := 0
                tx, position, valid := scalar(add(pointer, 10), limit, 9)
                if or(iszero(valid), iszero(lt(position, limit))) { leave }
                if iszero(eq(at(position), 32)) { leave }
                ty, position, valid := scalar(add(position, 1), limit, 9)
                if or(iszero(valid), gt(add(position, 8), limit)) { leave }
                if iszero(eq(and(mload(sub(position, 24)), 0xffffffffffffffff), 0x29207363616c6528)) {
                    leave
                }
                sx, position, valid := scalar(add(position, 8), limit, 12)
                if or(iszero(valid), iszero(lt(position, limit))) { leave }
                if iszero(eq(at(position), 32)) { leave }
                sy, position, valid := scalar(add(position, 1), limit, 12)
                if or(iszero(valid), iszero(eq(add(position, 1), limit))) { leave }
                ok := eq(at(position), 41)
            }

            let base := add(source, 32)
            x, y, scaleX, scaleY, recognized := placement(add(base, cursor), add(base, end))
        }
        if (!recognized) return false;
        if (matrix.a == _UNIT && matrix.d == _UNIT && matrix.b == 0 && matrix.c == 0) {
            matrix.e += x;
            matrix.f += y;
            matrix.a = scaleX;
            matrix.d = scaleY;
        } else {
            matrix.e += (matrix.a * x + matrix.c * y) / _UNIT;
            matrix.f += (matrix.b * x + matrix.d * y) / _UNIT;
            matrix.a = matrix.a * scaleX / _UNIT;
            matrix.b = matrix.b * scaleX / _UNIT;
            matrix.c = matrix.c * scaleY / _UNIT;
            matrix.d = matrix.d * scaleY / _UNIT;
        }
    }

    function _multiply(Matrix memory x, Matrix memory y) private pure returns (Matrix memory) {
        return Matrix(
            (x.a * y.a + x.c * y.b) / _UNIT,
            (x.b * y.a + x.d * y.b) / _UNIT,
            (x.a * y.c + x.c * y.d) / _UNIT,
            (x.b * y.c + x.d * y.d) / _UNIT,
            (x.a * y.e + x.c * y.f) / _UNIT + x.e,
            (x.b * y.e + x.d * y.f) / _UNIT + x.f
        );
    }

    function _skip(bytes memory source, uint256 cursor, uint256 end) private pure returns (uint256 next) {
        assembly ("memory-safe") {
            let base := add(source, 32)
            let position := add(base, cursor)
            let limit := add(base, end)
            for {} lt(position, limit) { position := add(position, 1) } {
                let character := and(mload(sub(position, 31)), 0xff)
                if iszero(or(or(eq(character, 32), eq(character, 44)), lt(sub(character, 9), 5))) { break }
            }
            next := sub(position, base)
        }
    }

    function _number(bytes memory source, uint256 cursor, uint256 end)
        private
        pure
        returns (int256 value, uint256 next)
    {
        cursor = _skip(source, cursor, end);
        bytes4 errorSelector = InvalidGeometry.selector;
        assembly ("memory-safe") {
            function characterAt(pointer, limit) -> character {
                if lt(pointer, limit) { character := and(mload(sub(pointer, 31)), 0xff) }
            }
            function fail(selector) {
                mstore(0, selector)
                revert(0, 4)
            }

            let base := add(source, 32)
            let limit := add(base, end)
            let position := add(base, cursor)
            let character := characterAt(position, limit)
            let negative := eq(character, 45)
            if or(negative, eq(character, 43)) {
                position := add(position, 1)
                character := characterAt(position, limit)
            }
            let digits := 0
            for {} lt(sub(character, 48), 10) {} {
                digits := add(digits, 1)
                value := add(mul(value, 10), sub(character, 48))
                if gt(value, 1000000) { fail(errorSelector) }
                position := add(position, 1)
                character := characterAt(position, limit)
            }
            value := mul(value, 1000000000000)
            if eq(character, 46) {
                position := add(position, 1)
                character := characterAt(position, limit)
                for { let place := 1000000000000 } lt(sub(character, 48), 10) {} {
                    digits := add(digits, 1)
                    place := div(place, 10)
                    value := add(value, mul(sub(character, 48), place))
                    position := add(position, 1)
                    character := characterAt(position, limit)
                }
            }
            if iszero(digits) { fail(errorSelector) }
            if or(eq(character, 101), eq(character, 69)) {
                position := add(position, 1)
                character := characterAt(position, limit)
                let negativeExponent := eq(character, 45)
                if or(negativeExponent, eq(character, 43)) {
                    position := add(position, 1)
                    character := characterAt(position, limit)
                }
                let exponent := 0
                let exponentStart := position
                for {} lt(sub(character, 48), 10) {} {
                    exponent := add(mul(exponent, 10), sub(character, 48))
                    if gt(exponent, 18) { fail(errorSelector) }
                    position := add(position, 1)
                    character := characterAt(position, limit)
                }
                if eq(exponentStart, position) { fail(errorSelector) }
                switch negativeExponent
                case 0 { value := mul(value, exp(10, exponent)) }
                default { value := div(value, exp(10, exponent)) }
            }
            if gt(value, 1000000000000000000) { fail(errorSelector) }
            if negative { value := sub(0, value) }
            next := sub(position, base)
        }
    }

    function _glyphId(bytes memory source, uint256 begin, uint256 end) private pure returns (uint256 id) {
        if (begin == end || end - begin > 3) revert InvalidGeometry();
        for (; begin < end; ++begin) {
            uint256 digit = uint8(source[begin]);
            if (digit < 48 || digit > 57) revert InvalidGeometry();
            id = id * 10 + digit - 48;
        }
        if (id > _MAX_GLYPH_ID) revert InvalidGeometry();
    }

    function _kind(TusSvgDocument.Document memory document, uint256 node) private pure returns (uint256 kind) {
        uint256 first = TusSvgDocument.start(document, node) + 1;
        uint256 end = TusSvgDocument.attributesStart(document, node);
        uint256 length = end - first;
        if (length > 8) return 0;
        bytes memory source = document.source;
        assembly ("memory-safe") {
            let name := and(mload(add(source, end)), sub(shl(shl(3, length), 1), 1))
            switch name
            case 0x67 { kind := 1 }
            case 0x757365 { kind := 2 }
            case 0x70617468 { kind := 3 }
            case 0x66696c746572 { kind := 4 }
            case 0x636c697050617468 { kind := 4 }
            case 0x7374796c65 { kind := 4 }
        }
    }

    /// @dev Fast path for the archive's common href, stroke width, transform ordering.
    ///      Other valid attribute orders use the general scanner.
    function _canonicalUse(bytes memory source, uint256 cursor, uint256 end, uint256[] memory atlas)
        private
        pure
        returns (uint256 member)
    {
        if (end - cursor < 51 || !TusSvgDocument.matches(source, cursor, ' href="#glyph-')) return 0;
        uint256 begin = cursor + 14;
        cursor = _findQuote(source, begin, begin + 4);
        if (cursor == begin + 4 || !TusSvgDocument.matches(source, cursor, '" stroke-width="')) return 0;
        uint256 glyph = atlas[_glyphId(source, begin, cursor)];
        if (glyph == 0) return 0;
        begin = cursor + 16;
        uint256 limit = begin + 24;
        if (limit > end) limit = end;
        cursor = _findQuote(source, begin, limit);
        if (cursor + 13 >= end || !TusSvgDocument.matches(source, cursor, '" transform="')) return 0;
        begin = cursor + 13;
        uint256 close = end - 4;
        if (!TusSvgDocument.matches(source, close, '" />') || begin >= close) return 0;
        if (_findQuote(source, begin, close) != close) return 0;
        return glyph | (begin << 64) | ((close - begin) << 96);
    }

    function _findQuote(bytes memory source, uint256 first, uint256 limit) private pure returns (uint256 position) {
        assembly ("memory-safe") {
            let base := add(source, 32)
            let ones := 0x0101010101010101010101010101010101010101010101010101010101010101
            let high := shl(7, ones)
            let quotes := mul(34, ones)
            position := first
            for {} iszero(gt(add(position, 32), limit)) {} {
                let word := xor(mload(add(base, position)), quotes)
                if and(and(sub(word, ones), not(word)), high) { break }
                position := add(position, 32)
            }
            for {} lt(position, limit) { position := add(position, 1) } {
                if eq(and(mload(add(source, add(position, 1))), 0xff), 34) { break }
            }
        }
    }

    function _equals(bytes memory source, uint256 offset, uint256 length, bytes memory value)
        private
        pure
        returns (bool)
    {
        return length == value.length && TusSvgDocument.matches(source, offset, value);
    }
}

src/libraries/TusSvgOutput.sol

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

/// @title TusSvgOutput
/// @notice Writes a bounded SVG without repeatedly allocating concatenated strings.
/// @author berny0x
library TusSvgOutput {
    struct Buffer {
        bytes data;
        uint256 length;
    }

    error OutputTooLarge();
    error InvalidSlice();

    /// @notice Reserves a logical output capacity and padding for partial word copies.
    function allocate(uint256 capacity) internal pure returns (Buffer memory buffer) {
        buffer.data = new bytes(capacity + 32);
    }

    /// @notice Copies a complete fragment at the current cursor.
    function append(Buffer memory buffer, bytes memory value) internal pure {
        appendSlice(buffer, value, 0, value.length);
    }

    /// @notice Copies part of a source fragment at the current cursor.
    function appendSlice(Buffer memory buffer, bytes memory source, uint256 start, uint256 length) internal pure {
        if (length > buffer.data.length - 32 - buffer.length) revert OutputTooLarge();
        if (start > source.length || length > source.length - start) revert InvalidSlice();
        bytes memory data = buffer.data;
        uint256 offset = buffer.length;
        assembly ("memory-safe") {
            let input := add(add(source, 32), start)
            let output := add(add(data, 32), offset)
            let fullLength := and(length, not(31))
            for { let cursor := 0 } lt(cursor, fullLength) { cursor := add(cursor, 32) } {
                mstore(add(output, cursor), mload(add(input, cursor)))
            }
            let tail := and(length, 31)
            if tail {
                let word := mload(sub(add(input, length), 32))
                mstore(add(output, fullLength), shl(shl(3, sub(32, tail)), word))
            }
        }
        buffer.length += length;
    }

    /// @notice Appends one byte.
    function appendByte(Buffer memory buffer, bytes1 value) internal pure {
        if (buffer.length == buffer.data.length - 32) revert OutputTooLarge();
        buffer.data[buffer.length++] = value;
    }

    /// @notice Writes an unsigned decimal integer without allocating a temporary string.
    function appendUint(Buffer memory buffer, uint256 value) internal pure {
        uint256 digits = 1;
        for (uint256 remaining = value; remaining >= 10; remaining /= 10) {
            ++digits;
        }
        if (digits > buffer.data.length - 32 - buffer.length) revert OutputTooLarge();
        bytes memory data = buffer.data;
        buffer.length += digits;
        uint256 end = buffer.length;
        assembly ("memory-safe") {
            let cursor := add(add(data, 32), end)
            let start := sub(cursor, digits)
            for {} gt(cursor, start) {} {
                cursor := sub(cursor, 1)
                mstore8(cursor, add(48, mod(value, 10)))
                value := div(value, 10)
            }
        }
    }

    /// @notice Returns the populated bytes and consumes the buffer.
    function finish(Buffer memory buffer) internal pure returns (bytes memory output) {
        output = buffer.data;
        uint256 length = buffer.length;
        assembly ("memory-safe") {
            mstore(output, length)
            mstore(add(add(output, 32), length), 0)
        }
    }
}

src/renderers/UsualSuspectsRenderer.sol

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

import {IUsualSuspectsData} from "../interfaces/IUsualSuspectsData.sol";
import {IUsualSuspectsRenderer} from "../interfaces/IUsualSuspectsRenderer.sol";
import {TusBinaryReader} from "../libraries/TusBinaryReader.sol";
import {TusFragmentDecoder} from "../libraries/TusFragmentDecoder.sol";
import {TusCatalog} from "../libraries/TusCatalog.sol";
import {TusSvgAssembler} from "../libraries/TusSvgAssembler.sol";
import {TusMetadata} from "../libraries/TusMetadata.sol";

/// @title UsualSuspectsRenderer
/// @notice Renders immutable TUS1 artwork as complete onchain SVG and uniform twelve-trait JSON.
/// @dev Allocation, token existence and reveal authorization belong to the calling NFT.
/// Compatible immutable replacements may change rendering code while retaining the archive identity.
/// @author berny0x
contract UsualSuspectsRenderer is IUsualSuspectsRenderer {
    IUsualSuspectsData internal immutable _data;
    bytes32 private immutable _dataHash;
    uint256 internal immutable _layout;

    error InvalidCollectionData();

    /// @notice Pins an immutable archive and validates its format headers and catalog references.
    /// @dev The data implementation must guarantee immutable bytes matching its advertised SHA-256.
    /// @param data The immutable TUS1 bytecode-shard reader.
    constructor(IUsualSuspectsData data) {
        if (address(data).code.length == 0) revert InvalidCollectionData();
        uint256 length = data.dataLength();
        bytes32 commitment = data.dataHash();
        if (length < 40 || length > 2_000_000 || commitment == bytes32(0)) revert InvalidCollectionData();
        bytes memory header = data.read(0, 40);
        if (
            TusBinaryReader.readBytes4(header, 0) != bytes4("TUS1") || TusBinaryReader.readUint16(header, 4) != 1
                || TusBinaryReader.readUint16(header, 6) != 0
        ) revert InvalidCollectionData();
        uint256 layout;
        uint256 cursor = 40;
        for (uint256 index; index < 4; ++index) {
            uint256 offset = TusBinaryReader.readUint32(header, 8 + index * 8);
            uint256 sectionLength = TusBinaryReader.readUint32(header, 12 + index * 8);
            if (offset != cursor || sectionLength == 0 || sectionLength > length - cursor) {
                revert InvalidCollectionData();
            }
            layout |= offset << ((7 - index * 2) * 32);
            layout |= sectionLength << ((6 - index * 2) * 32);
            cursor += sectionLength;
        }
        if (cursor != length) revert InvalidCollectionData();
        (uint256 fragmentOffset, uint256 fragmentLength) = TusCatalog.section(layout, 0);
        TusFragmentDecoder.Context memory fragments = TusFragmentDecoder.open(data, fragmentOffset, fragmentLength);
        TusFragmentDecoder.validate(fragments);
        TusCatalog.validate(TusCatalog.open(data, layout), fragments.fragmentCount);
        _data = data;
        _dataHash = commitment;
        _layout = layout;
    }

    /// @inheritdoc IUsualSuspectsRenderer
    function sourceFormat() external pure override returns (bytes4) {
        return bytes4("TUS1");
    }

    /// @inheritdoc IUsualSuspectsRenderer
    function collectionData() external view override returns (address) {
        return address(_data);
    }

    /// @inheritdoc IUsualSuspectsRenderer
    function dataHash() external view override returns (bytes32) {
        return _dataHash;
    }

    /// @inheritdoc IUsualSuspectsRenderer
    function renderSvg(uint256 artworkId) external view virtual override returns (string memory) {
        (TusCatalog.Context memory catalog, TusFragmentDecoder.Context memory fragments) = _open();
        TusCatalog.Selection memory selected = TusCatalog.select(catalog, artworkId);
        return string(TusSvgAssembler.assemble(catalog, selected, fragments));
    }

    /// @inheritdoc IUsualSuspectsRenderer
    function tokenURI(uint256 tokenId, uint256 artworkId, bool revealed)
        external
        view
        virtual
        override
        returns (string memory)
    {
        if (revealed && artworkId == 0) revert TusCatalog.InvalidPreset();
        bytes memory svg = new bytes(TusSvgAssembler.MAX_SVG_BYTES);
        bytes memory attributesJson = new bytes(TusMetadata.MAX_ATTRIBUTES_BYTES);
        uint256 scratch;
        assembly ("memory-safe") {
            scratch := mload(0x40)
        }
        (TusCatalog.Context memory catalog, TusFragmentDecoder.Context memory fragments) = _open();
        TusCatalog.Selection memory selected = TusCatalog.select(catalog, revealed ? artworkId : 0);
        bytes memory expandedSvg = TusSvgAssembler.assemble(catalog, selected, fragments);
        bytes memory expandedAttributes = TusMetadata.attributes(catalog, selected, fragments);
        TusBinaryReader.copy(expandedSvg, 0, svg, 0, expandedSvg.length);
        TusBinaryReader.copy(expandedAttributes, 0, attributesJson, 0, expandedAttributes.length);
        // Only these two reserved byte buffers survive into Base64/JSON encoding.
        // They precede scratch, contain copies rather than references, and their
        // lengths are bounded by the assembler and attribute serializer. Catalog,
        // selection, dictionary caches, programs and expanded fragments are never
        // read after this rewind. Keep this boundary before all decoder allocations.
        assembly ("memory-safe") {
            mstore(svg, mload(expandedSvg))
            mstore(attributesJson, mload(expandedAttributes))
            mstore(0x40, scratch)
        }
        return TusMetadata.tokenURI(tokenId, svg, attributesJson, revealed);
    }

    function _open()
        internal
        view
        returns (TusCatalog.Context memory catalog, TusFragmentDecoder.Context memory fragments)
    {
        catalog = TusCatalog.open(_data, _layout);
        (uint256 fragmentOffset, uint256 fragmentLength) = TusCatalog.section(_layout, 0);
        fragments = TusFragmentDecoder.open(_data, fragmentOffset, fragmentLength);
    }
}

src/renderers/UsualSuspectsSvgEffects.sol

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

import {TusSvgDocument} from "../libraries/TusSvgDocument.sol";
import {TusSvgEffects} from "../libraries/TusSvgEffects.sol";

/// @title UsualSuspectsSvgEffects
/// @notice Composes the corrected SVG layers and effects from transient scene data.
/// @author berny0x
contract UsualSuspectsSvgEffects {
    /// @notice Composes a previously parsed and merged scene.
    /// @param document The parsed original SVG.
    /// @param paths The merged geometry derived from the original glyphs.
    /// @param ranges Each merged group's byte range in paths.
    /// @return The complete SVG with corrected effects and animations.
    function render(TusSvgDocument.Document calldata document, bytes calldata paths, uint256[] calldata ranges)
        external
        pure
        returns (bytes memory)
    {
        return TusSvgEffects.render(document, paths, ranges);
    }
}

src/renderers/UsualSuspectsSvgTransform.sol

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

import {TusSvgDocument} from "../libraries/TusSvgDocument.sol";
import {TusSvgGeometry} from "../libraries/TusSvgGeometry.sol";
import {UsualSuspectsSvgEffects} from "./UsualSuspectsSvgEffects.sol";

/// @title UsualSuspectsSvgTransform
/// @notice Applies the collection's browser compatibility updates to original SVG bytes.
/// @author berny0x
contract UsualSuspectsSvgTransform {
    /// @notice Immutable code that composes the effects using the merged geometry.
    UsualSuspectsSvgEffects public immutable svgEffects;

    error InvalidSvgEffects();

    /// @notice Binds the collection's SVG effects code.
    /// @param effects The effect and composition helper.
    constructor(UsualSuspectsSvgEffects effects) {
        if (address(effects).code.length == 0) revert InvalidSvgEffects();
        svgEffects = effects;
    }

    /// @notice Builds a self-contained SVG from the original scene.
    /// @param originalSvg SVG assembled from the canonical archive.
    /// @return The corrected SVG with shared merged geometry.
    function transform(bytes calldata originalSvg) external view returns (bytes memory) {
        TusSvgDocument.Document memory document = TusSvgDocument.parseFrozen(originalSvg);
        (bytes memory paths, uint256[] memory ranges) = TusSvgGeometry.merge(document);
        return svgEffects.render(document, paths, ranges);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": [
    "seadrop/=lib/seadrop/src/",
    "ERC721A/=lib/seadrop/lib/ERC721A/contracts/",
    "openzeppelin-contracts/=lib/seadrop/lib/openzeppelin-contracts/contracts/",
    "solmate/=lib/seadrop/lib/solmate/src/",
    "utility-contracts/=lib/seadrop/lib/utility-contracts/src/",
    "forge-std/=lib/seadrop/lib/forge-std/src/",
    "ds-test/=lib/seadrop/lib/ds-test/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.