Skip to content
Verified contractExactMIT

AccretionDescriptor

Address0xc2de51d422b8938f0283559b6956f5f5e4e10391
Balance

0 ETH

 

Transactions

7

 

Compiler

solc 0.8.17

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.17+commit.8df45f5f
Language
solidity
Optimization
Yes, 1 runs
EVM version
london
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,300,618
Creation transaction
0x9069d7f08d…49b90097d2

src/AccretionDescriptor.sol

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

import { Base64 } from "openzeppelin-contracts/utils/Base64.sol";
import { Strings } from "openzeppelin-contracts/utils/Strings.sol";

import {
    AccretionTraits,
    IAccretionDescriptor,
    IAccretionToken
} from "./IAccretionDescriptor.sol";

/// @title  AccretionDescriptor
/// @notice The swappable metadata + render-query builder for AccretionSeaDrop. It
///         reads a token's immutable trait DNA (numeric indices) + live mutation
///         state back off the token, maps the DNA to human-readable strings, and
///         assembles:
///
///           - `imageParams(id)`  BIRTH-state render query string at the current thumbnail step (pre-warm)
///           - `renderParams(id)` live render query string
///           - `tokenURI(id)`     full base64 JSON: name, description,
///                                image = renderBase + params,
///                                animation_url = engine + params,
///                                attributes (filterable facets)
///
///         Index -> string label tables + the query/JSON assembly live HERE (not on
///         the token) so the token stays immutable and well under the 24576-byte
///         limit, while metadata shape / query format / feature set stay upgradeable
///         until the token owner calls lockDescriptor(). The label tables + params +
///         _attributes / _formAttrs are ported from AccretionExtension.sol; a
///         creatures block is added for the SeaDrop port's addCreature feature.
///
///         The seed roll is recomputed here IDENTICALLY to the token
///         (keccak256(id, chainid, tokenAddress)) so ?seed and the birth hue match.
///
///         INNATE GROWTH: every piece is born with ONE growth, its native Species form (branch / fan /
///         tube = growth forms 0-2, already seed-rolled per piece). The descriptor prepends it to the
///         planted sequence, so the rendered corals, the `&tends=` / `&growths=` params, the Growths
///         attribute and the per-form Coral attributes all count the same thing: 1 at birth, up to
///         1 + AccretionPrizes.MAX_PLANTED_GROWTHS = 15 when fully grown. `&tends=` keeps its name
///         only because the inscribed engine reads that param; nothing is tended any more.
///
///         SATELLITE READS ARE DEFENSIVE (M-06): every call into boost / prizes goes through _read,
///         a gas-capped staticcall that checks the target has code and returns enough data, so a bad
///         pointer (an EOA, the wrong contract, a reverting or malformed satellite) degrades to "no
///         bonus / nothing won" instead of reverting tokenURI for the whole collection.
///
///         DRAFT — first pass for human review.
interface IAccretionBoost {
    function settledBonusMilli(uint256 tokenId) external view returns (uint256);   // height TAKEN
    function givenMilli(uint256 tokenId) external view returns (uint256);         // height POURED AWAY
    function contribMilli(uint32 strength, uint32 durationSecs) external view returns (uint256);
    function boostParams(uint256 tokenId)
        external
        view
        returns (uint256 completedMilli, uint64 start, uint32 strength, uint32 durationSecs);
    // Orbit satellite extras (the paid AccretionBoost fallback lacks these; descriptor calls
    // them behind try/catch so it degrades cleanly to just the height boost).
    function orbitersOf(uint256 coreId) external view returns (uint256[] memory);
    function orbitingCore(uint256 tokenId) external view returns (uint256);
    function activeContribMilli(uint256 coreId) external view returns (uint256);   // Orbit: snapshotted-rate ramp target
}

/// @notice Everything a piece has WON. Creatures, growths and the Crown/Skull all live in one
/// satellite now, because under the game rules none of them is purchasable: growth that could be
/// bought would contradict the whole economy, so `tend` left the token and its state came here.
interface IAccretionPrizes {
    function hasCrown(uint256 id) external view returns (bool);
    function hasSkull(uint256 id) external view returns (bool);
    function creatureSeq(uint256 id) external view returns (uint256);   // 8 bits per id
    function creatureCount(uint256 id) external view returns (uint8);
    function growthSeq(uint256 id) external view returns (uint256);     // 4 bits per form
    function growthCount(uint256 id) external view returns (uint8);
}

/// @notice Recurring standings. Lifetime season wins per piece, granted by AccretionSeasons after a
/// season closes. Kept OUT of IAccretionPrizes on purpose: prizes holds won and pending credits and is
/// effectively permanent after launch, so season state lives in its own satellite to isolate that risk.
interface IAccretionSeasons {
    function winsOf(uint256 id) external view returns (uint256);
}

/// @notice The guaranteed floor under the lottery: every N metres a piece has EVER poured it earns a
/// companion it does not already hold, and growths once the roster is complete. Deliberately exposes
/// `creatureSeq`/`creatureCount` with the SAME signatures as IAccretionPrizes, so one selector and one
/// decoder serve both satellites and the two sets merge with no special-casing.
interface IAccretionMilestones {
    function creatureSeq(uint256 id) external view returns (uint256);
    function creatureCount(uint256 id) external view returns (uint8);
    function bonusGrowths(uint256 id) external view returns (uint16);
    function claimedCount(uint256 id) external view returns (uint32);
}

contract AccretionDescriptor is IAccretionDescriptor {
    using Strings for uint256;

    /// @notice Collection description embedded in every tokenURI. Lives here (not on
    /// the token) because it is pure presentation the descriptor owns; ported from
    /// AccretionExtension.DESCRIPTION.
    string public constant description =
        "A monolith stored forever on Bitcoin, cultivated by its Ethereum holder. It grows with Bitcoin block age and weathers; the reef responds to tending, attunement, and a kindled beacon. Transfers leave impact craters.";

    /// @notice The token contract this descriptor serves.
    IAccretionToken public immutable token;

    /// @dev Cached token address for the seed derivation (== the token's own
    /// address(this), so seeds are byte-identical to the token's roll).
    address private immutable _tokenAddr;

    /// @notice v1 holdings-boost satellite (set post-deploy via setBoost). Height =
    /// pinned base + its settled bonus; the live params carry the boost so the
    /// renderer can ramp the in-flight portion.
    IAccretionBoost public boost;
    IAccretionPrizes public prizes;     // every won thing: creatures, growths, Crown/Skull
    IAccretionSeasons public seasons;   // lifetime season wins per piece
    IAccretionMilestones public milestones;   // guaranteed grants earned by cumulative pouring
    address public owner;

    /// @notice One-way: once true, every setter here is disabled forever (M-04). Call freeze()
    /// BEFORE the token's lockDescriptor(), or a "locked" descriptor could still repoint satellites.
    bool public frozen;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event Frozen();

    /// @notice Start of the thumbnail age schedule (unix seconds). 0 = count from token #1's mint.
    /// Set it to when the mint closes so no thumbnail is ever older than its live piece.
    uint64 public thumbEpoch;
    event ThumbEpochSet(uint64 epoch);

    constructor(address token_) {
        token = IAccretionToken(token_);
        _tokenAddr = token_;
        owner = msg.sender;
    }

    function _onlyOwnerUnfrozen() internal view {
        require(msg.sender == owner, "!owner");
        require(!frozen, "frozen");
    }

    /// @notice Hand the descriptor to a new owner (e.g. the Safe). Still allowed after freeze, so a
    /// frozen descriptor can move to a Safe or be renounced, but it can no longer change anything.
    function transferOwnership(address n) external {
        require(msg.sender == owner, "!owner");
        require(n != address(0), "zero owner");
        emit OwnershipTransferred(owner, n);
        owner = n;
    }

    /// @notice Permanently disable every setter. Irreversible.
    function freeze() external {
        _onlyOwnerUnfrozen();
        frozen = true;
        emit Frozen();
    }

    /// @notice Wire the boost satellite (owner-only). The descriptor is swappable and
    /// the boost is deployed separately, so its address is set here post-deploy.
    /// @notice The Identity link satellite (AccretionIdentity). Optional: unset renders no param.
    address public identity;

    function setIdentity(address i_) external {
        _onlyOwnerUnfrozen();
        require(i_ == address(0) || i_.code.length > 0, "not a contract");
        identity = i_;
    }

    function setBoost(address b) external {
        _onlyOwnerUnfrozen();
        require(b == address(0) || b.code.length > 0, "not a contract");
        boost = IAccretionBoost(b);
    }

    /// @notice Wire the prizes satellite (owner-only). It records grant-only Crown/Skull wins;
    /// the descriptor reads them into the `&crown=1`/`&skull=1` render params + attributes.
    /// EFFECTIVELY PERMANENT AFTER LAUNCH: wins live in the prizes contract, so repointing this drops
    /// every earned Crown and Skull from metadata unless the new prizes imports `won`.
    function setPrizes(address j) external {
        _onlyOwnerUnfrozen();
        require(j == address(0) || j.code.length > 0, "not a contract");
        prizes = IAccretionPrizes(j);
    }

    /// @notice Wire the seasons satellite (owner-only). It records lifetime season wins; the descriptor
    /// reads them into the `&wins=N` render param + the "Seasons Won" attribute.
    /// Like prizes, REPOINTING THIS DROPS EVERY RECORDED WIN from metadata unless the new seasons
    /// contract imports `winsOf` first. AccretionSeasons.importWins exists for exactly that migration.
    function setSeasons(address s_) external {
        _onlyOwnerUnfrozen();
        require(s_ == address(0) || s_.code.length > 0, "not a contract");
        seasons = IAccretionSeasons(s_);
    }

    /// @notice Wire the milestones satellite (owner-only). It grants companions and growths on a
    /// cumulative-pour schedule; the descriptor merges them into `&creatures=` / `&growths=` and
    /// reports progress as the "Milestones" attribute. Like prizes and seasons, REPOINTING THIS DROPS
    /// every granted companion from metadata unless the new contract imports its state first.
    function setMilestones(address m_) external {
        _onlyOwnerUnfrozen();
        require(m_ == address(0) || m_.code.length > 0, "not a contract");
        milestones = IAccretionMilestones(m_);
    }

    /// @notice The single pre-reveal placeholder image every piece shows until the token's
    /// reveal (set before mint). Kept here (swappable descriptor) rather than on the token.
    string public preRevealImage;
    /// @notice Query appended to the token's animationBase for the pre-reveal animation_url. The engine's
    /// prereveal mode replaces every content param with a fixed set, so this can't expose any piece.
    string public constant PRE_REVEAL_QUERY = "?prereveal=1";
    function setPreRevealImage(string calldata uri) external {
        _onlyOwnerUnfrozen();
        preRevealImage = uri;
    }

    /// @notice Owner override for the thumbnail schedule's start (see thumbEpoch). No refresh event:
    /// thumbnails pick up the new step as each piece's metadata is re-read.
    function setThumbEpoch(uint64 e) external {
        _onlyOwnerUnfrozen();
        thumbEpoch = e;
        emit ThumbEpochSet(e);
    }

    /// @notice The age (in ~10-min Bitcoin blocks) every thumbnail renders at right now, and the
    /// matching base stone height in milli-meters (the engine's stoneHeight at that age).
    /// Thumbnails can't follow real time, since the image URL doubles as its cache key, so they step
    /// on a fixed schedule counted from thumbEpoch (or token #1's mint): day 0, 1, 2, 4, 7, 14, 21,
    /// 30, 45, 60, 90, then 180 for good. Steps round DOWN and are dense early, where the stone grows fastest.
    /// The clock is shared, not per piece, so a piece minted before the epoch never looks older than its
    /// live render; one minted well after it can (a late mint shows the collection's step). The URL
    /// only changes at a step boundary, so it stays cacheable and pre-warmable; the render
    /// service keeps the current and next step warm.
    function imageAge() public view returns (uint256 ageBlocks, uint256 baseMilli) {
        uint256 e = thumbEpoch;
        if (e == 0) e = token.mintUnix(1);
        uint256 d = (e == 0 || block.timestamp <= e) ? 0 : (block.timestamp - e) / 1 days;
        uint16[12] memory D = [uint16(0), 1, 2, 4, 7, 14, 21, 30, 45, 60, 90, 180];
        uint32[12] memory H = [uint32(7000), 9841, 11017, 12681, 14515, 17628, 20017, 22558, 26055, 29003, 33948, 45110];
        uint256 k;
        for (uint256 i = 1; i < 12 && D[i] <= d; i++) k = i;
        return (uint256(D[k]) * 144, H[k]);
    }

    // ── Defensive satellite reads (M-06) ────────────────────────────

    /// @dev Gas-capped staticcall into a satellite. ok=false if the target is unset / has no code,
    /// the call reverts or runs out of its gas cap, or it returns fewer than `words` 32-byte words.
    /// Never reverts the caller, so a bad satellite can only blank its own contribution.
    function _read(address target, bytes memory data, uint256 words) internal view returns (bool ok, bytes memory ret) {
        if (target == address(0) || target.code.length == 0) return (false, ret);
        // Copy at most MAX_RETURN_BYTES of return data. A plain `(ok, ret) = target.staticcall(data)` copies
        // ALL of it into memory, so a hostile satellite returning hundreds of KB per read (memory cost is
        // quadratic and accumulates across ~10 reads) could push tokenURI past RPC gas limits.
        uint256 cap = MAX_RETURN_BYTES;
        assembly {
            ok := staticcall(200000, target, add(data, 32), mload(data), 0, 0)
            let size := returndatasize()
            if gt(size, cap) { size := cap }
            ret := mload(0x40)
            mstore(ret, size)
            returndatacopy(add(ret, 32), 0, size)
            mstore(0x40, add(add(ret, 32), and(add(size, 31), not(31))))
        }
        if (ok && ret.length < words * 32) ok = false;
    }

    /// @dev Largest return any satellite read needs: orbitersOf = offset + length + up to 64 ids.
    uint256 private constant MAX_RETURN_BYTES = 66 * 32;

    /// @dev Valid token ids are 1..3333 (== AccretionSeaDrop.MAX_SUPPLY). Ids from a satellite outside
    /// this range are ignored: token.hue(id) would overflow in assetIndex and revert tokenURI.
    uint256 private constant MAX_TOKEN_ID = 3333;

    /// @dev The i-th 32-byte word of ABI return data, or 0 if `ret` is too short. Bounds-checked on
    /// its own (not only via _read's length check) so a short return can never read unrelated memory.
    function _word(bytes memory ret, uint256 i) internal pure returns (uint256 w) {
        if (ret.length < (i + 1) * 32) return 0;
        assembly { w := mload(add(ret, add(32, mul(i, 32)))) }
    }

    /// @dev A satellite bool read (Crown/Skull), false on any failure or non-canonical value.
    /// @dev Same M-06 discipline as _flag, for satellite views that return a number. A bad pointer
    /// yields 0, which every caller below treats as "nothing won" rather than reverting tokenURI.
    function _num(address target, bytes4 sel, uint256 id) internal view returns (uint256) {
        (bool ok, bytes memory r) = _read(target, abi.encodeWithSelector(sel, id), 1);
        return ok ? _word(r, 0) : 0;
    }

    /// @dev A COUNT from a satellite, clamped to its known cap. These used to come from the token as
    /// uint8, where the type did the bounding for free. Read from a swappable satellite they arrive
    /// as a raw uint256, and a hostile one returning 2^256-1 overflows the `i * bits` shift inside
    /// every loop below, reverting tokenURI for the whole collection. Clamping keeps M-06's promise:
    /// a bad satellite blanks its own contribution and can never brick the metadata.
    function _count(address target, bytes4 sel, uint256 id, uint256 cap) internal view returns (uint256) {
        uint256 n = _num(target, sel, id);
        return n > cap ? cap : n;
    }
    uint256 private constant CAP_CREATURES = 24;   // == AccretionPrizes.MAX_CREATURES
    /// @dev How many creature ids `_creatureName` actually knows. MUST move with it.
    ///
    /// This is the gate on the ATTRIBUTE path only; the render CSV is bounded by CAP_CREATURES and so
    /// always listed id 9. That split is exactly how The Hollow shipped able to DRAW but with no trait
    /// on any marketplace: the 2026-10-22 swap added the name and left this at 9, so the attribute
    /// loop skipped every Hollow and nobody could see or filter one. Raise both together, or not at all.
    uint256 private constant NAMED_CREATURES = 10;
    uint256 private constant CAP_GROWTHS   = 14;   // == AccretionPrizes.MAX_PLANTED_GROWTHS (+1 innate = 15 shown)

    function _flag(address target, bytes4 sel, uint256 id) internal view returns (bool) {
        (bool ok, bytes memory r) = _read(target, abi.encodeWithSelector(sel, id), 1);
        return ok && _word(r, 0) == 1;
    }

    /// @dev Lifetime season wins, 0 on any failure (M-06). CAP_WINS is PINNED to
    /// AccretionSeasons.MAX_WINS and to the engine's own clamp on `wins` in reef_monolith.html. All
    /// three must agree or metadata and art disagree about what a win total means; tests pin them.
    uint256 private constant CAP_WINS = 255;
    uint256 private constant CAP_MILESTONES = 9999;   // display only: a sane bound on a hostile read
    function _winCount(uint256 id) internal view returns (uint256) {
        return _count(address(seasons), IAccretionSeasons.winsOf.selector, id, CAP_WINS);
    }

    /// @dev Season wins -> render param. Emitted ONLY when non-zero, exactly like `&completedHm=`, so
    /// every piece that has not won keeps a byte-identical param string and its cached thumbnail stays
    /// valid. The engine reads this as a COUNT, so new seasons never need a new engine.
    function _winParams(uint256 id) internal view returns (string memory) {
        uint256 w = _winCount(id);
        return w > 0 ? string.concat("&wins=", w.toString()) : "";
    }

    function _crown(uint256 id) internal view returns (bool) { return _flag(address(prizes), IAccretionPrizes.hasCrown.selector, id); }
    function _skull(uint256 id) internal view returns (bool) { return _flag(address(prizes), IAccretionPrizes.hasSkull.selector, id); }

    /// @dev Won Crown/Skull -> render params (empty if no prizes / nothing won).
    function _jackpotParams(uint256 id) internal view returns (string memory) {
        return string.concat(_crown(id) ? "&crown=1" : "", _skull(id) ? "&skull=1" : "");
    }

    // ── JSON escaping for owner-set strings (L-04) ──────────────────

    /// @dev Escape a string for a JSON string literal: `"` and `\` are backslash-escaped and control
    /// characters become \u00XX. A normal URL passes through byte-identical (so image parity holds).
    function _esc(string memory s) internal pure returns (string memory) {
        bytes memory b = bytes(s);
        uint256 extra;
        for (uint256 i; i < b.length; i++) {
            bytes1 c = b[i];
            if (c == '"' || c == "\\") extra += 1;
            else if (uint8(c) < 0x20) extra += 5;
        }
        if (extra == 0) return s;
        bytes memory out = new bytes(b.length + extra);
        bytes memory hexd = "0123456789abcdef";
        uint256 k;
        for (uint256 i; i < b.length; i++) {
            bytes1 c = b[i];
            if (c == '"' || c == "\\") { out[k++] = "\\"; out[k++] = c; }
            else if (uint8(c) < 0x20) {
                out[k++] = "\\"; out[k++] = "u"; out[k++] = "0"; out[k++] = "0";
                out[k++] = hexd[uint8(c) >> 4]; out[k++] = hexd[uint8(c) & 0x0f];
            } else { out[k++] = c; }
        }
        return string(out);
    }

    // ── tokenURI ────────────────────────────────────────────────────

    function tokenURI(uint256 id) external view override returns (string memory) {
        // Pre-reveal: one shared placeholder for every piece. The offset that maps id -> world is
        // unknown until the token's reveal, so nothing per-token is emitted: no attributes, no seed.
        // animation_url is the live engine in its sealed prereveal mode, a constant query that makes
        // the engine ignore every content param and render one fixed world for all tokens.
        if (token.startingIndex() == 0) {
            return string.concat("data:application/json;base64,", Base64.encode(bytes(string.concat(
                '{"name":"ACCRETION #', id.toString(),
                '","description":"', description,
                '","image":"', _esc(preRevealImage),
                '","animation_url":"', _esc(token.animationBase()), PRE_REVEAL_QUERY, '"}'))));
        }
        AccretionTraits memory t = token.traits(id);
        // image = render-service still, pinned to a fixed age (deterministic + cacheable).
        string memory img = string.concat(_esc(token.renderBase()), _imageParams(id, t));
        // animation_url = live engine off the project sat, ageing in real time.
        string memory anim = string.concat(_esc(token.animationBase()), _liveParams(id, t));
        string memory json = string.concat(
            '{"name":"ACCRETION #', id.toString(),
            '","description":"', description, '",',
            '"image":"', img, '","animation_url":"', anim, '",',
            _attributes(id, t),
            '}'
        );
        return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
    }

    // ── Render query strings ────────────────────────────────────────

    /// @dev Static (seed + discrete traits) prefix shared by birth + live params.
    function _core(uint256 id, AccretionTraits memory t) internal view returns (string memory) {
        return string.concat(
            "?seed=0x", _seedHex(id),
            "&biome=", _biomeName(t.bi),
            "&shape=", _shapeName(t.si),
            "&species=", _speciesName(t.pi),
            "&terrain=", _terrainName(t.te),
            "&sky=", _skyName(t.sk)
        );
    }

    /// @dev Static (tier + secret + visage + fx) suffix shared by birth + live.
    function _extra(AccretionTraits memory t) internal pure returns (string memory) {
        return string.concat(
            "&tier=", _tierName(t.tier),
            "&secret=", t.secret ? "1" : "0",
            "&visage=", _visageName(t.vi),
            _fxParams(t.fx)
        );
    }

    /// @notice BIRTH-state IMAGE params (the pre-warm source of truth). Current thumbnail step
    /// (imageAge), no mutations, seed-default hue, no mintUnix. Resolves BEFORE mint and is
    /// byte-identical to the image params tokenURI emits at birth, so the pre-warmed cache hits.
    function imageParams(uint256 id) external view override returns (string memory) {
        AccretionTraits memory t = token.traits(id);
        (uint256 age, ) = imageAge();
        return string.concat(
            _core(id, t),
            "&tends=1&growths=", uint256(t.pi).toString(),        // born with its innate Species growth
            "&hue=", uint256(_birthHue(id)).toString(),
            "&transfers=0&age=", age.toString(),
            _extra(t),
            _jackpotParams(id)
        );
    }

    /// @dev Current-state IMAGE params used for tokenURI's `image`: live mutation state at the
    /// current thumbnail step (and a settled kindle flag, not a real-time fade), so the thumbnail
    /// only re-renders when the token is mutated or the schedule steps. No mintUnix, so the string
    /// (and cache key) is stable between steps for a given state.
    function _imageParams(uint256 id, AccretionTraits memory t) internal view returns (string memory) {
        (uint256 age, ) = imageAge();
        string memory state = string.concat(
            "&tends=", _growthCount(id).toString(),
            "&growths=", _growthCsv(id, t),
            "&hue=", uint256(token.hue(id)).toString(),
            "&transfers=", uint256(token.transferCount(id)).toString(),
            "&age=", age.toString()
        );
        // Settled boost height only (no live ramp) so the pinned thumbnail matches the
        // Height trait and stays cache-stable; 0 at birth keeps imageParams deterministic.
        uint256 bm = _bonusMilli(id);
        string memory tail = string.concat(
            _extra(t),
            _hasCreatures(id) ? string.concat("&creatures=", _creatureCsv(id)) : "",
            bm > 0 ? string.concat("&completedHm=", bm.toString()) : "",
            // The engine adds completedHm to the age curve, so a DRAINED piece needs its own term or
            // it would render at full natural height while its Height trait said otherwise. `givenHm`
            // is what the tower must lose, and the renderer subtracts it.
            _givenMilli(id) > 0 ? string.concat("&givenHm=", _givenMilli(id).toString()) : "",
            _orbitCard(id),
            _jackpotParams(id),
            _winParams(id),
            // THREE builders emit URLs, not two: renderParams, the public imageParams, and this one,
            // which is what tokenURI's `image` actually uses. A param added to only some of them ships
            // metadata the piece's own thumbnail contradicts. Any new param goes in every builder it
            // belongs in, or none.
            _identityParam(id)
        );
        return string.concat(_core(id, t), state, tail);
    }

    /// @notice LIVE render params for animation_url: current mutation state + real-time
    /// anchors (mintUnix drives ageing, kindleUnix drives the beacon fade). Not pinned.
    function renderParams(uint256 id) external view override returns (string memory) {
        return _liveParams(id, token.traits(id));
    }

    function _liveParams(uint256 id, AccretionTraits memory t) internal view returns (string memory) {
        string memory state = string.concat(
            "&tends=", _growthCount(id).toString(),
            "&growths=", _growthCsv(id, t),
            "&hue=", uint256(token.hue(id)).toString(),
            "&transfers=", uint256(token.transferCount(id)).toString(),
            "&mintUnix=", uint256(token.mintUnix(id)).toString()
        );
        string memory tail = string.concat(
            _extra(t),
            _hasCreatures(id) ? string.concat("&creatures=", _creatureCsv(id)) : "",
            _boostParams(id),
            _dormant(id),
            _jackpotParams(id),
            _winParams(id),
            // Unconditional on purpose. This lived inside _boostParams once, which early-returns for
            // any piece that has never orbited, so the companion silently vanished from the render URL
            // while still showing as a tokenURI attribute. The two paths must agree.
            _identityParam(id)
        );
        return string.concat(_core(id, t), state, tail);
    }

    /// @dev Rare post-filter treatments -> renderer query params (only those set).
    function _fxParams(uint8 fx) internal pure returns (string memory out) {
        string[4] memory p = ["&aberration=1", "&anamorphic=1", "&woodcut=1", "&crt=1"];
        for (uint256 i; i < 4; ++i) if (((fx >> i) & 1) == 1) out = string.concat(out, p[i]);
    }

    /// @dev Growths shown on the piece: the innate Species growth plus every tended one (1..15).
    /// @dev 1 innate Species form every piece is born with, plus every growth planted from a won
    /// charge. Reads the satellite: with none wired (or a bad pointer) a piece shows its innate coral
    /// and nothing else, which is exactly the correct pre-launch state.
    function _growthCount(uint256 id) internal view returns (uint256) {
        uint256 n = 1 + _count(address(prizes), IAccretionPrizes.growthCount.selector, id, CAP_GROWTHS)
                      + _msGrowths(id);
        return n > CAP_GROWTHS + 1 ? CAP_GROWTHS + 1 : n;
    }

    /// @dev Growth forms in order, CSV of form indices: the innate Species form first, then each
    /// tended form in tend order. Never empty, so every piece renders at least one coral.
    function _growthCsv(uint256 id, AccretionTraits memory t) internal view returns (string memory out) {
        out = uint256(t.pi).toString();
        uint256 seq = _num(address(prizes), IAccretionPrizes.growthSeq.selector, id);
        uint256 n = _count(address(prizes), IAccretionPrizes.growthCount.selector, id, CAP_GROWTHS);
        for (uint256 i; i < n; i++) {
            out = string.concat(out, ",", ((seq >> (i * 4)) & 15).toString());   // 4 bits per form
        }
        // Milestone growths carry no form of their own: the satellite grants a COUNT, deliberately,
        // so it never has to know the engine's form vocabulary. The form is derived here instead,
        // deterministically per (piece, index). GROWTH_FORMS is PINNED to GROWTH_TYPES.length in
        // reef_monolith.html; an index past the engine's list renders nothing.
        uint256 m = _msGrowths(id);
        for (uint256 i; i < m && n + i < CAP_GROWTHS; i++) {
            uint256 f = uint256(keccak256(abi.encodePacked(_tokenAddr, id, "ms", i))) % GROWTH_FORMS;
            out = string.concat(out, ",", f.toString());
        }
    }
    uint256 private constant GROWTH_FORMS = 7;   // == GROWTH_TYPES.length in reef_monolith.html

    /// @dev Companions from ONE satellite, appended to `acc` and skipping anything already emitted.
    /// `seen` is a bit per registry id; `n` is how many have been written so far.
    function _creatureRun(string memory acc, uint256 seen, uint256 n, address src, uint256 id)
        internal view returns (string memory, uint256, uint256)
    {
        uint256 seq = _num(src, IAccretionPrizes.creatureSeq.selector, id);
        uint256 k = _count(src, IAccretionPrizes.creatureCount.selector, id, CAP_CREATURES);
        for (uint256 i; i < k; i++) {
            if (n >= CAP_CREATURES) break;
            uint256 c = (seq >> (i * 8)) & 255;   // 8 bits: the roster outgrows 16 ids over seasons
            uint256 bit = uint256(1) << c;
            if (seen & bit != 0) continue;        // the roster is COLLECTED, so never list one twice
            seen |= bit;
            acc = n == 0 ? c.toString() : string.concat(acc, ",", c.toString());
            n++;
        }
        return (acc, seen, n);
    }

    /// @dev Added creatures in add order, CSV of registry ids (empty if none). Merges the lottery's
    /// set with the milestone set and DEDUPES: a piece that earned the same body down both paths shows
    /// it once, because two identical companions read as a bug rather than a reward. Milestones grant
    /// from the unheld set already, so this is a belt-and-braces guard against a repointed satellite.
    function _creatureCsv(uint256 id) internal view returns (string memory out) {
        uint256 seen;
        uint256 n;
        (out, seen, n) = _creatureRun("", seen, n, address(prizes), id);
        (out, , ) = _creatureRun(out, seen, n, address(milestones), id);
    }

    /// @dev Does this piece have any companion at all, from either satellite? Over-counts duplicates,
    /// which is harmless: every caller only asks whether the total is non-zero.
    function _hasCreatures(uint256 id) internal view returns (bool) {
        return _count(address(prizes), IAccretionPrizes.creatureCount.selector, id, CAP_CREATURES)
             + _count(address(milestones), IAccretionPrizes.creatureCount.selector, id, CAP_CREATURES) > 0;
    }

    /// @dev Growths granted by milestones, clamped like every other satellite read (M-06).
    function _msGrowths(uint256 id) internal view returns (uint256) {
        return _count(address(milestones), IAccretionMilestones.bonusGrowths.selector, id, CAP_GROWTHS);
    }

    // ── Holdings-boost (v1 satellite) ───────────────────────────────

    /// @dev Heights above this are treated as garbage from a bad satellite (1,000 km), which also
    /// keeps the base height + bonus far from overflow.
    uint256 private constant MAX_SANE_MILLI = 1e9;
    /// @dev The floor no piece can ever be poured below. Sits BELOW the 7000 birth height on purpose,
    /// so every piece starts the game with 2 m it can already give. MUST equal
    /// AccretionOrbit.POUR_FLOOR_MILLI and the engine's BIRTH_M, or a drained tower renders at a
    /// different height than its Height trait claims. `test_PourFloorMatchesBetweenOrbitAndDescriptor`
    /// pins the first two by draining a piece; nothing in Solidity can read the third, so the engine's
    /// copy is checked by hand whenever the engine is re-inscribed.
    uint256 internal constant POUR_FLOOR_MILLI = 5000;

    /// @dev Live boost params for the renderer (empty if no satellite / no boost yet / bad data).
    function _boostParams(uint256 id) internal view returns (string memory) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.boostParams.selector, id), 4);
        if (!ok) return "";
        uint256 completedMilli = _word(r, 0);
        uint256 start = _word(r, 1);
        uint256 strength = _word(r, 2);
        uint256 durationSecs = _word(r, 3);
        if (completedMilli > MAX_SANE_MILLI || start > type(uint64).max
            || strength > type(uint32).max || durationSecs > type(uint32).max) return "";
        // A piece that has only POURED (never hosted) still needs its term, so this cannot early-out
        // on the boost alone: a drained donor has completedMilli == 0 and start == 0 yet must render
        // shorter than the shared curve.
        uint256 given = _givenMilli(id);
        if (completedMilli == 0 && start == 0 && given == 0) return "";
        // Pass the active orbit's FULL target contribution so the renderer can ramp it
        // 0 -> full over [start, start+dur] without needing the contract's rate.
        string memory active = start > 0
            ? string.concat(
                "&boostStart=", start.toString(),
                "&boostDur=", durationSecs.toString(),
                "&boostFullHm=", _fullMilli(id, strength, durationSecs).toString(),
                "&orbiters=", strength.toString(),   // Core: how many donor worlds to render orbiting
                _orbHues(id)                         // Core: each orbiting donor's attune hue (energy colour)
            )
            : "";
        return string.concat(
            "&completedHm=", completedMilli.toString(),
            given > 0 ? string.concat("&givenHm=", given.toString()) : "",
            active
        );
    }

    /// @dev The active orbit's ramp target: Orbit's snapshotted-rate activeContribMilli if the satellite
    /// has it, else the boost-compatible contribMilli preview (the paid AccretionBoost), else 0.
    function _fullMilli(uint256 id, uint256 strength, uint256 durationSecs) internal view returns (uint256) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.activeContribMilli.selector, id), 1);
        if (!ok) {
            (ok, r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.contribMilli.selector, uint32(strength), uint32(durationSecs)), 1);
        }
        if (!ok) return 0;
        uint256 m = _word(r, 0);
        return m > MAX_SANE_MILLI ? 0 : m;
    }

    /// @dev CSV of each orbiting donor's attune hue (degrees), so the Core renders each feeder
    /// thread in that donor's colour. A satellite without orbitersOf (the paid AccretionBoost), or
    /// one returning malformed data, simply omits it and the renderer falls back to the Core hue.
    function _orbHues(uint256 coreId) internal view returns (string memory out) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.orbitersOf.selector, coreId), 2);
        if (!ok || _word(r, 0) != 32) return "";               // ABI: offset of the dynamic array
        uint256 n = _word(r, 1);
        if (n > 64 || r.length < (n + 2) * 32) return "";      // bounded; donors are capped at 20 anyway
        for (uint256 i; i < n; i++) {
            uint256 did = _word(r, i + 2);
            if (did == 0 || did > MAX_TOKEN_ID) continue;           // hostile / garbage id: skip, never revert
            string memory h = uint256(token.hue(did)).toString();
            out = bytes(out).length == 0 ? string.concat("&orbHues=", h) : string.concat(out, ",", h);
        }
    }

    /// @dev A token that is itself orbiting a Core renders dormant (drained), but only while its lock
    /// is actually running: once the lock expires (even before anyone releases the orbit) the piece
    /// is transferable, so it must not show a buyer drained art.
    function _dormant(uint256 id) internal view returns (string memory) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.orbitingCore.selector, id), 1);
        return ok && _word(r, 0) != 0 && token.locked(id) ? "&dormant=1" : "";
    }

    /// @dev Orbit state for the PINNED card: a donor renders dormant, a Core renders its orbiters.
    /// Only the flags that hold still for the whole orbit. The ramping height, its start and the donor
    /// hues stay in renderParams: putting them here would change the image URL (and so its cache entry)
    /// every block, or every time a donor attunes. Empty when nothing is orbiting.
    function _orbitCard(uint256 id) internal view returns (string memory) {
        string memory d = _dormant(id);
        if (bytes(d).length != 0) return d;
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.boostParams.selector, id), 4);
        if (!ok) return "";
        uint256 start = _word(r, 1);
        uint256 strength = _word(r, 2);
        if (start == 0 || strength == 0 || strength > type(uint32).max) return "";
        return string.concat("&orbiters=", strength.toString());
    }

    /// @dev The linked BlockForge Identity, 1..100, or "" when unset. The renderer resolves the index
    /// against the collection's known reveal base and then verifies the claim on Bitcoin, so a wrong
    /// number here draws nothing rather than drawing someone else's avatar.
    function _identityNum(uint256 id) internal view returns (uint256) {
        if (identity == address(0)) return 0;
        (bool ok, bytes memory r) = _read(identity, abi.encodeWithSelector(0xcf86d48c, id), 1);
        if (!ok) return 0;
        uint256 n = _word(r, 0);
        return n > 100 ? 0 : n;   // out of range reads as unset, never as some other character
    }

    /// @dev Emits the Identity index AND this piece's token id, together or not at all. The renderer
    /// needs `tid` to verify the claim on Bitcoin: it reads the Identity's child inscriptions and only
    /// draws the avatar when one names THIS token. Emitting them as a pair means an unlinked piece's
    /// URL stays byte-identical to today's, so its pre-warmed thumbnail is still valid.
    function _identityParam(uint256 id) internal view returns (string memory) {
        uint256 n = _identityNum(id);
        return n == 0 ? "" : string.concat("&identity=", n.toString(), "&tid=", id.toString());
    }

    /// @dev Orbit role for the attributes: "Core", "Orbiter", or "None".
    ///
    /// Decided LIVE from the satellite on every read, never from a stored flag, because a lock EXPIRES
    /// silently (there is no Unlocked event, `locked()` is the truth). A cached flag would keep telling
    /// buyers a piece was in orbit after it became transferable again, and nothing would correct it until
    /// somebody released the orbit.
    ///
    /// The lock, not the pending bonus, is the test, for the same reason `_dormant` uses it: between a
    /// lock lapsing and the keeper releasing the orbit, the piece IS transferable, and a buyer looking at
    /// it must not be told it is locked away. Such a piece reads "None" even though its bonus has yet to
    /// settle. A piece locked by the owner outside an orbit matches neither branch and also reads "None".
    function _orbitRole(uint256 id) internal view returns (string memory) {
        if (!token.locked(id)) return "None";                  // the 3,300 free pieces stop here, 2 fewer staticcalls
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.orbitingCore.selector, id), 1);
        if (ok && _word(r, 0) != 0) return "Orbiter";
        (ok, r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.boostParams.selector, id), 4);
        if (ok && _word(r, 1) != 0 && _word(r, 2) != 0) return "Core";
        return "None";
    }

    /// @dev Settled (stable) boost bonus in milli-meters; 0 if no satellite or bad data.
    /// @dev Height a piece has POURED AWAY, net of regeneration. Subtracted from the shared age
    /// curve, so a drained tower renders genuinely shorter. That is the entire visual language of the
    /// economy and it needs no new art: the tower is shorter, and that is the whole signal.
    function _givenMilli(uint256 id) internal view returns (uint256) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.givenMilli.selector, id), 1);
        if (!ok) return 0;
        uint256 m = _word(r, 0);
        return m > MAX_SANE_MILLI ? 0 : m;
    }

    /// @notice A piece's height right now: the shared age curve, MINUS what it poured away, PLUS what
    /// it took from donors. Floored at the pour floor, which the Orbit already guarantees by capping
    /// every pour at `natural - POUR_FLOOR`; the floor here is belt-and-braces against a mismatched or
    /// hostile satellite, since an underflow would revert tokenURI for the piece.
    function heightMilli(uint256 id) public view returns (uint256) {
        uint256 base = _baseMilliNow();
        uint256 given = _givenMilli(id);
        uint256 net = given >= base - POUR_FLOOR_MILLI ? POUR_FLOOR_MILLI : base - given;
        return net + _bonusMilli(id);
    }

    function _bonusMilli(uint256 id) internal view returns (uint256) {
        (bool ok, bytes memory r) = _read(address(boost), abi.encodeWithSelector(IAccretionBoost.settledBonusMilli.selector, id), 1);
        if (!ok) return 0;
        uint256 m = _word(r, 0);
        return m > MAX_SANE_MILLI ? 0 : m;
    }

    /// @dev Base stone height at the current thumbnail step, so the Height trait matches the image.
    function _baseMilliNow() internal view returns (uint256 m) {
        (, m) = imageAge();
    }

    /// @dev milli-meters -> "W.D" (one decimal), placed UNQUOTED as a JSON number.
    function _meters(uint256 milli) internal pure returns (string memory) {
        return string.concat((milli / 1000).toString(), ".", ((milli / 100) % 10).toString());
    }

    // ── Attributes ──────────────────────────────────────────────────

    function _attributes(uint256 id, AccretionTraits memory t) internal view returns (string memory) {
        string memory staticAttrs = string.concat(
            '{"trait_type":"Tier","value":"', _tierName(t.tier), '"},',
            '{"trait_type":"Biome","value":"', _biomeName(t.bi), '"},',
            '{"trait_type":"Shape","value":"', _shapeName(t.si), '"},',
            '{"trait_type":"Species","value":"', _speciesName(t.pi), '"},',
            '{"trait_type":"Terrain","value":"', _terrainName(t.te), '"},',
            '{"trait_type":"Sky","value":"', _skyName(t.sk), '"},',
            '{"trait_type":"Secret","value":"', t.secret ? "Yes" : "No", '"},'
        );
        // Visage (rare voxel face) + the prizes-won Crown/Skull each appear only when present,
        // so they read as rarity filters.
        string memory visAttr = t.vi == 0 ? "" : '{"trait_type":"Visage","value":"Face"},';
        string memory wonAttrs = _wonAttrs(id);
        string memory fxAttr = _fxAttrs(t.fx);
        string memory mutAttrs = string.concat(
            '{"trait_type":"Growths","value":"', _growthCount(id).toString(), '"},',
            '{"trait_type":"Transfers","value":"', uint256(token.transferCount(id)).toString(), '"},',
            '{"trait_type":"Orbit","value":"', _orbitRole(id), '"},',
            '{"trait_type":"Height","display_type":"number","value":', _meters(heightMilli(id)), '},',
            '{"trait_type":"Attune Hue","display_type":"number","value":', uint256(token.hue(id)).toString(), '}'
        );
        return string.concat(
            '"attributes":[', staticAttrs, visAttr, wonAttrs, fxAttr, mutAttrs,
            _formAttrs(id, t), _creatureAttrs(id), ']'
        );
    }

    /// @dev Jackpot-won Crown/Skull attributes (only when held, so they read as rarity filters).
    function _wonAttrs(uint256 id) internal view returns (string memory out) {
        if (_crown(id)) out = string.concat(out, '{"trait_type":"Crown","value":"Yes"},');
        if (_skull(id)) out = string.concat(out, '{"trait_type":"Skull","value":"Yes"},');
        // ONE numeric key for every season, never a key per season: at roughly 26 seasons a year a
        // per-season key would bury the trait panel and make each individual win less legible.
        uint256 w = _winCount(id);
        if (w > 0) out = string.concat(out, '{"trait_type":"Seasons Won","display_type":"number","value":', w.toString(), '},');
        // Milestones settled, the visible measure of how far a piece has been played. Numeric so it
        // sorts, and emitted only when non-zero so an unplayed piece keeps a byte-identical panel.
        uint256 ms_ = _count(address(milestones), IAccretionMilestones.claimedCount.selector, id, CAP_MILESTONES);
        if (ms_ > 0) out = string.concat(out, '{"trait_type":"Milestones","display_type":"number","value":', ms_.toString(), '},');
        // Identity reads as TWO keys on purpose. "Yes" is the filter a buyer actually wants ("show me
        // the pieces with a companion"); the number is a string, not display_type number, so it filters
        // to one character instead of offering a 1..100 range slider nobody would drag.
        uint256 idn = _identityNum(id);
        if (idn > 0) out = string.concat(out, '{"trait_type":"Identity","value":"Yes"},',
            '{"trait_type":"Identity #","value":"', idn.toString(), '"},');
    }

    /// @dev Rare post-filter treatments -> filterable OpenSea facets (only those set).
    function _fxAttrs(uint8 fx) internal pure returns (string memory out) {
        string[4] memory n = ["Aberration", "Anamorphic", "Woodcut", "CRT"];
        for (uint256 i; i < 4; ++i) {
            if (((fx >> i) & 1) == 1) out = string.concat(out, '{"trait_type":"', n[i], '","value":"Yes"},');
        }
    }

    /// @dev Per-form growth counts as filterable traits (only forms present appear), counting the
    /// innate Species growth AND every milestone growth, so the per-form totals add up to the Growths
    /// attribute at any `creaturePct`.
    function _formAttrs(uint256 id, AccretionTraits memory t) internal view returns (string memory out) {
        uint256 seq = _num(address(prizes), IAccretionPrizes.growthSeq.selector, id);
        uint256 n = _count(address(prizes), IAccretionPrizes.growthCount.selector, id, CAP_GROWTHS);
        uint256[7] memory c;
        if (t.pi < 3) c[t.pi] += 1;   // innate Species growth (forms 0-2)
        for (uint256 i; i < n; i++) { uint256 g = (seq >> (i * 4)) & 15; if (g < 7) c[g] += 1; }
        // Milestone growths, under the SAME derived form `_growthCsv` renders them as. Counting them
        // here is what keeps the per-form totals adding up to the Growths attribute. Omitted before,
        // so a piece drew corals the trait panel could not account for. Reachable even at
        // creaturePct = 100: once a piece holds every companion, `_pickUnheld` fails and milestones
        // fall through to growths on their own.
        uint256 m = _msGrowths(id);
        for (uint256 i; i < m && n + i < CAP_GROWTHS; i++) {
            c[uint256(keccak256(abi.encodePacked(_tokenAddr, id, "ms", i))) % GROWTH_FORMS] += 1;
        }
        for (uint256 f; f < 7; f++) {
            if (c[f] == 0) continue;
            out = string.concat(out, ',{"trait_type":"', _formName(f), ' Coral","value":"', c[f].toString(), '"}');
        }
    }

    /// @dev Won creatures as filterable traits. One of each per piece now, so this is a PRESENCE
    /// list rather than counts and every value is "Yes", which is also how Crown and Skull read.
    ///
    /// Bounded by NAMED, the descriptor's name table, not by the satellite's roster. The roster can
    /// grow past this; ids beyond the table simply do not surface as attributes until a descriptor
    /// carrying their names is swapped in, which is the same lockstep an engine re-inscribe needs to
    /// draw them. Silent omission is the right failure: a piece never loses a creature it won.
    ///
    /// Reads BOTH satellites, the same pair and in the same order as `_creatureCsv`. It used to read
    /// `prizes` alone, so a companion granted by a MILESTONE reached the art through `&creatures=` but
    /// never became a filterable trait: the piece visibly had the body while its trait panel showed
    /// only "Milestones: 1". Measured on the throwaway 2026-09-29.
    function _creatureAttrs(uint256 id) internal view returns (string memory out) {
        uint256 seen;
        (out, seen) = _creatureAttrRun("", seen, address(prizes), id);
        (out, ) = _creatureAttrRun(out, seen, address(milestones), id);
    }

    /// @dev One satellite's creatures as attributes. `seen` is carried across both calls so the two
    /// sources dedupe against each other exactly as they do for the CSV.
    function _creatureAttrRun(string memory acc, uint256 seen, address src, uint256 id)
        internal view returns (string memory, uint256)
    {
        uint256 seq = _num(src, IAccretionPrizes.creatureSeq.selector, id);
        uint256 k = _count(src, IAccretionPrizes.creatureCount.selector, id, CAP_CREATURES);
        for (uint256 i; i < k; i++) {
            uint256 g = (seq >> (i * 8)) & 255;
            uint256 bit = uint256(1) << g;
            if (g >= NAMED_CREATURES || seen & bit != 0) continue;
            seen |= bit;
            acc = string.concat(acc, ',{"trait_type":"', _creatureName(g), '","value":"Yes"}');
        }
        return (acc, seen);
    }

    // ── Seed (recomputed identically to the token) ──────────────────

    function _seed(uint256 id) internal view returns (bytes32) {
        // Shuffled world index (identity until the token's reveal). Both this and the
        // token's own _seed read the SAME assetIndex, so traits + ?seed stay consistent.
        return keccak256(abi.encodePacked(token.assetIndex(id), block.chainid, _tokenAddr));
    }

    function _pick(bytes32 s, string memory salt, uint256 total) internal pure returns (uint256) {
        return uint256(keccak256(abi.encodePacked(s, salt))) % total;
    }

    function _birthHue(uint256 id) internal view returns (uint16) {
        return uint16(_pick(_seed(id), "hue0", 360));
    }

    /// @dev First 8 hex chars of the seed (matches the Manifold extension's ?seed).
    function _seedHex(uint256 id) internal view returns (string memory) {
        bytes32 h = _seed(id);
        bytes memory out = new bytes(8);
        bytes memory abc = "0123456789abcdef";
        for (uint256 i = 0; i < 4; i++) {
            out[i * 2]     = abc[uint8(h[i]) >> 4];
            out[i * 2 + 1] = abc[uint8(h[i]) & 0x0f];
        }
        return string(out);
    }

    // ── Index -> label tables (mirror AccretionExtension strings) ───

    function _biomeName(uint8 bi) internal pure returns (string memory) {
        return bi == 0 ? "sandstone" : bi == 1 ? "granite" : bi == 2 ? "brick"
             : bi == 3 ? "metallic" : bi == 4 ? "basalt" : bi == 5 ? "abyssal"
             : bi == 6 ? "glacier" : bi == 7 ? "marble" : bi == 8 ? "aureate"
             : bi == 9 ? "malachite" : bi == 10 ? "umber" : "bismuth";
    }

    function _shapeName(uint8 si) internal pure returns (string memory) {
        return si == 0 ? "obelisk" : si == 1 ? "spire" : si == 2 ? "ziggurat"
             : si == 3 ? "leaning" : si == 4 ? "shattered" : si == 5 ? "twisted" : "cairn";
    }

    function _speciesName(uint8 pi) internal pure returns (string memory) {
        return pi == 0 ? "branch" : pi == 1 ? "fan" : "tube";
    }

    function _terrainName(uint8 te) internal pure returns (string memory) {
        return te == 0 ? "organic" : te == 1 ? "grid" : "scattered";
    }

    function _skyName(uint8 sk) internal pure returns (string memory) {
        return sk == 0 ? "clear" : sk == 1 ? "nebula" : "aurora";
    }

    function _visageName(uint8 vi) internal pure returns (string memory) {
        return vi == 1 ? "face" : "none";   // binary now; skull moved to the prizes (?skull=1)
    }

    function _tierName(uint8 tier) internal pure returns (string memory) {
        return tier == 4 ? "Legendary" : tier == 3 ? "Epic" : tier == 2 ? "Rare"
             : tier == 1 ? "Uncommon" : "Common";
    }

    function _formName(uint256 f) internal pure returns (string memory) {
        return f == 0 ? "Branch" : f == 1 ? "Fan" : f == 2 ? "Tube" : f == 3 ? "Brain"
             : f == 4 ? "Frond" : f == 5 ? "Anemone" : "Plate";
    }

    /// @dev Fixed 8-entry creature registry (index === id).
    /// @dev Index === creature id. The final branch is a CATCH-ALL, so any id past the last named one
    /// comes back "The Hollow": that is why NAMED_CREATURES gates the caller, and why the two constants
    /// have to be raised in the same commit as a new name.
    function _creatureName(uint256 k) internal pure returns (string memory) {
        return k == 0 ? "Golem" : k == 1 ? "Mammoth" : k == 2 ? "Sea Turtle" : k == 3 ? "Pepe"
             : k == 4 ? "Laser Bull" : k == 5 ? "CryptoPunk" : k == 6 ? "Ape" : k == 7 ? "Wizard"
             : k == 8 ? "Phoenix" : "The Hollow";
    }
}

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return result;
    }
}

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

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

pragma solidity ^0.8.0;

import "./math/Math.sol";

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/IAccretionDescriptor.sol

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

/// @notice The immutable, seed-rolled trait DNA for a token, as NUMERIC indices.
///
/// The Manifold AccretionExtension.Traits struct carried the human-readable strings
/// ("sandstone", "obelisk", ...) inline. Here the token returns only the numeric
/// bucket each trait rolled into, and the swappable descriptor maps index -> string.
/// This is a deliberate DRAFT deviation forced by size: the ERC721SeaDrop base is
/// ~16.4KB, and carrying the string tables on the token blew past the 24576-byte
/// limit. The WEIGHTS (the rarity thresholds) — the real source of truth — stay
/// on the immutable token; only the presentational labels move to the descriptor.
/// The thresholds are ported VERBATIM from AccretionExtension._traits().
struct AccretionTraits {
    uint8 bi;    // biome  0-8  (0 sandstone .. 7 marble, 8 aureate/legendary)
    uint8 si;    // shape  0-4  (0 obelisk,1 spire,2 ziggurat,3 leaning,4 shattered)
    uint8 pi;    // species 0-2 (0 branch,1 fan,2 tube)
    uint8 te;    // terrain 0-2 (0 organic,1 grid,2 scattered)
    uint8 sk;    // sky    0-2  (0 clear,1 nebula,2 aurora)
    uint8 vi;    // visage 0-2  (0 none,1 face,2 skull)
    uint8 fx;    // rare post-filter bitmask: 1=aberration 2=anamorphic 4=woodcut 8=crt
    bool secret;
    uint8 tier;  // 0 Common,1 Uncommon,2 Rare,3 Epic,4 Legendary
}

/// @notice The swappable metadata descriptor. The token contract delegates
/// `tokenURI(id)` and the render query-string builders to whatever address is
/// registered as its descriptor. This lets the immutable token keep frozen art +
/// mutation rules while the JSON shape / query format / feature set stays
/// upgradeable until the token owner calls lockDescriptor().
interface IAccretionDescriptor {
    /// @notice Build the full (base64 data URI) tokenURI for `tokenId`.
    function tokenURI(uint256 tokenId) external view returns (string memory);

    /// @notice BIRTH-state render query string (tends=0, seed-default hue, no
    /// kindle, no creatures). Depends only on immutable token inputs, so it
    /// resolves BEFORE mint — the pre-warm source of truth for the render service.
    function imageParams(uint256 tokenId) external view returns (string memory);

    /// @notice Live render query string: static traits + seed + current mutation
    /// state + ETH-native time anchors.
    function renderParams(uint256 tokenId) external view returns (string memory);
}

/// @notice The read surface the descriptor uses to pull the immutable trait DNA +
/// live mutation state off the token contract. AccretionSeaDrop implements each.
interface IAccretionToken {
    function traits(uint256 id) external view returns (AccretionTraits memory);
    function assetIndex(uint256 id) external view returns (uint256);   // shuffled world index (post-reveal)
    function startingIndex() external view returns (uint256);          // 0 until reveal (gates the placeholder)
    function renderBase() external view returns (string memory);
    function animationBase() external view returns (string memory);
    function transferCount(uint256 id) external view returns (uint32);
    function kindleUnix(uint256 id) external view returns (uint64);
    function hue(uint256 id) external view returns (uint16);
    function mintUnix(uint256 id) external view returns (uint64);
    // NOTE: growths and companions live on the PRIZES satellite, not here. They were declared on this
    // interface when the token still held them; a descriptor calling them on the token now reverts.
    function locked(uint256 id) external view returns (bool);          // orbit lock still running (expiry-based)
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "@manifoldxyz/creator-core-solidity/=node_modules/@manifoldxyz/creator-core-solidity/",
    "@manifoldxyz/libraries-solidity/=node_modules/@manifoldxyz/libraries-solidity/",
    "forge-std/=lib/forge-std/src/",
    "seadrop/=lib/seadrop/src/",
    "ERC721A/=lib/seadrop/lib/ERC721A/contracts/",
    "ERC721A-Upgradeable/=lib/seadrop/lib/ERC721A-Upgradeable/contracts/",
    "openzeppelin-contracts/=lib/seadrop/lib/openzeppelin-contracts/contracts/",
    "openzeppelin-contracts-upgradeable/=lib/seadrop/lib/openzeppelin-contracts-upgradeable/contracts/",
    "solmate/=lib/seadrop/lib/solmate/src/",
    "utility-contracts/=lib/seadrop/lib/utility-contracts/src/",
    "operator-filter-registry/=lib/seadrop/lib/operator-filter-registry/src/",
    "@ensdomains/=node_modules/@ensdomains/",
    "create2-helpers/=lib/seadrop/lib/create2-helpers/",
    "create2-scripts/=lib/seadrop/lib/create2-helpers/script/",
    "ds-test/=lib/seadrop/lib/ds-test/src/",
    "murky/=lib/seadrop/lib/murky/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.