-
Notifications
You must be signed in to change notification settings - Fork 25
Refactor contracts #122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Refactor contracts #122
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>' | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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))) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.