Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions contracts/script/L2Genesis.s.sol
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ contract GenesisEthscriptions is Ethscriptions {
require(ethscriptions[params.transactionHash].creator == address(0), "Ethscription already exists");

// Check protocol uniqueness using content URI hash
if (contentUriExists[params.contentUriHash]) {
if (firstEthscriptionByContentUri[params.contentUriHash] != bytes32(0)) {
if (!params.esip6) revert DuplicateContentUri();
}

// Store content and get content SHA (reusing parent's helper)
bytes32 contentSha = _storeContent(params.content);

// Mark content URI as used
contentUriExists[params.contentUriHash] = true;
// Mark content URI as used by storing this ethscription's tx hash
firstEthscriptionByContentUri[params.contentUriHash] = params.transactionHash;

// Set all values including genesis-specific ones
ethscriptions[params.transactionHash] = Ethscription({
Expand Down Expand Up @@ -341,7 +341,7 @@ contract L2Genesis is Script {
params.mimeSubtype = vm.parseJsonString(json, string.concat(basePath, ".mime_subtype"));
params.esip6 = vm.parseJsonBool(json, string.concat(basePath, ".esip6"));
params.protocolParams = Ethscriptions.ProtocolParams({
protocol: "",
protocolName: "",
operation: "",
data: ""
});
Expand Down
791 changes: 305 additions & 486 deletions contracts/src/Ethscriptions.sol

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion contracts/src/EthscriptionsProver.sol
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ contract EthscriptionsProver {
function _createAndSendProof(bytes32 ethscriptionTxHash, QueuedProof memory proofInfo) internal {
// Get ethscription data including previous owner
Ethscriptions.Ethscription memory etsc = ethscriptions.getEthscription(ethscriptionTxHash);
address currentOwner = ethscriptions.currentOwner(ethscriptionTxHash);
address currentOwner = ethscriptions.ownerOf(ethscriptionTxHash);

// Create proof struct with all ethscription data
EthscriptionDataProof memory proof = EthscriptionDataProof({
Expand Down
2 changes: 1 addition & 1 deletion contracts/src/L2/L1Block.sol
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ contract L1Block {
}

function _flushProofsIfLive() internal {
if (block.timestamp >= 1760630077) {
if (block.timestamp >= Constants.historicalBackfillApproxDoneAt) {
// Each proof includes its own block number and timestamp from when it was queued
IEthscriptionsProver(Predeploys.ETHSCRIPTIONS_PROVER).flushAllProofs();
}
Expand Down
2 changes: 2 additions & 0 deletions contracts/src/libraries/Constants.sol
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ library Constants {
/// @notice Storage slot for Initializable contract's initialized flag
/// @dev This is the keccak256 of "eip1967.proxy.initialized" - 1
bytes32 internal constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

uint256 internal constant historicalBackfillApproxDoneAt = 1760630077;

Copilot AI Oct 17, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider making historicalBackfillApproxDoneAt public to safely reference it across contracts and tests (e.g., L1Block and EthscriptionsProver tests). Changing to public constant avoids any visibility ambiguities and improves discoverability.

Suggested change
uint256 internal constant historicalBackfillApproxDoneAt = 1760630077;
uint256 public constant historicalBackfillApproxDoneAt = 1760630077;

Copilot uses AI. Check for mistakes.
}
208 changes: 208 additions & 0 deletions contracts/src/libraries/EthscriptionsRendererLib.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {Base64} from "solady/utils/Base64.sol";
import {LibString} from "solady/utils/LibString.sol";
import {Ethscriptions} from "../Ethscriptions.sol";

/// @title EthscriptionsRendererLib
/// @notice Library for rendering Ethscription metadata and media URIs
/// @dev Contains all token URI generation, media handling, and metadata formatting logic
library EthscriptionsRendererLib {
using LibString for *;

/// @notice Build attributes JSON array from ethscription data
/// @param etsc Storage pointer to the ethscription
/// @param txHash The transaction hash of the ethscription
/// @return JSON string of attributes array
function buildAttributes(Ethscriptions.Ethscription storage etsc, bytes32 txHash)
internal
view
returns (string memory)
{
// Build in chunks to avoid stack too deep
string memory part1 = string.concat(
'[{"trait_type":"Transaction Hash","value":"',
uint256(txHash).toHexString(),
'"},{"trait_type":"Ethscription Number","display_type":"number","value":',
etsc.ethscriptionNumber.toString(),
'},{"trait_type":"Creator","value":"',
etsc.creator.toHexString(),
'"},{"trait_type":"Initial Owner","value":"',
etsc.initialOwner.toHexString()
);

string memory part2 = string.concat(
'"},{"trait_type":"Content SHA","value":"',
uint256(etsc.content.contentSha).toHexString(),
'"},{"trait_type":"MIME Type","value":"',
etsc.content.mimetype.escapeJSON(),
'"},{"trait_type":"Media Type","value":"',
etsc.content.mediaType.escapeJSON(),
'"},{"trait_type":"MIME Subtype","value":"',
etsc.content.mimeSubtype.escapeJSON()
);

string memory part3 = string.concat(
'"},{"trait_type":"ESIP-6","value":"',
etsc.content.esip6 ? "true" : "false",
'"},{"trait_type":"L1 Block Number","display_type":"number","value":',
uint256(etsc.l1BlockNumber).toString(),
'},{"trait_type":"L2 Block Number","display_type":"number","value":',
uint256(etsc.l2BlockNumber).toString(),
'},{"trait_type":"Created At","display_type":"date","value":',
etsc.createdAt.toString(),
'}]'
);

return string.concat(part1, part2, part3);
}

/// @notice Generate the media URI for an ethscription
/// @param etsc Storage pointer to the ethscription
/// @param content The content bytes
/// @return mediaType Either "image" or "animation_url"
/// @return mediaUri The data URI for the media
function getMediaUri(Ethscriptions.Ethscription storage etsc, bytes memory content)
internal
view
returns (string memory mediaType, string memory mediaUri)
{
if (etsc.content.mimetype.startsWith("image/")) {
// Image content: wrap in SVG for pixel-perfect rendering
string memory imageDataUri = constructDataURI(etsc.content.mimetype, content);
string memory svg = wrapImageInSVG(imageDataUri);
mediaUri = constructDataURI("image/svg+xml", bytes(svg));
return ("image", mediaUri);
} else {
// Non-image content: use animation_url
if (etsc.content.mimetype.startsWith("video/") ||
etsc.content.mimetype.startsWith("audio/") ||
etsc.content.mimetype.eq("text/html")) {
// Video, audio, and HTML pass through directly as data URIs
mediaUri = constructDataURI(etsc.content.mimetype, content);
} else {
// Everything else (text/plain, application/json, etc.) uses the HTML viewer
mediaUri = createTextViewerDataURI(etsc.content.mimetype, content);
}
return ("animation_url", mediaUri);
}
}

/// @notice Build complete token URI JSON
/// @param etsc Storage pointer to the ethscription
/// @param txHash The transaction hash of the ethscription
/// @param content The content bytes
/// @return The complete base64-encoded data URI
function buildTokenURI(
Ethscriptions.Ethscription storage etsc,
bytes32 txHash,
bytes memory content
) internal view returns (string memory) {
// Get media URI
(string memory mediaType, string memory mediaUri) = getMediaUri(etsc, content);

// Build attributes
string memory attributes = buildAttributes(etsc, txHash);

// Build JSON
string memory json = string.concat(
'{"name":"Ethscription #',
etsc.ethscriptionNumber.toString(),
'","description":"Ethscription #',
etsc.ethscriptionNumber.toString(),
' created by ',
etsc.creator.toHexString(),
'","',
mediaType,
'":"',
mediaUri.escapeJSON(),
'","attributes":',
attributes,
'}'
);

return string.concat(
"data:application/json;base64,",
Base64.encode(bytes(json))
);
}

/// @notice Construct a base64-encoded data URI
/// @param mimetype The MIME type
/// @param content The content bytes
/// @return The complete data URI
function constructDataURI(string memory mimetype, bytes memory content)
internal
pure
returns (string memory)
{
return string.concat(
"data:",
mimetype,
";base64,",
Base64.encode(content)
);
}

/// @notice Wrap an image in SVG for pixel-perfect rendering
/// @param imageDataUri The image data URI to wrap
/// @return The SVG markup
function wrapImageInSVG(string memory imageDataUri)
internal
pure
returns (string memory)
{
// SVG wrapper that enforces pixelated/nearest-neighbor scaling for pixel art
return string.concat(
'<svg width="1200" height="1200" viewBox="0 0 1200 1200" version="1.2" xmlns="http://www.w3.org/2000/svg" style="background-image:url(',
imageDataUri,
');background-repeat:no-repeat;background-size:contain;background-position:center;image-rendering:-webkit-optimize-contrast;image-rendering:-moz-crisp-edges;image-rendering:pixelated;"></svg>'
);
}

/// @notice Create an HTML viewer data URI for text content
/// @param mimetype The MIME type of the content
/// @param content The content bytes
/// @return The HTML viewer data URI
function createTextViewerDataURI(string memory mimetype, bytes memory content)
internal
pure
returns (string memory)
{
// Base64 encode the content for embedding in HTML
string memory encodedContent = Base64.encode(content);

// Generate HTML with embedded content
string memory html = generateTextViewerHTML(encodedContent, mimetype);

// Return as base64-encoded HTML data URI
return constructDataURI("text/html", bytes(html));
}

/// @notice Generate minimal HTML viewer for text content
/// @param encodedPayload Base64-encoded content
/// @param mimetype The MIME type
/// @return The complete HTML string
function generateTextViewerHTML(string memory encodedPayload, string memory mimetype)
internal
pure
returns (string memory)
{
// Ultra-minimal HTML with inline styles optimized for iframe display
return string.concat(
'<!DOCTYPE html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>',
'<style>*{box-sizing:border-box;margin:0;padding:0;border:0}body{padding:6dvw;background:#0b0b0c;color:#f5f5f5;font-family:monospace;display:flex;justify-content:center;align-items:center;min-height:100dvh;overflow:hidden}',
'pre{white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;line-height:1.4;font-size:14px}</style></head>',
'<body><pre id="o"></pre><script>',
'const p="', encodedPayload, '";',
'const m="', mimetype.escapeJSON(), '";',
'function d(b){try{return decodeURIComponent(atob(b).split("").map(c=>"%"+("00"+c.charCodeAt(0).toString(16)).slice(-2)).join(""))}catch{return null}}',
'const r=d(p);let t="";',
'if(r!==null){t=r;try{const j=JSON.parse(r);t=JSON.stringify(j,null,2)}catch{}}',
'else{t="data:"+m+";base64,"+p}',
'document.getElementById("o").textContent=t||"(empty)";',
'</script></body></html>'
);
}
}
105 changes: 105 additions & 0 deletions contracts/src/libraries/SSTORE2ChunkedStorageLib.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {SSTORE2} from "solady/utils/SSTORE2.sol";

/// @title SSTORE2ChunkedStorageLib
/// @notice Generic library for storing and reading large content using chunked SSTORE2
/// @dev Handles content larger than SSTORE2's single-contract limit by splitting into chunks
library SSTORE2ChunkedStorageLib {
/// @dev Maximum chunk size for SSTORE2 (24KB - 1 byte for STOP opcode)
uint256 internal constant CHUNK_SIZE = 24575;

/// @notice Store content in chunked SSTORE2 contracts
/// @param content The content to store
/// @return pointers Array of SSTORE2 contract addresses containing the chunks
function store(bytes calldata content)
internal
returns (address[] memory pointers)
{
uint256 contentLength = content.length;

if (contentLength == 0) {
// Return empty array for empty content
return pointers;
}

// Calculate number of chunks needed
uint256 numChunks = (contentLength + CHUNK_SIZE - 1) / CHUNK_SIZE;
pointers = new address[](numChunks);

// Split content into chunks and store each via SSTORE2
for (uint256 i = 0; i < numChunks; i++) {
uint256 start = i * CHUNK_SIZE;
uint256 end = start + CHUNK_SIZE;
if (end > contentLength) {
end = contentLength;
}

// Use calldata slicing for efficiency
bytes calldata chunk = content[start:end];

// Store chunk and save pointer
pointers[i] = SSTORE2.write(chunk);
}

return pointers;
}

/// @notice Read content from storage array of SSTORE2 pointers
/// @param pointers Storage array of SSTORE2 contract addresses
/// @return content The concatenated content from all chunks
function read(address[] storage pointers)
internal
view
returns (bytes memory content)
{
uint256 length = pointers.length;

if (length == 0) {
return "";
}

if (length == 1) {
return SSTORE2.read(pointers[0]);
}

// Multiple chunks - use assembly for efficient concatenation
assembly {
// Calculate total size needed
let totalSize := 0
let pointersSlot := pointers.slot
let pointersLength := sload(pointersSlot)
let dataOffset := 0x01 // SSTORE2 data starts after STOP opcode

for { let i := 0 } lt(i, pointersLength) { i := add(i, 1) } {
// Storage array elements are at keccak256(slot) + index
mstore(0, pointersSlot)
let elementSlot := add(keccak256(0, 0x20), i)
let pointer := sload(elementSlot)
let codeSize := extcodesize(pointer)
totalSize := add(totalSize, sub(codeSize, dataOffset))
}

// Allocate result buffer
content := mload(0x40)
let contentPtr := add(content, 0x20)

// Copy data from each pointer
let currentOffset := 0
for { let i := 0 } lt(i, pointersLength) { i := add(i, 1) } {
mstore(0, pointersSlot)
let elementSlot := add(keccak256(0, 0x20), i)
let pointer := sload(elementSlot)
let codeSize := extcodesize(pointer)
let chunkSize := sub(codeSize, dataOffset)
extcodecopy(pointer, add(contentPtr, currentOffset), dataOffset, chunkSize)
currentOffset := add(currentOffset, chunkSize)
}

// Update length and free memory pointer with proper alignment
mstore(content, totalSize)
mstore(0x40, and(add(add(contentPtr, totalSize), 0x1f), not(0x1f)))
}
}
}
Loading