Skip to content
Verified contractExactMIT

TonalGeometries

Address0xda3ed34ba176086bced1f17cc5f0fea4c355ee2f
Balance

0.005 ETH

 

Transactions

8

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,380,907
Creation transaction
0x3897c1c3b5…6553cc9ae5

contracts/TonalGeometries.sol

// SPDX-License-Identifier: MIT
// TonalGeometries.sol -- on-chain ERC-721 for the Tonal Geometries series (Series trait "6").
//
// Derived from the Rounded Geometries review-package contract (same ERC-721 / 2981 /
// SSTORE2 renderer / owner-controls structure). Differences:
//   * Page: a hash-driven Tonal Geometries audiovisual piece (26,757 B, head + 2 SSTORE2 tails),
//     minified + mangled, NOT obfuscated.
//   * Max supply 150, mint price 0.001 ETH, royalty 10% (hard cap 10%), sale closed at deploy.
//   * Seed is keccak256(blockhash(block.number-1), tokenId, minter), stored at mint; the page
//     reads it as tokenData.hash.
//   * Hash-derived traits (reference/tonal_core.js, header comment): the hash is 16 big-endian
//     uint16 words; every trait is a uniform pick floor(w*N/65536). The contract emits Scale Family,
//     Scale, Base Pitch (first heard note, with cents), Tuning, Interval Path,
//     Contour, States, Second Voice for the stored hash, matching the page's
//     own derivation (tested against reference/expected_traits_vectors.json). Fixed traits:
//     Palette, Color Mapping, Color Drift, Structure. Artist / Moniker / Series appended.
//   * Sale switch is closed at deploy; owner opens it. Two-step ownership.
//
// !!! Assistant review only (see SECURITY_REVIEW.md) -- not an independent
// !!! professional audit. Nothing here is deployed.
//
// Review-package changes vs the Rounded Geometries packet: see CHANGELOG.md.
pragma solidity 0.8.24;

import {Base64} from "./lib/Base64.sol";
import {SSTORE2} from "./lib/SSTORE2.sol";
import {TonalTraits} from "./TonalTraits.sol";

interface IERC721Receiver {
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
        external
        returns (bytes4);
}

contract TonalGeometries {
    // ---------------------------------------------------------------- ERC721
    string public constant name = "Tonal Geometries";
    string public constant symbol = "TONGEO";

    mapping(uint256 => address) private _owners;
    mapping(address => uint256) private _balances;
    mapping(uint256 => address) private _tokenApprovals;
    mapping(address => mapping(address => bool)) private _operatorApprovals;
    uint256 private _totalSupply;

    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    error NonexistentToken();
    error NotAuthorized();
    error UnsafeRecipient();
    error LengthMismatch();
    error BadURI();

    // ERC-4906 metadata-update events
    event MetadataUpdate(uint256 _tokenId);
    event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);

    function supportsInterface(bytes4 id) external pure returns (bool) {
        return id == 0x01ffc5a7 // ERC165
            || id == 0x80ac58cd // ERC721
            || id == 0x5b5e139f // ERC721Metadata
            || id == 0x2a55205a // ERC2981
            || id == 0x49064906; // ERC4906
    }

    function balanceOf(address owner_) external view returns (uint256) {
        require(owner_ != address(0), "zero address");
        return _balances[owner_];
    }

    function ownerOf(uint256 tokenId) public view returns (address) {
        address o = _owners[tokenId];
        if (o == address(0)) revert NonexistentToken();
        return o;
    }

    function totalSupply() external view returns (uint256) {
        return _totalSupply;
    }

    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
        address o = ownerOf(tokenId);
        return spender == o || _tokenApprovals[tokenId] == spender || _operatorApprovals[o][spender];
    }

    function approve(address to, uint256 tokenId) external {
        address o = ownerOf(tokenId);
        require(msg.sender == o || _operatorApprovals[o][msg.sender], "not authorized");
        require(to != o, "approval to current owner");
        _tokenApprovals[tokenId] = to;
        emit Approval(o, to, tokenId);
    }

    function getApproved(uint256 tokenId) external view returns (address) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        return _tokenApprovals[tokenId];
    }

    function setApprovalForAll(address operator, bool approved) external {
        require(operator != msg.sender, "self approval");
        _operatorApprovals[msg.sender][operator] = approved;
        emit ApprovalForAll(msg.sender, operator, approved);
    }

    function isApprovedForAll(address owner_, address operator) external view returns (bool) {
        return _operatorApprovals[owner_][operator];
    }

    function transferFrom(address from, address to, uint256 tokenId) public {
        if (!_isApprovedOrOwner(msg.sender, tokenId)) revert NotAuthorized();
        if (_owners[tokenId] != from) revert NotAuthorized();
        require(to != address(0), "zero address");
        delete _tokenApprovals[tokenId];
        _balances[from]--;
        _balances[to]++;
        _owners[tokenId] = to;
        emit Approval(from, address(0), tokenId);
        emit Transfer(from, to, tokenId);
    }

    function safeTransferFrom(address from, address to, uint256 tokenId) external {
        safeTransferFrom(from, to, tokenId, "");
    }

    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
        transferFrom(from, to, tokenId);
        if (to.code.length > 0) {
            (bool ok, bytes memory ret) = to.call(
                abi.encodeWithSelector(
                    IERC721Receiver.onERC721Received.selector, msg.sender, from, tokenId, data
                )
            );
            // The receiver must return the 32-byte magic value. Accept >= 32
            // bytes (OpenZeppelin behavior) so recipients that append extra
            // return data are not rejected; short/empty returns still revert.
            // Note: abi.decode reverts on trailing data, so read the first
            // word directly.
            if (!ok || ret.length < 32) revert UnsafeRecipient();
            bytes4 retval;
            assembly { retval := mload(add(ret, 32)) }
            if (retval != IERC721Receiver.onERC721Received.selector) revert UnsafeRecipient();
        }
    }

    function _mint(address to) internal returns (uint256 tokenId) {
        require(to != address(0), "zero address");
        tokenId = ++_nextId;
        _owners[tokenId] = to;
        _balances[to]++;
        _totalSupply++;
        emit Transfer(address(0), to, tokenId);
    }

    // ---------------------------------------------------------------- minting
    // Release config (Calvin, 2026-10-18; supply 150 since 2026-10-27): 150 supply, 0.001 ETH mint, sale closed at deploy.
    uint256 public constant MAX_SUPPLY = 150;
    uint256 public mintPrice = 0.001 ether;
    bool public saleActive = false;

    uint256 private _nextId = 0;
    mapping(uint256 => bytes32) private _tokenSeed;

    mapping(uint256 => string) private _tokenImage;
    string private _contractImage;

    // ------------------------------------------------------- on-chain renderer
    uint256 public constant MAX_PAGE_BYTES = 150_000; // sanity cap; page is 26,757 B

    /// Pure trait-derivation contract, created by this constructor (immutable, no admin).
    TonalTraits public immutable traits;

    address public headPtr;
    address[] public tailPtrs;

    error PageTooLarge();

    function _isChunk(address ptr) internal view returns (bool) {
        if (ptr == address(0)) return false;
        if (ptr.code.length == 0) return false;
        bytes memory b = new bytes(1);
        assembly { extcodecopy(ptr, add(b, 32), 0, 1) }
        return b[0] == 0x00;
    }

    function _checkPointers(address _headPtr, address[] memory _tailPtrs) internal view {
        if (_tailPtrs.length < 2 || _tailPtrs.length > 6) revert PageTooLarge();
        if (!_isChunk(_headPtr)) revert SSTORE2.InvalidPointer();
        uint256 total = _headPtr.code.length - 1;
        if (total > MAX_PAGE_BYTES) revert PageTooLarge();
        for (uint256 i = 0; i < _tailPtrs.length; i++) {
            if (!_isChunk(_tailPtrs[i])) revert SSTORE2.InvalidPointer();
            total += _tailPtrs[i].code.length - 1;
            if (total > MAX_PAGE_BYTES) revert PageTooLarge();
        }
    }

    function setPage(address _headPtr, address[] calldata _tailPtrs) external onlyOwner {
        _checkPointers(_headPtr, _tailPtrs);
        headPtr = _headPtr;
        delete tailPtrs;
        for (uint256 i = 0; i < _tailPtrs.length; i++) {
            tailPtrs.push(_tailPtrs[i]);
        }
        if (_totalSupply > 0) emit BatchMetadataUpdate(1, _totalSupply);
    }

    // ------------------------------------------------- collection-level metadata
    string private _externalLink;
    string private _collectionDescription;

    event ContractURIUpdated();

    function _checkText(string memory text) internal pure {
        bytes memory b = bytes(text);
        if (b.length > 2048) revert BadURI();
        for (uint256 i = 0; i < b.length; i++) {
            uint8 ch = uint8(b[i]);
            if (ch < 0x20 || ch > 0x7E || ch == 0x22 || ch == 0x5c) revert BadURI();
        }
    }

    function setExternalLink(string calldata link) external onlyOwner {
        _checkURI(link);
        _externalLink = link;
        emit ContractURIUpdated();
    }

    function setCollectionDescription(string calldata text) external onlyOwner {
        _checkText(text);
        _collectionDescription = text;
        emit ContractURIUpdated();
    }

    function externalLink() external view returns (string memory) {
        return _externalLink;
    }

    function collectionDescription() external view returns (string memory) {
        return bytes(_collectionDescription).length > 0 ? _collectionDescription : DESCRIPTION;
    }

    /// @notice The live renderer HTML for a token, with its on-chain hash injected.
    /// Layout: the deploy script splits the page at the /*__TOKENDATA__*/
    /// marker (right after <body>), then splits the remainder into
    /// EIP-170-safe chunks (each data chunk <= 24,575 bytes + 1 STOP byte):
    ///   head  = HTML prefix up to (not including) the marker
    ///   tails = 2..6 chunks starting AT the marker
    /// tokenHTML = head + {"tokenId":N,"hash":"<64hex>"} + tail0 + tail1 + ...
    /// The JSON lands in the page's `const tokenData = <here>/*__TOKENDATA__*/;`
    /// so tokenData is defined BEFORE the main script reads it. The marker
    /// itself stays in the output (it is a harmless JS comment).
    function tokenHTML(uint256 tokenId) public view returns (string memory) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        bytes memory mid = abi.encodePacked(
            '{"tokenId":',
            _toString(tokenId),
            ',"hash":"',
            _toHex(_tokenSeed[tokenId]),
            '"}'
        );
        bytes memory head = SSTORE2.read(headPtr);
        if (tailPtrs.length < 2 || tailPtrs.length > 6) revert PageTooLarge();
        uint256 total = head.length + mid.length;
        bytes[] memory tails = new bytes[](tailPtrs.length);
        for (uint256 i = 0; i < tailPtrs.length; i++) {
            tails[i] = SSTORE2.read(tailPtrs[i]);
            total += tails[i].length;
        }
        bytes memory page = new bytes(total);
        uint256 off = _copy(page, 0, head);
        off = _copy(page, off, mid);
        for (uint256 i = 0; i < tails.length; i++) {
            off = _copy(page, off, tails[i]);
        }
        return string(page);
    }

    function _copy(bytes memory dest, uint256 off, bytes memory src) internal pure returns (uint256) {
        uint256 len = src.length;
        assembly {
            mcopy(add(add(dest, 32), off), add(src, 32), len)
        }
        return off + len;
    }

    address public owner;
    modifier onlyOwner() {
        require(msg.sender == owner, "not owner");
        _;
    }

    address public pendingOwner;

    event SaleToggled(bool active);
    event MintPriceSet(uint256 price);
    event TokenMediaSet(uint256[] tokenIds);
    event ContractImageSet(string imageURI);
    event OwnershipTransferProposed(address indexed current, address indexed proposed);
    event OwnershipTransferred(address indexed previous, address indexed newOwner);
    event OwnershipRenounced(address indexed previous);
    event RoyaltyUpdated(address indexed receiver, uint96 bps);

    constructor(address _headPtr, address[] memory _tailPtrs, address _royaltyReceiver) {
        require(_royaltyReceiver != address(0), "zero receiver");
        _checkPointers(_headPtr, _tailPtrs);
        headPtr = _headPtr;
        for (uint256 i = 0; i < _tailPtrs.length; i++) {
            tailPtrs.push(_tailPtrs[i]);
        }
        owner = msg.sender;
        traits = new TonalTraits();
        royaltyReceiver = _royaltyReceiver;
        require(royaltyBps <= MAX_ROYALTY_BPS, "bps too high");
        emit OwnershipTransferred(address(0), msg.sender);
    }

    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "zero owner"); // use renounceOwnership to give up control
        pendingOwner = newOwner;
        emit OwnershipTransferProposed(owner, newOwner);
    }

    function acceptOwnership() external {
        require(msg.sender == pendingOwner, "not proposed");
        address previous = owner;
        owner = pendingOwner;
        pendingOwner = address(0);
        emit OwnershipTransferred(previous, owner);
    }

    function renounceOwnership() external onlyOwner {
        // After renounce no one can withdraw or close the sale; ETH from a still-open
        // sale would be locked forever, so require the sale to be closed first.
        require(!saleActive, "close sale first");
        address previous = owner;
        uint256 bal = address(this).balance;
        owner = address(0);
        pendingOwner = address(0);
        emit OwnershipRenounced(previous);
        if (bal > 0) {
            (bool ok,) = previous.call{value: bal}("");
            require(ok, "withdraw failed");
        }
    }

    function mint() external payable returns (uint256 tokenId) {
        require(saleActive, "sale closed");
        require(_nextId < MAX_SUPPLY, "sold out");
        require(msg.value == mintPrice, "incorrect payment");
        tokenId = _mint(msg.sender);
        bytes32 seed = keccak256(abi.encodePacked(blockhash(block.number - 1), tokenId, msg.sender));
        // No-duplicate rule (nodup_v1 study): the full derived trait list must be new to the collection.
        // If it is already taken, re-derive deterministically: seed_n = keccak256(seed_{n-1}, n).
        bytes32 key = comboKey(seed);
        uint256 n;
        while (_comboUsed[key]) {
            unchecked {
                ++n;
            }
            require(n <= MAX_REROLLS, "reroll limit");
            seed = keccak256(abi.encodePacked(seed, n));
            key = comboKey(seed);
        }
        _comboUsed[key] = true;
        _tokenSeed[tokenId] = seed; // final seed: tokenURI, attributes and the page all read this one value
        if (n > 0) emit SeedRerolled(tokenId, n);
    }

    /// @notice Identity of a seed's full derived trait list (equal keys <=> identical trait text; see TonalTraits.comboKey).
    function comboKey(bytes32 seed) public view returns (bytes32) {
        return traits.comboKey(seed);
    }

    /// @notice True if some minted token already has this exact derived trait list.
    function comboUsed(bytes32 key) external view returns (bool) {
        return _comboUsed[key];
    }

    function tokenSeed(uint256 tokenId) external view returns (bytes32) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        return _tokenSeed[tokenId];
    }

    function setMintPrice(uint256 p) external onlyOwner {
        mintPrice = p;
        emit MintPriceSet(p);
    }

    function setSaleActive(bool a) external onlyOwner {
        saleActive = a;
        emit SaleToggled(a);
    }

    function withdraw() external onlyOwner {
        (bool ok,) = owner.call{value: address(this).balance}("");
        require(ok, "withdraw failed");
    }

    // ---------------------------------------------------------------- royalties (ERC2981)
    address public royaltyReceiver;
    uint96 public constant MAX_ROYALTY_BPS = 1000; // hard cap: 10%
    uint96 public royaltyBps = 1000; // 10%

    // ---------------------------------------------------------------- no-duplicate traits (appended: keeps slots 0-17)
    uint256 public constant MAX_REROLLS = 32;
    mapping(bytes32 => bool) internal _comboUsed;
    event SeedRerolled(uint256 indexed tokenId, uint256 rerolls);

    function royaltyInfo(uint256, uint256 salePrice) external view returns (address, uint256) {
        return (royaltyReceiver, (salePrice * royaltyBps) / 10000);
    }

    function setRoyalty(address r, uint96 bps) external onlyOwner {
        require(r != address(0), "zero receiver");
        require(bps <= MAX_ROYALTY_BPS, "bps too high");
        royaltyReceiver = r;
        royaltyBps = bps;
        emit RoyaltyUpdated(r, bps);
    }

    function _checkURI(string memory uri) internal pure {
        bytes memory b = bytes(uri);
        if (b.length == 0) return;
        if (b.length > 2048) revert BadURI();
        if (!_startsWith(b, "ipfs://") && !_startsWith(b, "https://")) revert BadURI();
        for (uint256 i = 0; i < b.length; i++) {
            uint8 ch = uint8(b[i]);
            if (ch < 0x21 || ch > 0x7E || ch == 0x22 || ch == 0x5c) revert BadURI();
        }
    }

    function _startsWith(bytes memory b, string memory prefix) internal pure returns (bool) {
        bytes memory p = bytes(prefix);
        if (b.length < p.length) return false;
        for (uint256 i = 0; i < p.length; i++) {
            if (b[i] != p[i]) return false;
        }
        return true;
    }

    function setTokenImage(
        uint256[] calldata tokenIds,
        string[] calldata imageURIs
    ) external onlyOwner {
        if (tokenIds.length != imageURIs.length) {
            revert LengthMismatch();
        }
        for (uint256 i = 0; i < tokenIds.length; i++) {
            if (_owners[tokenIds[i]] == address(0)) revert NonexistentToken();
            _checkURI(imageURIs[i]);
            _tokenImage[tokenIds[i]] = imageURIs[i];
        }
        emit TokenMediaSet(tokenIds);
        for (uint256 i = 0; i < tokenIds.length; i++) {
            emit MetadataUpdate(tokenIds[i]);
        }
    }

    function tokenImage(uint256 tokenId) external view returns (string memory) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        return _tokenImage[tokenId];
    }

    function setContractImage(string calldata imageURI) external onlyOwner {
        _checkURI(imageURI);
        _contractImage = imageURI;
        emit ContractImageSet(imageURI);
        if (_totalSupply > 0) emit BatchMetadataUpdate(1, _totalSupply);
    }

    // ------------------------------------------------------------- metadata
    string private constant DESCRIPTION =
        "Tonal Geometries is a series of 150 generative audiovisual pieces: a melody drawn from a world scale and tuning is played as sound and mapped onto the vibration modes of a steel plate, whose sand patterns glide with it. Each token's hash sets its scale, tuning and pitch, and the code and hash are stored on-chain. Tap or drag to rotate; press S or double-tap for sound.";

    function contractURI() external view returns (string memory) {
        string memory json = string(
            abi.encodePacked(
                '{"name":"Tonal Geometries",',
                '"description":"',
                bytes(_collectionDescription).length > 0 ? _collectionDescription : DESCRIPTION,
                '",',
                '"image":"',
                bytes(_contractImage).length > 0 ? _contractImage : _placeholderImage(0),
                bytes(_externalLink).length > 0
                    ? string(abi.encodePacked('","external_link":"', _externalLink))
                    : "",
                '"}'
            )
        );
        return string(abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(json))));
    }

    function tokenURI(uint256 tokenId) public view returns (string memory) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        bytes32 seed = _tokenSeed[tokenId];
        string memory anim = string(
            abi.encodePacked("data:text/html;base64,", Base64.encode(bytes(tokenHTML(tokenId))))
        );
        string memory json = string(
            abi.encodePacked(
                '{"name":"Tonal Geometries #',
                _toString(tokenId),
                '",',
                '"description":"',
                DESCRIPTION,
                '",',
                '"image":"',
                bytes(_tokenImage[tokenId]).length > 0 ? _tokenImage[tokenId] : _placeholderImage(tokenId),
                '",',
                '"animation_url":"',
                anim,
                '",',
                '"attributes":',
                _attributesJson(seed),
                "}"
            )
        );
        return string(abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(json))));
    }

    function _placeholderImage(uint256 tokenId) internal pure returns (string memory) {
        string memory svg = string(
            abi.encodePacked(
                '<svg xmlns="http://www.w3.org/2000/svg" width="600" height="600">',
                '<rect width="600" height="600" fill="#000000"/>',
                '<text x="300" y="290" fill="#e8e4d8" font-family="monospace" font-size="26" text-anchor="middle">TONAL GEOMETRIES</text>',
                '<text x="300" y="330" fill="#c96f4a" font-family="monospace" font-size="20" text-anchor="middle">#',
                _toString(tokenId),
                "</text></svg>"
            )
        );
        return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(bytes(svg))));
    }

    // --------------------------------------- traits: port of reference/tonal_core.js tonalDerive()
    // Words w0..w15 = 16 big-endian uint16 of the seed. pk(w,N) = floor(w*N/65536).
    //   w2 Scale(7; family follows) w3 Root(12) w4 Tuning(4) w5 Octave Band(3) w6 Interval Path(6) w7 Contour(3)
    //   w8 States(3..8) w13 Second Voice(5). w0, w1, w9 (loop fixed at 120 s), w14 unused; w15 page-only.
    // "Base Pitch" is the FIRST HEARD NOTE (state 0 of voice 1, after contour and octave placement), exactly as the page
    // displays it: note name + cents offset ('c' = cents, e.g. "D5 +16c") + frequency. It is computed here with integer
    // fixed-point (1e-6 cent units) from precomputed log tables; see caveats in SECURITY_REVIEW.md.

    /// @notice The marketplace attributes for a token (derived traits + fixed series traits + Artist/Moniker/Series).
    function tokenAttributes(uint256 tokenId) public view returns (string memory) {
        if (_owners[tokenId] == address(0)) revert NonexistentToken();
        return _attributesJson(_tokenSeed[tokenId]);
    }

    function _attributesJson(bytes32 seed) internal view returns (string memory) {
        return string(abi.encodePacked(traits.derived(seed), FIXED_TRAITS, ARTIST_TRAITS));
    }

    /// @dev Series-fixed traits (identical for every token).
    string private constant FIXED_TRAITS =
        '{"trait_type":"Palette","value":"Sunlight"},{"trait_type":"Color Mapping","value":"Along Line + Per State"},{"trait_type":"Color Drift","value":"Medium"},{"trait_type":"Structure","value":"Single Square"},';

    /// @dev Series-umbrella traits (artist identity). Closes the attributes array.
    /// Series 6 (confirmed by Calvin 2026-10-15).
    string private constant ARTIST_TRAITS =
        '{"trait_type":"Artist","value":"Calvin Fought"},{"trait_type":"Moniker","value":"Coattails"},{"trait_type":"Series","value":"6"}]';

    // ---------------------------------------------------------------- helpers
    bytes16 private constant _HEX = "0123456789abcdef";

    function _toHex(bytes32 v) internal pure returns (string memory) {
        bytes memory s = new bytes(64);
        for (uint256 i = 0; i < 32; i++) {
            s[2 * i] = _HEX[uint8(v[i] >> 4)];
            s[2 * i + 1] = _HEX[uint8(v[i] & 0x0f)];
        }
        return string(s);
    }

    function _toString(uint256 v) internal pure returns (string memory) {
        if (v == 0) return "0";
        uint256 len = 0;
        uint256 x = v;
        while (x > 0) {
            len++;
            x /= 10;
        }
        bytes memory s = new bytes(len);
        x = v;
        while (x > 0) {
            s[--len] = bytes1(uint8(48 + (x % 10)));
            x /= 10;
        }
        return string(s);
    }
}

contracts/TonalTraits.sol

// SPDX-License-Identifier: MIT
// TonalTraits.sol -- pure trait derivation for Tonal Geometries (deployed by the TonalGeometries constructor).
// Port of reference/tonal_core.js tonalDerive(): hash -> scale / tuning / first heard note attributes.
// Kept in its own contract so that TonalGeometries stays under the EIP-170 24,576-byte runtime limit.
// No state, no admin, no external calls; immutable once deployed.
pragma solidity 0.8.24;

contract TonalTraits {
    function _pk(uint256 w, uint256 n) private pure returns (uint256) {
        return (w * n) >> 16;
    }

    function _w(bytes32 seed, uint256 i) private pure returns (uint256) {
        return (uint256(seed) >> (240 - 16 * i)) & 0xffff;
    }

    function derived(bytes32 seed) external pure returns (string memory) {
        uint256 si = _scale(seed);
        uint256 fi = si < 3 ? 0 : (si < 5 ? 1 : 2);
        string memory head = string(
            abi.encodePacked(
                '[{"trait_type":"Scale Family","value":"',
                _segment(FAMILY_NAMES, fi),
                '"},{"trait_type":"Scale","value":"',
                _segment(SCALE_NAMES, si)
            )
        );
        head = string(
            abi.encodePacked(head, '"},{"trait_type":"Base Pitch","value":"', _basePitch(seed, si), '"},')
        );
        return string(abi.encodePacked(head, _attributesTail(seed)));
    }

    /// @notice Identity of the seed's full derived trait list without building the text (nodup_v1 study).
    /// Scale, displayed Tuning, Interval Path, Contour, States, Second Voice and the exact first-heard pitch
    /// (Base Pitch is a pure function of scale + that pitch; distinct pitches in one combo are >= 100 cents apart,
    /// see tools/nodup_injective.js), so equal keys <=> equal trait text.
    function comboKey(bytes32 seed) external pure returns (bytes32) {
        uint256 si = _scale(seed);
        return keccak256(
            abi.encode(
                si,
                _pk(_w(seed, 4), 4),
                _mot(seed),
                _pk(_w(seed, 7), 3),
                _pk(_w(seed, 8), 6),
                _pk(_w(seed, 13), 5),
                _firstPitch(seed, si)
            )
        );
    }

    function _attributesTail(bytes32 seed) private pure returns (string memory) {
        string memory a = string(
            abi.encodePacked(
                '{"trait_type":"Tuning","value":"',
                _segment(TUNING_NAMES, _pk(_w(seed, 4), 4)),
                '"},{"trait_type":"Interval Path","value":"',
                _segment(MOTIF_NAMES, _mot(seed)),
                '"},{"trait_type":"Contour","value":"',
                _segment(CONTOUR_NAMES, _pk(_w(seed, 7), 3))
            )
        );
        string memory b = string(
            abi.encodePacked(
                '"},{"trait_type":"States","value":"',
                _toString(3 + _pk(_w(seed, 8), 6)),
                '"},{"trait_type":"Second Voice","value":"',
                _segment(SV_NAMES, _pk(_w(seed, 13), 5))
            )
        );
        return string(abi.encodePacked(a, b, '"},'));
    }

    // ---- first heard note ("Base Pitch") ----
    // Pitch unit: 1e-6 cent. One semitone = 1e8, one octave = 1.2e9. Absolute pitch is "midi * 1e8".
    int256 private constant SEMI = 100_000_000_000;
    int256 private constant OCT = 1_200_000_000_000;

    struct Pm {
        uint256 n; // scale size (Root+Octave)
        uint256 tun;
        int256 rootMidi; // 48 + 12*band + root
        bytes units; // this scale's 24-grid units
    }

    function _u(bytes memory b, uint256 i, uint256 width) private pure returns (uint256 v) {
        for (uint256 k = 0; k < width; k++) v = (v << 8) | uint8(b[i * width + k]);
    }

    function _floorDiv(int256 a, int256 b) private pure returns (int256 q) {
        q = a / b;
        if ((a % b != 0) && ((a < 0) != (b < 0))) q--;
    }

    function _abs(int256 x) private pure returns (int256) {
        return x < 0 ? -x : x;
    }

    /// absolute pitch of degree d (midi * 1e8), before the loudness-range octave shift
    function _abp(Pm memory P, int256 d) private pure returns (int256) {
        int256 o = _floorDiv(d, int256(P.n));
        uint256 u = uint8(P.units[uint256(d - o * int256(P.n))]);
        return P.rootMidi * SEMI + int256(_u(CENTS_TUNING, P.tun * 25 + u, 6)) + OCT * o;
    }

    /// Scale index (w2, 6 scales). s = pk(w2, 7): s < 5 -> s, s == 6 -> 5, s == 5 -> pk((w2 * 7) & 0xFFFF, 6)
    /// (the 7-way pick keeps every hash on its earlier scale; the 6th slot is redistributed by the next digits of w2).
    function _scale(bytes32 seed) private pure returns (uint256 si) {
        uint256 w = _w(seed, 2);
        si = _pk(w, 7);
        if (si == 6) si = 5;
        else if (si == 5) {
            uint256 q = _pk((w * 7) & 0xFFFF, 6);
            si = q < 5 ? q : 5;
        }
    }

    /// Interval Path index (w6, 5 paths). m = pk(w6, 6): m < 3 -> m, m > 3 -> m - 1, m == 3 -> pk((w6 * 6) & 0xFFFF, 5).
    function _mot(bytes32 seed) private pure returns (uint256 mot) {
        uint256 w = _w(seed, 6);
        mot = _pk(w, 6);
        if (mot > 3) mot--;
        else if (mot == 3) mot = _pk((w * 6) & 0xFFFF, 5);
    }

    function _motif(Pm memory P, uint256 mot, uint256 K, uint256 j) private pure returns (int256 d) {
        if (mot == 0) d = int256(2 * j);
        else if (mot == 1) d = int256(j);
        else if (mot == 2) d = int256(K - 1 - j);
        else if (mot == 3) d = (j & 1) == 1 ? int256((j >> 1) + 1) : int256(0);
        else d = int256(4 * j);
        // fold into two scale periods
        int256 wrapN = int256(P.n);
        while (d >= 2 * wrapN) d -= wrapN;
    }

    function _degrees(Pm memory P, bytes32 seed, uint256 K) private pure returns (int256[8] memory D) {
        uint256 mot = _mot(seed);
        for (uint256 j = 0; j < K; j++) D[j] = _motif(P, mot, K, j);
        uint256 cont = _pk(_w(seed, 7), 3);
        if (cont == 1) {
            for (uint256 j = 0; j < K / 2; j++) (D[j], D[K - 1 - j]) = (D[K - 1 - j], D[j]);
        } else if (cont == 2) {
            int256 mx = D[0];
            for (uint256 j = 1; j < K; j++) if (D[j] > mx) mx = D[j];
            for (uint256 j = 0; j < K; j++) D[j] = mx - D[j];
        }
    }

    function _newPm(bytes32 seed, uint256 scaleIdx) private pure returns (Pm memory P) {
        P.tun = _pk(_w(seed, 4), 4);
        if (scaleIdx == 5 && (P.tun == 1 || P.tun == 3)) P.tun = P.tun == 1 ? 4 : 5; // Lydian dominant: 45/32 + 16/9 variant tables
        P.rootMidi = int256(48 + 12 * _pk(_w(seed, 5), 3) + _pk(_w(seed, 3), 12));
        uint256 off;
        for (uint256 k = 0; k < scaleIdx; k++) off += uint8(SC_LEN[k]);
        P.n = uint8(SC_LEN[scaleIdx]);
        P.units = new bytes(P.n);
        for (uint256 k = 0; k < P.n; k++) P.units[k] = SC_UNITS[off + k];
    }

    function _firstPitch(bytes32 seed, uint256 scaleIdx) private pure returns (int256) {
        Pm memory P = _newPm(seed, scaleIdx);
        uint256 K = 3 + _pk(_w(seed, 8), 6);
        int256[8] memory D = _degrees(P, seed, K);
        uint256 sv = _pk(_w(seed, 13), 5);
        int256 mx = type(int256).min;
        int256 mn = type(int256).max;
        for (uint256 j = 0; j < K; j++) {
            int256 a = _abp(P, D[j]);
            int256 off2 = sv == 4 ? (j % 2 == 0 ? int256(2) : int256(-1)) : _svOff(sv);
            int256 b = _abp(P, D[j] + off2);
            if (a > mx) mx = a;
            if (b > mx) mx = b;
            if (a < mn) mn = a;
            if (b < mn) mn = b;
        }
        int256 shift = 0;
        while (mx + shift * OCT > C1000) shift--;
        // v28 range fit: cap 500 Hz unless that pushes the lowest tone under 70 Hz; floor 70 Hz; then the whole token one octave down
        while (mx + shift * OCT > C500 && mn + (shift - 1) * OCT >= C70) shift--;
        while (mn + shift * OCT < C70 && mx + (shift + 1) * OCT <= C500) shift++;
        return _abp(P, D[0]) + (shift - 1) * OCT;
    }

    function _svOff(uint256 sv) private pure returns (int256) {
        if (sv == 0) return -1;
        if (sv == 1) return 2;
        if (sv == 2) return 4;
        if (sv == 3) return -2;
        return 0;
    }

    function _basePitch(bytes32 seed, uint256 scaleIdx) private pure returns (string memory) {
        int256 m = _firstPitch(seed, scaleIdx);
        int256 r = _floorDiv(m + SEMI / 2, SEMI); // nearest midi note (round half up)
        int256 c = _floorDiv(m - r * SEMI + 500_000_000, 1_000_000_000); // cents offset, rounded
        string memory note = string(
            abi.encodePacked(_segment(NOTE_NAMES, uint256(((r % 12) + 12) % 12)), _signed(_floorDiv(r, 12) - 1))
        );
        if (c != 0) note = string(abi.encodePacked(note, c > 0 ? " +" : " -", _toString(uint256(_abs(c))), "c"));
        // frequency = 432 * 2^((m - 69*1e8) / 1.2e9)  (A4 = 432 Hz convention), one decimal (round half up)
        int256 e = m - 69 * SEMI;
        int256 k = _floorDiv(e, OCT);
        uint256 t = (uint256(e - k * OCT) * 693147180559945309) / uint256(OCT); // x*ln2, 1e18 scale
        uint256 term = 1e18;
        uint256 sum = 1e18;
        for (uint256 i = 1; i <= 24; i++) {
            term = (term * t) / 1e18 / i;
            sum += term;
        }
        uint256 num = 4320 * sum;
        if (k >= 0) num <<= uint256(k);
        else num >>= uint256(-k);
        uint256 hz10 = (num + 5e17 + 1e10) / 1e18; // +1e-8: exact .x5 ties round up like JS toFixed(1)
        return string(
            abi.encodePacked(note, " (", _toString(hz10 / 10), ".", _toString(hz10 % 10), " Hz)")
        );
    }

    function _signed(int256 v) private pure returns (string memory) {
        return v < 0 ? string(abi.encodePacked("-", _toString(uint256(-v)))) : _toString(uint256(v));
    }

    bytes private constant SC_UNITS = hex"0004080e1200040a0e1400040a0e120004080c0e12160004080a0e12160004080c0e1214";
    bytes private constant SC_LEN = hex"050505070707";
    bytes private constant CENTS_TUNING = hex"000000000000000ba43b740000174876e8000022ecb25c00002e90edd000003a352944000045d964b80000517da02c00005d21dba0000068c617140000746a52880000800e8dfc00008bb2c9700000975704e40000a2fb40580000ae9f7bcc0000ba43b7400000c5e7f2b40000d18c2e280000dd30699c0000e8d4a5100000f478e0840001001d1bf800010bc1576c0001176592e000000000000000000d01da0e8b001a03b41d160024bed7e8ac002f79fbb443003c7bd5c2ce00497dafd1590051b7e3a5110059f21778c90066f3f187540073f5cb95df007eb0ef617500896c132d0c00966ded3b9600a36fc74a2100b071a158ac00bd737b673700c5adaf3aef00cde7e30ea700dd6aad151100eced771b7a00f527aaef3200fd61dec2ea010a63b8d17501176592e000000000000000000d3c13c375001a782786ea0024f9119d96002f79fbb4430039fae5caef00447bcfe19c0051b7e3a511005ef3f76886006974e17f320073f5cb95df008131df5953008e6df31cc80098eedd337500a36fc74a2100b0abdb0d9600bde7eed10b00c868d8e7b800d2e9c2fe6400dd6aad151100e7eb972bbd00f527aaef32010263beb2a7010ce4a8c95301176592e0000000000000000008da6fd1b00011b4dfa35f001f56f5afe2002cf90bbc64003a9b21c8e700483d37d569005117a7a7190059f21778c90067942d854b0075364391ce007e10b3637e0086eb23352d00948d3941b000a22f4f4e3200ab09bf1fe200b3e42ef19200c18644fe1400cf285b0a9700dcca71171900ea6c87239c00f346f6f54b00fc2166c6fb0109c37cd37e01176592e000000000000000000d01da0e8b001a03b41d160024bed7e8ac002f79fbb443003c7bd5c2ce00497dafd1590051b7e3a5110059f21778c90066f3f187540073f5cb95df007eb0ef617500896c132d0c00966ded3b9600a36fc74a2100b071a158ac00bd737b673700c5adaf3aef00cde7e30ea700dae9bd1d3200e7eb972bbd00f2a6baf75400fd61dec2ea010a63b8d17501176592e0000000000000000008da6fd1b00011b4dfa35f001f56f5afe2002cf90bbc64003a9b21c8e700483d37d569005117a7a7190059f21778c90067942d854b0075364391ce007f512b5f6d00896c132d0c0095cdb13d9f00a22f4f4e3200ab09bf1fe200b3e42ef19200c18644fe1400cf285b0a9700db89f91b2a00e7eb972bbd00f2067ef95c00fc2166c6fb0109c37cd37e01176592e000";
    int256 private constant C1000 = 8353076138998;
    int256 private constant C500 = 7153076138998;
    int256 private constant C70 = 3749274617738;
    string private constant FAMILY_NAMES = "Pentatonic|Diatonic Bright|Overtone";
    string private constant SCALE_NAMES = "Major pentatonic|Egyptian (suspended) pentatonic|Major pentatonic mode 4 (Zhi / Yo type)|Lydian|Ionian (major)|Lydian dominant (acoustic / overtone scale)";
    string private constant TUNING_NAMES = "12-TET|5-Limit Just|Pythagorean|1/4-Comma Meantone";
    string private constant MOTIF_NAMES = "Arpeggio|Stepwise Rise|Stepwise Fall|Pedal Tone|Degree-Fifths Ladder";
    string private constant CONTOUR_NAMES = "Prime|Retrograde|Inversion";
    string private constant SV_NAMES = "Next scale degree down|Chord third (+2 degrees)|Chord fifth (+4 degrees)|Chord third below (-2 degrees)|Alternating third / step down";
    string private constant NOTE_NAMES = "C|C#|D|D#|E|F|F#|G|G#|A|A#|B";

    /// @dev i-th '|'-separated segment of s.
    function _segment(string memory s, uint256 idx) private pure returns (string memory) {
        bytes memory b = bytes(s);
        uint256 start = 0;
        uint256 seen = 0;
        for (uint256 k = 0; k <= b.length; k++) {
            if (k == b.length || b[k] == "|") {
                if (seen == idx) {
                    bytes memory out = new bytes(k - start);
                    for (uint256 m = 0; m < out.length; m++) out[m] = b[start + m];
                    return string(out);
                }
                seen++;
                start = k + 1;
            }
        }
        revert("bad segment");
    }


    function _toString(uint256 v) private pure returns (string memory) {
        if (v == 0) return "0";
        uint256 len = 0;
        uint256 x = v;
        while (x > 0) {
            len++;
            x /= 10;
        }
        bytes memory s = new bytes(len);
        x = v;
        while (x > 0) {
            s[--len] = bytes1(uint8(48 + (x % 10)));
            x /= 10;
        }
        return string(s);
    }
}

contracts/lib/Base64.sol

// Base64.sol — base64 encoder with an assembly hot loop.
//
// Used to build data: URIs for token metadata and the rendered HTML page.
// tokenURI base64-encodes ~130KB; the loop below costs ~150 gas per 3-byte
// group (~5M gas total), safe for eth_call. These are `view` functions meant
// to be called off-chain, where gas cost is irrelevant — but indexers still
// enforce block gas limits, so the encoder must be lean.
pragma solidity ^0.8.24;

library Base64 {
    function encode(bytes memory data) internal pure returns (string memory result) {
        uint256 n = data.length;
        if (n == 0) return "";
        uint256 outLen = 4 * ((n + 2) / 3);
        result = new string(outLen);
        bytes memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        assembly {
            let t := add(table, 32)
            let src := add(data, 32)
            let dst := add(result, 32)
            let fullEnd := add(src, sub(n, mod(n, 3)))
            for {} lt(src, fullEnd) {} {
                let b := mload(src)
                let triple := or(shl(16, byte(0, b)), or(shl(8, byte(1, b)), byte(2, b)))
                mstore8(dst, byte(0, mload(add(t, shr(18, triple)))))
                mstore8(add(dst, 1), byte(0, mload(add(t, and(shr(12, triple), 0x3F)))))
                mstore8(add(dst, 2), byte(0, mload(add(t, and(shr(6, triple), 0x3F)))))
                mstore8(add(dst, 3), byte(0, mload(add(t, and(triple, 0x3F)))))
                src := add(src, 3)
                dst := add(dst, 4)
            }
            let rem := mod(n, 3)
            if rem {
                let b0 := byte(0, mload(src))
                let b1 := 0
                if gt(rem, 1) { b1 := byte(1, mload(src)) }
                let triple := or(shl(16, b0), shl(8, b1))
                mstore8(dst, byte(0, mload(add(t, shr(18, triple)))))
                mstore8(add(dst, 1), byte(0, mload(add(t, and(shr(12, triple), 0x3F)))))
                if eq(rem, 2) {
                    mstore8(add(dst, 2), byte(0, mload(add(t, and(shr(6, triple), 0x3F)))))
                    mstore8(add(dst, 3), 0x3d)
                }
                if eq(rem, 1) {
                    mstore8(add(dst, 2), 0x3d)
                    mstore8(add(dst, 3), 0x3d)
                }
            }
        }
    }
}

contracts/lib/SSTORE2.sol

// SSTORE2.sol — minimal write/read for storing bulk data in contract code.
//
// Stores arbitrary bytes as the code of a freshly deployed contract
// (prefixed with a single 0x00 STOP byte). Reading uses EXTCODECOPY.
// Writing costs ~200 gas/byte (contract code deposit) vs ~625 gas/byte for
// SSTORE slots, which is why the artwork script lives here instead of in
// contract storage.
//
// The init code is built in plain Solidity (abi.encodePacked) and only the
// CREATE itself is assembly:
//
//   PUSH2 <dlen> | PUSH2 20 | PUSH1 1 | CODECOPY | PUSH1 0 | PUSH1 0 |
//   MSTORE8 | PUSH2 <dlen+1> | PUSH1 0 | RETURN
//
// which copies `data` (appended after the 20 init bytes, i.e. at code offset
// 20) to memory[1..1+dlen], writes 0x00 at memory[0], and returns dlen+1
// bytes. The deployed runtime code is therefore 0x00 || data.
pragma solidity ^0.8.24;

library SSTORE2 {
    error WriteFailed();
    error ChunkTooLarge();
    error InvalidPointer();

    /// @notice Store `data` in a new contract's code. Returns its address.
    /// @dev Max 65534 bytes per chunk (dlen+1 must fit in the PUSH2); the
    /// renderer pipeline chunks at 20KB to stay under the 24KB limit anyway.
    function write(bytes memory data) internal returns (address pointer) {
        uint256 dlen = data.length;
        // dlen == 0xFFFF would wrap uint16(dlen + 1) to 0 and deploy empty
        // code (Grok review v3 L2).
        if (dlen == 0 || dlen >= 0xFFFF) revert ChunkTooLarge();
        bytes memory init = abi.encodePacked(
            hex"61", uint16(dlen), // PUSH2 dlen        (CODECOPY size)
            hex"61", uint16(20), // PUSH2 20          (data offset in creation code)
            hex"60", uint8(1), // PUSH1 1           (memory dest)
            hex"39", // CODECOPY
            hex"60", uint8(0), // PUSH1 0
            hex"60", uint8(0), // PUSH1 0
            hex"53", // MSTORE8 (mem[0] = 0x00 STOP)
            hex"61", uint16(dlen + 1), // PUSH2 dlen+1       (RETURN size)
            hex"60", uint8(0), // PUSH1 0           (RETURN offset)
            hex"f3" // RETURN
        );
        bytes memory creation = abi.encodePacked(init, data);
        assembly {
            pointer := create(0, add(creation, 32), mload(creation))
        }
        if (pointer == address(0)) revert WriteFailed();
    }

    /// @notice Read back bytes stored with `write`.
    /// @dev Guards the `extcodesize - 1` underflow: a non-pointer (EOA,
    /// address(0), or codeless account) would wrap `size` to 2^256-1 and
    /// OOG the extcodecopy, bricking tokenURI/tokenHTML (Grok review M2).
    /// Also requires the 0x00 STOP prefix `write` plants, so a random
    /// contract's code is never misread as a chunk (Grok review v3 L4).
    function read(address pointer) internal view returns (bytes memory data) {
        if (pointer.code.length <= 1) revert InvalidPointer();
        bytes memory probe = new bytes(1);
        assembly {
            extcodecopy(pointer, add(probe, 32), 0, 1)
        }
        if (probe[0] != 0x00) revert InvalidPointer();
        assembly {
            let size := sub(extcodesize(pointer), 1)
            data := mload(0x40)
            mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
            mstore(data, size)
            extcodecopy(pointer, add(data, 32), 1, size)
        }
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.