Verified contractExactMIT
TraceColorStore
Address0x30c666e4e646164f1b5fa09098c88eec8a9dc155
- Balance
0 ETH
- Transactions
221
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,200,164
- Creation transaction
- 0x8407429ede…88a436e106
3 files
src/trace/TraceColorStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {MerkleProof} from "../../lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol";
import {SSTORE2} from "./SSTORE2.sol";
interface IColorToken {
function metadata(uint256 tokenId, string calldata key) external view returns (bytes memory);
function setMetadata(uint256 tokenId, string calldata key, bytes calldata value) external;
function decoder() external view returns (address);
}
interface IColorDecoder {
function stateOf(uint256 cipher) external view returns (uint8);
function characterOf(uint256 cipher) external view returns (uint256);
}
/// @notice The colored characters, kept secret until each one is revealed.
///
/// All records are committed up front as one Merkle root (set once, never changed): a record can
/// be neither swapped nor seen before its character is revealed. A record is written only for a
/// token that is already decoded to exactly that character, with a proof against the root.
/// Anyone may submit (the proof is the authority); our relayer does it right after each reveal.
///
/// The record goes to SSTORE2; its pointer goes on the token's shelf under "color". The token
/// itself then emits ERC-4906 MetadataUpdate(tokenId), so marketplaces re-read that token.
///
/// record (packed) = kind | enc | preset | tw | th (1 byte each)
/// | len3 grid | len3 traits | len3 anim | len3 extra (len3 = 3-byte big-endian length)
/// kind 0 = regular character, 1 = 1/1 (its own style and motion in `extra`)
/// enc 0 = grid as is (4 bits per cell), 1 = grid deflate-raw compressed
/// preset 1..25 (0 for a 1/1: the style is in `extra`)
/// traits the metadata attributes after Stage, as a JSON fragment, exactly as published
/// anim the record's motion as JSON ("" for a still character)
/// leaf = keccak256(bytes.concat(keccak256(abi.encode(character, keccak256(record)))))
///
/// The renderer code and the 25 style presets carry no secret: they are stored in full, then locked.
///
/// Late 1/1s: a 1/1 that is not in the main tree can come later through a "late root" that names exactly
/// which characters it covers. Late roots accept only 1/1 records (kind 1), a character can be named by one
/// late root only, and the owner can add late roots until lockLateRoots(). Regular characters are only ever
/// in the main root.
contract TraceColorStore {
IColorToken public immutable token;
address public owner;
bytes32 public root; // set once
address[] private _js; // renderer JS, in chunks
bool public jsLocked;
mapping(uint256 => address) private _preset;
bool public presetsLocked;
mapping(uint256 => bytes32) public lateRootOf; // character -> the late root naming it
bool public lateRootsLocked;
string private constant KEY = "color";
uint8 private constant DECODED = 3; // TraceDecoder.State.Decoded
event OwnershipTransferred(address indexed from, address indexed to);
event RootSet(bytes32 root);
event JsLocked(uint256 chunks);
event PresetSet(uint256 indexed id);
event PresetsLocked();
event LateRootAdded(bytes32 indexed root, uint256[] characters);
event LateRootsLocked();
event Recorded(uint256 indexed tokenId, uint256 indexed character, address pointer);
error NotOwner();
error RootAlreadySet();
error NoRoot();
error Locked();
error NotDecoded(uint256 tokenId);
error WrongCharacter(uint256 tokenId, uint256 character);
error BadProof(uint256 tokenId);
error LengthMismatch();
error AlreadyNamed(uint256 character);
constructor(address token_) {
token = IColorToken(token_);
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
modifier onlyOwner() { if (msg.sender != owner) revert NotOwner(); _; }
function transferOwnership(address to) external onlyOwner {
emit OwnershipTransferred(owner, to);
owner = to;
}
// ─── commitment ────────────────────────────────────────────────────────
function setRoot(bytes32 root_) external onlyOwner {
if (root != bytes32(0)) revert RootAlreadySet();
root = root_;
emit RootSet(root_);
}
/// @notice A root for 1/1s that come after the main root: only these characters, only 1/1 records.
function addLateRoot(bytes32 root_, uint256[] calldata characters) external onlyOwner {
if (lateRootsLocked) revert Locked();
for (uint256 i; i < characters.length; i++) {
if (lateRootOf[characters[i]] != bytes32(0)) revert AlreadyNamed(characters[i]);
lateRootOf[characters[i]] = root_;
}
emit LateRootAdded(root_, characters);
}
function lockLateRoots() external onlyOwner {
lateRootsLocked = true;
emit LateRootsLocked();
}
// ─── renderer code and presets: public, stored in full, then locked ───
function addJsChunk(bytes calldata chunk) external onlyOwner {
if (jsLocked) revert Locked();
_js.push(SSTORE2.write(chunk));
}
function lockJs() external onlyOwner {
jsLocked = true;
emit JsLocked(_js.length);
}
function js() external view returns (bytes memory out) {
for (uint256 i; i < _js.length; i++) out = bytes.concat(out, SSTORE2.read(_js[i]));
}
function setPreset(uint256 id, bytes calldata styleJson) external onlyOwner {
if (presetsLocked) revert Locked();
_preset[id] = SSTORE2.write(styleJson);
emit PresetSet(id);
}
function lockPresets() external onlyOwner {
presetsLocked = true;
emit PresetsLocked();
}
/// @notice The style JSON of preset `id` ("" when there is none).
function preset(uint256 id) external view returns (bytes memory) {
address p = _preset[id];
return p == address(0) ? bytes("") : SSTORE2.read(p);
}
// ─── records ───────────────────────────────────────────────────────────
function leafOf(uint256 character, bytes calldata record) public pure returns (bytes32) {
return keccak256(bytes.concat(keccak256(abi.encode(character, keccak256(record)))));
}
/// @notice Write the record of an already decoded token. Already written: does nothing.
function submit(uint256 tokenId, uint256 character, bytes calldata record, bytes32[] calldata proof) public {
if (root == bytes32(0)) revert NoRoot();
IColorDecoder d = IColorDecoder(token.decoder());
if (d.stateOf(tokenId) != DECODED) revert NotDecoded(tokenId);
if (d.characterOf(tokenId) != character) revert WrongCharacter(tokenId, character);
if (token.metadata(tokenId, KEY).length != 0) return;
bytes32 leaf = leafOf(character, record);
if (!MerkleProof.verifyCalldata(proof, root, leaf)) {
bytes32 late = lateRootOf[character];
bool oneOfOne = record.length > 0 && uint8(record[0]) == 1;
if (late == bytes32(0) || !oneOfOne || !MerkleProof.verifyCalldata(proof, late, leaf)) revert BadProof(tokenId);
}
address p = SSTORE2.write(record);
token.setMetadata(tokenId, KEY, abi.encodePacked(p));
emit Recorded(tokenId, character, p);
}
function submitMany(
uint256[] calldata tokenIds,
uint256[] calldata characters,
bytes[] calldata records,
bytes32[][] calldata proofs
) external {
uint256 n = tokenIds.length;
if (characters.length != n || records.length != n || proofs.length != n) revert LengthMismatch();
for (uint256 i; i < n; i++) submit(tokenIds[i], characters[i], records[i], proofs[i]);
}
/// @notice The record of a token ("" when it has none yet).
function recordOf(uint256 tokenId) external view returns (bytes memory) {
bytes memory v = token.metadata(tokenId, KEY);
if (v.length != 20) return "";
return SSTORE2.read(address(bytes20(v)));
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*
* _Available since v4.7._
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*
* _Available since v4.7._
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be proved to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* _Available since v4.7._
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* _Available since v4.7._
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and the sibling nodes in `proof`,
* consuming from one or the other at each step according to the instructions given by
* `proofFlags`.
*
* _Available since v4.7._
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}
*
* _Available since v4.7._
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the merkle tree.
uint256 leavesLen = leaves.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof");
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value for the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
return hashes[totalHashes - 1];
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
src/trace/SSTORE2.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.17;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2)
library SSTORE2 {
uint256 internal constant DATA_OFFSET = 1; // skip the first byte (a STOP opcode) so the pointer can't be called.
function write(bytes memory data) internal returns (address pointer) {
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex"00", data);
bytes memory creationCode = abi.encodePacked(
//---------------------------------------------------------------------------------//
// Opcode | Mnemonic | Stack | Memory //
//---------------------------------------------------------------------------------//
// 0x60_0B | PUSH1 11 | 11 | //
// 0x59 | MSIZE | 0 11 | //
// 0x81 | DUP2 | 11 0 11 | //
// 0x38 | CODESIZE | codesize 11 0 11 | //
// 0x03 | SUB | (codesize-11) 0 11 | //
// 0x80 | DUP1 | (codesize-11) (..) | //
// 0x92 | SWAP3 | ... | //
// 0x59 | MSIZE | ... | //
// 0x39 | CODECOPY | | [0..] = runtimeCode //
// 0xF3 | RETURN | | //
//---------------------------------------------------------------------------------//
hex"60_0B_59_81_38_03_80_92_59_39_F3",
runtimeCode
);
assembly {
pointer := create(0, add(creationCode, 32), mload(creationCode))
}
require(pointer != address(0), "DEPLOYMENT_FAILED");
}
function read(address pointer) internal view returns (bytes memory) {
return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
}
function readBytecode(address pointer, uint256 start, uint256 size)
private
view
returns (bytes memory data)
{
assembly {
data := mload(0x40)
// round (size + 32) up to a word boundary and bump the free-memory pointer.
mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
mstore(data, size)
extcodecopy(pointer, add(data, 32), start, size)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"forge-std/=lib/forge-std/src/",
"ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",
"ERC721A/=lib-upgradeable/utility-contracts/lib/ERC721A/contracts/",
"ds-test/=lib-upgradeable/utility-contracts/lib/solmate/lib/ds-test/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"solmate/=lib-upgradeable/solmate/src/",
"utility-contracts/=lib-upgradeable/utility-contracts/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.