Verified contractExactMIT
AssetStore
Address0xa647cfbf081c73fbe939fe44560600bfcf3b4af5
- Balance
0 ETH
- Transactions
16
- 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
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,159,543
- Creation transaction
- 0xd925c00f75…97d24225fa
5 files
- src/legacy/AssetStore.solmain36.96 KB
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/utils/SSTORE2.sol12.63 KB
- src/lib/Errors.sol548 B
- src/lib/LibBlobHeader.sol7.36 KB
src/legacy/AssetStore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Ownable} from "solady/src/auth/Ownable.sol";
import {SSTORE2} from "solady/src/utils/SSTORE2.sol";
import {SourceInfo, LibBlobHeader} from "../lib/LibBlobHeader.sol";
import {
StrideMismatch,
MaxLayersExceeded,
MaxTraitsExceeded,
TokenIdOutOfRange,
MissingRequiredSource
} from "../lib/Errors.sol";
error InvalidTokenId();
error InvalidMimeType();
error InvalidSize();
error LengthMismatch();
error InvalidAvif();
error AssetIdAlreadyUsed();
error InvalidTraitId();
error UnsupportedTableKind(uint8 tableKind);
/**
* @title AssetStore (MetaFoxes V5)
* @notice Unified storage contract using BlobHeader self-describing tables and SSTORE2.
* @dev Internal storage: Source pointers + BlobHeader; output: Bundle API for renderers.
*/
contract AssetStore is Ownable {
using LibBlobHeader for SourceInfo;
uint256 private constant TOKEN_IMAGE_PAGE_BYTES = 24_570;
uint16 public constant STOLEN_WHITE_ASSET_ID = 18;
string public constant STOLEN_DESCRIPTION = "DO NOT BUY! THIS TOKEN HAS BEEN MARKED AS STOLEN.";
// Original shared warning for the three historical incidents; stored once in bytecode.
string private constant HISTORICAL_STOLEN_DESCRIPTION = "DO NOT BUY! THIS TOKEN WAS STOLEN IN A PHISHING ATTACK! IMAGE ALTERED BASED ON VOTES ON https://snapshot.box/#/s:nextdao.eth";
mapping(uint256 => uint256) public stolenBitmap;
// ── TableKind Constants ──
uint8 internal constant TABLE_CATEGORIES_TEXT = 1;
uint8 internal constant TABLE_TRAITS_TEXT = 2;
uint8 internal constant TABLE_ASSETS = 3;
uint8 internal constant TABLE_TOKEN_ASSET_IDS = 4;
uint8 internal constant TABLE_TOKEN_TRAIT_IDS = 5;
uint8 internal constant TABLE_TOKEN_ATTRIBUTES = 7;
uint8 internal constant TABLE_TOKEN_EXTRA_ATTRIBUTES = 8;
uint8 internal constant TABLE_TOKEN_BG = 9;
uint8 internal constant TABLE_TOKEN_NAME = 10;
uint8 internal constant TABLE_TOKEN_DESC = 11;
// Optional exact original JSON (without image), for metadata not representable by dictionary traits.
uint8 public constant TABLE_TOKEN_METADATA = 12;
// ── Asset Data Flags (byte [23] of AssetRecord) ──
// low4 = dataFlags
uint8 public constant FLAG_MULTIPART = 0x01;
uint8 public constant FLAG_SLICED = 0x02;
uint8 public constant FLAG_DATA_IS_BASE64 = 0x04;
uint8 public constant FLAG_RESERVED_0X08 = 0x08;
// high4 = renderFlags
uint8 public constant FLAG_LAYER_PIXELATED = 0x10; // Renderer: add style='image-rendering:pixelated' to this <image>
// ── Visual Configuration ──
uint256 public tokenIdStart;
uint256 public totalTokens;
uint256 public maxTokenId;
// ── Source Tables (1-12, excluding unused Table 6) ──
mapping(uint8 => SourceInfo) internal _sources;
// ── Patch System ──
uint16 public patchBitmap; // bit i = tableKind i has patches
uint16 public sourceBitmap; // bit i = tableKind i has source
mapping(uint8 => mapping(uint256 => bytes)) internal _patches;
// ── Metadata ──
string public baseName;
string public collectionName;
string public baseDescription;
string public baseExternalUrlPrefix;
string public baseAnimationUrlPrefix;
string public baseJsonExtra;
// ── Events ──
event SourceSet(uint8 indexed tableKind, address ptr, uint32 stride, uint32 count);
event PatchSet(uint8 indexed tableKind, uint256 indexed id, bool active);
event TokenImageUpdated(uint256 indexed tokenId, uint16 indexed assetId, address pointer, uint32 imageBytes);
event TokenAdded(uint256 indexed tokenId, uint16 indexed assetId);
event TokenMarkedStolen(uint256 indexed tokenId);
// ═══════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════
constructor() {
_initializeOwner(msg.sender);
baseName = "On-Chain NFT";
baseDescription = "Fully on-chain composable NFT";
}
// ═══════════════════════════════════════════════════════════
// OWNERSHIP
// ═══════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════
// SOURCE CONFIGURATION
// ═══════════════════════════════════════════════════════════
/// @notice Unified source setter. Table 6 is intentionally unsupported for MetaFoxes.
function setSource(uint8 tableKind, address ptr) external onlyOwner notFrozen {
if (tableKind == 6) revert UnsupportedTableKind(tableKind);
// 1. Slot reference
SourceInfo storage slot = _sources[tableKind];
// 2. Parse & validate — ONE inline
SourceInfo memory src = LibBlobHeader.parseAndValidate(ptr, tableKind);
// 3. Per-source stride/mode validation
// TEXT tables (Categories/Traits/AttributeKeys): stride is dynamic (max name length)
if (tableKind == TABLE_ASSETS) {
if (src.stride != 36) revert StrideMismatch(36, src.stride);
} else if (tableKind == TABLE_TOKEN_ASSET_IDS) {
if (src.stride != uint32(src.aux) * 2) {
revert StrideMismatch(uint32(src.aux) * 2, src.stride);
}
if (src.aux > 12287) revert MaxLayersExceeded(src.aux);
} else if (tableKind == TABLE_TOKEN_TRAIT_IDS) {
if (src.stride != uint32(src.aux) * 2) {
revert StrideMismatch(uint32(src.aux) * 2, src.stride);
}
if (src.aux > 12287) revert MaxTraitsExceeded(src.aux);
} else if (
tableKind == TABLE_TOKEN_ATTRIBUTES || tableKind == TABLE_TOKEN_EXTRA_ATTRIBUTES
|| tableKind == TABLE_TOKEN_DESC || tableKind == TABLE_TOKEN_METADATA
) {
// Pointer-row tables: stride must be 32 (each row = [pagePtr:20][dataParam:4][reserved:8])
if (src.stride != 32) revert StrideMismatch(32, src.stride);
} else if (tableKind == TABLE_TOKEN_BG) {
if (src.stride != 4) revert StrideMismatch(4, src.stride);
}
// TOKEN_NAME: no stride check (fixed-stride text rows)
// 5. Write to storage
slot.ptr = src.ptr;
slot.stride = src.stride;
slot.count = src.count;
slot.idStart = src.idStart;
slot.aux = src.aux;
slot.pageSize = src.pageSize;
sourceBitmap |= uint16(1) << tableKind;
// 6. Emit
emit SourceSet(tableKind, ptr, src.stride, src.count);
}
// ═══════════════════════════════════════════════════════════
// PATCH MAPPING
// ═══════════════════════════════════════════════════════════
/// @notice Set patches for a single table. Single patch = arrays of length 1.
function batchSetPatch(uint8 tableKind, uint256[] calldata ids, bytes[] calldata data) external onlyOwner notFrozen {
if (tableKind == 6) revert UnsupportedTableKind(tableKind);
if (ids.length != data.length) revert LengthMismatch();
bool anySet;
for (uint256 i; i < ids.length;) {
if (data[i].length == 0) {
delete _patches[tableKind][ids[i]];
} else {
_patches[tableKind][ids[i]] = data[i];
anySet = true;
}
emit PatchSet(tableKind, ids[i], data[i].length > 0);
unchecked {
++i;
}
}
if (anySet) {
patchBitmap |= uint16(1) << tableKind;
}
}
/// @notice Link uploaded image pages, writing the small index in this owner transaction.
/// @param assetId A fresh, unused asset ID; existing/shared assets are never overwritten.
/// @dev AVIF encoding and 1000x1000 dimensions must be checked by the upload client.
function updateTokenImage(uint256 tokenId, uint16 assetId, address[] calldata imagePages, uint32 imageBytes)
external onlyOwner notFrozen
{
requireValidToken(tokenId);
_validateImageWrite(assetId, imagePages, imageBytes);
_storeTokenImage(tokenId, assetId, imagePages, imageBytes);
}
/// @notice Read the scalable bitmap (256 token IDs per storage word).
function isTokenStolen(uint256 tokenId) public view returns (bool) {
return stolenBitmap[tokenId >> 8] & (uint256(1) << (tokenId & 255)) != 0;
}
/// @notice Mark an existing NFT stolen using shared text rules and the original white asset.
/// @dev Bitmap takes priority over Patch/Source. Only one bit is written; existing data is untouched.
function markTokenStolen(uint256 tokenId) external onlyOwner notFrozen {
requireValidToken(tokenId);
if (isTokenStolen(tokenId)) return;
bytes memory white = _readRow(TABLE_ASSETS, STOLEN_WHITE_ASSET_ID);
bytes memory expected = abi.encodePacked(
address(0x31c2E9EE7318b22A577090701Eb4fc08B7a4F258), uint16(0), uint8(3), uint8(0),
uint8(255), uint8(0), uint16(0), uint32(347), uint16(1000), uint16(1000)
);
if (keccak256(white) != keccak256(expected)) revert InvalidSize();
_validateImagePage(address(0x31c2E9EE7318b22A577090701Eb4fc08B7a4F258), 347);
stolenBitmap[tokenId >> 8] |= uint256(1) << (tokenId & 255);
emit TokenMarkedStolen(tokenId);
}
/// @notice Register a new token's image, traits and range atomically. Does not mint ERC-721.
/// @dev Name and description inherit base metadata unless independently overridden.
/// Empty traitIds writes a complete zero-filled Table 5 row, returning attributes: [].
function addToken(
uint256 tokenId, uint16 assetId, address[] calldata imagePages, uint32 imageBytes, uint16[] calldata traitIds
)
external onlyOwner notFrozen
{
if (tokenId < tokenIdStart || tokenId <= maxTokenId) revert InvalidTokenId();
SourceInfo memory recipes = _sources[TABLE_TOKEN_ASSET_IDS];
if (
_patches[TABLE_TOKEN_ASSET_IDS][tokenId].length != 0
|| (tokenId >= recipes.idStart && tokenId - recipes.idStart < recipes.count)
) revert InvalidTokenId();
_validateImageWrite(assetId, imagePages, imageBytes);
SourceInfo memory traits = _sources[TABLE_TOKEN_TRAIT_IDS];
if (traits.ptr == address(0)) revert MissingRequiredSource("token-traits");
if (traits.aux != 2 || traits.stride != 4 || traitIds.length > 2) revert InvalidSize();
bytes memory traitRow = new bytes(4);
for (uint256 i; i < traitIds.length; ++i) {
uint16 id = traitIds[i];
if (id == 0) continue;
bytes memory row = _readRow(TABLE_TRAITS_TEXT, id);
if (row.length < 5 || row[4] == 0 || uint256(uint8(row[4])) + 5 > row.length) {
revert InvalidTraitId();
}
bytes memory category = _readRow(TABLE_CATEGORIES_TEXT, _readUint16BE(row, 2));
if (category.length < 3 || category[2] == 0 || uint256(uint8(category[2])) + 3 > category.length) {
revert InvalidTraitId();
}
traitRow[i * 2] = bytes1(uint8(id >> 8));
traitRow[i * 2 + 1] = bytes1(uint8(id));
}
_storeTokenImage(tokenId, assetId, imagePages, imageBytes);
_setTokenPatch(TABLE_TOKEN_TRAIT_IDS, tokenId, traitRow);
maxTokenId = tokenId;
totalTokens += 1;
emit TokenAdded(tokenId, assetId);
}
function _validateImageWrite(uint16 assetId, address[] calldata imagePages, uint32 imageBytes)
private view
{
if (assetId == 0) revert InvalidTokenId();
SourceInfo memory assets = _sources[TABLE_ASSETS];
SourceInfo memory recipes = _sources[TABLE_TOKEN_ASSET_IDS];
if (assets.ptr == address(0)) revert MissingRequiredSource("assets");
if (recipes.ptr == address(0)) revert MissingRequiredSource("token-assets");
if (assets.stride != 36 || recipes.stride != 2 || recipes.aux != 1) revert InvalidSize();
if (
_patches[TABLE_ASSETS][assetId].length != 0
|| (assetId >= assets.idStart && uint256(assetId) - assets.idStart < assets.count)
) revert AssetIdAlreadyUsed();
if (imageBytes < 16) revert InvalidAvif();
uint256 count = (uint256(imageBytes) + TOKEN_IMAGE_PAGE_BYTES - 1) / TOKEN_IMAGE_PAGE_BYTES;
if (imagePages.length != count || count * 32 + 1 > 24576) revert InvalidSize();
for (uint256 i; i < count; ++i) {
uint256 pageBytes = i + 1 == count ? uint256(imageBytes) - i * TOKEN_IMAGE_PAGE_BYTES : TOKEN_IMAGE_PAGE_BYTES;
_validateImagePage(imagePages[i], pageBytes);
}
address first = imagePages[0];
uint256 firstBytes = count == 1 ? imageBytes : TOKEN_IMAGE_PAGE_BYTES;
// A cheap AVIF container check; dimensions/decoding belong to the upload client.
bytes memory header = SSTORE2.read(first, 0, 16);
if (_imageWord(header, 4) != bytes4("ftyp")) revert InvalidAvif();
uint256 boxSize = uint32(_imageWord(header, 0));
if (boxSize < 16 || boxSize > firstBytes || boxSize % 4 != 0) revert InvalidAvif();
bool avifBrand = _imageWord(header, 8) == bytes4("avif");
if (!avifBrand) {
header = SSTORE2.read(first, 0, boxSize);
for (uint256 i = 16; !avifBrand && i < boxSize; i += 4) {
avifBrand = _imageWord(header, i) == bytes4("avif");
}
}
if (!avifBrand) revert InvalidAvif();
}
function _validateImagePage(address pointer, uint256 length) private view {
if (pointer == address(0) || pointer.code.length != length + 1) revert InvalidSize();
uint256 firstByte;
assembly ("memory-safe") {
extcodecopy(pointer, 0, 0, 1)
firstByte := byte(0, mload(0))
}
if (firstByte != 0) revert InvalidSize();
}
function _imageWord(bytes memory data, uint256 offset) private pure returns (bytes4 value) {
assembly ("memory-safe") { value := mload(add(add(data, 32), offset)) }
}
function _storeTokenImage(uint256 tokenId, uint16 assetId, address[] calldata imagePages, uint32 imageBytes)
private
{
address pointer = imagePages[0];
uint8 flags;
if (imagePages.length > 1) {
bytes memory index = new bytes(imagePages.length * 32);
for (uint256 i; i < imagePages.length; ++i) {
address page = imagePages[i];
assembly ("memory-safe") { mstore(add(add(index, 32), mul(i, 32)), page) }
}
bytes32 salt = keccak256(index);
pointer = SSTORE2.predictCounterfactualAddress(index, salt, address(this));
if (pointer.code.length == 0) pointer = SSTORE2.writeCounterfactual(index, salt);
flags = FLAG_MULTIPART;
}
bytes memory assetRow = abi.encodePacked(
pointer, uint16(0), uint8(3), flags, uint8(255), uint8(0), uint16(0),
imageBytes, uint16(1000), uint16(1000)
);
_setTokenPatch(TABLE_ASSETS, assetId, assetRow);
_setTokenPatch(TABLE_TOKEN_ASSET_IDS, tokenId, abi.encodePacked(assetId));
emit TokenImageUpdated(tokenId, assetId, pointer, imageBytes);
}
function _setTokenPatch(uint8 tableKind, uint256 id, bytes memory data) private {
_patches[tableKind][id] = data;
patchBitmap |= uint16(1) << tableKind;
emit PatchSet(tableKind, id, true);
}
/// @notice Read the effective row value (patch > source > empty).
/// For pointer-row tables (7/8/11/12), returns dereferenced data, not the pointer row.
function getRow(uint8 tableKind, uint256 id) external view returns (bytes memory) {
if (
tableKind == TABLE_TOKEN_ATTRIBUTES || tableKind == TABLE_TOKEN_EXTRA_ATTRIBUTES
|| tableKind == TABLE_TOKEN_DESC || tableKind == TABLE_TOKEN_METADATA
) {
return _readAttributeData(tableKind, id);
}
return _readRow(tableKind, id);
}
// ═══════════════════════════════════════════════════════════
// BASIC CONFIGURATION
// ═══════════════════════════════════════════════════════════
function setTokenIdStart(uint256 _start) external onlyOwner notFrozen {
tokenIdStart = _start;
}
function setTotalTokens(uint256 _total) external onlyOwner notFrozen {
totalTokens = _total;
}
function setMaxTokenId(uint256 _maxId) external onlyOwner notFrozen {
maxTokenId = _maxId;
}
/// @notice MIME type lookup by ID. Pure — no SLOAD.
function getMimeType(uint256 id) external pure returns (string memory) {
return _mimeType(uint8(id));
}
function _mimeType(uint8 id) internal pure returns (string memory) {
if (id == 0) return "image/png";
if (id == 1) return "image/webp";
if (id == 2) return "image/svg+xml";
if (id == 3) return "image/avif";
if (id == 4) return "image/gif";
if (id == 5) return "image/jpeg";
if (id == 6) return "application/octet-stream";
if (id == 7) return "application/x-onchain-rgba";
revert InvalidMimeType();
}
function setBaseMetadata(string calldata _baseName, string calldata _collectionName, string calldata _desc)
external
onlyOwner notFrozen
{
baseName = _baseName;
collectionName = _collectionName;
baseDescription = _desc;
}
function setBaseExternalUrlPrefix(string calldata _prefix) external onlyOwner notFrozen {
baseExternalUrlPrefix = _prefix;
}
function setBaseAnimationUrlPrefix(string calldata _prefix) external onlyOwner notFrozen {
baseAnimationUrlPrefix = _prefix;
}
function setBaseJsonExtra(string calldata _extra) external onlyOwner notFrozen {
baseJsonExtra = _extra;
}
// ═══════════════════════════════════════════════════════════
// BUNDLE API
// ═══════════════════════════════════════════════════════════
/**
* @notice Render bundle for renderers (single-call read path).
* @dev Packed layout per layer (asset record first 32 bytes, no repack):
* [0..19] ptr (address)
* [20..21] traitId (uint16, ignored by renderers)
* [22] mimeTypeId (uint8)
* [23] flags (low4=dataFlags, high4=renderFlags; bit4=FLAG_LAYER_PIXELATED)
* [24] opacity (uint8)
* [25] blendMode (uint8, 0-15)
* [26..27] reserved
* [28..31] dataParam (uint32)
*/
function getTokenRenderBundle(uint256 tokenId)
external
view
returns (uint16 canvasWidth, uint16 canvasHeight, uint32 totalBytes, bytes memory packed)
{
_validateTokenId(tokenId);
if (sourceBitmap & (uint16(1) << TABLE_ASSETS) == 0) {
revert MissingRequiredSource("assets");
}
// Get assetIds from TOKEN_ASSET_IDS table
SourceInfo memory _assetIds = _sources[TABLE_TOKEN_ASSET_IDS];
bool sharedWhite = isTokenStolen(tokenId);
bytes memory layerRow = sharedWhite
? abi.encodePacked(STOLEN_WHITE_ASSET_ID)
: _readRow(TABLE_TOKEN_ASSET_IDS, _assetIds, tokenId);
uint256 maxLayers = sharedWhite ? 1 : _assetIds.aux;
// Count non-zero layers
uint256 layerCount;
for (uint256 i; i < maxLayers;) {
if (_readUint16BE(layerRow, i * 2) != 0) layerCount++;
unchecked {
++i;
}
}
if (layerCount == 0) revert InvalidTokenId();
packed = new bytes(layerCount * 32);
SourceInfo memory _assets = _sources[TABLE_ASSETS]; // cache: avoid repeated SLOAD
uint256 outIdx;
for (uint256 i; i < maxLayers;) {
uint16 assetId = _readUint16BE(layerRow, i * 2);
if (assetId == 0) {
unchecked {
++i;
}
continue;
}
bytes memory assetRow = _readRow(TABLE_ASSETS, _assets, assetId);
uint256 aw; // asset word (32 bytes)
assembly {
aw := mload(add(assetRow, 32))
}
// Empty asset record → non-existent token (gap)
if (aw == 0) revert InvalidTokenId();
uint8 dataFlags = uint8(uint8(aw >> 64) & 0x0F);
// First layer → canvas dimensions from asset record bytes 32-35
if (outIdx == 0) {
canvasWidth = _readUint16BE(assetRow, 32);
canvasHeight = _readUint16BE(assetRow, 34);
}
// Accumulate byte size
uint32 dp = uint32(aw);
totalBytes += (dataFlags & FLAG_SLICED) != 0 ? uint32(uint16(dp)) : dp;
// Store asset record word directly (no repack)
assembly {
mstore(add(add(packed, 32), mul(outIdx, 32)), aw)
}
unchecked {
outIdx++;
++i;
}
}
}
/**
* @notice Aggregated metadata bundle for renderers.
* @dev Returns all metadata needed for JSON construction in a single call.
*/
function getTokenMetadataBundle(uint256 tokenId)
external
view
returns (
string memory name,
string memory description,
string memory externalUrl,
string memory animationUrl,
string memory backgroundColor,
string[] memory traitTypes,
string[] memory traitValues,
bytes memory tokenAttributes,
bytes memory extraAttributes,
string memory jsonExtra
)
{
_validateTokenId(tokenId);
// Bitmap is the primary stolen path. Unmarked tokens keep the original Patch/Source path.
if (isTokenStolen(tokenId)) {
name = string.concat("Meta Fox #", _toString(tokenId), " (STOLEN! DO NOT BUY!)");
description = tokenId == 18 || tokenId == 21 || tokenId == 111
? HISTORICAL_STOLEN_DESCRIPTION : STOLEN_DESCRIPTION;
} else {
// Name is semantic UTF-8; the Renderer escapes at the JSON boundary.
bytes memory tokenName = _readRow(TABLE_TOKEN_NAME, tokenId);
if (tokenName.length >= 1) {
uint256 tokenNameLength = uint8(tokenName[0]);
if (tokenNameLength != 0 && tokenNameLength + 1 <= tokenName.length) {
name = _extractString(tokenName, 1, tokenNameLength);
}
}
if (bytes(name).length == 0) {
string memory bn = baseName;
name = bytes(bn).length > 0
? string.concat(bn, " #", _toString(tokenId))
: string.concat("#", _toString(tokenId));
}
bytes memory tokenDescription = _readAttributeData(TABLE_TOKEN_DESC, tokenId);
description = tokenDescription.length == 0 ? baseDescription : string(tokenDescription);
}
// 3. URLs (prefix-based)
if (bytes(baseExternalUrlPrefix).length > 0) {
externalUrl = string.concat(baseExternalUrlPrefix, _toString(tokenId));
}
if (bytes(baseAnimationUrlPrefix).length > 0) {
animationUrl = string.concat(baseAnimationUrlPrefix, _toString(tokenId));
}
// 4. Standard attributes come from dictionary traits only.
(traitTypes, traitValues) = _resolveTraits(tokenId);
// 5. Standard metadata has no per-token background or raw JSON patches.
backgroundColor = "";
tokenAttributes = "";
extraAttributes = "";
// 6. JSON extra is collection-level only.
jsonExtra = baseJsonExtra;
}
/// @notice Collection metadata bundle (used by Renderer)
function getCollectionMetadataBundle()
external
view
returns (
uint256 totalTokens_,
uint256 elementCount_,
uint256 tokenIdStart_,
string memory baseName_,
string memory baseDescription_,
string memory baseAnimationUrlPrefix_,
string memory baseJsonExtra_,
uint256 maxTokenId_
)
{
totalTokens_ = totalTokens;
elementCount_ = _sources[TABLE_ASSETS].count;
tokenIdStart_ = tokenIdStart;
baseName_ = baseName;
baseDescription_ = baseDescription;
baseAnimationUrlPrefix_ = baseAnimationUrlPrefix;
baseJsonExtra_ = baseJsonExtra;
maxTokenId_ = maxTokenId;
}
// ═══════════════════════════════════════════════════════════
// READ PRIMITIVES (external tools / contracts)
// ═══════════════════════════════════════════════════════════
// ── A) Source / Table Level ──
/// @notice Get cached SourceInfo for a table by kind.
function getSourceInfo(uint8 tableKind) external view returns (SourceInfo memory) {
return _sources[tableKind];
}
// ═══════════════════════════════════════════════════════════
// INTERNAL HELPERS
// ═══════════════════════════════════════════════════════════
/// @dev Unified read: patch > source > empty. Version A (auto-loads source).
function _readRow(uint8 tableKind, uint256 id) internal view returns (bytes memory) {
uint16 pBm = patchBitmap;
uint16 sBm = sourceBitmap;
if (pBm & (uint16(1) << tableKind) != 0) {
bytes storage p = _patches[tableKind][id];
if (p.length > 0) return p;
}
if (sBm & (uint16(1) << tableKind) == 0) return "";
return LibBlobHeader.readRow(_sources[tableKind], id);
}
/// @dev Version B: uses cached SourceInfo (for loops to avoid repeated SLOAD).
function _readRow(uint8 tableKind, SourceInfo memory src, uint256 id) internal view returns (bytes memory) {
if (patchBitmap & (uint16(1) << tableKind) != 0) {
bytes storage p = _patches[tableKind][id];
if (p.length > 0) return p;
}
return LibBlobHeader.readRow(src, id);
}
function _validateTokenId(uint256 tokenId) internal view {
uint256 maxId = maxTokenId;
if (maxId < tokenIdStart) revert TokenIdOutOfRange(tokenId);
if (tokenId < tokenIdStart || tokenId > maxId) {
revert TokenIdOutOfRange(tokenId);
}
}
// ── Trait Resolution ──
/**
* @dev Resolve traits using effective category and trait rows (patch > source).
*
* traitsText row format (V5 implementation):
* [0:2] id (uint16 BE)
* [2:4] categoryId (uint16 BE)
* [4] nameLen (uint8)
* [5:5+nameLen] name (UTF-8)
*/
function _resolveTraits(uint256 tokenId)
internal
view
returns (string[] memory traitTypes, string[] memory traitValues)
{
if (((sourceBitmap | patchBitmap) & (uint16(1) << TABLE_CATEGORIES_TEXT)) == 0) {
return (traitTypes, traitValues);
}
SourceInfo memory _cats = _sources[TABLE_CATEGORIES_TEXT];
SourceInfo memory _traits = _sources[TABLE_TRAITS_TEXT];
// Prefer explicit token traits when present; otherwise derive from TOKEN_ASSET_IDS + ASSETS.
uint16[] memory traitIds;
SourceInfo memory _tokenTraits = _sources[TABLE_TOKEN_TRAIT_IDS];
if (_tokenTraits.ptr != address(0)) {
traitIds = _getTokenTraitIds(tokenId);
} else {
traitIds = _getLayerTraitIds(tokenId);
}
// Count non-zero
uint256 validCount;
for (uint256 i; i < traitIds.length;) {
if (traitIds[i] != 0) validCount++;
unchecked {
++i;
}
}
traitTypes = new string[](validCount);
traitValues = new string[](validCount);
uint256 idx;
for (uint256 i; i < traitIds.length;) {
uint16 traitId = traitIds[i];
if (traitId == 0) {
unchecked {
++i;
}
continue;
}
// Read trait row: [id:2, categoryId:2, nameLen:1, name:...]
bytes memory traitRow = _readRow(TABLE_TRAITS_TEXT, _traits, traitId);
uint16 categoryId = _readUint16BE(traitRow, 2);
uint8 nameLen = uint8(traitRow[4]);
traitValues[idx] = _extractString(traitRow, 5, nameLen);
traitTypes[idx] = _readCategoryName(_cats, categoryId);
unchecked {
idx++;
++i;
}
}
}
/// @dev Get traitIds by reading token_assetIds then asset records
function _getLayerTraitIds(uint256 tokenId) internal view returns (uint16[] memory traitIds) {
SourceInfo memory _layers = _sources[TABLE_TOKEN_ASSET_IDS];
bytes memory layerRow = _readRow(TABLE_TOKEN_ASSET_IDS, _layers, tokenId);
uint256 maxLayers = _layers.aux;
SourceInfo memory _assets = _sources[TABLE_ASSETS];
traitIds = new uint16[](maxLayers);
for (uint256 i; i < maxLayers;) {
uint16 assetId = _readUint16BE(layerRow, i * 2);
if (assetId != 0) {
bytes memory assetRow = _readRow(TABLE_ASSETS, _assets, assetId);
// traitId at AssetRecord bytes [20..21]
traitIds[i] = _readUint16BE(assetRow, 20);
}
unchecked {
++i;
}
}
}
/// @dev Get traitIds directly from _sources[TABLE_TOKEN_TRAIT_IDS].
function _getTokenTraitIds(uint256 tokenId) internal view returns (uint16[] memory traitIds) {
SourceInfo memory _tokenTraits = _sources[TABLE_TOKEN_TRAIT_IDS];
bytes memory row = _readRow(TABLE_TOKEN_TRAIT_IDS, _tokenTraits, tokenId);
uint256 maxTraits = _tokenTraits.aux;
traitIds = new uint16[](maxTraits);
for (uint256 i; i < maxTraits;) {
traitIds[i] = _readUint16BE(row, i * 2);
unchecked {
++i;
}
}
}
/// @dev Resolve the effective category row, including patch-only categories.
function _readCategoryName(SourceInfo memory source, uint16 categoryId)
internal
view
returns (string memory)
{
bytes memory row = _readRow(TABLE_CATEGORIES_TEXT, source, categoryId);
if (row.length == 0) return "";
if (row.length < 3) revert InvalidSize();
uint8 nameLen = uint8(row[2]);
if (uint256(nameLen) + 3 > row.length) revert InvalidSize();
if (nameLen == 0) return "";
return _extractString(row, 3, nameLen);
}
/// @dev Read data from pointer-row tables (TABLE 7/8/11/12).
/// Patch: stored directly as raw bytes.
/// Source: row = [pagePtr:20][dataParam:4][reserved:8], dereference via SSTORE2.
function _readAttributeData(uint8 tableKind, uint256 tokenId) internal view returns (bytes memory) {
// 1. Check patch first (direct KV/TLV bytes)
if (patchBitmap & (uint16(1) << tableKind) != 0) {
bytes storage p = _patches[tableKind][tokenId];
if (p.length > 0) return p;
}
// 2. Check source (pointer row → dereference)
if (sourceBitmap & (uint16(1) << tableKind) == 0) return "";
bytes memory row = LibBlobHeader.readRow(_sources[tableKind], tokenId);
if (row.length == 0) return "";
// 3. Dereference: row = [pagePtr:20][dataParam:4][reserved:8]
address pagePtr;
uint32 dataParam;
assembly {
let w := mload(add(row, 32))
pagePtr := shr(96, w)
dataParam := and(shr(64, w), 0xffffffff)
}
if (pagePtr == address(0)) return "";
uint256 offset = uint256(dataParam >> 16);
uint256 length = uint256(dataParam & 0xffff);
if (length == 0) return "";
// 4. Read actual data from page blob via SSTORE2
return SSTORE2.read(pagePtr, offset, offset + length);
}
// ── Low-Level Helpers ──
function _readUint16BE(bytes memory data, uint256 offset) internal pure returns (uint16) {
return (uint16(uint8(data[offset])) << 8) | uint16(uint8(data[offset + 1]));
}
function _extractString(bytes memory data, uint256 offset, uint256 len)
internal
pure
returns (string memory result)
{
result = new string(len);
assembly {
let s := add(add(data, 32), offset)
let d := add(result, 32)
for {
let j := 0
} lt(j, len) {
j := add(j, 32)
} {
mstore(add(d, j), mload(add(s, j)))
}
}
}
function _toString(uint256 value) internal pure returns (string memory) {
if (value == 0) return "0";
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + (value % 10)));
value /= 10;
}
return string(buffer);
}
// ═══════════════════════════════════════════════════════════
// TOKEN VALIDATION
// ═══════════════════════════════════════════════════════════
function requireValidToken(uint256 tokenId) public view {
if (maxTokenId < tokenIdStart || tokenId < tokenIdStart || tokenId > maxTokenId) {
revert TokenIdOutOfRange(tokenId);
}
bytes memory layerRow = _readRow(TABLE_TOKEN_ASSET_IDS, tokenId);
if (layerRow.length == 0) revert InvalidTokenId();
for (uint256 i; i < layerRow.length;) {
if (layerRow[i] != 0) return;
unchecked {
++i;
}
}
revert InvalidTokenId();
}
// Freezing is available only by an explicit owner action.
bool public frozen;
error ContentFrozen();
event ContentFrozenPermanently();
modifier notFrozen() {
if (frozen) revert ContentFrozen();
_;
}
/// @notice Irreversibly lock artwork and metadata configuration.
function freeze() external onlyOwner notFrozen {
frozen = true;
emit ContentFrozenPermanently();
}
}
lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
lib/solady/src/utils/SSTORE2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SSTORE2.sol)
/// @author Saw-mon-and-Natalie (https://github.com/Saw-mon-and-Natalie)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
/// @author Modified from SSTORE3 (https://github.com/Philogy/sstore3)
library SSTORE2 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The proxy initialization code.
uint256 private constant _CREATE3_PROXY_INITCODE = 0x67363d3d37363d34f03d5260086018f3;
/// @dev Hash of the `_CREATE3_PROXY_INITCODE`.
/// Equivalent to `keccak256(abi.encodePacked(hex"67363d3d37363d34f03d5260086018f3"))`.
bytes32 internal constant CREATE3_PROXY_INITCODE_HASH =
0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unable to deploy the storage contract.
error DeploymentFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* WRITE LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
function write(bytes memory data) internal returns (address pointer) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data) // Let `l` be `n + 1`. +1 as we prefix a STOP opcode.
/**
* ---------------------------------------------------+
* Opcode | Mnemonic | Stack | Memory |
* ---------------------------------------------------|
* 61 l | PUSH2 l | l | |
* 80 | DUP1 | l l | |
* 60 0xa | PUSH1 0xa | 0xa l l | |
* 3D | RETURNDATASIZE | 0 0xa l l | |
* 39 | CODECOPY | l | [0..l): code |
* 3D | RETURNDATASIZE | 0 l | [0..l): code |
* F3 | RETURN | | [0..l): code |
* 00 | STOP | | |
* ---------------------------------------------------+
* @dev Prefix the bytecode with a STOP opcode to ensure it cannot be called.
* Also PUSH2 is used since max contract size cap is 24,576 bytes which is less than 2 ** 16.
*/
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create(0, add(data, 0x15), add(n, 0xb))
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract with `salt`
/// and returns its normal CREATE2 deterministic address.
function writeCounterfactual(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
// Deploy a new contract with the generated creation code.
pointer := create2(0, add(data, 0x15), add(n, 0xb), salt)
if iszero(pointer) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Writes `data` into the bytecode of a storage contract and returns its address.
/// This uses the so-called "CREATE3" workflow,
/// which means that `pointer` is agnostic to `data, and only depends on `salt`.
function writeDeterministic(bytes memory data, bytes32 salt)
internal
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
mstore(0x00, _CREATE3_PROXY_INITCODE) // Store the `_PROXY_INITCODE`.
let proxy := create2(0, 0x10, 0x10, salt)
if iszero(proxy) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, proxy) // Store the proxy's address.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
mstore(add(data, gt(n, 0xfffe)), add(0xfe61000180600a3d393df300, shl(0x40, n)))
if iszero(
mul( // The arguments of `mul` are evaluated last to first.
extcodesize(pointer),
call(gas(), proxy, 0, add(data, 0x15), add(n, 0xb), codesize(), 0x00)
)
) {
mstore(0x00, 0x30116425) // `DeploymentFailed()`.
revert(0x1c, 0x04)
}
mstore(data, n) // Restore the length of `data`.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ADDRESS CALCULATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the initialization code hash of the storage contract for `data`.
/// Used for mining vanity addresses with create2crunch.
function initCodeHash(bytes memory data) internal pure returns (bytes32 hash) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(data)
// Do a out-of-gas revert if `n + 1` is more than 2 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0xfffe))
mstore(data, add(0x61000180600a3d393df300, shl(0x40, n)))
hash := keccak256(add(data, 0x15), add(n, 0xb))
mstore(data, n) // Restore the length of `data`.
}
}
/// @dev Equivalent to `predictCounterfactualAddress(data, salt, address(this))`
function predictCounterfactualAddress(bytes memory data, bytes32 salt)
internal
view
returns (address pointer)
{
pointer = predictCounterfactualAddress(data, salt, address(this));
}
/// @dev Returns the CREATE2 address of the storage contract for `data`
/// deployed with `salt` by `deployer`.
/// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
function predictCounterfactualAddress(bytes memory data, bytes32 salt, address deployer)
internal
pure
returns (address predicted)
{
bytes32 hash = initCodeHash(data);
/// @solidity memory-safe-assembly
assembly {
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, hash)
mstore(0x01, shl(96, deployer))
mstore(0x15, salt)
predicted := keccak256(0x00, 0x55)
// Restore the part of the free memory pointer that has been overwritten.
mstore(0x35, 0)
}
}
/// @dev Equivalent to `predictDeterministicAddress(salt, address(this))`.
function predictDeterministicAddress(bytes32 salt) internal view returns (address pointer) {
pointer = predictDeterministicAddress(salt, address(this));
}
/// @dev Returns the "CREATE3" deterministic address for `salt` with `deployer`.
function predictDeterministicAddress(bytes32 salt, address deployer)
internal
pure
returns (address pointer)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, deployer) // Store `deployer`.
mstore8(0x0b, 0xff) // Store the prefix.
mstore(0x20, salt) // Store the salt.
mstore(0x40, CREATE3_PROXY_INITCODE_HASH) // Store the bytecode hash.
mstore(0x14, keccak256(0x0b, 0x55)) // Store the proxy's address.
mstore(0x40, m) // Restore the free memory pointer.
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01).
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex).
mstore(0x00, 0xd694)
mstore8(0x34, 0x01) // Nonce of the proxy contract (1).
pointer := keccak256(0x1e, 0x17)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* READ LOGIC */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `read(pointer, 0, 2 ** 256 - 1)`.
function read(address pointer) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
extcodecopy(pointer, add(data, 0x1f), 0x00, add(n, 0x21))
mstore(data, n) // Store the length.
mstore(0x40, add(n, add(data, 0x40))) // Allocate memory.
}
}
/// @dev Equivalent to `read(pointer, start, 2 ** 256 - 1)`.
function read(address pointer, uint256 start) internal view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
let n := and(0xffffffffff, sub(extcodesize(pointer), 0x01))
let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
extcodecopy(pointer, add(data, 0x1f), start, add(l, 0x21))
mstore(data, mul(sub(n, start), lt(start, n))) // Store the length.
mstore(0x40, add(data, add(0x40, mload(data)))) // Allocate memory.
}
}
/// @dev Returns a slice of the data on `pointer` from `start` to `end`.
/// `start` and `end` will be clamped to the range `[0, args.length]`.
/// The `pointer` MUST be deployed via the SSTORE2 write functions.
/// Otherwise, the behavior is undefined.
/// Out-of-gas reverts if `pointer` does not have any code.
function read(address pointer, uint256 start, uint256 end)
internal
view
returns (bytes memory data)
{
/// @solidity memory-safe-assembly
assembly {
data := mload(0x40)
if iszero(lt(end, 0xffff)) { end := 0xffff }
let d := mul(sub(end, start), lt(start, end))
extcodecopy(pointer, add(data, 0x1f), start, add(d, 0x01))
if iszero(and(0xff, mload(add(data, d)))) {
let n := sub(extcodesize(pointer), 0x01)
returndatacopy(returndatasize(), returndatasize(), shr(40, n))
d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
}
mstore(data, d) // Store the length.
mstore(add(add(data, 0x20), d), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(data, 0x40), d)) // Allocate memory.
}
}
}
src/lib/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// V5 AssetStore errors (spec §13)
error InvalidBlobMagic();
error InvalidBlobVersion();
error TableKindMismatch(uint8 expected, uint8 actual);
error StrideMismatch(uint32 expected, uint32 actual);
error TokenIdOutOfRange(uint256 tokenId);
error MissingRequiredSource(string sourceName);
error MaxLayersExceeded(uint16 maxLayers);
error MaxTraitsExceeded(uint16 maxTraits);
error SourceRangeMismatch(uint32 expectedIdStart, uint32 expectedCount, uint32 actualIdStart, uint32 actualCount);
src/lib/LibBlobHeader.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {SSTORE2} from "solady/src/utils/SSTORE2.sol";
import {InvalidBlobMagic, InvalidBlobVersion, TableKindMismatch} from "./Errors.sol";
/// @notice Cached BlobHeader fields for a Source table.
/// Every Source MUST be stored as a SourceInfo, caching header fields
/// at configuration time to avoid re-reading on each readRow call.
struct SourceInfo {
address ptr; // root blob SSTORE2 pointer
uint32 stride; // row byte size
uint32 count; // number of rows
uint32 idStart; // first logical id
uint16 aux; // maxLayers / maxTraits / maxNameLen (else 0)
uint32 pageSize; // multipart page size; 0 = single-blob
}
// ============================================================
// LibBlobHeader — Responsibilities & Invariants (V5, Frozen)
// ============================================================
// 1. BlobHeader is mandatory: every Source pointer MUST reference
// a root blob whose first 64 bytes are a valid BlobHeader.
// 2. Header-only semantics: operates on table blobs, NOT asset
// payload blobs (SSTORE2 asset data handled elsewhere).
// 3. Header validation: parseAndValidate(ptr) MUST validate magic,
// version, headerLen==64; failure MUST revert.
// 4. Table identity: parseAndValidate(ptr, expectedKind) MUST ensure
// header.tableKind == expectedKind; otherwise revert.
// 5. Optional Sources: if ptr == address(0), read ops MUST return
// zero/empty and MUST NOT revert.
// 6. Row addressing: rowOffset = DATA_OFFSET + (id - idStart) * stride
// 7. Single-blob tables: pageSize == 0 → read directly from root blob
// 8. Multipart tables: pageSize > 0 → resolve chunk pointer, read chunk
// 9. No cross-page records: pageSize % stride == 0 guaranteed
// 10. Pure bytes API: readRow returns raw bytes only, no decoding
// 11. SSTORE2 semantics: ALL offset values are SSTORE2 payload offsets.
// Use SSTORE2.read() for reading, NOT raw extcodecopy.
// ============================================================
library LibBlobHeader {
uint256 internal constant BLOB_HEADER_SIZE = 64;
uint256 internal constant DATA_OFFSET = 64;
/// @notice Parse and validate BlobHeader, return cached SourceInfo
/// @param ptr Root blob SSTORE2 pointer
/// @param expectedKind Expected tableKind value
/// @return src SourceInfo with cached header fields
function parseAndValidate(address ptr, uint8 expectedKind) internal view returns (SourceInfo memory src) {
// Read Word0 (first 32 bytes) of BlobHeader via SSTORE2
bytes memory header = SSTORE2.read(ptr, 0, 32);
uint256 word0;
assembly {
word0 := mload(add(header, 32))
}
// ── Validate (Invariants 3 & 4) ──
// BlobHeader Word0 layout (big-endian):
// [0:4] magic → shr 224
// [4:5] version → shr 216
// [5:7] headerLen → shr 200
// [7:8] tableKind → shr 192
// [8:9] encoding → shr 184 (skipped)
// [9:13] stride → shr 152
// [13:17] count → shr 120
// [17:21] idStart → shr 88
// [21:23] aux → shr 72
// [23:27] pageSize → shr 40
if (uint32(word0 >> 224) != 0x4F434231) revert InvalidBlobMagic();
if (uint8(word0 >> 216) != 1) revert InvalidBlobVersion();
if (uint16(word0 >> 200) != 64) revert InvalidBlobVersion();
uint8 tableKind = uint8(word0 >> 192);
if (tableKind != expectedKind) revert TableKindMismatch(expectedKind, tableKind);
// ── Parse fields into SourceInfo ──
src = SourceInfo({
ptr: ptr,
stride: uint32(word0 >> 152),
count: uint32(word0 >> 120),
idStart: uint32(word0 >> 88),
aux: uint16(word0 >> 72),
pageSize: uint32(word0 >> 40)
});
}
/// @notice Read a single row by logical id
/// @param src Cached SourceInfo
/// @param id Logical row id
/// @return row Raw row bytes; empty if src.ptr == address(0)
function readRow(SourceInfo memory src, uint256 id) internal view returns (bytes memory row) {
// Invariant 5: optional source → return empty
if (src.ptr == address(0)) return row;
// Invariant 6: row offset calculation
uint256 byteOffset = (id - src.idStart) * src.stride;
if (src.pageSize == 0) {
// Invariant 7: single-blob — direct read from root
row = SSTORE2.read(src.ptr, DATA_OFFSET + byteOffset, DATA_OFFSET + byteOffset + src.stride);
} else {
// Invariant 8: multipart — resolve chunk pointer first
// Invariant 9: pageSize % stride == 0 (no cross-page)
uint256 chunkIndex = byteOffset / src.pageSize;
uint256 offsetInChunk = byteOffset % src.pageSize;
// Read 32-byte chunk pointer from root index
bytes memory ptrSlot =
SSTORE2.read(src.ptr, DATA_OFFSET + chunkIndex * 32, DATA_OFFSET + chunkIndex * 32 + 32);
address chunkPtr;
assembly {
chunkPtr := mload(add(ptrSlot, 32))
}
// Read from chunk (chunks have no header, pure data)
row = SSTORE2.read(chunkPtr, offsetInChunk, offsetInChunk + src.stride);
}
// Invariant 10: pure bytes, no decoding
}
/// @notice Read entire table data (optimized for small single-blob tables)
/// @param src Cached SourceInfo
/// @return data All rows concatenated; empty if src.ptr == address(0)
function readAll(SourceInfo memory src) internal view returns (bytes memory data) {
// Invariant 5: optional source → return empty
if (src.ptr == address(0)) return data;
uint256 totalBytes = uint256(src.count) * uint256(src.stride);
if (src.pageSize == 0) {
// Single-blob: one SSTORE2 read
data = SSTORE2.read(src.ptr, DATA_OFFSET, DATA_OFFSET + totalBytes);
} else {
// Multipart: concatenate chunks
data = new bytes(totalBytes);
uint256 chunkCount = (totalBytes + src.pageSize - 1) / src.pageSize;
uint256 remaining = totalBytes;
uint256 written;
for (uint256 i; i < chunkCount;) {
bytes memory ptrSlot = SSTORE2.read(src.ptr, DATA_OFFSET + i * 32, DATA_OFFSET + i * 32 + 32);
address chunkPtr;
assembly {
chunkPtr := mload(add(ptrSlot, 32))
}
uint256 chunkLen = remaining >= src.pageSize ? uint256(src.pageSize) : remaining;
bytes memory chunk = SSTORE2.read(chunkPtr, 0, chunkLen);
// Memory copy: chunk → data[written..]
assembly {
let s := add(chunk, 32)
let d := add(add(data, 32), written)
for { let j := 0 } lt(j, chunkLen) { j := add(j, 32) } {
mstore(add(d, j), mload(add(s, j)))
}
}
written += chunkLen;
remaining -= chunkLen;
unchecked {
++i;
}
}
}
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.