Skip to content
Verified contractPartialMIT

PanoramaRendererV7

Address0x45585e33df15489d8fccef44a0afc5ad6cd12f1f
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
prague
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,480,588
Creation transaction
0x759702f96c…da5e56dc01
Libraries
src/PanoramaRendererV7.sol:PanoramaRendererV7Html0xb42b…e332e2

src/PanoramaRendererV7.sol

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

import { Base64 } from "solady/utils/Base64.sol";
import { LibString } from "solady/utils/LibString.sol";
import { DynamicBufferLib } from "solady/utils/DynamicBufferLib.sol";
import { IPanorama } from "./interfaces/IPanorama.sol";
import { IPanoramaStorage } from "./interfaces/IPanoramaStorage.sol";
import { IPanoramaSeason4Storage } from "./interfaces/IPanoramaSeason4Storage.sol";
import { IPanoramaSeason4SceneRenderer } from "./interfaces/IPanoramaSeason4SceneRenderer.sol";
import { IPanoramaSeason4Music } from "./interfaces/IPanoramaSeason4Music.sol";
import { Base64InPlace } from "./utils/Base64InPlace.sol";
import { PanoramaRendererV6 } from "./PanoramaRendererV6.sol";

/// @title PanoramaRendererV7
/// @author Yigit Duman (@yigitduman)
/// @notice PanoramaRendererV6 with the scene renderer's code read from
///         PanoramaSeason4SceneRenderer, which keeps the gzip as it is, in fragments stored once
///         each: a new scene renderer costs what its new bytes cost. The template stays in
///         PanoramaSeason4Storage. The pages are built by PanoramaRendererV7Html, this renderer's
///         own linked library, which encodes the code where it lands. Every answer is V6's for the
///         same gzip, byte for byte.
contract PanoramaRendererV7 is PanoramaRendererV6 {
    using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;

    /// @notice PanoramaSeason4SceneRenderer: the scene renderer's code. Unset or without code,
    ///         every Season 4 token shows its video.
    address public season4SceneRenderer;

    constructor(
        address _panorama,
        string memory _prerevealBaseUrl,
        string memory _prerevealVideoBaseUrl
    ) PanoramaRendererV6(_panorama, _prerevealBaseUrl, _prerevealVideoBaseUrl) { }

    function setSeason4SceneRenderer(address _season4SceneRenderer) external onlyOwner {
        season4SceneRenderer = _season4SceneRenderer;
    }

    /// @dev V5's, to this renderer's own library.
    function _returnFromHtml(bytes memory data) internal view override {
        address html = address(PanoramaRendererV7Html);
        assembly ("memory-safe") {
            let ok := staticcall(gas(), html, add(data, 0x20), mload(data), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if iszero(ok) { revert(0, returndatasize()) }
            return(0, returndatasize())
        }
    }

    /// @dev V5's, read through this renderer's own library.
    function _appendSeason4Traits(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal view override {
        if (!_isSeason4(tokenId) || season4Storage.code.length == 0) return;
        (bool ok, bytes memory ret) = address(PanoramaRendererV7Html).staticcall{ gas: 8_000_000 }(
            abi.encodeWithSelector(PanoramaRendererV7Html.season4Traits.selector, season4Storage, tokenId)
        );
        if (ok) buf.p(abi.decode(ret, (bytes)));
    }

    /// @dev V5's, with the scene renderer asked of PanoramaSeason4SceneRenderer.
    function _showsDynamicScene(uint256 tokenId) internal view override returns (bool) {
        address s4 = season4Storage;
        if (!_isSeason4(tokenId) || s4.code.length == 0) return false;
        try IPanoramaSeason4Storage(s4).viewOf(tokenId) returns (IPanoramaSeason4Storage.View v) {
            if (v != IPanoramaSeason4Storage.View.DynamicScene) return false;
        } catch {
            return false;
        }
        return _hasSceneRenderer();
    }

    /// @dev V5's, with the scene renderer asked of PanoramaSeason4SceneRenderer.
    function _isOnChain(IPanoramaStorage store, uint256 tokenId) internal view override returns (bool) {
        if (!_isSeason4(tokenId)) return store.isFullyUploaded(tokenId);
        address s4 = season4Storage;
        if (s4.code.length == 0) return false;
        try IPanoramaSeason4Storage(s4).isDayDataFullyUploaded(tokenId) returns (bool uploaded) {
            return uploaded && _hasSceneRenderer();
        } catch {
            return false;
        }
    }

    /// @dev Whether a dynamic scene can be built: the store names this renderer's
    ///      PanoramaSeason4Storage (the page's template is read from it) and holds a scene
    ///      renderer. Anything missing or failing means none. Read by hand: this renderer is
    ///      close to the contract size limit, and two try blocks take 164 bytes more.
    function _hasSceneRenderer() internal view returns (bool has) {
        address code = season4SceneRenderer;
        address s4 = season4Storage;
        assembly ("memory-safe") {
            mstore(0x00, 0xf8a18de0) // season4Storage()
            if and(gt(returndatasize(), 0x1f), staticcall(gas(), code, 0x1c, 0x04, 0x00, 0x20)) {
                if eq(mload(0x00), s4) {
                    mstore(0x00, 0x2a4086b1) // hasSceneRenderer()
                    if and(gt(returndatasize(), 0x1f), staticcall(gas(), code, 0x1c, 0x04, 0x00, 0x20)) {
                        has := eq(mload(0x00), 1)
                    }
                }
            }
        }
    }
}

/// @title PanoramaRendererV7Html
/// @author Yigit Duman (@yigitduman)
/// @notice The large answers of PanoramaRendererV7: a token whose still is on-chain, a Season 4
///         token's dynamic scene, and the whole-artwork page. Linked into the renderer and called
///         by it alone; it holds no state.
///
///         These are data URIs inside data URIs: JSON in base64, holding a still in base64, or an
///         HTML page in base64 holding gzipped code and day data in base64. Built by joining
///         strings, a megabyte is copied several times, and memory costs with the square of its
///         size (a 1.27 MB still came to about a billion gas). So they are written once, into one
///         buffer of their final size: each piece is encoded where it lands (Base64InPlace),
///         padded with spaces so that its base64 joins the next piece's. The spaces fall where
///         the page ignores them (JSON and HTML whitespace, or base64 text, which `atob` reads
///         without spaces). A token's JSON with a still and nothing else is exactly what
///         PanoramaRendererV4 returned.
///
///         PanoramaRendererV5Html with the scene renderer's code read from
///         PanoramaSeason4SceneRenderer, which keeps the gzip as it is: the code is encoded three
///         times where it lands, as a day's data is (about 108 gas a byte on every answer that
///         carries it), so a new scene renderer stores 2.37 times fewer bytes. Every answer is
///         the one PanoramaRendererV5Html gives for the same gzip, byte for byte.
///
///         What does not fit in one answer is read by the page itself, one fragment a call, from
///         the RPC addresses PanoramaSeason4Storage keeps (a holder's for their token first, then
///         the artist's): a day's data larger than a browser opens inside a page, and in the whole
///         artwork every Season 4 day and any still the CDN does not answer for.
library PanoramaRendererV7Html {
    using LibString for uint256;
    using LibString for int256;
    using LibString for address;
    using LibString for string;
    using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;

    uint256 internal constant SEASON_4_FIRST = 211;
    uint256 internal constant SEASON_4_LAST = 270;

    /// @dev The longest page address a browser opens inside a frame (Chromium stops at 2 MiB).
    ///      A day's data goes inside its dynamic scene only while the page stays this short;
    ///      past it the page reads the uploaded data over RPC.
    uint256 internal constant MAX_PAGE_URI = 2_000_000;

    /// @dev The longest answer that keeps a call well under the 500M gas the strictest node
    ///      allows (Alchemy 550M, Tenderly 500M). Panorama copies the answer twice on its way
    ///      out, so the gas grows with the square of its size: measured, about 41M per MB plus
    ///      18.7M per MB squared, 390M at this length. A day's data goes inside its page only
    ///      while the answer stays this short.
    uint256 internal constant MAX_ANSWER = 3_600_000;

    /// @dev The same for the whole artwork, which spends about 180M gas on its entries before
    ///      any still (measured cold at #256): its newest still is its `image` only while the
    ///      answer stays this short, else MURI's or the CDN's address.
    uint256 internal constant MAX_WHOLE_ANSWER = 2_400_000;

    /// @dev The most gas the music controller gets for its traits, and the most traits kept.
    uint256 internal constant MUSIC_TRAITS_GAS = 3_000_000;
    uint256 internal constant MAX_MUSIC_TRAITS = 16;
    /// @dev The most gas `season4Traits` gives its own `musicTraits` (which gives the controller
    ///      MUSIC_TRAITS_GAS of it).
    uint256 internal constant MUSIC_CALL_GAS = 5_000_000;

    /// @dev How many times a piece is base64-encoded on its way into the answer: the token's
    ///      JSON once (and a still inside it twice), the page's HTML twice, the scene renderer's
    ///      code and the day data inside the page three times.
    uint8 internal constant JSON = 1;
    uint8 internal constant HTML = 2;
    uint8 internal constant DATA = 3;

    bytes internal constant JSON_URI = "data:application/json;base64,";
    bytes internal constant HTML_URI = "data:text/html;base64,";
    bytes internal constant STILL_URI = "data:image/webp;base64,";
    bytes internal constant ANIMATION = '","animation_url":"';

    /// @dev `text`, then (JSON only) the bytes behind `pointers` as a base64 still, then `rest`.
    struct Piece {
        uint8 depth;
        bytes text;
        address[] pointers;
        bytes rest;
    }

    /*//////////////////////////////////////////////////////////////
                                 STILL
    //////////////////////////////////////////////////////////////*/

    /// @notice A token's metadata with its uploaded still as `image`, byte for byte what
    ///         PanoramaRendererV4 returned.
    /// @param head The token's JSON up to the opening quote of `image`'s value.
    /// @param rest The rest of the JSON, from the quote that closes it.
    function stillJson(
        bytes calldata head,
        bytes calldata rest,
        address panorama,
        uint256 tokenId
    ) external view returns (string memory) {
        Piece[] memory pieces = new Piece[](1);
        pieces[0] = _jsonStill(head, _stillPointers(panorama, tokenId), rest);
        _returnJsonUri(pieces);
    }

    /*//////////////////////////////////////////////////////////////
                                 TRAITS
    //////////////////////////////////////////////////////////////*/

    /// @notice A Season 4 token's traits as JSON attributes, each starting with a comma: the
    ///         ones the artists set in the storage (`getTokenTraits`), then the music
    ///         controller's (`musicTraits`). The music's are read in a call of their own, so a
    ///         missing, reverting or malformed controller drops only them.
    function season4Traits(address season4Storage, uint256 tokenId) external view returns (bytes memory out) {
        (string[] memory names, string[] memory values) =
            IPanoramaSeason4Storage(season4Storage).getTokenTraits(tokenId);
        out = _traits(names, values);
        (bool ok, bytes memory ret) = address(this).staticcall{ gas: MUSIC_CALL_GAS }(
            abi.encodeWithSelector(PanoramaRendererV7Html.musicTraits.selector, season4Storage, tokenId)
        );
        if (ok) out = bytes.concat(out, abi.decode(ret, (bytes)));
    }

    /// @notice The music controller's traits for a Season 4 token as JSON attributes, each
    ///         starting with a comma; empty without a controller. The first MAX_MUSIC_TRAITS
    ///         pairs are kept, leaving out a pair whose name is empty or over 64 bytes or whose
    ///         value is over 128. Reverts when the controller reverts or answers malformed
    ///         (`season4Traits` then adds none of the music's).
    function musicTraits(address season4Storage, uint256 tokenId) external view returns (bytes memory out) {
        address music = IPanoramaSeason4Storage(season4Storage).musicController();
        if (music.code.length == 0) return out;
        (string[] memory names, string[] memory values) =
            IPanoramaSeason4Music(music).musicTraits{ gas: MUSIC_TRAITS_GAS }(tokenId);
        out = _traits(names, values);
    }

    /// @dev The first MAX_MUSIC_TRAITS pairs as JSON attributes, leaving out a pair whose name
    ///      is empty or over 64 bytes or whose value is over 128.
    function _traits(string[] memory names, string[] memory values) private pure returns (bytes memory out) {
        uint256 n = names.length < values.length ? names.length : values.length;
        if (n > MAX_MUSIC_TRAITS) n = MAX_MUSIC_TRAITS;
        for (uint256 i; i < n; ++i) {
            uint256 k = bytes(names[i]).length;
            if (k == 0 || k > 64 || bytes(values[i]).length > 128) continue;
            out = abi.encodePacked(
                out, ',{"trait_type":"', names[i].escapeJSON(), '","value":"', values[i].escapeJSON(), '"}'
            );
        }
    }

    /*//////////////////////////////////////////////////////////////
                              DYNAMIC SCENE
    //////////////////////////////////////////////////////////////*/

    /// @notice A Season 4 token's metadata with its dynamic scene as `animation_url`.
    /// @param beforeStill With the still on-chain, the JSON up to the opening quote of `image`'s
    ///        value; else empty.
    /// @param head The JSON (after the still, when there is one) up to the opening quote of
    ///        `animation_url`'s value.
    /// @param tail The rest of the JSON, from the quote that closes it.
    /// @param dayDataUrl The day data's CDN address.
    function dynamicSceneJson(
        bytes calldata beforeStill,
        bytes calldata head,
        bytes calldata tail,
        address season4Storage,
        uint256 tokenId,
        bytes calldata dayDataUrl
    ) external view returns (string memory) {
        IPanoramaSeason4Storage s4 = IPanoramaSeason4Storage(season4Storage);
        bool uploaded = s4.isDayDataFullyUploaded(tokenId);

        Piece[] memory pieces = new Piece[](7);
        pieces[0] = beforeStill.length > 0
            ? _jsonStill(beforeStill, _stillPointers(s4.panorama(), tokenId), abi.encodePacked(head, HTML_URI))
            : _json(abi.encodePacked(head, HTML_URI));
        pieces[1] = _html(_sceneSettings(s4, tokenId, uploaded, dayDataUrl));
        pieces[2] = _data(_sceneRenderer().getSceneRendererFragmentPointers());
        pieces[3] = _html('","data":"');
        if (uploaded) pieces[4] = _data(s4.getDayDataFragmentPointers(tokenId));
        pieces[5] = _html(abi.encodePacked('"}', s4.getSceneRendererHtmlSuffixData()));
        pieces[6] = _json(tail);
        _fitDynamicScene(pieces, beforeStill, head, tokenId);
    }

    /// @dev Ends the call with the dynamic scene's answer, fitted. The uploaded day data stays inside
    ///      the page while the page is short enough for a browser to open; otherwise the page reads
    ///      it over RPC, then from `url`. The page is the artwork and the still its thumbnail: when
    ///      the two do not fit in one answer, the still yields first (its MURI or CDN address in
    ///      `image`), then the day (read over RPC).
    function _fitDynamicScene(
        Piece[] memory pieces,
        bytes calldata beforeStill,
        bytes calldata head,
        uint256 tokenId
    ) private view {
        Piece memory still = pieces[0];
        if (pieces[4].pointers.length > 0) {
            uint256 page;
            for (uint256 i = 1; i < 6; ++i) {
                page += _encodedLength(pieces[i], false);
            }
            if (HTML_URI.length + (page * 3) / 4 > MAX_PAGE_URI) delete pieces[4];
        }
        bool hasStill = beforeStill.length > 0;
        if (hasStill && _answerLength(pieces) > MAX_ANSWER) {
            pieces[0] = _json(_imageByAddress(beforeStill, head, tokenId));
        }
        if (_answerLength(pieces) > MAX_ANSWER) {
            delete pieces[4];
            pieces[0] = still;
            if (hasStill && _answerLength(pieces) > MAX_ANSWER) {
                pieces[0] = _json(_imageByAddress(beforeStill, head, tokenId));
            }
        }
        _returnJsonUri(pieces);
    }

    /// @dev The token's JSON head with its image as an address (asked of the renderer that called),
    ///      for when its still does not fit.
    function _imageByAddress(
        bytes calldata beforeStill,
        bytes calldata head,
        uint256 tokenId
    ) internal view returns (bytes memory) {
        string memory image = PanoramaRendererV7(msg.sender).resolveTableauOffchainImageUrl(tokenId);
        return abi.encodePacked(beforeStill, image.escapeJSON(), head, HTML_URI);
    }

    /// @dev The template's prefix, then the day's settings, read by the page as `S4`, up to the
    ///      opening quote of `code`'s value.
    function _sceneSettings(
        IPanoramaSeason4Storage s4,
        uint256 tokenId,
        bool uploaded,
        bytes calldata dayDataUrl
    ) internal view returns (bytes memory) {
        DynamicBufferLib.DynamicBuffer memory open;
        open.p(s4.getSceneRendererHtmlPrefixData());
        open.p('{"token":');
        open.p(bytes(tokenId.toString()));
        open.p(',"day":');
        open.p(bytes((tokenId - SEASON_4_FIRST + 1).toString()));
        open.p(',"url":"');
        open.p(bytes(string(dayDataUrl).escapeJSON()));
        open.p('","fragmentSize":');
        open.p(bytes(s4.FRAGMENT_SIZE().toString()));
        open.p(',"hashes":');
        _appendHashes(open, s4.getDayDataFragmentHashes(tokenId));
        open.p(',"uploaded":');
        open.p(uploaded ? bytes("true") : bytes("false"));
        open.p(',"chain":"');
        open.p(bytes(address(s4).toHexStringChecksummed()));
        open.p('","rpc":[');
        _appendUrls(open, s4.getTokenRpcUrls(tokenId), false);
        _appendUrls(open, s4.getRpcUrls(), s4.getTokenRpcUrls(tokenId).length > 0);
        open.p('],"code":"');
        return open.data;
    }

    /*//////////////////////////////////////////////////////////////
                             WHOLE ARTWORK
    //////////////////////////////////////////////////////////////*/

    /// @notice The ERC-20 metadata: the whole artwork. Before Season 4 (or without its code)
    ///         exactly as PanoramaRendererV4 built it; after, the page also carries the scene
    ///         renderer, the RPC addresses, and with each entry what can be read on-chain.
    /// @param image The newest tableau's image from MURI or the CDN, escaped, used unless its
    ///        still is on-chain and fits.
    function panoramaJson(
        bytes calldata image,
        address panorama,
        address season4Storage
    ) external view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        uint256 count = store.entryCount();
        address[] memory still;
        if (count > 0 && store.isFullyUploaded(count)) still = store.getFragmentPointers(count);

        DynamicBufferLib.DynamicBuffer memory head;
        head.p('{"name":"Panorama","description":"');
        head.p(bytes(store.erc20TokenDescription().escapeJSON()));
        head.p('","external_url":"');
        head.p(bytes(store.externalUrl().escapeJSON()));
        head.p('","image":"');
        bytes memory tail =
            abi.encodePacked('","attributes":[{"trait_type":"Tableau Length","value":"', count.toString(), '"}]}');

        if (count < SEASON_4_FIRST || season4Storage.code.length == 0 || !_hasSceneRenderer(season4Storage)) {
            return _wholeStills(
                head.data, image, abi.encodePacked(ANIMATION, _panoramaHtmlUri(store, panorama, count), tail), still
            );
        }
        _wholeDynamic(head.data, image, tail, still, panorama, IPanoramaSeason4Storage(season4Storage));
    }

    /// @dev The whole artwork with Season 4 drawn as dynamic scenes: the page also carries the scene renderer
    ///      and the RPC addresses. Ends the call.
    function _wholeDynamic(
        bytes memory head,
        bytes memory image,
        bytes memory tail,
        address[] memory still,
        address panorama,
        IPanoramaSeason4Storage s4
    ) private view {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        DynamicBufferLib.DynamicBuffer memory html = _panoramaHtmlStart(store, panorama, store.entryCount(), s4);
        html.p(";var RPC=[");
        _appendUrls(html, s4.getRpcUrls(), false);
        html.p('],S4A="');
        html.p(bytes(address(s4).toHexStringChecksummed()));
        html.p('",S4C="');

        Piece[] memory pieces = new Piece[](5);
        pieces[0] = _jsonStill(head, still, abi.encodePacked(ANIMATION, HTML_URI));
        pieces[1] = _html(html.data);
        pieces[2] = _data(_sceneRenderer().getSceneRendererFragmentPointers());
        pieces[3] = _html(abi.encodePacked('"', store.getPanoramaHtmlSuffixData()));
        pieces[4] = _json(tail);
        if (still.length == 0 || _answerLength(pieces) > MAX_WHOLE_ANSWER) {
            pieces[0] = _json(abi.encodePacked(head, image, ANIMATION, HTML_URI));
        }
        _returnJsonUri(pieces);
    }

    /// @dev The whole artwork before Season 4 lives: V4's answer, its newest still in place when
    ///      on-chain and short enough.
    function _wholeStills(
        bytes memory head,
        bytes memory image,
        bytes memory rest,
        address[] memory still
    ) private view returns (string memory) {
        Piece[] memory one = new Piece[](1);
        one[0] = _jsonStill(head, still, rest);
        if (still.length == 0 || _answerLength(one) > MAX_WHOLE_ANSWER) {
            return string.concat(string(JSON_URI), Base64.encode(abi.encodePacked(head, image, rest)));
        }
        _returnJsonUri(one);
    }

    /// @notice The whole-artwork page of stills, as PanoramaRendererV4's `renderPanoramaHtml`.
    function panoramaHtml(address panorama) external view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        return string(_panoramaHtmlUri(store, panorama, store.entryCount()));
    }

    function _panoramaHtmlUri(
        IPanoramaStorage store,
        address panorama,
        uint256 count
    ) internal view returns (bytes memory) {
        DynamicBufferLib.DynamicBuffer memory html =
            _panoramaHtmlStart(store, panorama, count, IPanoramaSeason4Storage(address(0)));
        html.p(store.getPanoramaHtmlSuffixData());
        return abi.encodePacked(HTML_URI, Base64.encode(html.data, false, false));
    }

    /// @dev The viewer template's prefix, the tableau data and the three variables, as V4 wrote
    ///      them. With a Season 4 storage, an entry whose still is on-chain also carries its
    ///      fragment count ("o") and the keccak256 of its fragment hashes ("r"), and a Season 4
    ///      entry its day data hashes ("h") and whether they are uploaded ("u").
    function _panoramaHtmlStart(
        IPanoramaStorage store,
        address panorama,
        uint256 count,
        IPanoramaSeason4Storage s4
    ) internal view returns (DynamicBufferLib.DynamicBuffer memory buf) {
        buf.reserve(65_536 + count * 1024);
        buf.p(store.getPanoramaHtmlPrefixData());
        buf.p("[");
        for (uint256 i = 1; i <= count; ++i) {
            if (i > 1) buf.p(",");
            _appendHtmlTableauEntry(buf, store, s4, i);
        }
        buf.p("]");
        buf.p(";var START_TS=");
        buf.p(bytes(uint256(store.startTimestamp()).toString()));
        buf.p(";var NFT_ADDR=\"");
        buf.p(bytes(panorama.toHexStringChecksummed()));
        buf.p("\";var ERC20_ADDR=\"");
        buf.p(bytes(IPanorama(panorama).panoramaERC20().toHexStringChecksummed()));
        buf.p("\"");
    }

    function _appendHtmlTableauEntry(
        DynamicBufferLib.DynamicBuffer memory buf,
        IPanoramaStorage store,
        IPanoramaSeason4Storage s4,
        uint256 tokenId
    ) internal view {
        IPanoramaStorage.TableauData memory d = store.getTableauData(tokenId);

        buf.p('{"p":');
        buf.p(bytes(uint256(d.price).toString()));
        buf.p(',"c":');
        buf.p(bytes(int256(d.changeBps).toString()));
        buf.p(',"t":');
        buf.p(bytes(uint256(d.timestamp).toString()));
        buf.p(',"m":');
        buf.p(bytes(uint256(d.moodIndex).toString()));

        if (bytes(d.name).length > 0) {
            buf.p(',"n":"');
            buf.p(bytes(d.name.escapeJSON()));
            buf.p('"');
        }
        if (bytes(d.prompt).length > 0) {
            buf.p(',"pr":"');
            buf.p(bytes(d.prompt.escapeJSON()));
            buf.p('"');
        }
        if (d.seed != 0) {
            buf.p(',"s":');
            buf.p(bytes(d.seed.toString()));
        }
        if (address(s4) != address(0)) {
            // A still on-chain: the viewer reads its fragments over RPC when the CDN fails, and keeps them
            // only when the keccak256 of their hashes one after another is "r".
            uint256 fragments = d.imageFragmentHashes.length;
            if (fragments > 0 && d.uploadedFragmentCount == fragments) {
                buf.p(',"o":');
                buf.p(bytes(fragments.toString()));
                buf.p(',"r":"');
                buf.p(bytes(uint256(keccak256(abi.encodePacked(d.imageFragmentHashes))).toHexString(32)));
                buf.p('"');
            }
            // A Season 4 day drawn as a dynamic scene: the viewer reads its day data over RPC once uploaded, else
            // from the CDN, and checks it against these.
            if (tokenId >= SEASON_4_FIRST && tokenId <= SEASON_4_LAST) {
                buf.p(',"h":');
                _appendHashes(buf, s4.getDayDataFragmentHashes(tokenId));
                if (s4.isDayDataFullyUploaded(tokenId)) buf.p(',"u":1');
            }
        }

        buf.p("}");
    }

    /// @dev Appends `["0x…",…]`: a day's fragment hashes, empty before the day is final.
    function _appendHashes(DynamicBufferLib.DynamicBuffer memory buf, bytes32[] memory hashes) internal pure {
        buf.p("[");
        for (uint256 i; i < hashes.length; ++i) {
            buf.p(i == 0 ? bytes('"') : bytes(',"'));
            buf.p(bytes(uint256(hashes[i]).toHexString(32)));
            buf.p('"');
        }
        buf.p("]");
    }

    /// @dev Appends `"a","b"`, after a comma when `more`. The storage checked each address
    ///      carries nothing to escape.
    function _appendUrls(DynamicBufferLib.DynamicBuffer memory buf, string[] memory urls, bool more) internal pure {
        for (uint256 i; i < urls.length; ++i) {
            buf.p(more || i > 0 ? bytes(',"') : bytes('"'));
            buf.p(bytes(urls[i]));
            buf.p('"');
        }
    }

    /// @dev PanoramaSeason4SceneRenderer, the scene renderer's code, named by the renderer that
    ///      called (as its image is asked of it).
    function _sceneRenderer() internal view returns (IPanoramaSeason4SceneRenderer) {
        return IPanoramaSeason4SceneRenderer(PanoramaRendererV7(msg.sender).season4SceneRenderer());
    }

    /// @dev Whether a dynamic scene can be built: the store names the renderer's
    ///      PanoramaSeason4Storage and holds a scene renderer. Anything missing or failing means none.
    function _hasSceneRenderer(address season4Storage) internal view returns (bool) {
        IPanoramaSeason4SceneRenderer code = _sceneRenderer();
        if (address(code).code.length == 0) return false;
        try code.season4Storage() returns (address named) {
            if (named != season4Storage) return false;
        } catch {
            return false;
        }
        try code.hasSceneRenderer() returns (bool has) {
            return has;
        } catch {
            return false;
        }
    }

    /// @dev A tableau's still fragments in PanoramaStorage.
    function _stillPointers(address panorama, uint256 tokenId) internal view returns (address[] memory) {
        return IPanoramaStorage(IPanorama(panorama).storageContract()).getFragmentPointers(tokenId);
    }

    /*//////////////////////////////////////////////////////////////
                              ONE BUFFER
    //////////////////////////////////////////////////////////////*/

    function _json(bytes memory text) private pure returns (Piece memory piece) {
        piece.depth = JSON;
        piece.text = text;
    }

    /// @dev JSON with a still in it: `text` (ending where the image's value opens), the still's
    ///      data URI, then `rest`.
    function _jsonStill(
        bytes memory text,
        address[] memory pointers,
        bytes memory rest
    ) private pure returns (Piece memory piece) {
        piece.depth = JSON;
        piece.text = abi.encodePacked(text, STILL_URI);
        piece.pointers = pointers;
        piece.rest = rest;
    }

    function _html(bytes memory text) private pure returns (Piece memory piece) {
        piece.depth = HTML;
        piece.text = text;
    }

    function _data(address[] memory pointers) private pure returns (Piece memory piece) {
        piece.depth = DATA;
        piece.pointers = pointers;
    }

    /// @dev Returns `data:application/json;base64,` followed by the pieces, each encoded `depth`
    ///      times where it lands. JSON pieces come first and last; the first is padded with
    ///      leading spaces to whole base64 groups, HTML and DATA pieces with trailing spaces.
    ///      Ends the call.
    function _returnJsonUri(Piece[] memory pieces) private view {
        uint256 total = _answerLength(pieces);

        uint256 ptr;
        assembly ("memory-safe") {
            ptr := mload(0x40)
            mstore(0x40, add(ptr, add(total, 0x80)))
        }
        uint256 table = Base64InPlace.newTable();
        uint256 at = _put(ptr + 0x40, JSON_URI);
        for (uint256 i; i < pieces.length; ++i) {
            at = _writePiece(table, at, pieces[i], i + 1 == pieces.length);
        }

        assembly ("memory-safe") {
            mstore(add(add(ptr, 0x40), total), 0)
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), total)
            return(ptr, add(0x40, and(add(total, 0x1f), not(0x1f))))
        }
    }

    /// @dev The length of the answer the pieces make.
    function _answerLength(Piece[] memory pieces) private view returns (uint256 total) {
        total = JSON_URI.length;
        for (uint256 i; i < pieces.length; ++i) {
            total += _encodedLength(pieces[i], i + 1 == pieces.length);
        }
    }

    /// @dev What a piece becomes in the answer.
    function _encodedLength(Piece memory piece, bool isLast) private view returns (uint256) {
        if (piece.depth == JSON) {
            uint256 len = _jsonLength(piece);
            return _b64(isLast ? len : _pad(len, 3));
        }
        if (piece.depth == HTML) return (_pad(piece.text.length, 9) * 16) / 9;
        uint256 size = _size(piece.pointers);
        return size == 0 ? 0 : (_pad(_b64(size), 9) * 16) / 9;
    }

    /// @dev A JSON piece's plain length, its still in base64.
    function _jsonLength(Piece memory piece) private view returns (uint256 len) {
        len = piece.text.length + piece.rest.length;
        if (piece.pointers.length > 0) len += _b64(_size(piece.pointers));
    }

    /// @dev Writes a piece at `at`, its plain bytes first staged at the right end of its place,
    ///      then encoded leftwards over them. Returns where the next piece starts.
    function _writePiece(uint256 table, uint256 at, Piece memory piece, bool isLast) private view returns (uint256) {
        if (piece.depth == JSON) {
            uint256 len = _jsonLength(piece);
            uint256 n = isLast ? len : _pad(len, 3);
            uint256 end = at + _b64(n);
            _spaces(end - n, n - len);
            uint256 next = _put(end - len, piece.text);
            if (piece.pointers.length > 0) next = _putEncoded(table, next, piece.pointers);
            _put(next, piece.rest);
            Base64InPlace.encode(table, at, end - n, n);
            return end;
        }
        if (piece.depth == HTML) {
            uint256 t = _pad(piece.text.length, 9);
            uint256 end = at + (t * 16) / 9;
            _spaces(_put(end - t, piece.text), t - piece.text.length);
            _encodeTwice(table, at, end, t);
            return end;
        }
        uint256 size = _size(piece.pointers);
        if (size == 0) return at;
        uint256 s0 = _b64(size);
        uint256 s = _pad(s0, 9);
        uint256 dataEnd = at + (s * 16) / 9;
        _putEncoded(table, dataEnd - s, piece.pointers);
        _spaces(dataEnd - s + s0, s - s0);
        _encodeTwice(table, at, dataEnd, s);
        return dataEnd;
    }

    /// @dev Writes the base64 of the bytes behind `pointers` at `at`, read in at the right end of
    ///      its place first. Returns where it ends.
    function _putEncoded(uint256 table, uint256 at, address[] memory pointers) private view returns (uint256 end) {
        uint256 size = _size(pointers);
        end = at + _b64(size);
        uint256 from = end - size;
        for (uint256 i; i < pointers.length; ++i) {
            from = _readPointer(from, pointers[i]);
        }
        Base64InPlace.encode(table, at, end - size, size);
    }

    /// @dev `len` bytes ending at `end` become their base64's base64, starting at `at`.
    function _encodeTwice(uint256 table, uint256 at, uint256 end, uint256 len) private pure {
        uint256 once = _b64(len);
        Base64InPlace.encode(table, end - once, end - len, len);
        Base64InPlace.encode(table, at, end - once, once);
    }

    function _b64(uint256 len) private pure returns (uint256) {
        return Base64InPlace.encodedLength(len);
    }

    function _pad(uint256 len, uint256 unit) private pure returns (uint256) {
        // forge-lint: disable-next-line(divide-before-multiply)
        return ((len + unit - 1) / unit) * unit;
    }

    /// @dev Total bytes held by SSTORE2 pointers.
    function _size(address[] memory pointers) private view returns (uint256 size) {
        for (uint256 i; i < pointers.length; ++i) {
            size += pointers[i].code.length - 1;
        }
    }

    function _put(uint256 at, bytes memory data) private pure returns (uint256 next) {
        assembly ("memory-safe") {
            let len := mload(data)
            mcopy(at, add(data, 0x20), len)
            next := add(at, len)
        }
    }

    function _spaces(uint256 at, uint256 count) private pure {
        assembly ("memory-safe") {
            for { let i } lt(i, count) { i := add(i, 1) } { mstore8(add(at, i), 0x20) }
        }
    }

    /// @dev Copies an SSTORE2 pointer's data to `at` (SSTORE2.read without a new buffer).
    function _readPointer(uint256 at, address pointer) private view returns (uint256 next) {
        assembly ("memory-safe") {
            let size := sub(extcodesize(pointer), 1)
            extcodecopy(pointer, at, 1, size)
            next := add(at, size)
        }
    }
}

node_modules/solady/src/auth/Ownable.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/solady/src/utils/Base64.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/solady/src/utils/DynamicBufferLib.sol

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

/// @notice Library for buffers with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicBufferLib.sol)
/// @author Modified from cozyco (https://github.com/samkingco/cozyco/blob/main/contracts/utils/DynamicBuffer.sol)
library DynamicBufferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STRUCTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Type to represent a dynamic buffer in memory.
    /// You can directly assign to `data`, and the `p` function will
    /// take care of the memory allocation.
    struct DynamicBuffer {
        bytes data;
    }

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

    // Some of these functions return the same buffer for function chaining.
    // e.g. `buffer.p("1").p("2")`.

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

    /// @dev Reserves at least `minimum` amount of contiguous memory.
    function reserve(DynamicBuffer memory buffer, uint256 minimum)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = buffer;
        uint256 n = buffer.data.length;
        if (minimum > n) {
            uint256 i = 0x40;
            do {} while ((i <<= 1) < minimum);
            bytes memory data;
            /// @solidity memory-safe-assembly
            assembly {
                data := 0x01
                mstore(data, sub(i, n))
            }
            result = p(result, data);
        }
    }

    /// @dev Clears the buffer without deallocating the memory.
    function clear(DynamicBuffer memory buffer)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(mload(buffer), 0)
        }
        result = buffer;
    }

    /// @dev Returns a string pointing to the underlying bytes data.
    /// Note: The string WILL change if the buffer is updated.
    function s(DynamicBuffer memory buffer) internal pure returns (string memory) {
        return string(buffer.data);
    }

    /// @dev Appends `data` to `buffer`.
    function p(DynamicBuffer memory buffer, bytes memory data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = buffer;
        if (data.length == uint256(0)) return result;
        /// @solidity memory-safe-assembly
        assembly {
            let w := not(0x1f)
            let bufData := mload(buffer)
            let bufDataLen := mload(bufData)
            let newBufDataLen := add(mload(data), bufDataLen)
            // Some random prime number to multiply `cap`, so that
            // we know that the `cap` is for a dynamic buffer.
            // Selected to be larger than any memory pointer realistically.
            let prime := 1621250193422201
            let cap := mload(add(bufData, w)) // `mload(sub(bufData, 0x20))`.
            // Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
            cap := mul(div(cap, prime), iszero(mod(cap, prime)))

            // Expand / Reallocate memory if required.
            // Note that we need to allocate an extra word for the length, and
            // and another extra word as a safety word (giving a total of 0x40 bytes).
            // Without the safety word, the backwards copying can cause a buffer overflow.
            for {} iszero(lt(newBufDataLen, cap)) {} {
                // Approximately more than double the capacity to ensure more than enough space.
                let newCap := and(add(cap, add(or(cap, newBufDataLen), 0x20)), w)
                // If the memory is contiguous, we can simply expand it.
                if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
                    // Store `cap * prime` in the word before the length.
                    mstore(add(bufData, w), mul(prime, newCap))
                    mstore(0x40, add(bufData, add(0x40, newCap))) // Expand the memory allocation.
                    break
                }
                // Set the `newBufData` to point to the word after `cap`.
                let newBufData := add(mload(0x40), 0x20)
                mstore(0x40, add(newBufData, add(0x40, newCap))) // Reallocate the memory.
                mstore(buffer, newBufData) // Store the `newBufData`.
                // Copy `bufData` one word at a time, backwards.
                for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
                    mstore(add(newBufData, o), mload(add(bufData, o)))
                    o := add(o, w) // `sub(o, 0x20)`.
                    if iszero(o) { break }
                }
                // Store `cap * prime` in the word before the length.
                mstore(add(newBufData, w), mul(prime, newCap))
                bufData := newBufData // Assign `newBufData` to `bufData`.
                break
            }
            // If it's a reserve operation, set the variables to skip the appending.
            if eq(data, 0x01) {
                mstore(data, 0x00)
                newBufDataLen := bufDataLen
            }
            // Copy `data` one word at a time, backwards.
            for { let o := and(add(mload(data), 0x20), w) } 1 {} {
                mstore(add(add(bufData, bufDataLen), o), mload(add(data, o)))
                o := add(o, w) // `sub(o, 0x20)`.
                if iszero(o) { break }
            }
            mstore(add(add(bufData, 0x20), newBufDataLen), 0) // Zeroize the word after the buffer.
            mstore(bufData, newBufDataLen) // Store the length.
        }
    }

    /// @dev Appends `data0`, `data1` to `buffer`.
    function p(DynamicBuffer memory buffer, bytes memory data0, bytes memory data1)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(p(buffer, data0), data1);
    }

    /// @dev Appends `data0` .. `data2` to `buffer`.
    function p(
        DynamicBuffer memory buffer,
        bytes memory data0,
        bytes memory data1,
        bytes memory data2
    ) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = p(p(p(buffer, data0), data1), data2);
    }

    /// @dev Appends `data0` .. `data3` to `buffer`.
    function p(
        DynamicBuffer memory buffer,
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3
    ) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = p(p(p(p(buffer, data0), data1), data2), data3);
    }

    /// @dev Appends `data0` .. `data4` to `buffer`.
    function p(
        DynamicBuffer memory buffer,
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4
    ) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = p(p(p(p(p(buffer, data0), data1), data2), data3), data4);
    }

    /// @dev Appends `data0` .. `data5` to `buffer`.
    function p(
        DynamicBuffer memory buffer,
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4,
        bytes memory data5
    ) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5);
    }

    /// @dev Appends `data0` .. `data6` to `buffer`.
    function p(
        DynamicBuffer memory buffer,
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4,
        bytes memory data5,
        bytes memory data6
    ) internal pure returns (DynamicBuffer memory result) {
        _deallocate(result);
        result = p(p(p(p(p(p(p(buffer, data0), data1), data2), data3), data4), data5), data6);
    }

    /// @dev Appends `abi.encodePacked(bool(data))` to buffer.
    function pBool(DynamicBuffer memory buffer, bool data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        uint256 casted;
        /// @solidity memory-safe-assembly
        assembly {
            casted := iszero(iszero(data))
        }
        result = p(buffer, _single(casted, 1));
    }

    /// @dev Appends `abi.encodePacked(address(data))` to buffer.
    function pAddress(DynamicBuffer memory buffer, address data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(uint256(uint160(data)), 20));
    }

    /// @dev Appends `abi.encodePacked(uint8(data))` to buffer.
    function pUint8(DynamicBuffer memory buffer, uint8 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 1));
    }

    /// @dev Appends `abi.encodePacked(uint16(data))` to buffer.
    function pUint16(DynamicBuffer memory buffer, uint16 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 2));
    }

    /// @dev Appends `abi.encodePacked(uint24(data))` to buffer.
    function pUint24(DynamicBuffer memory buffer, uint24 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 3));
    }

    /// @dev Appends `abi.encodePacked(uint32(data))` to buffer.
    function pUint32(DynamicBuffer memory buffer, uint32 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 4));
    }

    /// @dev Appends `abi.encodePacked(uint40(data))` to buffer.
    function pUint40(DynamicBuffer memory buffer, uint40 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 5));
    }

    /// @dev Appends `abi.encodePacked(uint48(data))` to buffer.
    function pUint48(DynamicBuffer memory buffer, uint48 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 6));
    }

    /// @dev Appends `abi.encodePacked(uint56(data))` to buffer.
    function pUint56(DynamicBuffer memory buffer, uint56 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 7));
    }

    /// @dev Appends `abi.encodePacked(uint64(data))` to buffer.
    function pUint64(DynamicBuffer memory buffer, uint64 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 8));
    }

    /// @dev Appends `abi.encodePacked(uint72(data))` to buffer.
    function pUint72(DynamicBuffer memory buffer, uint72 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 9));
    }

    /// @dev Appends `abi.encodePacked(uint80(data))` to buffer.
    function pUint80(DynamicBuffer memory buffer, uint80 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 10));
    }

    /// @dev Appends `abi.encodePacked(uint88(data))` to buffer.
    function pUint88(DynamicBuffer memory buffer, uint88 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 11));
    }

    /// @dev Appends `abi.encodePacked(uint96(data))` to buffer.
    function pUint96(DynamicBuffer memory buffer, uint96 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 12));
    }

    /// @dev Appends `abi.encodePacked(uint104(data))` to buffer.
    function pUint104(DynamicBuffer memory buffer, uint104 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 13));
    }

    /// @dev Appends `abi.encodePacked(uint112(data))` to buffer.
    function pUint112(DynamicBuffer memory buffer, uint112 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 14));
    }

    /// @dev Appends `abi.encodePacked(uint120(data))` to buffer.
    function pUint120(DynamicBuffer memory buffer, uint120 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 15));
    }

    /// @dev Appends `abi.encodePacked(uint128(data))` to buffer.
    function pUint128(DynamicBuffer memory buffer, uint128 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 16));
    }

    /// @dev Appends `abi.encodePacked(uint136(data))` to buffer.
    function pUint136(DynamicBuffer memory buffer, uint136 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 17));
    }

    /// @dev Appends `abi.encodePacked(uint144(data))` to buffer.
    function pUint144(DynamicBuffer memory buffer, uint144 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 18));
    }

    /// @dev Appends `abi.encodePacked(uint152(data))` to buffer.
    function pUint152(DynamicBuffer memory buffer, uint152 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 19));
    }

    /// @dev Appends `abi.encodePacked(uint160(data))` to buffer.
    function pUint160(DynamicBuffer memory buffer, uint160 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 20));
    }

    /// @dev Appends `abi.encodePacked(uint168(data))` to buffer.
    function pUint168(DynamicBuffer memory buffer, uint168 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 21));
    }

    /// @dev Appends `abi.encodePacked(uint176(data))` to buffer.
    function pUint176(DynamicBuffer memory buffer, uint176 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 22));
    }

    /// @dev Appends `abi.encodePacked(uint184(data))` to buffer.
    function pUint184(DynamicBuffer memory buffer, uint184 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 23));
    }

    /// @dev Appends `abi.encodePacked(uint192(data))` to buffer.
    function pUint192(DynamicBuffer memory buffer, uint192 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 24));
    }

    /// @dev Appends `abi.encodePacked(uint200(data))` to buffer.
    function pUint200(DynamicBuffer memory buffer, uint200 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 25));
    }

    /// @dev Appends `abi.encodePacked(uint208(data))` to buffer.
    function pUint208(DynamicBuffer memory buffer, uint208 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 26));
    }

    /// @dev Appends `abi.encodePacked(uint216(data))` to buffer.
    function pUint216(DynamicBuffer memory buffer, uint216 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 27));
    }

    /// @dev Appends `abi.encodePacked(uint224(data))` to buffer.
    function pUint224(DynamicBuffer memory buffer, uint224 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 28));
    }

    /// @dev Appends `abi.encodePacked(uint232(data))` to buffer.
    function pUint232(DynamicBuffer memory buffer, uint232 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 29));
    }

    /// @dev Appends `abi.encodePacked(uint240(data))` to buffer.
    function pUint240(DynamicBuffer memory buffer, uint240 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 30));
    }

    /// @dev Appends `abi.encodePacked(uint248(data))` to buffer.
    function pUint248(DynamicBuffer memory buffer, uint248 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 31));
    }

    /// @dev Appends `abi.encodePacked(uint256(data))` to buffer.
    function pUint256(DynamicBuffer memory buffer, uint256 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(data, 32));
    }

    /// @dev Appends `abi.encodePacked(bytes1(data))` to buffer.
    function pBytes1(DynamicBuffer memory buffer, bytes1 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 1));
    }

    /// @dev Appends `abi.encodePacked(bytes2(data))` to buffer.
    function pBytes2(DynamicBuffer memory buffer, bytes2 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 2));
    }

    /// @dev Appends `abi.encodePacked(bytes3(data))` to buffer.
    function pBytes3(DynamicBuffer memory buffer, bytes3 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 3));
    }

    /// @dev Appends `abi.encodePacked(bytes4(data))` to buffer.
    function pBytes4(DynamicBuffer memory buffer, bytes4 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 4));
    }

    /// @dev Appends `abi.encodePacked(bytes5(data))` to buffer.
    function pBytes5(DynamicBuffer memory buffer, bytes5 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 5));
    }

    /// @dev Appends `abi.encodePacked(bytes6(data))` to buffer.
    function pBytes6(DynamicBuffer memory buffer, bytes6 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 6));
    }

    /// @dev Appends `abi.encodePacked(bytes7(data))` to buffer.
    function pBytes7(DynamicBuffer memory buffer, bytes7 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 7));
    }

    /// @dev Appends `abi.encodePacked(bytes8(data))` to buffer.
    function pBytes8(DynamicBuffer memory buffer, bytes8 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 8));
    }

    /// @dev Appends `abi.encodePacked(bytes9(data))` to buffer.
    function pBytes9(DynamicBuffer memory buffer, bytes9 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 9));
    }

    /// @dev Appends `abi.encodePacked(bytes10(data))` to buffer.
    function pBytes10(DynamicBuffer memory buffer, bytes10 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 10));
    }

    /// @dev Appends `abi.encodePacked(bytes11(data))` to buffer.
    function pBytes11(DynamicBuffer memory buffer, bytes11 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 11));
    }

    /// @dev Appends `abi.encodePacked(bytes12(data))` to buffer.
    function pBytes12(DynamicBuffer memory buffer, bytes12 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 12));
    }

    /// @dev Appends `abi.encodePacked(bytes13(data))` to buffer.
    function pBytes13(DynamicBuffer memory buffer, bytes13 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 13));
    }

    /// @dev Appends `abi.encodePacked(bytes14(data))` to buffer.
    function pBytes14(DynamicBuffer memory buffer, bytes14 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 14));
    }

    /// @dev Appends `abi.encodePacked(bytes15(data))` to buffer.
    function pBytes15(DynamicBuffer memory buffer, bytes15 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 15));
    }

    /// @dev Appends `abi.encodePacked(bytes16(data))` to buffer.
    function pBytes16(DynamicBuffer memory buffer, bytes16 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 16));
    }

    /// @dev Appends `abi.encodePacked(bytes17(data))` to buffer.
    function pBytes17(DynamicBuffer memory buffer, bytes17 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 17));
    }

    /// @dev Appends `abi.encodePacked(bytes18(data))` to buffer.
    function pBytes18(DynamicBuffer memory buffer, bytes18 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 18));
    }

    /// @dev Appends `abi.encodePacked(bytes19(data))` to buffer.
    function pBytes19(DynamicBuffer memory buffer, bytes19 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 19));
    }

    /// @dev Appends `abi.encodePacked(bytes20(data))` to buffer.
    function pBytes20(DynamicBuffer memory buffer, bytes20 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 20));
    }

    /// @dev Appends `abi.encodePacked(bytes21(data))` to buffer.
    function pBytes21(DynamicBuffer memory buffer, bytes21 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 21));
    }

    /// @dev Appends `abi.encodePacked(bytes22(data))` to buffer.
    function pBytes22(DynamicBuffer memory buffer, bytes22 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 22));
    }

    /// @dev Appends `abi.encodePacked(bytes23(data))` to buffer.
    function pBytes23(DynamicBuffer memory buffer, bytes23 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 23));
    }

    /// @dev Appends `abi.encodePacked(bytes24(data))` to buffer.
    function pBytes24(DynamicBuffer memory buffer, bytes24 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 24));
    }

    /// @dev Appends `abi.encodePacked(bytes25(data))` to buffer.
    function pBytes25(DynamicBuffer memory buffer, bytes25 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 25));
    }

    /// @dev Appends `abi.encodePacked(bytes26(data))` to buffer.
    function pBytes26(DynamicBuffer memory buffer, bytes26 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 26));
    }

    /// @dev Appends `abi.encodePacked(bytes27(data))` to buffer.
    function pBytes27(DynamicBuffer memory buffer, bytes27 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 27));
    }

    /// @dev Appends `abi.encodePacked(bytes28(data))` to buffer.
    function pBytes28(DynamicBuffer memory buffer, bytes28 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 28));
    }

    /// @dev Appends `abi.encodePacked(bytes29(data))` to buffer.
    function pBytes29(DynamicBuffer memory buffer, bytes29 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 29));
    }

    /// @dev Appends `abi.encodePacked(bytes30(data))` to buffer.
    function pBytes30(DynamicBuffer memory buffer, bytes30 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 30));
    }

    /// @dev Appends `abi.encodePacked(bytes31(data))` to buffer.
    function pBytes31(DynamicBuffer memory buffer, bytes31 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 31));
    }

    /// @dev Appends `abi.encodePacked(bytes32(data))` to buffer.
    function pBytes32(DynamicBuffer memory buffer, bytes32 data)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        _deallocate(result);
        result = p(buffer, _single(bytes32(data), 32));
    }

    /// @dev Shorthand for returning a new buffer.
    function p() internal pure returns (DynamicBuffer memory result) {}

    /// @dev Shorthand for `p(p(), data)`.
    function p(bytes memory data) internal pure returns (DynamicBuffer memory result) {
        p(result, data);
    }

    /// @dev Shorthand for `p(p(), data0, data1)`.
    function p(bytes memory data0, bytes memory data1)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        p(p(result, data0), data1);
    }

    /// @dev Shorthand for `p(p(), data0, .., data2)`.
    function p(bytes memory data0, bytes memory data1, bytes memory data2)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        p(p(p(result, data0), data1), data2);
    }

    /// @dev Shorthand for `p(p(), data0, .., data3)`.
    function p(bytes memory data0, bytes memory data1, bytes memory data2, bytes memory data3)
        internal
        pure
        returns (DynamicBuffer memory result)
    {
        p(p(p(p(result, data0), data1), data2), data3);
    }

    /// @dev Shorthand for `p(p(), data0, .., data4)`.
    function p(
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4
    ) internal pure returns (DynamicBuffer memory result) {
        p(p(p(p(p(result, data0), data1), data2), data3), data4);
    }

    /// @dev Shorthand for `p(p(), data0, .., data5)`.
    function p(
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4,
        bytes memory data5
    ) internal pure returns (DynamicBuffer memory result) {
        p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5);
    }

    /// @dev Shorthand for `p(p(), data0, .., data6)`.
    function p(
        bytes memory data0,
        bytes memory data1,
        bytes memory data2,
        bytes memory data3,
        bytes memory data4,
        bytes memory data5,
        bytes memory data6
    ) internal pure returns (DynamicBuffer memory result) {
        p(p(p(p(p(p(p(result, data0), data1), data2), data3), data4), data5), data6);
    }

    /// @dev Shorthand for `pBool(p(), data)`.
    function pBool(bool data) internal pure returns (DynamicBuffer memory result) {
        pBool(result, data);
    }

    /// @dev Shorthand for `pAddress(p(), data)`.
    function pAddress(address data) internal pure returns (DynamicBuffer memory result) {
        pAddress(result, data);
    }

    /// @dev Shorthand for `pUint8(p(), data)`.
    function pUint8(uint8 data) internal pure returns (DynamicBuffer memory result) {
        pUint8(result, data);
    }

    /// @dev Shorthand for `pUint16(p(), data)`.
    function pUint16(uint16 data) internal pure returns (DynamicBuffer memory result) {
        pUint16(result, data);
    }

    /// @dev Shorthand for `pUint24(p(), data)`.
    function pUint24(uint24 data) internal pure returns (DynamicBuffer memory result) {
        pUint24(result, data);
    }

    /// @dev Shorthand for `pUint32(p(), data)`.
    function pUint32(uint32 data) internal pure returns (DynamicBuffer memory result) {
        pUint32(result, data);
    }

    /// @dev Shorthand for `pUint40(p(), data)`.
    function pUint40(uint40 data) internal pure returns (DynamicBuffer memory result) {
        pUint40(result, data);
    }

    /// @dev Shorthand for `pUint48(p(), data)`.
    function pUint48(uint48 data) internal pure returns (DynamicBuffer memory result) {
        pUint48(result, data);
    }

    /// @dev Shorthand for `pUint56(p(), data)`.
    function pUint56(uint56 data) internal pure returns (DynamicBuffer memory result) {
        pUint56(result, data);
    }

    /// @dev Shorthand for `pUint64(p(), data)`.
    function pUint64(uint64 data) internal pure returns (DynamicBuffer memory result) {
        pUint64(result, data);
    }

    /// @dev Shorthand for `pUint72(p(), data)`.
    function pUint72(uint72 data) internal pure returns (DynamicBuffer memory result) {
        pUint72(result, data);
    }

    /// @dev Shorthand for `pUint80(p(), data)`.
    function pUint80(uint80 data) internal pure returns (DynamicBuffer memory result) {
        pUint80(result, data);
    }

    /// @dev Shorthand for `pUint88(p(), data)`.
    function pUint88(uint88 data) internal pure returns (DynamicBuffer memory result) {
        pUint88(result, data);
    }

    /// @dev Shorthand for `pUint96(p(), data)`.
    function pUint96(uint96 data) internal pure returns (DynamicBuffer memory result) {
        pUint96(result, data);
    }

    /// @dev Shorthand for `pUint104(p(), data)`.
    function pUint104(uint104 data) internal pure returns (DynamicBuffer memory result) {
        pUint104(result, data);
    }

    /// @dev Shorthand for `pUint112(p(), data)`.
    function pUint112(uint112 data) internal pure returns (DynamicBuffer memory result) {
        pUint112(result, data);
    }

    /// @dev Shorthand for `pUint120(p(), data)`.
    function pUint120(uint120 data) internal pure returns (DynamicBuffer memory result) {
        pUint120(result, data);
    }

    /// @dev Shorthand for `pUint128(p(), data)`.
    function pUint128(uint128 data) internal pure returns (DynamicBuffer memory result) {
        pUint128(result, data);
    }

    /// @dev Shorthand for `pUint136(p(), data)`.
    function pUint136(uint136 data) internal pure returns (DynamicBuffer memory result) {
        pUint136(result, data);
    }

    /// @dev Shorthand for `pUint144(p(), data)`.
    function pUint144(uint144 data) internal pure returns (DynamicBuffer memory result) {
        pUint144(result, data);
    }

    /// @dev Shorthand for `pUint152(p(), data)`.
    function pUint152(uint152 data) internal pure returns (DynamicBuffer memory result) {
        pUint152(result, data);
    }

    /// @dev Shorthand for `pUint160(p(), data)`.
    function pUint160(uint160 data) internal pure returns (DynamicBuffer memory result) {
        pUint160(result, data);
    }

    /// @dev Shorthand for `pUint168(p(), data)`.
    function pUint168(uint168 data) internal pure returns (DynamicBuffer memory result) {
        pUint168(result, data);
    }

    /// @dev Shorthand for `pUint176(p(), data)`.
    function pUint176(uint176 data) internal pure returns (DynamicBuffer memory result) {
        pUint176(result, data);
    }

    /// @dev Shorthand for `pUint184(p(), data)`.
    function pUint184(uint184 data) internal pure returns (DynamicBuffer memory result) {
        pUint184(result, data);
    }

    /// @dev Shorthand for `pUint192(p(), data)`.
    function pUint192(uint192 data) internal pure returns (DynamicBuffer memory result) {
        pUint192(result, data);
    }

    /// @dev Shorthand for `pUint200(p(), data)`.
    function pUint200(uint200 data) internal pure returns (DynamicBuffer memory result) {
        pUint200(result, data);
    }

    /// @dev Shorthand for `pUint208(p(), data)`.
    function pUint208(uint208 data) internal pure returns (DynamicBuffer memory result) {
        pUint208(result, data);
    }

    /// @dev Shorthand for `pUint216(p(), data)`.
    function pUint216(uint216 data) internal pure returns (DynamicBuffer memory result) {
        pUint216(result, data);
    }

    /// @dev Shorthand for `pUint224(p(), data)`.
    function pUint224(uint224 data) internal pure returns (DynamicBuffer memory result) {
        pUint224(result, data);
    }

    /// @dev Shorthand for `pUint232(p(), data)`.
    function pUint232(uint232 data) internal pure returns (DynamicBuffer memory result) {
        pUint232(result, data);
    }

    /// @dev Shorthand for `pUint240(p(), data)`.
    function pUint240(uint240 data) internal pure returns (DynamicBuffer memory result) {
        pUint240(result, data);
    }

    /// @dev Shorthand for `pUint248(p(), data)`.
    function pUint248(uint248 data) internal pure returns (DynamicBuffer memory result) {
        pUint248(result, data);
    }

    /// @dev Shorthand for `pUint256(p(), data)`.
    function pUint256(uint256 data) internal pure returns (DynamicBuffer memory result) {
        pUint256(result, data);
    }

    /// @dev Shorthand for `pBytes1(p(), data)`.
    function pBytes1(bytes1 data) internal pure returns (DynamicBuffer memory result) {
        pBytes1(result, data);
    }

    /// @dev Shorthand for `pBytes2(p(), data)`.
    function pBytes2(bytes2 data) internal pure returns (DynamicBuffer memory result) {
        pBytes2(result, data);
    }

    /// @dev Shorthand for `pBytes3(p(), data)`.
    function pBytes3(bytes3 data) internal pure returns (DynamicBuffer memory result) {
        pBytes3(result, data);
    }

    /// @dev Shorthand for `pBytes4(p(), data)`.
    function pBytes4(bytes4 data) internal pure returns (DynamicBuffer memory result) {
        pBytes4(result, data);
    }

    /// @dev Shorthand for `pBytes5(p(), data)`.
    function pBytes5(bytes5 data) internal pure returns (DynamicBuffer memory result) {
        pBytes5(result, data);
    }

    /// @dev Shorthand for `pBytes6(p(), data)`.
    function pBytes6(bytes6 data) internal pure returns (DynamicBuffer memory result) {
        pBytes6(result, data);
    }

    /// @dev Shorthand for `pBytes7(p(), data)`.
    function pBytes7(bytes7 data) internal pure returns (DynamicBuffer memory result) {
        pBytes7(result, data);
    }

    /// @dev Shorthand for `pBytes8(p(), data)`.
    function pBytes8(bytes8 data) internal pure returns (DynamicBuffer memory result) {
        pBytes8(result, data);
    }

    /// @dev Shorthand for `pBytes9(p(), data)`.
    function pBytes9(bytes9 data) internal pure returns (DynamicBuffer memory result) {
        pBytes9(result, data);
    }

    /// @dev Shorthand for `pBytes10(p(), data)`.
    function pBytes10(bytes10 data) internal pure returns (DynamicBuffer memory result) {
        pBytes10(result, data);
    }

    /// @dev Shorthand for `pBytes11(p(), data)`.
    function pBytes11(bytes11 data) internal pure returns (DynamicBuffer memory result) {
        pBytes11(result, data);
    }

    /// @dev Shorthand for `pBytes12(p(), data)`.
    function pBytes12(bytes12 data) internal pure returns (DynamicBuffer memory result) {
        pBytes12(result, data);
    }

    /// @dev Shorthand for `pBytes13(p(), data)`.
    function pBytes13(bytes13 data) internal pure returns (DynamicBuffer memory result) {
        pBytes13(result, data);
    }

    /// @dev Shorthand for `pBytes14(p(), data)`.
    function pBytes14(bytes14 data) internal pure returns (DynamicBuffer memory result) {
        pBytes14(result, data);
    }

    /// @dev Shorthand for `pBytes15(p(), data)`.
    function pBytes15(bytes15 data) internal pure returns (DynamicBuffer memory result) {
        pBytes15(result, data);
    }

    /// @dev Shorthand for `pBytes16(p(), data)`.
    function pBytes16(bytes16 data) internal pure returns (DynamicBuffer memory result) {
        pBytes16(result, data);
    }

    /// @dev Shorthand for `pBytes17(p(), data)`.
    function pBytes17(bytes17 data) internal pure returns (DynamicBuffer memory result) {
        pBytes17(result, data);
    }

    /// @dev Shorthand for `pBytes18(p(), data)`.
    function pBytes18(bytes18 data) internal pure returns (DynamicBuffer memory result) {
        pBytes18(result, data);
    }

    /// @dev Shorthand for `pBytes19(p(), data)`.
    function pBytes19(bytes19 data) internal pure returns (DynamicBuffer memory result) {
        pBytes19(result, data);
    }

    /// @dev Shorthand for `pBytes20(p(), data)`.
    function pBytes20(bytes20 data) internal pure returns (DynamicBuffer memory result) {
        pBytes20(result, data);
    }

    /// @dev Shorthand for `pBytes21(p(), data)`.
    function pBytes21(bytes21 data) internal pure returns (DynamicBuffer memory result) {
        pBytes21(result, data);
    }

    /// @dev Shorthand for `pBytes22(p(), data)`.
    function pBytes22(bytes22 data) internal pure returns (DynamicBuffer memory result) {
        pBytes22(result, data);
    }

    /// @dev Shorthand for `pBytes23(p(), data)`.
    function pBytes23(bytes23 data) internal pure returns (DynamicBuffer memory result) {
        pBytes23(result, data);
    }

    /// @dev Shorthand for `pBytes24(p(), data)`.
    function pBytes24(bytes24 data) internal pure returns (DynamicBuffer memory result) {
        pBytes24(result, data);
    }

    /// @dev Shorthand for `pBytes25(p(), data)`.
    function pBytes25(bytes25 data) internal pure returns (DynamicBuffer memory result) {
        pBytes25(result, data);
    }

    /// @dev Shorthand for `pBytes26(p(), data)`.
    function pBytes26(bytes26 data) internal pure returns (DynamicBuffer memory result) {
        pBytes26(result, data);
    }

    /// @dev Shorthand for `pBytes27(p(), data)`.
    function pBytes27(bytes27 data) internal pure returns (DynamicBuffer memory result) {
        pBytes27(result, data);
    }

    /// @dev Shorthand for `pBytes28(p(), data)`.
    function pBytes28(bytes28 data) internal pure returns (DynamicBuffer memory result) {
        pBytes28(result, data);
    }

    /// @dev Shorthand for `pBytes29(p(), data)`.
    function pBytes29(bytes29 data) internal pure returns (DynamicBuffer memory result) {
        pBytes29(result, data);
    }

    /// @dev Shorthand for `pBytes30(p(), data)`.
    function pBytes30(bytes30 data) internal pure returns (DynamicBuffer memory result) {
        pBytes30(result, data);
    }

    /// @dev Shorthand for `pBytes31(p(), data)`.
    function pBytes31(bytes31 data) internal pure returns (DynamicBuffer memory result) {
        pBytes31(result, data);
    }

    /// @dev Shorthand for `pBytes32(p(), data)`.
    function pBytes32(bytes32 data) internal pure returns (DynamicBuffer memory result) {
        pBytes32(result, data);
    }

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

    /// @dev Helper for deallocating an automatically allocated `buffer` pointer.
    function _deallocate(DynamicBuffer memory result) private pure {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x40, result) // Deallocate, as we have already allocated.
        }
    }

    /// @dev Returns a temporary bytes string of length `n` for `data`.
    function _single(uint256 data, uint256 n) private pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 0x00
            mstore(n, data)
            mstore(result, n)
        }
    }

    /// @dev Returns a temporary bytes string of length `n` for `data`.
    function _single(bytes32 data, uint256 n) private pure returns (bytes memory result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := 0x00
            mstore(0x20, data)
            mstore(result, n)
        }
    }
}

node_modules/solady/src/utils/LibBytes.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/solady/src/utils/LibString.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/solady/src/utils/Lifebuoy.sol

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

/// @notice Class that allows for rescue of ETH, ERC20, ERC721 tokens.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Lifebuoy.sol)
///
/// @dev This contract is created to mitigate the following disasters:
/// - Careless user sends tokens to the wrong chain or wrong contract.
/// - Careless dev deploys a contract without a withdraw function in attempt to rescue
///   careless user's tokens, due to deployment nonce mismatch caused by
///   script misfire / misconfiguration.
/// - Careless dev forgets to add a withdraw function to a NFT sale contract.
///
/// Note: if you are deploying via a untrusted `tx.origin`,
/// you MUST override `_lifebuoyDefaultDeployer` to return a trusted address.
///
/// For best safety:
/// - For non-escrow contracts, inherit Lifebuoy as much as possible,
///   and leave it unlocked.
/// - For escrow contracts, lock access as tight as possible,
///   as soon as possible. Or simply don't inherit Lifebuoy.
/// Escrow: Your contract is designed to hold ETH, ERC20s, ERC721s
/// (e.g. liquidity pools).
///
/// All rescue and rescue authorization functions require either:
/// - Caller is the deployer
///   AND the contract is not a proxy
///   AND `rescueLocked() & _LIFEBUOY_DEPLOYER_ACCESS_LOCK == 0`.
/// - Caller is `owner()`
///   AND `rescueLocked() & _LIFEBUOY_OWNER_ACCESS_LOCK == 0`.
///
/// The choice of using bit flags to represent locked statuses is for
/// efficiency, flexibility, convenience.
///
/// This contract is optimized with a priority on minimal bytecode size,
/// as the methods are not intended to be called often.
contract Lifebuoy {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to rescue or lock the rescue function.
    error RescueUnauthorizedOrLocked();

    /// @dev The rescue operation has failed due to a failed transfer.
    error RescueTransferFailed();

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

    // These flags are kept internal to avoid bloating up the function dispatch.
    // You can just copy paste this into your own code.

    /// @dev Flag to denote that the deployer's access is locked. (1)
    uint256 internal constant _LIFEBUOY_DEPLOYER_ACCESS_LOCK = 1 << 0;

    /// @dev Flag to denote that the `owner()`'s access is locked. (2)
    uint256 internal constant _LIFEBUOY_OWNER_ACCESS_LOCK = 1 << 1;

    /// @dev Flag to denote that the `lockRescue` function is locked. (4)
    uint256 internal constant _LIFEBUOY_LOCK_RESCUE_LOCK = 1 << 2;

    /// @dev Flag to denote that the `rescueETH` function is locked. (8)
    uint256 internal constant _LIFEBUOY_RESCUE_ETH_LOCK = 1 << 3;

    /// @dev Flag to denote that the `rescueERC20` function is locked. (16)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC20_LOCK = 1 << 4;

    /// @dev Flag to denote that the `rescueERC721` function is locked. (32)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC721_LOCK = 1 << 5;

    /// @dev Flag to denote that the `rescueERC1155` function is locked. (64)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC1155_LOCK = 1 << 6;

    /// @dev Flag to denote that the `rescueERC6909` function is locked. (128)
    uint256 internal constant _LIFEBUOY_RESCUE_ERC6909_LOCK = 1 << 7;

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

    /// @dev For checking that the caller is the deployer and
    /// that the context is not a delegatecall
    /// (so that the implementation deployer cannot drain proxies).
    bytes32 internal immutable _lifebuoyDeployerHash;

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

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

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

    constructor() payable {
        bytes32 hash;
        uint256 deployer = uint160(_lifebuoyDefaultDeployer());
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, address())
            mstore(0x20, deployer)
            hash := keccak256(0x00, 0x40)
        }
        _lifebuoyDeployerHash = hash;
    }

    /// @dev Returns `tx.origin` by default. Override to return another address if needed.
    ///
    /// Note: If you are deploying via a untrusted `tx.origin` (e.g. ERC4337 bundler)
    /// you MUST override this function to return a trusted address.
    function _lifebuoyDefaultDeployer() internal view virtual returns (address) {
        // I know about EIP7645, and I will stop it if it gets traction.
        // Worse case, I will add an `ecrecover` method. But not today.
        return tx.origin;
    }

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

    /// @dev Sends `amount` (in wei) ETH from the current contract to `to`.
    /// Reverts upon failure.
    function rescueETH(address to, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ETH_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0x7ec62e76) // `RescueTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC20(address token, address to, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC20_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            // `RescueTransferFailed()` and `transfer(address,uint256)`.
            mstore(0x00, shl(96, 0x7ec62e76a9059cbb))
            if iszero(call(gas(), token, callvalue(), 0x10, 0x44, codesize(), 0x00)) {
                revert(0x0c, 0x04)
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends `id` of ERC721 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC721(address token, address to, uint256 id)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC721_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, id) // Store the `id` argument.
            mstore(0x40, shr(96, shl(96, to))) // Store the `to` argument.
            mstore(0x20, address()) // Store the `from` argument.
            // `RescueTransferFailed()` and `transferFrom(address,address,uint256)`.
            mstore(0x00, 0x7ec62e7623b872dd)
            if iszero(call(gas(), token, callvalue(), 0x1c, 0x64, codesize(), 0x00)) {
                revert(0x18, 0x04)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of `id` of ERC1155 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC1155(
        address token,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata data
    ) public payable virtual onlyRescuer(_LIFEBUOY_RESCUE_ERC1155_LOCK) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            // `RescueTransferFailed()` and `safeTransferFrom(address,address,uint256,uint256,bytes)`.
            mstore(m, 0x7ec62e76f242432a)
            mstore(add(0x20, m), address()) // Store the `from` argument.
            mstore(add(0x40, m), shr(96, shl(96, to))) // Store the `to` argument.
            mstore(add(0x60, m), id) // Store the `id` argument.
            mstore(add(0x80, m), amount) // Store the `amount` argument.
            mstore(add(0xa0, m), 0xa0) // Store the offset to `data`.
            mstore(add(0xc0, m), data.length)
            calldatacopy(add(m, 0xe0), data.offset, data.length)
            // forgefmt: disable-next-item
            if iszero(
                call(gas(), token, callvalue(), add(m, 0x1c), add(0xc4, data.length), codesize(), 0x00)
            ) { revert(add(m, 0x18), 0x04) }
        }
    }

    /// @dev Sends `amount` of `id` of ERC6909 `token` from the current contract to `to`.
    /// Does not check for existence of token or return data. Reverts upon failure.
    function rescueERC6909(address token, address to, uint256 id, uint256 amount)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_RESCUE_ERC6909_LOCK)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, id) // Store the `id` argument.
            mstore(0x54, amount) // Store the `amount` argument.
            // `RescueTransferFailed()` and `transfer(address,uint256,uint256)`.
            mstore(0x00, shl(96, 0x7ec62e76095bcdb6))
            if iszero(call(gas(), token, callvalue(), 0x10, 0x64, codesize(), 0x00)) {
                revert(0x0c, 0x04)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

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

    /// @dev Returns the flags denoting whether access to rescue functions
    /// (including `lockRescue`) is locked.
    function rescueLocked() public view virtual returns (uint256 locks) {
        /// @solidity memory-safe-assembly
        assembly {
            locks := sload(_RESCUE_LOCKED_FLAGS_SLOT)
        }
    }

    /// @dev Locks (i.e. permanently removes) access to rescue functions (including `lockRescue`).
    function lockRescue(uint256 locksToSet)
        public
        payable
        virtual
        onlyRescuer(_LIFEBUOY_LOCK_RESCUE_LOCK)
    {
        _lockRescue(locksToSet);
    }

    /// @dev Internal function to set the lock flags without going through access control.
    function _lockRescue(uint256 locksToSet) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            let s := _RESCUE_LOCKED_FLAGS_SLOT
            sstore(s, or(sload(s), locksToSet))
        }
    }

    /// @dev Requires that the rescue function being guarded is:
    /// 1. Not locked, AND
    /// 2. Called by either:
    ///   (a) The `owner()`, OR
    ///   (b) The deployer (if not via a delegate call and deployer is an EOA).
    function _checkRescuer(uint256 modeLock) internal view virtual {
        uint256 locks = rescueLocked();
        bytes32 h = _lifebuoyDeployerHash;
        /// @solidity memory-safe-assembly
        assembly {
            for {} 1 {} {
                // If the `modeLock` flag is true, set all bits in `locks` to true.
                locks := or(sub(0, iszero(iszero(and(modeLock, locks)))), locks)
                // Caller is the deployer
                // AND the contract is not a proxy
                // AND `locks & _LIFEBUOY_DEPLOYER_ACCESS_LOCK` is false.
                mstore(0x20, caller())
                mstore(and(locks, _LIFEBUOY_DEPLOYER_ACCESS_LOCK), address())
                if eq(keccak256(0x00, 0x40), h) { break }
                // If the caller is `owner()`
                // AND `locks & _LIFEBUOY_OWNER_ACCESS_LOCK` is false.
                mstore(0x08, 0x8da5cb5b0a0362e0) // `owner()` and `RescueUnauthorizedOrLocked()`.
                if and( // The arguments of `and` are evaluated from right to left.
                    lt(
                        and(locks, _LIFEBUOY_OWNER_ACCESS_LOCK),
                        and(gt(returndatasize(), 0x1f), eq(mload(0x00), caller()))
                    ),
                    staticcall(gas(), address(), 0x20, 0x04, 0x00, 0x20)
                ) { break }
                revert(0x24, 0x04)
            }
        }
    }

    /// @dev Modifier that calls `_checkRescuer()` at the start of the function.
    modifier onlyRescuer(uint256 modeLock) virtual {
        _checkRescuer(modeLock);
        _;
    }
}

src/PanoramaRendererV5.sol

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

import { Ownable } from "solady/auth/Ownable.sol";
import { Lifebuoy } from "solady/utils/Lifebuoy.sol";
import { Base64 } from "solady/utils/Base64.sol";
import { LibString } from "solady/utils/LibString.sol";
import { DynamicBufferLib } from "solady/utils/DynamicBufferLib.sol";
import { IPanoramaRenderer } from "./interfaces/IPanoramaRenderer.sol";
import { IPanorama } from "./interfaces/IPanorama.sol";
import { IPanoramaStorage } from "./interfaces/IPanoramaStorage.sol";
import { IMURIProtocol } from "./interfaces/IMURIProtocol.sol";
import { IPanoramaWorkflowLedger } from "./interfaces/IPanoramaWorkflowLedger.sol";
import { IPanoramaSeason4Storage } from "./interfaces/IPanoramaSeason4Storage.sol";
import { IPanoramaSeason4Music } from "./interfaces/IPanoramaSeason4Music.sol";
import { Base64InPlace } from "./utils/Base64InPlace.sol";

/// @title PanoramaRendererV5
/// @author Yigit Duman (@yigitduman)
/// @notice Fifth-generation renderer: PanoramaRendererV4 plus Season 4 (#211-#270,
///         with Dav). Tokens #1-#210 render exactly as in V4.
///         - "Season" is "4" and "Artist" is "Dav & Yigit Duman" for #211-#270, revealed or not.
///         - "Artist" names the season's artist with Yigit Duman for Seasons 2 and 3 too
///           ("DeltaSauce & Yigit Duman", "Pale Kirill & Yigit Duman"); Season 1 stays
///           "Yigit Duman". This is the one difference from V4 on #91-#210.
///         - "Lead" trait: the stranger who leads the day (ten days each, the sixth nine);
///           day 60 (#270) has none. On unrevealed tokens too.
///         - `animation_url` of a revealed Season 4 token is the holder's choice, kept in
///           PanoramaSeason4Storage: the static video (default: MURI once the token's record
///           exists, else the CDN address derived from its date, as images are), or the dynamic
///           scene of its day, built from the scene renderer and the day data held on-chain.
///         - The dynamic scene is the Season 4 artwork and the still its thumbnail, each on-chain on its
///           own: "Status: On-chain" on a Season 4 token means its dynamic scene is (scene renderer stored, day
///           data uploaded), the still uploaded or not. When both do not fit in one answer, the day
///           stays inside its page and the still is given by its MURI or CDN address.
///         - The whole-artwork page (the ERC-20 metadata) carries the scene renderer once
///           it is stored and Season 4 has begun, and draws each Season 4 day live.
///         The pages are built by PanoramaRendererV5Html, a library in this file linked into
///         the renderer (together they are larger than one contract may be).
contract PanoramaRendererV5 is IPanoramaRenderer, Ownable, Lifebuoy {
    using LibString for uint256;
    using LibString for int256;
    using LibString for address;
    using LibString for string;
    using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;

    uint256 internal constant SEASON_1_END = 90;
    uint256 internal constant SEASON_2_END = 180;
    uint256 internal constant SEASON_3_END = 210;
    uint256 internal constant SEASON_4_END = 270;
    uint256 internal constant SEASON_3_DAYS_PER_ZONE = 5;

    /// @dev Pale Kirill's 30 Season 3 themes (tokens #181-#210), pipe-delimited, in daily
    ///      reveal order. Token #181 = "Creator", token #210 = "Love". Mirrors
    ///      panorama-season3/frontend/src/lib/season3Zones.ts (sentence case here).
    string internal constant SEASON_3_THEMES =
        "Creator|Home|Internal error|Blueprint|Passion|Architect|River|Loading|Hoop|Nostalgia|Knight|Castle|Strategy|Sword|Hope|Lamb|Garden|Childhood|Flowers|Silence|Angel|Hut|Searching|Monument|Faith|Soul|Basketball court|Death|Family tree|Love";

    /// @dev The six zones, five days each, in route order.
    string internal constant SEASON_3_ZONES = "Interface|City|Suburb|Village|Nature|Abstract";

    /// @dev What each of a zone's five days is about, in the same order in every zone.
    string internal constant SEASON_3_KINDS = "Figure|Place|Event|Object|Feeling";

    /// @dev The artist named for each season, in season order.
    string internal constant SEASON_ARTISTS =
        "Yigit Duman|DeltaSauce & Yigit Duman|Pale Kirill & Yigit Duman|Dav & Yigit Duman";

    /// @dev Season 4's six leads in order: ten days each, the sixth nine; day 60 has none.
    string internal constant SEASON_4_LEADS = "Newcomer|Night Worker|Caretaker|Performer|Runaway|Young One";

    string internal constant MONTH_NAMES =
        "January|February|March|April|May|June|July|August|September|October|November|December";

    /// @dev Mood labels by moodIndex 0-6.
    string internal constant MOOD_LABELS =
        "Extreme Bliss|High Bliss|Mild Joy|Equilibrium|Mild Suffering|Deep Suffering|Extreme Anguish";

    /// @dev The 90 Season 2 technologies (tokens #91-#180), pipe-delimited, in daily
    ///      reveal order — the order they were invented. Token #91 = "Stone tools",
    ///      token #180 = "Artificial intelligence".
    string internal constant SEASON_2_TECHNOLOGIES =
        "Stone tools|Controlled fire|Irrigation systems|Plow|Wheel and axle|Writing systems|Bronze metallurgy|Sailing ships|Coinage|Road networks|Paper|Compass|Glass & lenses|Gunpowder|Mechanical clock|Printing press|Telescope|Steam engine|Textile machinery (loom)|Vaccination|Telegraph|Railroads|Anesthesia|Sanitation & plumbing|Photography|Telephone|X-ray imaging|Internal combustion engine|Automobile|Electric power grid|Assembly line|Radio broadcasting|Airplane|Steel-frame skyscrapers|Refrigeration|Radar|Antibiotics|Nuclear fission|Television|Transistor|Plastics|Rockets|Satellites|Space Travel|High-speed rail (bullet trains)|Laser technology|Integrated circuits|Pacemakers & medical implants|Video Games|Computer networking|Robotics & industrial automation|Personal computer|VHS|Space telescopes (Hubble / JWST)|GPS|World Wide Web|Email|Search engines|DVD|Digital cameras|International Space Station|E-commerce platforms|Wi-Fi|Digital music players|Mobile phones & smartphones|Digital payments|Social media|Wind turbines|Cloud computing|Video calling|Blockchain|LED lighting|Streaming media|3D printing|Drones|Renewable solar power|Bionic prosthetics|CRISPR gene editing|Augmented reality|Virtual reality|Battery storage|Facial recognition|Electric vehicles|Vertical farming|Autonomous vehicles|Lab-grown meat|Brain-computer interfaces|Quantum computing|Humanoid robots|Artificial intelligence";

    address public panorama;
    string public prerevealBaseUrl;
    /// @notice PanoramaWorkflowLedger whose steps fill the "workflows" field; unset = none.
    address public workflowLedger;
    /// @notice PanoramaSeason4Storage: the dynamic scene, each day's data and the holders' choices.
    address public season4Storage;

    constructor(address _panorama, string memory _prerevealBaseUrl) {
        _initializeOwner(msg.sender);
        panorama = _panorama;
        prerevealBaseUrl = _prerevealBaseUrl;
    }

    function setPanorama(address _panorama) external onlyOwner {
        panorama = _panorama;
    }

    function setPrerevealBaseUrl(string calldata _url) external onlyOwner {
        prerevealBaseUrl = _url;
    }

    function setWorkflowLedger(address _ledger) external onlyOwner {
        workflowLedger = _ledger;
    }

    function setSeason4Storage(address _season4Storage) external onlyOwner {
        season4Storage = _season4Storage;
    }

    /*//////////////////////////////////////////////////////////////
                        TABLEAU URL RESOLUTION
    //////////////////////////////////////////////////////////////*/

    function resolveTableauImageUrl(uint256 tokenId) public view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());

        // Priority 1: On-chain image from SSTORE2 fragments
        string memory onchainUri = store.getOnchainImageDataUri(tokenId);
        if (bytes(onchainUri).length > 0) {
            return onchainUri;
        }

        return resolveTableauOffchainImageUrl(tokenId);
    }

    /// @notice A tableau's image when its still is not on-chain, or does not fit beside its dynamic
    ///         scene: MURI's thumbnail, else the CDN address derived from its date.
    function resolveTableauOffchainImageUrl(uint256 tokenId) public view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        // Priority 2: MURI Protocol
        IMURIProtocol muri = IMURIProtocol(IPanorama(panorama).muriProtocol());
        if (address(muri) != address(0)) {
            try muri.renderImage(panorama, tokenId) returns (string memory imageUri) {
                if (imageUri.startsWith("http") || imageUri.startsWith("data:image/")) {
                    return imageUri;
                }
                // solhint-disable-next-line no-empty-blocks
            } catch { }
        }

        // Priority 3: CDN fallback — derive URL from timestamp
        return _cdnUrl(store, tokenId, "optimized_", ".webp");
    }

    function resolveTableauAnimationUrl(uint256 tokenId) public view returns (string memory) {
        if (_isSeason4(tokenId)) return _resolveSeason4VideoUrl(tokenId);

        IMURIProtocol muri = IMURIProtocol(IPanorama(panorama).muriProtocol());

        if (address(muri) != address(0)) {
            // Only render animation when display mode is HTML (dynamic).
            // tokenData() returns the full Token struct; displayMode sits at word 4 (offset 0x80).
            if (!_isMuriHtmlMode(address(muri), panorama, tokenId)) return "";

            try muri.renderHTML(panorama, tokenId) returns (string memory htmlUri) {
                return htmlUri;
                // solhint-disable-next-line no-empty-blocks
            } catch { }
        }

        return "";
    }

    /// @dev Reads displayMode from MURI's public tokenData mapping via low-level staticcall.
    ///      Token struct ABI: [metadata_off, thumbnail_off, artwork_off, permissions, displayMode, htmlTemplate_off]
    ///      displayMode is at word index 4 (byte offset 0x80). Returns true only for HTML (1).
    function _isMuriHtmlMode(address muri, address nft, uint256 tokenId) internal view returns (bool) {
        // tokenData(address,uint256) selector = 0x24ba4328
        (bool ok, bytes memory ret) = muri.staticcall(abi.encodeWithSelector(0x24ba4328, nft, tokenId));
        // Need at least 5 words (0xa0 bytes) to contain the displayMode field
        if (!ok || ret.length < 0xa0) return false;
        uint256 mode;
        assembly {
            // ret starts at ret+0x20 (skip length prefix), displayMode is at word 4 (offset 0x80)
            mode := mload(add(ret, 0xa0))
        }
        return mode == 1; // DisplayMode.HTML = 1
    }

    /// @dev A Season 4 token's static video. MURI's record holds the video (its thumbnail is
    ///      the still): its page in HTML mode, else the selected link, by MURI's own rule. Before
    ///      the record exists, the CDN address derived from the date.
    function _resolveSeason4VideoUrl(uint256 tokenId) internal view returns (string memory) {
        IMURIProtocol muri = IMURIProtocol(IPanorama(panorama).muriProtocol());
        if (address(muri).code.length > 0) {
            try muri.getArtwork(panorama, tokenId) returns (IMURIProtocol.Artwork memory art) {
                uint256 links = art.artistUris.length;
                if (links > 0 && art.isAnimationUri) {
                    if (_isMuriHtmlMode(address(muri), panorama, tokenId)) {
                        try muri.renderHTML(panorama, tokenId) returns (string memory htmlUri) {
                            return htmlUri;
                            // solhint-disable-next-line no-empty-blocks
                        } catch { }
                    }
                    return art.artistUris[art.selectedArtistUriIndex < links ? art.selectedArtistUriIndex : 0];
                }
                // solhint-disable-next-line no-empty-blocks
            } catch { }
        }
        return _cdnUrl(IPanoramaStorage(IPanorama(panorama).storageContract()), tokenId, "video_", ".mp4");
    }

    /// @dev A tableau's file on the CDN, derived from its date: `{cdnBase}{name}{date}{ext}`,
    ///      with "updated_" after the name once the next day has joined it. "" without a CDN
    ///      base or a date.
    function _cdnUrl(
        IPanoramaStorage store,
        uint256 tokenId,
        string memory name,
        string memory ext
    ) internal view returns (string memory) {
        IPanoramaStorage.TableauData memory d = store.getTableauData(tokenId);
        string memory cdn = store.cdnBase();
        if (bytes(cdn).length == 0 || d.timestamp == 0) return "";
        string memory updated = tokenId < store.entryCount() ? "updated_" : "";
        return string.concat(cdn, name, updated, _formatDate(d.timestamp), ext);
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 METADATA
    //////////////////////////////////////////////////////////////*/

    /// @dev The JSON is written by PanoramaRendererV5Html, which writes the newest tableau's still
    ///      in place when it is on-chain and fits, else uses its address resolved here.
    function tokenURI() external view override returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        uint256 count = store.entryCount();
        bytes memory image;
        if (count > 0) image = bytes(resolveTableauOffchainImageUrl(count).escapeJSON());
        _returnFromHtml(
            abi.encodeWithSelector(PanoramaRendererV5Html.panoramaJson.selector, image, panorama, season4Storage)
        );
    }

    function renderPanoramaHtml() public view returns (string memory) {
        _returnFromHtml(abi.encodeWithSelector(PanoramaRendererV5Html.panoramaHtml.selector, panorama));
    }

    /// @dev Calls the linked PanoramaRendererV5Html and returns its answer as this call's own,
    ///      without copying a page of a megabyte or more again.
    function _returnFromHtml(bytes memory data) internal view virtual {
        address html = address(PanoramaRendererV5Html);
        assembly ("memory-safe") {
            let ok := staticcall(gas(), html, add(data, 0x20), mload(data), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if iszero(ok) { revert(0, returndatasize()) }
            return(0, returndatasize())
        }
    }

    /*//////////////////////////////////////////////////////////////
                           ERC721 METADATA
    //////////////////////////////////////////////////////////////*/

    function tokenURI(uint256 tokenId) external view override returns (string memory) {
        return _buildErc721Metadata(tokenId);
    }

    function _buildErc721Metadata(uint256 tokenId) internal view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        bool isRevealed = tokenId <= store.entryCount();

        if (!isRevealed) {
            return _buildUnrevealedMetadata(tokenId, store);
        }

        IPanoramaStorage.TableauData memory d = store.getTableauData(tokenId);
        DynamicBufferLib.DynamicBuffer memory buf;

        // Name
        buf.p('{"name":"');
        if (bytes(d.name).length > 0) {
            buf.p(bytes(d.name.escapeJSON()));
        } else {
            buf.p("Panorama Tableau #");
            buf.p(bytes(tokenId.toString()));
        }

        // Description
        _appendDescription(buf, d);

        // Image. A still uploaded on-chain is written in by PanoramaRendererV5Html where it lands:
        // the JSON so far is set aside as `beforeStill` and the rest written after it.
        buf.p('","image":"');
        bytes memory beforeStill;
        if (store.isFullyUploaded(tokenId)) {
            beforeStill = buf.data;
            DynamicBufferLib.DynamicBuffer memory afterStill;
            buf = afterStill;
        } else {
            buf.p(bytes(resolveTableauImageUrl(tokenId).escapeJSON()));
        }

        buf.p('","external_url":"');
        buf.p(bytes(store.externalUrl().escapeJSON()));
        buf.p("/tableau/");
        buf.p(bytes(tokenId.toString()));

        // Season 4: the holder's dynamic scene, built in one buffer by PanoramaRendererV5Html.
        if (_showsDynamicScene(tokenId)) {
            buf.p('","animation_url":"');
            _returnDynamicScene(beforeStill, buf.data, d, store, tokenId);
        }

        // Animation URL from MURI Protocol (skip when image is fully on-chain)
        _appendAnimationUrl(buf, store, tokenId);

        // Attributes
        _appendAttributes(buf, d, store, tokenId);
        buf.p("]");

        // Every generation step, when the workflow ledger has them
        string memory workflows = _ledgerWorkflows(tokenId);
        if (bytes(workflows).length > 0) {
            buf.p(',"workflows":');
            buf.p(bytes(workflows));
        }
        buf.p("}");

        if (beforeStill.length > 0) {
            _returnFromHtml(
                abi.encodeWithSelector(
                    PanoramaRendererV5Html.stillJson.selector, beforeStill, buf.data, panorama, tokenId
                )
            );
        }
        return string.concat("data:application/json;base64,", Base64.encode(bytes(string(buf.data))));
    }

    /// @dev Ends the call with the token's metadata, its dynamic scene as `animation_url`.
    function _returnDynamicScene(
        bytes memory beforeStill,
        bytes memory head,
        IPanoramaStorage.TableauData memory d,
        IPanoramaStorage store,
        uint256 tokenId
    ) internal view {
        DynamicBufferLib.DynamicBuffer memory tail;
        _appendAttributes(tail, d, store, tokenId);
        tail.p("]");
        string memory steps = _ledgerWorkflows(tokenId);
        if (bytes(steps).length > 0) {
            tail.p(',"workflows":');
            tail.p(bytes(steps));
        }
        tail.p("}");
        _returnFromHtml(
            abi.encodeWithSelector(
                PanoramaRendererV5Html.dynamicSceneJson.selector,
                beforeStill,
                head,
                tail.data,
                season4Storage,
                tokenId,
                bytes(_cdnUrl(store, tokenId, "daydata_", ".bin"))
            )
        );
    }

    function _buildUnrevealedMetadata(
        uint256 tokenId,
        IPanoramaStorage store
    ) internal view virtual returns (string memory) {
        DynamicBufferLib.DynamicBuffer memory buf;
        buf.p('{"name":"Panorama Tableau #');
        buf.p(bytes(tokenId.toString()));
        buf.p('","description":"This edition has not yet been revealed.');
        buf.p('","image":"');
        if (bytes(prerevealBaseUrl).length > 0) {
            buf.p(bytes(prerevealBaseUrl.escapeJSON()));
            buf.p(bytes(tokenId.toString()));
            buf.p(".webp");
        }
        buf.p('","external_url":"');
        buf.p(bytes(store.externalUrl().escapeJSON()));
        buf.p("/tableau/");
        buf.p(bytes(tokenId.toString()));
        buf.p('","attributes":[');
        buf.p('{"trait_type":"Season","value":"');
        buf.p(bytes(_seasonLabel(tokenId, 0)));
        buf.p('"}');
        _appendArtist(buf, tokenId);
        _appendTechnology(buf, tokenId);
        _appendSeason3(buf, tokenId);
        _appendLead(buf, tokenId);
        buf.p(',{"trait_type":"Reveal Date","value":"');
        uint256 revealTs = uint256(store.startTimestamp()) + (tokenId - 1) * 86_400;
        // forge-lint: disable-next-line(unsafe-typecast)
        buf.p(bytes(_formatDate(uint40(revealTs))));
        buf.p('"}');
        buf.p("]}");
        return string.concat("data:application/json;base64,", Base64.encode(bytes(string(buf.data))));
    }

    function _appendDescription(
        DynamicBufferLib.DynamicBuffer memory buf,
        IPanoramaStorage.TableauData memory d
    ) internal pure {
        buf.p('","description":"');
        if (bytes(d.description).length > 0) {
            buf.p(bytes(d.description.escapeJSON()));
            return;
        }
        buf.p("This segment of Panorama is generated in ");
        buf.p(bytes(_formatDateLong(d.timestamp)));
        buf.p(" with $PANO coin price of $");
        buf.p(bytes(_formatPrice(d.price)));
        buf.p(" which represents a ");
        int256 bps = int256(d.changeBps);
        if (bps == 0) {
            buf.p("no change");
        } else if (bps > 0) {
            // forge-lint: disable-next-line(unsafe-typecast)
            buf.p(bytes(_formatBps(uint256(bps))));
            buf.p(" increase");
        } else {
            // forge-lint: disable-next-line(unsafe-typecast)
            buf.p(bytes(_formatBps(uint256(-bps))));
            buf.p(" drop");
        }
        buf.p(".\\n\\nThe generated prompt to create the tableau:\\n");
        buf.p(bytes(d.prompt.escapeJSON()));
    }

    function _appendAnimationUrl(
        DynamicBufferLib.DynamicBuffer memory buf,
        IPanoramaStorage store,
        uint256 tokenId
    ) internal view {
        // A Season 4 token's animation is its video, also once its still is on-chain.
        if (!_isSeason4(tokenId) && store.isFullyUploaded(tokenId)) return;
        string memory animUrl = resolveTableauAnimationUrl(tokenId);
        if (bytes(animUrl).length > 0) {
            buf.p('","animation_url":"');
            buf.p(bytes(animUrl.escapeJSON()));
        }
    }

    function _appendAttributes(
        DynamicBufferLib.DynamicBuffer memory buf,
        IPanoramaStorage.TableauData memory d,
        IPanoramaStorage store,
        uint256 tokenId
    ) internal view {
        buf.p('","attributes":[');

        buf.p('{"trait_type":"Mood","value":"');
        buf.p(bytes(_moodLabel(d.moodIndex)));
        buf.p('"},');

        buf.p('{"trait_type":"Price","value":"');
        buf.p(bytes(_formatPrice(d.price)));
        buf.p('"},');

        buf.p('{"trait_type":"Price Change","value":"');
        buf.p(bytes(_formatChange(int256(d.changeBps))));
        buf.p('"},');

        buf.p('{"trait_type":"Season","value":"');
        buf.p(bytes(_seasonLabel(tokenId, d.season)));
        buf.p('"}');
        _appendArtist(buf, tokenId);

        _appendTechnology(buf, tokenId);
        _appendSeason3(buf, tokenId);
        _appendLead(buf, tokenId);
        _appendSeason4Traits(buf, tokenId);

        if (_isOnChain(store, tokenId)) {
            buf.p(',{"trait_type":"Status","value":"On-chain"}');
        }

        buf.p(',{"trait_type":"Reveal Date","value":"');
        if (d.timestamp > 0) {
            buf.p(bytes(_formatDate(d.timestamp)));
        } else {
            uint256 revealTs = uint256(store.startTimestamp()) + (tokenId - 1) * 86_400;
            // forge-lint: disable-next-line(unsafe-typecast)
            buf.p(bytes(_formatDate(uint40(revealTs))));
        }
        buf.p('"}');
    }

    /// @dev The ledger's `renderWorkflows` output for a token, or "" when no ledger is set
    ///      or the call reverts. An address without code counts as unset: its empty return
    ///      data would fail to decode outside the catch.
    function _ledgerWorkflows(uint256 tokenId) internal view returns (string memory) {
        address ledger = workflowLedger;
        if (ledger.code.length == 0) return "";
        try IPanoramaWorkflowLedger(ledger).renderWorkflows(tokenId) returns (string memory out) {
            return out;
        } catch {
            return "";
        }
    }

    /// @dev Appends a ",{Technology}" attribute for Season 2 tokens; no-op otherwise.
    function _appendTechnology(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal pure {
        string memory tech = technologyName(tokenId);
        if (bytes(tech).length == 0) return;
        buf.p(',{"trait_type":"Technology","value":"');
        buf.p(bytes(tech));
        buf.p('"}');
    }

    /*//////////////////////////////////////////////////////////////
                        SEASONS & TECHNOLOGIES
    //////////////////////////////////////////////////////////////*/

    /// @notice The Season 2 technology depicted by a token, or "" outside #91-#180.
    ///         Token #91 = "Stone tools" ... token #180 = "Artificial intelligence".
    function technologyName(uint256 tokenId) public pure returns (string memory) {
        if (tokenId <= SEASON_1_END || tokenId > SEASON_2_END) return "";
        return _segment(SEASON_2_TECHNOLOGIES, tokenId - SEASON_1_END - 1);
    }

    /// @notice The artist named for a token's season: "Yigit Duman" (#1-#90), "DeltaSauce &
    ///         Yigit Duman" (#91-#180), "Pale Kirill & Yigit Duman" (#181-#210), "Dav & Yigit
    ///         Duman" (#211-#270), or "" beyond #270.
    function artistName(uint256 tokenId) public pure returns (string memory) {
        if (tokenId == 0 || tokenId > SEASON_4_END) return "";
        if (tokenId <= SEASON_1_END) return _segment(SEASON_ARTISTS, 0);
        if (tokenId <= SEASON_2_END) return _segment(SEASON_ARTISTS, 1);
        if (tokenId <= SEASON_3_END) return _segment(SEASON_ARTISTS, 2);
        return _segment(SEASON_ARTISTS, 3);
    }

    /// @notice The stranger who leads a Season 4 day: "Newcomer" for #211-#220 ... "Young One"
    ///         for #261-#269, or "" for #270 (day 60 has no lead) and outside Season 4.
    function leadName(uint256 tokenId) public pure returns (string memory) {
        if (!_isSeason4(tokenId) || tokenId == SEASON_4_END) return "";
        return _segment(SEASON_4_LEADS, (tokenId - SEASON_3_END - 1) / 10);
    }

    /// @dev Appends ',{"trait_type":"Lead",...}' for a Season 4 day with a lead; no-op otherwise.
    function _appendLead(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal pure {
        string memory lead = leadName(tokenId);
        if (bytes(lead).length == 0) return;
        buf.p(',{"trait_type":"Lead","value":"');
        buf.p(bytes(lead));
        buf.p('"}');
    }

    /// @dev Appends a revealed Season 4 token's traits from the storage, then the music
    ///      controller's (IPanoramaSeason4Music), read and checked by the library within 8M gas;
    ///      a missing storage adds nothing.
    function _appendSeason4Traits(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal view virtual {
        if (!_isSeason4(tokenId) || season4Storage.code.length == 0) return;
        (bool ok, bytes memory ret) = address(PanoramaRendererV5Html).staticcall{ gas: 8_000_000 }(
            abi.encodeWithSelector(PanoramaRendererV5Html.season4Traits.selector, season4Storage, tokenId)
        );
        if (ok) buf.p(abi.decode(ret, (bytes)));
    }

    function _isSeason4(uint256 tokenId) internal pure returns (bool) {
        return tokenId > SEASON_3_END && tokenId <= SEASON_4_END;
    }

    /// @dev True when a revealed Season 4 token's holder chose the dynamic scene and it can be
    ///      built. Anything missing or failing means the static video.
    function _showsDynamicScene(uint256 tokenId) internal view virtual returns (bool) {
        address s4 = season4Storage;
        if (!_isSeason4(tokenId) || s4.code.length == 0) return false;
        try IPanoramaSeason4Storage(s4).viewOf(tokenId) returns (IPanoramaSeason4Storage.View v) {
            if (v != IPanoramaSeason4Storage.View.DynamicScene) return false;
        } catch {
            return false;
        }
        try IPanoramaSeason4Storage(s4).hasSceneRenderer() returns (bool has) {
            return has;
        } catch {
            return false;
        }
    }

    /// @dev The artwork is on-chain: a still for Seasons 1-3; for Season 4 the dynamic scene (its
    ///      scene renderer stored and the day's data uploaded), whose still is only its thumbnail.
    function _isOnChain(IPanoramaStorage store, uint256 tokenId) internal view virtual returns (bool) {
        if (!_isSeason4(tokenId)) return store.isFullyUploaded(tokenId);
        address s4 = season4Storage;
        if (s4.code.length == 0) return false;
        try IPanoramaSeason4Storage(s4).isDayDataFullyUploaded(tokenId) returns (bool uploaded) {
            return uploaded && IPanoramaSeason4Storage(s4).hasSceneRenderer();
        } catch {
            return false;
        }
    }

    /// @dev Appends ',{"trait_type":"Artist",...}' when the token's season has one; no-op otherwise.
    function _appendArtist(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal pure {
        string memory artist = artistName(tokenId);
        if (bytes(artist).length == 0) return;
        buf.p(',{"trait_type":"Artist","value":"');
        buf.p(bytes(artist));
        buf.p('"}');
    }

    /// @notice Pale Kirill's theme for a Season 3 day, or "" outside #181-#210.
    ///         Token #181 = "Creator" ... token #210 = "Love".
    function themeName(uint256 tokenId) public pure returns (string memory) {
        if (!_isSeason3(tokenId)) return "";
        return _segment(SEASON_3_THEMES, tokenId - SEASON_2_END - 1);
    }

    /// @notice The zone a Season 3 day belongs to ("Interface" for #181-#185 ... "Abstract"
    ///         for #206-#210), or "" outside #181-#210.
    function zoneName(uint256 tokenId) public pure returns (string memory) {
        if (!_isSeason3(tokenId)) return "";
        return _segment(SEASON_3_ZONES, (tokenId - SEASON_2_END - 1) / SEASON_3_DAYS_PER_ZONE);
    }

    /// @notice What a Season 3 day's theme is ("Figure", "Place", "Event", "Object" or
    ///         "Feeling", by its position in its zone), or "" outside #181-#210.
    function kindName(uint256 tokenId) public pure returns (string memory) {
        if (!_isSeason3(tokenId)) return "";
        return _segment(SEASON_3_KINDS, (tokenId - SEASON_2_END - 1) % SEASON_3_DAYS_PER_ZONE);
    }

    /// @dev Appends ",{Theme},{Zone},{Kind}" attributes for Season 3 tokens; no-op otherwise.
    function _appendSeason3(DynamicBufferLib.DynamicBuffer memory buf, uint256 tokenId) internal pure {
        if (!_isSeason3(tokenId)) return;
        buf.p(',{"trait_type":"Theme","value":"');
        buf.p(bytes(themeName(tokenId)));
        buf.p('"},{"trait_type":"Zone","value":"');
        buf.p(bytes(zoneName(tokenId)));
        buf.p('"},{"trait_type":"Kind","value":"');
        buf.p(bytes(kindName(tokenId)));
        buf.p('"}');
    }

    function _isSeason3(uint256 tokenId) internal pure returns (bool) {
        return tokenId > SEASON_2_END && tokenId <= SEASON_3_END;
    }

    /// @dev The `index`-th (0-based) entry of a pipe-delimited list, or "" past its end.
    function _segment(string memory list, uint256 index) internal pure returns (string memory) {
        bytes memory packed = bytes(list);
        uint256 len = packed.length;
        uint256 seg;
        uint256 start;
        for (uint256 i; i <= len; ++i) {
            if (i == len || packed[i] == "|") {
                if (seg == index) {
                    bytes memory out = new bytes(i - start);
                    for (uint256 j; j < out.length; ++j) {
                        out[j] = packed[start + j];
                    }
                    return string(out);
                }
                ++seg;
                start = i + 1;
            }
        }
        return "";
    }

    /// @dev Season label: #1-#90 → "1", #91-#180 → "2", #181-#210 → "3". Beyond #210 the
    ///      season is not yet announced: fall back to the stored value when set, else "?"
    ///      (mirrors frontend seasonLabel()).
    function _seasonLabel(uint256 tokenId, uint8 storedSeason) internal pure returns (string memory) {
        if (tokenId <= SEASON_1_END) return "1";
        if (tokenId <= SEASON_2_END) return "2";
        if (tokenId <= SEASON_3_END) return "3";
        if (tokenId <= SEASON_4_END) return "4";
        if (storedSeason > 0) return uint256(storedSeason).toString();
        return "?";
    }

    /*//////////////////////////////////////////////////////////////
                              FORMATTING
    //////////////////////////////////////////////////////////////*/

    /// @dev Formats basis points as "X.XX%". E.g. 150 → "1.50%", 1378 → "13.78%"
    function _formatBps(uint256 absBps) internal pure returns (string memory) {
        uint256 whole = absBps / 100;
        uint256 frac = absBps % 100;
        string memory fracStr;
        if (frac < 10) {
            fracStr = string.concat("0", frac.toString());
        } else {
            fracStr = frac.toString();
        }
        return string.concat(whole.toString(), ".", fracStr, "%");
    }

    /// @dev Formats signed basis points as a human-readable percentage.
    ///      E.g. 243 → "+2.43%", -150 → "-1.50%", 0 → "0.00%"
    function _formatChange(int256 bps) internal pure returns (string memory) {
        if (bps == 0) return "0.00%";
        if (bps > 0) {
            // forge-lint: disable-next-line(unsafe-typecast)
            return string.concat("+", _formatBps(uint256(bps)));
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        return string.concat("-", _formatBps(uint256(-bps)));
    }

    /// @dev Formats a unix timestamp as "YYYY-MM-DD"
    function _formatDate(uint40 ts) internal pure returns (string memory) {
        (uint256 year, uint256 month, uint256 day) = _daysToDate(uint256(ts) / 86_400);
        string memory m = month < 10 ? string.concat("0", month.toString()) : month.toString();
        string memory dd = day < 10 ? string.concat("0", day.toString()) : day.toString();
        return string.concat(year.toString(), "-", m, "-", dd);
    }

    /// @dev Civil date from day count (days since epoch). Based on Howard Hinnant's algorithm.
    function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) {
        uint256 z = _days + 719_468;
        uint256 era = z / 146_097;
        uint256 doe = z - era * 146_097;
        uint256 yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
        year = yoe + era * 400;
        uint256 doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        uint256 mp = (5 * doy + 2) / 153;
        day = doy - (153 * mp + 2) / 5 + 1;
        month = mp < 10 ? mp + 3 : mp - 9;
        if (month <= 2) ++year;
    }

    /// @dev Formats a unix timestamp as "Month Day, Year". E.g. 1741219200 → "March 6, 2026"
    function _formatDateLong(uint40 ts) internal pure returns (string memory) {
        (uint256 year, uint256 month, uint256 day) = _daysToDate(uint256(ts) / 86_400);
        return string.concat(_monthName(month), " ", day.toString(), ", ", year.toString());
    }

    function _monthName(uint256 month) internal pure returns (string memory) {
        if (month == 0 || month > 12) return "";
        return _segment(MONTH_NAMES, month - 1);
    }

    /// @dev Formats a WAD price (18 decimals) as a human-readable decimal with up to
    ///      6 fractional digits, trailing zeros trimmed. E.g. 224300000000000000 → "0.2243",
    ///      170678334619567890 → "0.170678", 2e18 → "2"
    function _formatPrice(uint256 wad) internal pure returns (string memory) {
        uint256 whole = wad / 1e18;
        uint256 frac = (wad % 1e18) / 1e12; // truncate to 6 digits
        if (frac == 0) return whole.toString();
        // Pad fractional part with leading zeros
        bytes memory padded = new bytes(6);
        bytes memory fracBytes = bytes(frac.toString());
        uint256 padLen = 6 - fracBytes.length;
        for (uint256 i; i < 6; ++i) {
            padded[i] = i < padLen ? bytes1("0") : fracBytes[i - padLen];
        }
        // Trim trailing zeros
        uint256 keep = 6;
        while (keep > 0 && padded[keep - 1] == "0") {
            --keep;
        }
        bytes memory trimmed = new bytes(keep);
        for (uint256 i; i < keep; ++i) {
            trimmed[i] = padded[i];
        }
        return string.concat(whole.toString(), ".", string(trimmed));
    }

    function _moodLabel(uint8 moodIndex) internal pure returns (string memory) {
        if (moodIndex > 6) return "Unknown";
        return _segment(MOOD_LABELS, moodIndex);
    }
}

/// @title PanoramaRendererV5Html
/// @author Yigit Duman (@yigitduman)
/// @notice The large answers of PanoramaRendererV5: a token whose still is on-chain, a Season 4
///         token's dynamic scene, and the whole-artwork page. Linked into the renderer and called
///         by it alone; it holds no state.
///
///         These are data URIs inside data URIs: JSON in base64, holding a still in base64, or an
///         HTML page in base64 holding gzipped code and day data in base64. Built by joining
///         strings, a megabyte is copied several times, and memory costs with the square of its
///         size (a 1.27 MB still came to about a billion gas). So they are written once, into one
///         buffer of their final size: each piece is encoded where it lands (Base64InPlace),
///         padded with spaces so that its base64 joins the next piece's. The spaces fall where
///         the page ignores them (JSON and HTML whitespace, or base64 text, which `atob` reads
///         without spaces). A token's JSON with a still and nothing else is exactly what
///         PanoramaRendererV4 returned.
///
///         The scene renderer is stored as it appears in the answer (the build encodes its
///         gzip three times over, padded the same way), so it is copied, never encoded: encoding
///         333 KB three times on every call would cost about 36M gas more.
///
///         What does not fit in one answer is read by the page itself, one fragment a call, from
///         the RPC addresses PanoramaSeason4Storage keeps (a holder's for their token first, then
///         the artist's): a day's data larger than a browser opens inside a page, and in the whole
///         artwork every Season 4 day and any still the CDN does not answer for.
library PanoramaRendererV5Html {
    using LibString for uint256;
    using LibString for int256;
    using LibString for address;
    using LibString for string;
    using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;

    uint256 internal constant SEASON_4_FIRST = 211;
    uint256 internal constant SEASON_4_LAST = 270;

    /// @dev The longest page address a browser opens inside a frame (Chromium stops at 2 MiB).
    ///      A day's data goes inside its dynamic scene only while the page stays this short;
    ///      past it the page reads the uploaded data over RPC.
    uint256 internal constant MAX_PAGE_URI = 2_000_000;

    /// @dev The longest answer that keeps a call well under the 500M gas the strictest node
    ///      allows (Alchemy 550M, Tenderly 500M). Panorama copies the answer twice on its way
    ///      out, so the gas grows with the square of its size: measured, about 41M per MB plus
    ///      18.7M per MB squared, 390M at this length. A day's data goes inside its page only
    ///      while the answer stays this short.
    uint256 internal constant MAX_ANSWER = 3_600_000;

    /// @dev The same for the whole artwork, which spends about 180M gas on its entries before
    ///      any still (measured cold at #256): its newest still is its `image` only while the
    ///      answer stays this short, else MURI's or the CDN's address.
    uint256 internal constant MAX_WHOLE_ANSWER = 2_400_000;

    /// @dev The most gas the music controller gets for its traits, and the most traits kept.
    uint256 internal constant MUSIC_TRAITS_GAS = 3_000_000;
    uint256 internal constant MAX_MUSIC_TRAITS = 16;
    /// @dev The most gas `season4Traits` gives its own `musicTraits` (which gives the controller
    ///      MUSIC_TRAITS_GAS of it).
    uint256 internal constant MUSIC_CALL_GAS = 5_000_000;

    /// @dev How many times a piece is base64-encoded on its way into the answer: the token's
    ///      JSON once (and a still inside it twice), the page's HTML twice, the day data inside
    ///      the page three times. CODE is the scene renderer, already in its final form.
    uint8 internal constant CODE = 0;
    uint8 internal constant JSON = 1;
    uint8 internal constant HTML = 2;
    uint8 internal constant DATA = 3;

    /// @dev The stored scene renderer is not in its final form: its length must be a multiple of 16 (the
    ///      base64 of the base64 of whole 9-byte groups).
    error SceneRendererNotAligned();

    bytes internal constant JSON_URI = "data:application/json;base64,";
    bytes internal constant HTML_URI = "data:text/html;base64,";
    bytes internal constant STILL_URI = "data:image/webp;base64,";
    bytes internal constant ANIMATION = '","animation_url":"';

    /// @dev `text`, then (JSON only) the bytes behind `pointers` as a base64 still, then `rest`.
    struct Piece {
        uint8 depth;
        bytes text;
        address[] pointers;
        bytes rest;
    }

    /*//////////////////////////////////////////////////////////////
                                 STILL
    //////////////////////////////////////////////////////////////*/

    /// @notice A token's metadata with its uploaded still as `image`, byte for byte what
    ///         PanoramaRendererV4 returned.
    /// @param head The token's JSON up to the opening quote of `image`'s value.
    /// @param rest The rest of the JSON, from the quote that closes it.
    function stillJson(
        bytes calldata head,
        bytes calldata rest,
        address panorama,
        uint256 tokenId
    ) external view returns (string memory) {
        Piece[] memory pieces = new Piece[](1);
        pieces[0] = _jsonStill(head, _stillPointers(panorama, tokenId), rest);
        _returnJsonUri(pieces);
    }

    /*//////////////////////////////////////////////////////////////
                                 TRAITS
    //////////////////////////////////////////////////////////////*/

    /// @notice A Season 4 token's traits as JSON attributes, each starting with a comma: the
    ///         ones the artists set in the storage (`getTokenTraits`), then the music
    ///         controller's (`musicTraits`). The music's are read in a call of their own, so a
    ///         missing, reverting or malformed controller drops only them.
    function season4Traits(address season4Storage, uint256 tokenId) external view returns (bytes memory out) {
        (string[] memory names, string[] memory values) =
            IPanoramaSeason4Storage(season4Storage).getTokenTraits(tokenId);
        out = _traits(names, values);
        (bool ok, bytes memory ret) = address(this).staticcall{ gas: MUSIC_CALL_GAS }(
            abi.encodeWithSelector(PanoramaRendererV5Html.musicTraits.selector, season4Storage, tokenId)
        );
        if (ok) out = bytes.concat(out, abi.decode(ret, (bytes)));
    }

    /// @notice The music controller's traits for a Season 4 token as JSON attributes, each
    ///         starting with a comma; empty without a controller. The first MAX_MUSIC_TRAITS
    ///         pairs are kept, leaving out a pair whose name is empty or over 64 bytes or whose
    ///         value is over 128. Reverts when the controller reverts or answers malformed
    ///         (`season4Traits` then adds none of the music's).
    function musicTraits(address season4Storage, uint256 tokenId) external view returns (bytes memory out) {
        address music = IPanoramaSeason4Storage(season4Storage).musicController();
        if (music.code.length == 0) return out;
        (string[] memory names, string[] memory values) =
            IPanoramaSeason4Music(music).musicTraits{ gas: MUSIC_TRAITS_GAS }(tokenId);
        out = _traits(names, values);
    }

    /// @dev The first MAX_MUSIC_TRAITS pairs as JSON attributes, leaving out a pair whose name
    ///      is empty or over 64 bytes or whose value is over 128.
    function _traits(string[] memory names, string[] memory values) private pure returns (bytes memory out) {
        uint256 n = names.length < values.length ? names.length : values.length;
        if (n > MAX_MUSIC_TRAITS) n = MAX_MUSIC_TRAITS;
        for (uint256 i; i < n; ++i) {
            uint256 k = bytes(names[i]).length;
            if (k == 0 || k > 64 || bytes(values[i]).length > 128) continue;
            out = abi.encodePacked(
                out, ',{"trait_type":"', names[i].escapeJSON(), '","value":"', values[i].escapeJSON(), '"}'
            );
        }
    }

    /*//////////////////////////////////////////////////////////////
                              DYNAMIC SCENE
    //////////////////////////////////////////////////////////////*/

    /// @notice A Season 4 token's metadata with its dynamic scene as `animation_url`.
    /// @param beforeStill With the still on-chain, the JSON up to the opening quote of `image`'s
    ///        value; else empty.
    /// @param head The JSON (after the still, when there is one) up to the opening quote of
    ///        `animation_url`'s value.
    /// @param tail The rest of the JSON, from the quote that closes it.
    /// @param dayDataUrl The day data's CDN address.
    function dynamicSceneJson(
        bytes calldata beforeStill,
        bytes calldata head,
        bytes calldata tail,
        address season4Storage,
        uint256 tokenId,
        bytes calldata dayDataUrl
    ) external view returns (string memory) {
        IPanoramaSeason4Storage s4 = IPanoramaSeason4Storage(season4Storage);
        bool uploaded = s4.isDayDataFullyUploaded(tokenId);

        Piece[] memory pieces = new Piece[](7);
        pieces[0] = beforeStill.length > 0
            ? _jsonStill(beforeStill, _stillPointers(s4.panorama(), tokenId), abi.encodePacked(head, HTML_URI))
            : _json(abi.encodePacked(head, HTML_URI));
        pieces[1] = _html(_sceneSettings(s4, tokenId, uploaded, dayDataUrl));
        pieces[2] = _code(s4.getSceneRendererFragmentPointers());
        pieces[3] = _html('","data":"');
        if (uploaded) pieces[4] = _data(s4.getDayDataFragmentPointers(tokenId));
        pieces[5] = _html(abi.encodePacked('"}', s4.getSceneRendererHtmlSuffixData()));
        pieces[6] = _json(tail);
        _fitDynamicScene(pieces, beforeStill, head, tokenId);
    }

    /// @dev Ends the call with the dynamic scene's answer, fitted. The uploaded day data stays inside
    ///      the page while the page is short enough for a browser to open; otherwise the page reads
    ///      it over RPC, then from `url`. The page is the artwork and the still its thumbnail: when
    ///      the two do not fit in one answer, the still yields first (its MURI or CDN address in
    ///      `image`), then the day (read over RPC).
    function _fitDynamicScene(
        Piece[] memory pieces,
        bytes calldata beforeStill,
        bytes calldata head,
        uint256 tokenId
    ) private view {
        Piece memory still = pieces[0];
        if (pieces[4].pointers.length > 0) {
            uint256 page;
            for (uint256 i = 1; i < 6; ++i) {
                page += _encodedLength(pieces[i], false);
            }
            if (HTML_URI.length + (page * 3) / 4 > MAX_PAGE_URI) delete pieces[4];
        }
        bool hasStill = beforeStill.length > 0;
        if (hasStill && _answerLength(pieces) > MAX_ANSWER) {
            pieces[0] = _json(_imageByAddress(beforeStill, head, tokenId));
        }
        if (_answerLength(pieces) > MAX_ANSWER) {
            delete pieces[4];
            pieces[0] = still;
            if (hasStill && _answerLength(pieces) > MAX_ANSWER) {
                pieces[0] = _json(_imageByAddress(beforeStill, head, tokenId));
            }
        }
        _returnJsonUri(pieces);
    }

    /// @dev The token's JSON head with its image as an address (asked of the renderer that called),
    ///      for when its still does not fit.
    function _imageByAddress(
        bytes calldata beforeStill,
        bytes calldata head,
        uint256 tokenId
    ) internal view returns (bytes memory) {
        string memory image = PanoramaRendererV5(msg.sender).resolveTableauOffchainImageUrl(tokenId);
        return abi.encodePacked(beforeStill, image.escapeJSON(), head, HTML_URI);
    }

    /// @dev The template's prefix, then the day's settings, read by the page as `S4`, up to the
    ///      opening quote of `code`'s value.
    function _sceneSettings(
        IPanoramaSeason4Storage s4,
        uint256 tokenId,
        bool uploaded,
        bytes calldata dayDataUrl
    ) internal view returns (bytes memory) {
        DynamicBufferLib.DynamicBuffer memory open;
        open.p(s4.getSceneRendererHtmlPrefixData());
        open.p('{"token":');
        open.p(bytes(tokenId.toString()));
        open.p(',"day":');
        open.p(bytes((tokenId - SEASON_4_FIRST + 1).toString()));
        open.p(',"url":"');
        open.p(bytes(string(dayDataUrl).escapeJSON()));
        open.p('","fragmentSize":');
        open.p(bytes(s4.FRAGMENT_SIZE().toString()));
        open.p(',"hashes":');
        _appendHashes(open, s4.getDayDataFragmentHashes(tokenId));
        open.p(',"uploaded":');
        open.p(uploaded ? bytes("true") : bytes("false"));
        open.p(',"chain":"');
        open.p(bytes(address(s4).toHexStringChecksummed()));
        open.p('","rpc":[');
        _appendUrls(open, s4.getTokenRpcUrls(tokenId), false);
        _appendUrls(open, s4.getRpcUrls(), s4.getTokenRpcUrls(tokenId).length > 0);
        open.p('],"code":"');
        return open.data;
    }

    /*//////////////////////////////////////////////////////////////
                             WHOLE ARTWORK
    //////////////////////////////////////////////////////////////*/

    /// @notice The ERC-20 metadata: the whole artwork. Before Season 4 (or without its code)
    ///         exactly as PanoramaRendererV4 built it; after, the page also carries the scene
    ///         renderer, the RPC addresses, and with each entry what can be read on-chain.
    /// @param image The newest tableau's image from MURI or the CDN, escaped, used unless its
    ///        still is on-chain and fits.
    function panoramaJson(
        bytes calldata image,
        address panorama,
        address season4Storage
    ) external view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        uint256 count = store.entryCount();
        address[] memory still;
        if (count > 0 && store.isFullyUploaded(count)) still = store.getFragmentPointers(count);

        DynamicBufferLib.DynamicBuffer memory head;
        head.p('{"name":"Panorama","description":"');
        head.p(bytes(store.erc20TokenDescription().escapeJSON()));
        head.p('","external_url":"');
        head.p(bytes(store.externalUrl().escapeJSON()));
        head.p('","image":"');
        bytes memory tail =
            abi.encodePacked('","attributes":[{"trait_type":"Tableau Length","value":"', count.toString(), '"}]}');

        if (
            count < SEASON_4_FIRST || season4Storage.code.length == 0
                || !IPanoramaSeason4Storage(season4Storage).hasSceneRenderer()
        ) {
            return _wholeStills(
                head.data, image, abi.encodePacked(ANIMATION, _panoramaHtmlUri(store, panorama, count), tail), still
            );
        }
        _wholeDynamic(head.data, image, tail, still, panorama, IPanoramaSeason4Storage(season4Storage));
    }

    /// @dev The whole artwork with Season 4 drawn as dynamic scenes: the page also carries the scene renderer
    ///      and the RPC addresses. Ends the call.
    function _wholeDynamic(
        bytes memory head,
        bytes memory image,
        bytes memory tail,
        address[] memory still,
        address panorama,
        IPanoramaSeason4Storage s4
    ) private view {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        DynamicBufferLib.DynamicBuffer memory html = _panoramaHtmlStart(store, panorama, store.entryCount(), s4);
        html.p(";var RPC=[");
        _appendUrls(html, s4.getRpcUrls(), false);
        html.p('],S4A="');
        html.p(bytes(address(s4).toHexStringChecksummed()));
        html.p('",S4C="');

        Piece[] memory pieces = new Piece[](5);
        pieces[0] = _jsonStill(head, still, abi.encodePacked(ANIMATION, HTML_URI));
        pieces[1] = _html(html.data);
        pieces[2] = _code(s4.getSceneRendererFragmentPointers());
        pieces[3] = _html(abi.encodePacked('"', store.getPanoramaHtmlSuffixData()));
        pieces[4] = _json(tail);
        if (still.length == 0 || _answerLength(pieces) > MAX_WHOLE_ANSWER) {
            pieces[0] = _json(abi.encodePacked(head, image, ANIMATION, HTML_URI));
        }
        _returnJsonUri(pieces);
    }

    /// @dev The whole artwork before Season 4 lives: V4's answer, its newest still in place when
    ///      on-chain and short enough.
    function _wholeStills(
        bytes memory head,
        bytes memory image,
        bytes memory rest,
        address[] memory still
    ) private view returns (string memory) {
        Piece[] memory one = new Piece[](1);
        one[0] = _jsonStill(head, still, rest);
        if (still.length == 0 || _answerLength(one) > MAX_WHOLE_ANSWER) {
            return string.concat(string(JSON_URI), Base64.encode(abi.encodePacked(head, image, rest)));
        }
        _returnJsonUri(one);
    }

    /// @notice The whole-artwork page of stills, as PanoramaRendererV4's `renderPanoramaHtml`.
    function panoramaHtml(address panorama) external view returns (string memory) {
        IPanoramaStorage store = IPanoramaStorage(IPanorama(panorama).storageContract());
        return string(_panoramaHtmlUri(store, panorama, store.entryCount()));
    }

    function _panoramaHtmlUri(
        IPanoramaStorage store,
        address panorama,
        uint256 count
    ) internal view returns (bytes memory) {
        DynamicBufferLib.DynamicBuffer memory html =
            _panoramaHtmlStart(store, panorama, count, IPanoramaSeason4Storage(address(0)));
        html.p(store.getPanoramaHtmlSuffixData());
        return abi.encodePacked(HTML_URI, Base64.encode(html.data, false, false));
    }

    /// @dev The viewer template's prefix, the tableau data and the three variables, as V4 wrote
    ///      them. With a Season 4 storage, an entry whose still is on-chain also carries its
    ///      fragment count ("o") and the keccak256 of its fragment hashes ("r"), and a Season 4
    ///      entry its day data hashes ("h") and whether they are uploaded ("u").
    function _panoramaHtmlStart(
        IPanoramaStorage store,
        address panorama,
        uint256 count,
        IPanoramaSeason4Storage s4
    ) internal view returns (DynamicBufferLib.DynamicBuffer memory buf) {
        buf.reserve(65_536 + count * 1024);
        buf.p(store.getPanoramaHtmlPrefixData());
        buf.p("[");
        for (uint256 i = 1; i <= count; ++i) {
            if (i > 1) buf.p(",");
            _appendHtmlTableauEntry(buf, store, s4, i);
        }
        buf.p("]");
        buf.p(";var START_TS=");
        buf.p(bytes(uint256(store.startTimestamp()).toString()));
        buf.p(";var NFT_ADDR=\"");
        buf.p(bytes(panorama.toHexStringChecksummed()));
        buf.p("\";var ERC20_ADDR=\"");
        buf.p(bytes(IPanorama(panorama).panoramaERC20().toHexStringChecksummed()));
        buf.p("\"");
    }

    function _appendHtmlTableauEntry(
        DynamicBufferLib.DynamicBuffer memory buf,
        IPanoramaStorage store,
        IPanoramaSeason4Storage s4,
        uint256 tokenId
    ) internal view {
        IPanoramaStorage.TableauData memory d = store.getTableauData(tokenId);

        buf.p('{"p":');
        buf.p(bytes(uint256(d.price).toString()));
        buf.p(',"c":');
        buf.p(bytes(int256(d.changeBps).toString()));
        buf.p(',"t":');
        buf.p(bytes(uint256(d.timestamp).toString()));
        buf.p(',"m":');
        buf.p(bytes(uint256(d.moodIndex).toString()));

        if (bytes(d.name).length > 0) {
            buf.p(',"n":"');
            buf.p(bytes(d.name.escapeJSON()));
            buf.p('"');
        }
        if (bytes(d.prompt).length > 0) {
            buf.p(',"pr":"');
            buf.p(bytes(d.prompt.escapeJSON()));
            buf.p('"');
        }
        if (d.seed != 0) {
            buf.p(',"s":');
            buf.p(bytes(d.seed.toString()));
        }
        if (address(s4) != address(0)) {
            // A still on-chain: the viewer reads its fragments over RPC when the CDN fails, and keeps them
            // only when the keccak256 of their hashes one after another is "r".
            uint256 fragments = d.imageFragmentHashes.length;
            if (fragments > 0 && d.uploadedFragmentCount == fragments) {
                buf.p(',"o":');
                buf.p(bytes(fragments.toString()));
                buf.p(',"r":"');
                buf.p(bytes(uint256(keccak256(abi.encodePacked(d.imageFragmentHashes))).toHexString(32)));
                buf.p('"');
            }
            // A Season 4 day drawn as a dynamic scene: the viewer reads its day data over RPC once uploaded, else
            // from the CDN, and checks it against these.
            if (tokenId >= SEASON_4_FIRST && tokenId <= SEASON_4_LAST) {
                buf.p(',"h":');
                _appendHashes(buf, s4.getDayDataFragmentHashes(tokenId));
                if (s4.isDayDataFullyUploaded(tokenId)) buf.p(',"u":1');
            }
        }

        buf.p("}");
    }

    /// @dev Appends `["0x…",…]`: a day's fragment hashes, empty before the day is final.
    function _appendHashes(DynamicBufferLib.DynamicBuffer memory buf, bytes32[] memory hashes) internal pure {
        buf.p("[");
        for (uint256 i; i < hashes.length; ++i) {
            buf.p(i == 0 ? bytes('"') : bytes(',"'));
            buf.p(bytes(uint256(hashes[i]).toHexString(32)));
            buf.p('"');
        }
        buf.p("]");
    }

    /// @dev Appends `"a","b"`, after a comma when `more`. The storage checked each address
    ///      carries nothing to escape.
    function _appendUrls(DynamicBufferLib.DynamicBuffer memory buf, string[] memory urls, bool more) internal pure {
        for (uint256 i; i < urls.length; ++i) {
            buf.p(more || i > 0 ? bytes(',"') : bytes('"'));
            buf.p(bytes(urls[i]));
            buf.p('"');
        }
    }

    /// @dev A tableau's still fragments in PanoramaStorage.
    function _stillPointers(address panorama, uint256 tokenId) internal view returns (address[] memory) {
        return IPanoramaStorage(IPanorama(panorama).storageContract()).getFragmentPointers(tokenId);
    }

    /*//////////////////////////////////////////////////////////////
                              ONE BUFFER
    //////////////////////////////////////////////////////////////*/

    function _json(bytes memory text) private pure returns (Piece memory piece) {
        piece.depth = JSON;
        piece.text = text;
    }

    /// @dev JSON with a still in it: `text` (ending where the image's value opens), the still's
    ///      data URI, then `rest`.
    function _jsonStill(
        bytes memory text,
        address[] memory pointers,
        bytes memory rest
    ) private pure returns (Piece memory piece) {
        piece.depth = JSON;
        piece.text = abi.encodePacked(text, STILL_URI);
        piece.pointers = pointers;
        piece.rest = rest;
    }

    function _html(bytes memory text) private pure returns (Piece memory piece) {
        piece.depth = HTML;
        piece.text = text;
    }

    function _data(address[] memory pointers) private pure returns (Piece memory piece) {
        piece.depth = DATA;
        piece.pointers = pointers;
    }

    function _code(address[] memory pointers) private pure returns (Piece memory piece) {
        piece.depth = CODE;
        piece.pointers = pointers;
    }

    /// @dev Returns `data:application/json;base64,` followed by the pieces, each encoded `depth`
    ///      times where it lands. JSON pieces come first and last; the first is padded with
    ///      leading spaces to whole base64 groups, HTML and DATA pieces with trailing spaces.
    ///      Ends the call.
    function _returnJsonUri(Piece[] memory pieces) private view {
        uint256 total = _answerLength(pieces);

        uint256 ptr;
        assembly ("memory-safe") {
            ptr := mload(0x40)
            mstore(0x40, add(ptr, add(total, 0x80)))
        }
        uint256 table = Base64InPlace.newTable();
        uint256 at = _put(ptr + 0x40, JSON_URI);
        for (uint256 i; i < pieces.length; ++i) {
            at = _writePiece(table, at, pieces[i], i + 1 == pieces.length);
        }

        assembly ("memory-safe") {
            mstore(add(add(ptr, 0x40), total), 0)
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), total)
            return(ptr, add(0x40, and(add(total, 0x1f), not(0x1f))))
        }
    }

    /// @dev The length of the answer the pieces make.
    function _answerLength(Piece[] memory pieces) private view returns (uint256 total) {
        total = JSON_URI.length;
        for (uint256 i; i < pieces.length; ++i) {
            total += _encodedLength(pieces[i], i + 1 == pieces.length);
        }
    }

    /// @dev What a piece becomes in the answer.
    function _encodedLength(Piece memory piece, bool isLast) private view returns (uint256) {
        if (piece.depth == CODE) {
            uint256 codeSize = _size(piece.pointers);
            if (codeSize % 16 != 0) revert SceneRendererNotAligned();
            return codeSize;
        }
        if (piece.depth == JSON) {
            uint256 len = _jsonLength(piece);
            return _b64(isLast ? len : _pad(len, 3));
        }
        if (piece.depth == HTML) return (_pad(piece.text.length, 9) * 16) / 9;
        uint256 size = _size(piece.pointers);
        return size == 0 ? 0 : (_pad(_b64(size), 9) * 16) / 9;
    }

    /// @dev A JSON piece's plain length, its still in base64.
    function _jsonLength(Piece memory piece) private view returns (uint256 len) {
        len = piece.text.length + piece.rest.length;
        if (piece.pointers.length > 0) len += _b64(_size(piece.pointers));
    }

    /// @dev Writes a piece at `at`, its plain bytes first staged at the right end of its place,
    ///      then encoded leftwards over them. Returns where the next piece starts.
    function _writePiece(uint256 table, uint256 at, Piece memory piece, bool isLast) private view returns (uint256) {
        if (piece.depth == CODE) {
            for (uint256 i; i < piece.pointers.length; ++i) {
                at = _readPointer(at, piece.pointers[i]);
            }
            return at;
        }
        if (piece.depth == JSON) {
            uint256 len = _jsonLength(piece);
            uint256 n = isLast ? len : _pad(len, 3);
            uint256 end = at + _b64(n);
            _spaces(end - n, n - len);
            uint256 next = _put(end - len, piece.text);
            if (piece.pointers.length > 0) next = _putEncoded(table, next, piece.pointers);
            _put(next, piece.rest);
            Base64InPlace.encode(table, at, end - n, n);
            return end;
        }
        if (piece.depth == HTML) {
            uint256 t = _pad(piece.text.length, 9);
            uint256 end = at + (t * 16) / 9;
            _spaces(_put(end - t, piece.text), t - piece.text.length);
            _encodeTwice(table, at, end, t);
            return end;
        }
        uint256 size = _size(piece.pointers);
        if (size == 0) return at;
        uint256 s0 = _b64(size);
        uint256 s = _pad(s0, 9);
        uint256 dataEnd = at + (s * 16) / 9;
        _putEncoded(table, dataEnd - s, piece.pointers);
        _spaces(dataEnd - s + s0, s - s0);
        _encodeTwice(table, at, dataEnd, s);
        return dataEnd;
    }

    /// @dev Writes the base64 of the bytes behind `pointers` at `at`, read in at the right end of
    ///      its place first. Returns where it ends.
    function _putEncoded(uint256 table, uint256 at, address[] memory pointers) private view returns (uint256 end) {
        uint256 size = _size(pointers);
        end = at + _b64(size);
        uint256 from = end - size;
        for (uint256 i; i < pointers.length; ++i) {
            from = _readPointer(from, pointers[i]);
        }
        Base64InPlace.encode(table, at, end - size, size);
    }

    /// @dev `len` bytes ending at `end` become their base64's base64, starting at `at`.
    function _encodeTwice(uint256 table, uint256 at, uint256 end, uint256 len) private pure {
        uint256 once = _b64(len);
        Base64InPlace.encode(table, end - once, end - len, len);
        Base64InPlace.encode(table, at, end - once, once);
    }

    function _b64(uint256 len) private pure returns (uint256) {
        return Base64InPlace.encodedLength(len);
    }

    function _pad(uint256 len, uint256 unit) private pure returns (uint256) {
        // forge-lint: disable-next-line(divide-before-multiply)
        return ((len + unit - 1) / unit) * unit;
    }

    /// @dev Total bytes held by SSTORE2 pointers.
    function _size(address[] memory pointers) private view returns (uint256 size) {
        for (uint256 i; i < pointers.length; ++i) {
            size += pointers[i].code.length - 1;
        }
    }

    function _put(uint256 at, bytes memory data) private pure returns (uint256 next) {
        assembly ("memory-safe") {
            let len := mload(data)
            mcopy(at, add(data, 0x20), len)
            next := add(at, len)
        }
    }

    function _spaces(uint256 at, uint256 count) private pure {
        assembly ("memory-safe") {
            for { let i } lt(i, count) { i := add(i, 1) } { mstore8(add(at, i), 0x20) }
        }
    }

    /// @dev Copies an SSTORE2 pointer's data to `at` (SSTORE2.read without a new buffer).
    function _readPointer(uint256 at, address pointer) private view returns (uint256 next) {
        assembly ("memory-safe") {
            let size := sub(extcodesize(pointer), 1)
            extcodecopy(pointer, at, 1, size)
            next := add(at, size)
        }
    }
}

src/PanoramaRendererV6.sol

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

import { Base64 } from "solady/utils/Base64.sol";
import { LibString } from "solady/utils/LibString.sol";
import { DynamicBufferLib } from "solady/utils/DynamicBufferLib.sol";
import { IPanoramaStorage } from "./interfaces/IPanoramaStorage.sol";
import { PanoramaRendererV5 } from "./PanoramaRendererV5.sol";

/// @title PanoramaRendererV6
/// @author Yigit Duman (@yigitduman)
/// @notice PanoramaRendererV5 plus a prereveal video for Season 4: an unrevealed Season 4 token
///         (#211-#270) keeps its prereveal still as `image` and, while `prerevealVideoBaseUrl` is
///         set, gets `<prerevealVideoBaseUrl><token>.mp4` as `animation_url` (a video with sound).
///         Everything else is V5's, byte for byte, and it links V5's deployed library
///         (PanoramaRendererV5Html).
contract PanoramaRendererV6 is PanoramaRendererV5 {
    using LibString for uint256;
    using LibString for string;
    using DynamicBufferLib for DynamicBufferLib.DynamicBuffer;

    /// @notice Where an unrevealed Season 4 token's prereveal video is (`<base><token>.mp4`);
    ///         empty = none, as in V5.
    string public prerevealVideoBaseUrl;

    constructor(
        address _panorama,
        string memory _prerevealBaseUrl,
        string memory _prerevealVideoBaseUrl
    ) PanoramaRendererV5(_panorama, _prerevealBaseUrl) {
        prerevealVideoBaseUrl = _prerevealVideoBaseUrl;
    }

    function setPrerevealVideoBaseUrl(string calldata _url) external onlyOwner {
        prerevealVideoBaseUrl = _url;
    }

    /// @dev V5's unrevealed metadata, with the prereveal video after `image` on a Season 4 token.
    function _buildUnrevealedMetadata(
        uint256 tokenId,
        IPanoramaStorage store
    ) internal view override returns (string memory) {
        DynamicBufferLib.DynamicBuffer memory buf;
        buf.p('{"name":"Panorama Tableau #');
        buf.p(bytes(tokenId.toString()));
        buf.p('","description":"This edition has not yet been revealed.');
        buf.p('","image":"');
        if (bytes(prerevealBaseUrl).length > 0) {
            buf.p(bytes(prerevealBaseUrl.escapeJSON()));
            buf.p(bytes(tokenId.toString()));
            buf.p(".webp");
        }
        if (_isSeason4(tokenId) && bytes(prerevealVideoBaseUrl).length > 0) {
            buf.p('","animation_url":"');
            buf.p(bytes(prerevealVideoBaseUrl.escapeJSON()));
            buf.p(bytes(tokenId.toString()));
            buf.p(".mp4");
        }
        buf.p('","external_url":"');
        buf.p(bytes(store.externalUrl().escapeJSON()));
        buf.p("/tableau/");
        buf.p(bytes(tokenId.toString()));
        buf.p('","attributes":[');
        buf.p('{"trait_type":"Season","value":"');
        buf.p(bytes(_seasonLabel(tokenId, 0)));
        buf.p('"}');
        _appendArtist(buf, tokenId);
        _appendTechnology(buf, tokenId);
        _appendSeason3(buf, tokenId);
        _appendLead(buf, tokenId);
        buf.p(',{"trait_type":"Reveal Date","value":"');
        uint256 revealTs = uint256(store.startTimestamp()) + (tokenId - 1) * 86_400;
        // forge-lint: disable-next-line(unsafe-typecast)
        buf.p(bytes(_formatDate(uint40(revealTs))));
        buf.p('"}');
        buf.p("]}");
        return string.concat("data:application/json;base64,", Base64.encode(bytes(string(buf.data))));
    }
}

src/interfaces/IMURIProtocol.sol

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

interface IMURIProtocol {
    enum DisplayMode {
        DIRECT_FILE,
        HTML
    }

    enum ThumbnailKind {
        ON_CHAIN,
        OFF_CHAIN
    }

    struct Artwork {
        string[] artistUris;
        string[] collectorUris;
        string mimeType;
        string fileHash;
        bool isAnimationUri;
        uint256 selectedArtistUriIndex;
    }

    struct Permissions {
        uint16 flags;
    }

    struct OnChainThumbnail {
        string mimeType;
        address[] chunks;
        bool zipped;
    }

    struct OffChainThumbnail {
        string[] uris;
        uint256 selectedUriIndex;
    }

    struct Thumbnail {
        ThumbnailKind kind;
        OnChainThumbnail onChain;
        OffChainThumbnail offChain;
    }

    struct HtmlTemplate {
        address[] chunks;
        bool zipped;
    }

    struct InitConfig {
        string metadata;
        Artwork artwork;
        Thumbnail thumbnail;
        DisplayMode displayMode;
        Permissions permissions;
        HtmlTemplate htmlTemplate;
    }

    function registerContract(address contractAddress, address operatorAddress) external;

    function initializeTokenData(
        address contractAddress,
        uint256 tokenId,
        InitConfig calldata config,
        bytes[] calldata thumbnailChunks,
        string[] calldata htmlTemplateChunks
    ) external;

    function updateThumbnail(
        address contractAddress,
        uint256 tokenId,
        Thumbnail calldata thumbnail,
        bytes[] calldata thumbnailChunks
    ) external;

    function getArtwork(address contractAddress, uint256 tokenId) external view returns (Artwork memory);

    function renderImage(address contractAddress, uint256 tokenId) external view returns (string memory);
    function renderMetadata(address contractAddress, uint256 tokenId) external view returns (string memory);
    // forge-lint: disable-next-line(mixed-case-function)
    function renderHTML(address contractAddress, uint256 tokenId) external view returns (string memory);
}

src/interfaces/IPanorama.sol

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

interface IPanorama {
    error MaxSupplyReached();
    error RendererNotSet();
    error NotOwnerOrOperator();

    event MetadataUpdate(uint256 _tokenId);
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
    event AuthorizedOperatorUpdated(address indexed operator, bool indexed authorized);

    // ERC20
    function tokenURI() external view returns (string memory);

    // State
    function MAX_SUPPLY() external view returns (uint256);
    function totalMinted() external view returns (uint256);
    function totalBurned() external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function renderer() external view returns (address);
    function storageContract() external view returns (address);
    function muriOperator() external view returns (address);
    function panoramaERC20() external view returns (address);
    function muriProtocol() external view returns (address);
    function authorizedOperators(address operator) external view returns (bool);

    // Mutations
    function mintTo(address to) external returns (uint256);
    function mintTo(address to, uint256 quantity) external returns (uint256[] memory);
    function burn(uint256 tokenId) external;
    function signalMetadataUpdate() external;
    function signalMetadataUpdate(uint256 tokenId) external;
    function signalBatchMetadataUpdate(uint256 fromTokenId, uint256 toTokenId) external;
    function setAuthorizedOperator(address operator, bool authorized) external;
    function setRenderer(address _renderer) external;
    function setStorageContract(address _storage) external;
    function setMuriOperator(address _muriOperator) external;
    function setPanoramaERC20(address _token) external;
    function setMuriProtocol(address _muriProtocol) external;
    function mintController() external view returns (address);
    function maxSupply() external view returns (uint256);
    function mintCap() external view returns (uint256);
    function setMintController(address _mintController) external;
}

src/interfaces/IPanoramaRenderer.sol

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

interface IPanoramaRenderer {
    error PanoramaNotSet();

    // State
    function panorama() external view returns (address);
    function prerevealBaseUrl() external view returns (string memory);

    // View
    function tokenURI() external view returns (string memory);
    function tokenURI(uint256 tokenId) external view returns (string memory);
    function renderPanoramaHtml() external view returns (string memory);
    function resolveTableauImageUrl(uint256 tokenId) external view returns (string memory);
    function resolveTableauAnimationUrl(uint256 tokenId) external view returns (string memory);

    // Mutations
    function setPanorama(address _panorama) external;
    function setPrerevealBaseUrl(string calldata _url) external;
}

src/interfaces/IPanoramaSeason4Music.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.34 <0.9.0;

/// @notice What Panorama asks of Season 4's music controller (Dav's), set in
///         PanoramaSeason4Storage.musicController.
///
///         The controller reads from Panorama: the day's lead
///         (PanoramaSeason4Storage.leadOf, 0-5, 6 for #270), the mood its price set
///         (moodOf, 0 Extreme Bliss to 6 Extreme Anguish, once revealed) and the RPC
///         addresses a page reads through (getRpcUrlsFor: the holder's, then the artist's).
///         Token ids are Panorama's, 211-270.
interface IPanoramaSeason4Music {
    /// @notice The music's traits for a Season 4 token, added after Panorama's own (Season,
    ///         Artist, Lead, Mood, Price, ...) and the day's own (PanoramaSeason4Storage
    ///         getTokenTraits). Names and values pair by index.
    /// @dev The renderer reads this with at most MUSIC_TRAITS_GAS (3M) and keeps the first
    ///      16 pairs; a pair whose name is empty or over 64 bytes, or whose value is over 128
    ///      bytes, is left out. Both are written as JSON strings (escaped by the renderer).
    ///      A revert, a malformed answer or running out of gas adds no traits and never
    ///      stops the token's metadata. Return empty arrays for a token with no music yet.
    function musicTraits(uint256 tokenId) external view returns (string[] memory names, string[] memory values);
}

src/interfaces/IPanoramaSeason4SceneRenderer.sol

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

interface IPanoramaSeason4SceneRenderer {
    error FragmentSizeInvalid();
    error FragmentNotUploaded();

    event Season4StorageSet(address indexed season4Storage);
    event SceneRendererFragmentUploaded(bytes32 indexed fragmentHash, address pointer);
    event SceneRendererFragmentHashesSet(uint256 fragmentCount);

    // State
    function FRAGMENT_SIZE() external view returns (uint256);
    function season4Storage() external view returns (address);
    function fragmentPointers(bytes32 fragmentHash) external view returns (address);

    // View
    function getSceneRendererFragmentHashes() external view returns (bytes32[] memory);
    function getSceneRendererFragmentPointers() external view returns (address[] memory);
    function hasSceneRenderer() external view returns (bool);

    // Mutations
    function setSeason4Storage(address _season4Storage) external;
    function uploadSceneRendererFragment(bytes calldata data) external returns (address pointer);
    function setSceneRendererFragmentHashes(bytes32[] calldata hashes) external;
}

src/interfaces/IPanoramaSeason4Storage.sol

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

interface IPanoramaSeason4Storage {
    error InvalidIndex();
    error HtmlTemplateNotSet();
    error NotOwnerOrOperator();
    error NotTokenHolder();
    error FragmentIndexOutOfBounds();
    error FragmentAlreadyUploaded();
    error FragmentHashMismatch();
    error FragmentSizeInvalid();
    error NoFragmentsConfigured();
    error FragmentNotUploaded();
    error InvalidRpcUrl();
    error NotRevealed();
    error InvalidTrait();

    /// @notice What a Season 4 token's `animation_url` shows. The holder chooses.
    enum View {
        StaticVideo,
        DynamicScene
    }

    /// @dev Bytes stored on-chain as ordered fragments, as PanoramaStorage stores a tableau's
    /// image. The owner (or an operator, for day data) commits the keccak256 hash of each
    /// fragment, then anyone can upload the bytes: each upload must match its hash. Every
    /// fragment but the last is FRAGMENT_SIZE bytes, so the dynamic scene can check data it
    /// fetched from a link against the same hashes.
    struct FragmentData {
        bytes32[] fragmentHashes;
        address[] fragmentPointers;
        uint256 uploadedFragmentCount;
    }

    event AuthorizedOperatorUpdated(address indexed operator, bool indexed authorized);
    event SceneRendererFragmentHashesSet(uint256 indexed fragmentCount);
    event SceneRendererFragmentUploaded(uint256 indexed fragmentIndex, address indexed pointer);
    event SceneRendererFinalized(uint256 indexed fragmentCount);
    event DayDataFragmentHashesSet(uint256 indexed tokenId, uint256 indexed fragmentCount);
    event DayDataFragmentUploaded(uint256 indexed tokenId, uint256 indexed fragmentIndex, address indexed pointer);
    event DayDataFinalized(uint256 indexed tokenId, uint256 indexed fragmentCount);
    event ViewSet(uint256 indexed tokenId, address indexed holder, View view_);
    event RpcUrlLimitsSet(uint256 maxRpcUrls, uint256 maxRpcUrlLength);
    event RpcUrlsSet(uint256 count);
    event TokenRpcUrlsSet(uint256 indexed tokenId, address indexed holder, uint256 count);
    event MusicControllerSet(address indexed musicController);
    event TokenTraitsSet(uint256 indexed tokenId, uint256 count);

    // State
    function FIRST_TOKEN_ID() external view returns (uint256);
    function LAST_TOKEN_ID() external view returns (uint256);
    function FRAGMENT_SIZE() external view returns (uint256);
    function ALL_LEADS() external view returns (uint8);
    function maxRpcUrls() external view returns (uint256);
    function maxRpcUrlLength() external view returns (uint256);
    function panorama() external view returns (address);
    function authorizedOperators(address operator) external view returns (bool);
    function sceneRendererHtmlPrefixPointer() external view returns (address);
    function sceneRendererHtmlSuffixPointer() external view returns (address);
    function viewOf(uint256 tokenId) external view returns (View);
    function musicController() external view returns (address);
    function MAX_TRAITS() external view returns (uint256);
    function getTokenTraits(uint256 tokenId) external view returns (string[] memory names, string[] memory values);

    // View: dynamic scene
    function getSceneRendererHtmlPrefixData() external view returns (bytes memory);
    function getSceneRendererHtmlSuffixData() external view returns (bytes memory);
    function getSceneRendererFragmentHashes() external view returns (bytes32[] memory);
    function getSceneRendererFragmentPointers() external view returns (address[] memory);
    function isSceneRendererFullyUploaded() external view returns (bool);
    function hasSceneRenderer() external view returns (bool);

    // View: day data
    function getDayDataFragmentHashes(uint256 tokenId) external view returns (bytes32[] memory);
    function getDayDataFragmentPointers(uint256 tokenId) external view returns (address[] memory);
    function getUploadedDayDataFragmentCount(uint256 tokenId) external view returns (uint256);
    function isDayDataFullyUploaded(uint256 tokenId) external view returns (bool);
    function getDayDataFragment(uint256 tokenId, uint256 fragmentIndex) external view returns (bytes memory);
    function getImageFragment(uint256 tokenId, uint256 fragmentIndex) external view returns (bytes memory);

    // View: RPC addresses
    function getRpcUrls() external view returns (string[] memory);
    function getTokenRpcUrls(uint256 tokenId) external view returns (string[] memory);
    function getRpcUrlsFor(uint256 tokenId) external view returns (string[] memory);

    // View: music (what the music controller reads)
    function leadOf(uint256 tokenId) external view returns (uint8);
    function moodOf(uint256 tokenId) external view returns (uint8);

    // Mutations
    function setPanorama(address _panorama) external;
    function setAuthorizedOperator(address operator, bool authorized) external;
    function setSceneRendererHtmlPrefix(bytes calldata _data) external;
    function setSceneRendererHtmlSuffix(bytes calldata _data) external;
    function setSceneRendererFragmentHashes(bytes32[] calldata hashes) external;
    function uploadSceneRendererFragment(uint256 fragmentIndex, bytes calldata data) external;
    function setDayDataFragmentHashes(uint256 tokenId, bytes32[] calldata hashes) external;
    function uploadDayDataFragment(uint256 tokenId, uint256 fragmentIndex, bytes calldata data) external;
    function setDayDataFragmentPointer(uint256 tokenId, uint256 fragmentIndex, address pointer) external;
    function removeDayDataFragmentPointer(uint256 tokenId, uint256 fragmentIndex) external;
    function clearDayData(uint256 tokenId) external;
    function setView(uint256 tokenId, View view_) external;
    function setMusicController(address _musicController) external;
    function setRpcUrlLimits(uint256 _maxRpcUrls, uint256 _maxRpcUrlLength) external;
    function setRpcUrls(string[] calldata urls) external;
    function setTokenRpcUrls(uint256 tokenId, string[] calldata urls) external;
    function setTokenTraits(uint256 tokenId, string[] calldata names, string[] calldata values) external;
}

src/interfaces/IPanoramaStorage.sol

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

interface IPanoramaStorage {
    error InvalidIndex();
    error LengthMismatch();
    error HtmlTemplateNotSet();
    error InvalidWorkflowId();
    error NotOwnerOrOperator();
    error FragmentIndexOutOfBounds();
    error FragmentAlreadyUploaded();
    error FragmentHashMismatch();
    error NotFullyUploaded();
    error NoFragmentsConfigured();

    event EntryAdded(uint256 indexed tokenId, uint256 indexed price, int256 indexed changeBps);
    event WorkflowAdded(uint256 indexed id, string name);
    event WorkflowUpdated(uint256 indexed id);
    event ImageFragmentHashesSet(uint256 indexed tokenId, uint256 indexed fragmentCount);
    event ImageFragmentUploaded(uint256 indexed tokenId, uint256 indexed fragmentIndex, address indexed pointer);
    event TableauFinalized(uint256 indexed tokenId, uint256 indexed fragmentCount);
    event AuthorizedOperatorUpdated(address indexed operator, bool indexed authorized);

    /// @dev Each tableau is a single 1920x1080 AI-generated painting in the panorama.
    /// Its image can be stored fully on-chain by splitting the raw image bytes (WebP)
    /// into ordered fragments. The owner commits keccak256 hashes for each fragment,
    /// then anyone can upload the corresponding data (hash-verified, permissionless).
    /// Once all fragments are uploaded, `uploadImageFragment` automatically
    /// finalizes the tableau. The image is served directly via `getOnchainImageDataUri`,
    /// fully retrievable from contract storage without any external dependency.
    struct TableauData {
        uint256 price;
        int256 changeBps;
        uint40 timestamp;
        uint8 moodIndex;
        uint8 workflowId;
        uint8 season;
        uint256 seed;
        string prompt;
        string name;
        string description;
        /// @dev Ordered keccak256 hashes of each image fragment. Set by the owner/operator
        /// before upload begins. The image bytes are split into N sequential chunks off-chain,
        /// each chunk hashed, and the hash array committed here. This serves as a commitment
        /// scheme: uploaders must provide data matching each hash exactly.
        bytes32[] imageFragmentHashes;
        /// @dev SSTORE2 pointers to uploaded fragment data, parallel to imageFragmentHashes.
        /// Each slot starts as address(0) and is filled when the corresponding fragment is
        /// uploaded via `uploadImageFragment`. Reading the stored bytes: `SSTORE2.read(pointer)`.
        address[] imageFragmentPointers;
        /// @dev Number of fragments uploaded so far. When this equals imageFragmentHashes.length,
        /// the image is fully on-chain and `finalizeOnchainTableau` can be called.
        uint256 uploadedFragmentCount;
    }

    struct Workflow {
        string name;
        address jsonPointer;
        string gpuUsed;
        string cudaVersion;
        bytes32[] modelSha256;
        string[] customNodeNames;
        string[] customNodeVersions;
        bytes32[] customNodeSha256;
        string[] modelDownloadLinks;
    }

    // State
    function panorama() external view returns (address);
    function authorizedOperators(address operator) external view returns (bool);
    function erc20TokenDescription() external view returns (string memory);
    function externalUrl() external view returns (string memory);
    function startTimestamp() external view returns (uint40);
    function cdnBase() external view returns (string memory);
    function panoramaHtmlPrefixPointer() external view returns (address);
    function panoramaHtmlSuffixPointer() external view returns (address);
    function entryCount() external view returns (uint256);

    // View — Tableau
    function getTableauData(uint256 tokenId) external view returns (TableauData memory);
    function getPanoramaHtmlPrefixData() external view returns (bytes memory);
    function getPanoramaHtmlSuffixData() external view returns (bytes memory);

    // View — Image Fragments
    function getImageFragmentHashes(uint256 tokenId) external view returns (bytes32[] memory);
    function getTotalFragments(uint256 tokenId) external view returns (uint256);
    function getFragmentPointer(uint256 tokenId, uint256 index) external view returns (address);
    function getFragmentPointers(uint256 tokenId) external view returns (address[] memory);
    function getUploadedFragmentCount(uint256 tokenId) external view returns (uint256);
    function isFullyUploaded(uint256 tokenId) external view returns (bool);
    function getOnchainImageDataUri(uint256 tokenId) external view returns (string memory);

    // View — Workflows
    function getWorkflow(uint256 id) external view returns (Workflow memory);
    function getWorkflowCount() external view returns (uint256);
    function getWorkflowJson(uint256 id) external view returns (bytes memory);

    // Mutations — Config
    function setPanorama(address _panorama) external;
    function setAuthorizedOperator(address operator, bool authorized) external;
    function setCdnBase(string calldata _cdnBase) external;
    function setExternalUrl(string calldata _url) external;
    function setStartTimestamp(uint40 _startTimestamp) external;
    function updateErc20Description(string calldata _description) external;
    function setPanoramaHtmlPrefix(bytes calldata _data) external;
    function setPanoramaHtmlSuffix(bytes calldata _data) external;

    // Mutations — Tableau
    function addTableauEntry(TableauData calldata data) external;
    function batchAddTableauEntries(TableauData[] calldata entries) external;
    function setTableauPrice(uint256 tokenId, uint256 price) external;
    function setTableauChangeBps(uint256 tokenId, int256 changeBps) external;
    function setTableauTimestamp(uint256 tokenId, uint40 timestamp) external;
    function setTableauMoodIndex(uint256 tokenId, uint8 moodIndex) external;
    function setTableauWorkflowId(uint256 tokenId, uint8 workflowId) external;
    function setTableauSeason(uint256 tokenId, uint8 season) external;
    function setTableauSeed(uint256 tokenId, uint256 seed) external;
    function setTableauPrompt(uint256 tokenId, string calldata prompt) external;
    function setCustomTableauName(uint256 tokenId, string calldata _name) external;
    function setCustomTableauDescription(uint256 tokenId, string calldata description) external;

    // Mutations — Image Fragments
    function setTableauImageFragmentHashes(uint256 tokenId, bytes32[] calldata hashes) external;
    function batchSetTableauImageFragmentHashes(uint256[] calldata tokenIds, bytes32[][] calldata hashes) external;
    function uploadImageFragment(uint256 tokenId, uint256 fragmentIndex, bytes calldata data) external;
    function setFragmentPointer(uint256 tokenId, uint256 fragmentIndex, address pointer) external;
    function removeFragmentPointer(uint256 tokenId, uint256 fragmentIndex) external;
    function clearFragmentData(uint256 tokenId) external;

    // Mutations — Workflows
    function addWorkflow(Workflow calldata wf, bytes calldata json) external returns (uint256 id);
    function updateWorkflowName(uint256 id, string calldata _name) external;
    function updateWorkflowJson(uint256 id, bytes calldata json) external;
    function updateWorkflowGpu(uint256 id, string calldata gpu, string calldata cuda) external;
    function updateWorkflowModels(uint256 id, bytes32[] calldata modelHashes, string[] calldata downloadLinks) external;
    function updateWorkflowCustomNodes(
        uint256 id,
        string[] calldata names,
        string[] calldata versions,
        bytes32[] calldata nodeHashes
    ) external;
}

src/interfaces/IPanoramaWorkflowLedger.sol

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

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

/// @notice Ordered generation steps per Panorama tableau: which registered ComfyUI workflow
///         ran at each step and with which parameters, so a tableau can be reproduced step
///         by step (tile → seam → retouch composite → inpaint repaints → grain).
interface IPanoramaWorkflowLedger {
    error Unauthorized();
    error InvalidTokenId();
    error UnknownWorkflow(uint16 workflowId);
    error LengthMismatch();
    error NoSteps();
    error TooManySteps();
    error StepIndexOutOfBounds();

    event StepsAppended(uint256 indexed tokenId, uint256 fromIndex, uint256 count);
    event StepsCleared(uint256 indexed tokenId);

    // State
    function store() external view returns (IPanoramaStorage);
    function NO_WORKFLOW() external view returns (uint16);
    function MAX_CHUNK_SIZE() external view returns (uint256);
    function MAX_STEPS() external view returns (uint256);

    // Mutations
    function appendSteps(uint256 tokenId, uint16[] calldata workflowIds, bytes[] calldata params) external;
    function appendStepsBatch(
        uint256[] calldata tokenIds,
        uint16[][] calldata workflowIds,
        bytes[][] calldata params
    ) external;
    function clearSteps(uint256 tokenId) external;

    // Views
    function stepCount(uint256 tokenId) external view returns (uint256);
    function getStep(uint256 tokenId, uint256 index) external view returns (uint16 workflowId, bytes memory params);
    function getSteps(uint256 tokenId) external view returns (uint16[] memory workflowIds, bytes[] memory params);

    // Rendering (read by PanoramaRendererV3)
    function renderWorkflows(uint256 tokenId) external view returns (string memory);
}

src/utils/Base64InPlace.sol

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

/// @title Base64InPlace
/// @notice Base64 between two memory positions, with no allocation.
/// @dev The source may sit inside the output region when it is right-aligned in it
///      (`src + len == dst + encodedLength(len)`): every group is read before the four bytes it
///      becomes are written, and the write position never passes the read position. That lets a
///      page nested in several data URIs be built in one buffer of its final size.
library Base64InPlace {
    /// @notice Length of the padded base64 of `len` bytes.
    function encodedLength(uint256 len) internal pure returns (uint256) {
        return 4 * ((len + 2) / 3);
    }

    /// @notice Builds the lookup table `encode` reads: for each 12-bit value, its two base64
    ///         characters. 8,192 bytes plus a word of slack; build it once per call.
    function newTable() internal pure returns (uint256 table) {
        assembly ("memory-safe") {
            table := mload(0x40)
            mstore(0x40, add(table, 0x2040))
            mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
            mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
            let at := table
            for { let hi } lt(hi, 64) { hi := add(hi, 1) } {
                let first := shl(248, mload(hi))
                for { let lo } lt(lo, 64) { lo := add(lo, 1) } {
                    mstore(at, or(first, shl(240, and(mload(lo), 0xff))))
                    at := add(at, 2)
                }
            }
            mstore(0x40, add(table, 0x2040))
        }
    }

    /// @notice Writes the padded base64 of memory `[src, src + len)` at `dst`.
    /// @dev Safe when the regions do not overlap, or when `src >= dst + encodedLength(len) - len`.
    ///      `table` comes from `newTable`. The bulk goes thirty bytes a turn, two characters a
    ///      lookup; each write there spills thirty bytes ahead, so the last fifty groups are
    ///      written a byte at a time, which keeps the write behind the read in place and leaves
    ///      nothing past the end. Uses 0x1f..0x5e and restores the free memory pointer.
    function encode(uint256 table, uint256 dst, uint256 src, uint256 len) internal pure {
        assembly ("memory-safe") {
            let groups := div(len, 3)
            if gt(groups, 50) {
                let fastEnd := add(src, mul(3, sub(groups, 50)))
                for { } lt(src, fastEnd) { } {
                    let w := mload(src)
                    mstore(dst, mload(add(table, and(shr(243, w), 0x1ffe))))
                    mstore(add(dst, 2), mload(add(table, and(shr(231, w), 0x1ffe))))
                    mstore(add(dst, 4), mload(add(table, and(shr(219, w), 0x1ffe))))
                    mstore(add(dst, 6), mload(add(table, and(shr(207, w), 0x1ffe))))
                    mstore(add(dst, 8), mload(add(table, and(shr(195, w), 0x1ffe))))
                    mstore(add(dst, 10), mload(add(table, and(shr(183, w), 0x1ffe))))
                    mstore(add(dst, 12), mload(add(table, and(shr(171, w), 0x1ffe))))
                    mstore(add(dst, 14), mload(add(table, and(shr(159, w), 0x1ffe))))
                    mstore(add(dst, 16), mload(add(table, and(shr(147, w), 0x1ffe))))
                    mstore(add(dst, 18), mload(add(table, and(shr(135, w), 0x1ffe))))
                    mstore(add(dst, 20), mload(add(table, and(shr(123, w), 0x1ffe))))
                    mstore(add(dst, 22), mload(add(table, and(shr(111, w), 0x1ffe))))
                    mstore(add(dst, 24), mload(add(table, and(shr(99, w), 0x1ffe))))
                    mstore(add(dst, 26), mload(add(table, and(shr(87, w), 0x1ffe))))
                    mstore(add(dst, 28), mload(add(table, and(shr(75, w), 0x1ffe))))
                    mstore(add(dst, 30), mload(add(table, and(shr(63, w), 0x1ffe))))
                    mstore(add(dst, 32), mload(add(table, and(shr(51, w), 0x1ffe))))
                    mstore(add(dst, 34), mload(add(table, and(shr(39, w), 0x1ffe))))
                    mstore(add(dst, 36), mload(add(table, and(shr(27, w), 0x1ffe))))
                    mstore(add(dst, 38), mload(add(table, and(shr(15, w), 0x1ffe))))
                    src := add(src, 30)
                    dst := add(dst, 40)
                }
                // The turn may have run past fastEnd by up to nine groups; what is left is still
                // at least forty groups, enough to cover the spill.
                len := sub(len, sub(src, sub(fastEnd, mul(3, sub(groups, 50)))))
            }

            let fmp := mload(0x40)
            mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
            mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")

            // mload(s) puts the next three source bytes in the low 24 bits.
            let s := sub(src, 29)
            let end := add(dst, shl(2, div(len, 3)))
            for { } lt(dst, end) { } {
                let input := mload(s)
                mstore8(dst, mload(and(shr(18, input), 0x3F)))
                mstore8(add(dst, 1), mload(and(shr(12, input), 0x3F)))
                mstore8(add(dst, 2), mload(and(shr(6, input), 0x3F)))
                mstore8(add(dst, 3), mload(and(input, 0x3F)))
                s := add(s, 3)
                dst := add(dst, 4)
            }

            let r := mod(len, 3)
            if r {
                // Keep the r real bytes, zero what follows them.
                let input := and(mload(s), shl(shl(3, sub(3, r)), 0xffffff))
                mstore8(dst, mload(and(shr(18, input), 0x3F)))
                mstore8(add(dst, 1), mload(and(shr(12, input), 0x3F)))
                switch r
                case 1 { mstore8(add(dst, 2), 0x3d) }
                default { mstore8(add(dst, 2), mload(and(shr(6, input), 0x3F))) }
                mstore8(add(dst, 3), 0x3d)
            }

            mstore(0x40, fmp)
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/PanoramaRendererV7.sol": {
      "PanoramaRendererV7Html": "0xb42bc047bd1914422b9781e924116909cae332e2"
    }
  },
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "forge-std/=node_modules/forge-std/",
    "solady/=node_modules/solady/src/",
    "@uniswap/v4-core/=node_modules/@uniswap/v4-core/",
    "@uniswap/v4-periphery/=node_modules/@uniswap/v4-periphery/",
    "@ensdomains/=node_modules/@ensdomains/",
    "@manifoldxyz/=node_modules/@manifoldxyz/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "ds-test/=node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
    "erc4626-tests/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=node_modules/@uniswap/v4-periphery/lib/permit2/lib/forge-gas-snapshot/",
    "openzeppelin-contracts/=node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
    "permit2/=node_modules/@uniswap/v4-periphery/lib/permit2/",
    "solmate/=node_modules/@uniswap/v4-core/lib/solmate/",
    "v4-core/=node_modules/@uniswap/v4-periphery/lib/v4-core/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.