Verified contractExactMIT
Renderer
Address0xef08decc8f34b1f45e5f74a33eec535653bc39bc
- Balance
0 ETH
- Transactions
1
- 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,335,955
- Creation transaction
- 0x3d72370a1d…70922c892e
19 files
- src/legacy/Renderer.solmain561 B
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/utils/Base64.sol7.72 KB
- lib/solady/src/utils/LibBytes.sol38.18 KB
- lib/solady/src/utils/LibString.sol44.25 KB
- lib/solady/src/utils/SSTORE2.sol12.63 KB
- src/legacy/AssetStore.sol37.15 KB
- src/legacy/LayeredRendererBase.sol7.44 KB
- src/legacy/LibMetadataReader.sol6.64 KB
- src/legacy/RendererBase.sol7.04 KB
- src/legacy/StreamingRendererBase.sol1.59 KB
- src/lib/DynamicBufferLibEx.sol6.65 KB
- src/lib/Errors.sol548 B
- src/lib/LibAssetReader.sol18.36 KB
- src/lib/LibBase64Pair.sol4.48 KB
- src/lib/LibBase64Tables.sol4.83 KB
- src/lib/LibBase64URI.sol5.29 KB
- src/lib/LibBlobHeader.sol7.36 KB
- src/lib/LibRenderStream.sol11.55 KB
src/legacy/Renderer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {LayeredRendererBase} from "./LayeredRendererBase.sol";
/// @notice Raw image renderer; escapes '+' inline without a counting pass.
contract Renderer is LayeredRendererBase {
constructor(address store_, uint8 method_, address conservation_)
LayeredRendererBase(store_, method_, conservation_) {}
function _payloadMode(uint8 flags) internal pure override returns (uint8) {
if ((flags & FLAG_DATA_IS_BASE64) != 0) revert InvalidAssetStorageMode();
return 2;
}
}
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/Base64.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library to encode strings in Base64.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Base64.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Base64.sol)
/// @author Modified from (https://github.com/Brechtpd/base64/blob/main/base64.sol) by Brecht Devos - <[email protected]>.
library Base64 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ENCODING / DECODING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// See: https://datatracker.ietf.org/doc/html/rfc4648
/// @param fileSafe Whether to replace '+' with '-' and '/' with '_'.
/// @param noPadding Whether to strip away the padding.
function encode(bytes memory data, bool fileSafe, bool noPadding)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let dataLength := mload(data)
if dataLength {
// Multiply by 4/3 rounded up.
// The `shl(2, ...)` is equivalent to multiplying by 4.
let encodedLength := shl(2, div(add(dataLength, 2), 3))
// Set `result` to point to the start of the free memory.
result := mload(0x40)
// Store the table into the scratch space.
// Offsetted by -1 byte so that the `mload` will load the character.
// We will rewrite the free memory pointer at `0x40` later with
// the allocated size.
// The magic constant 0x0670 will turn "-_" into "+/".
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, xor("ghijklmnopqrstuvwxyz0123456789-_", mul(iszero(fileSafe), 0x0670)))
// Skip the first slot, which stores the length.
let ptr := add(result, 0x20)
let end := add(ptr, encodedLength)
let dataEnd := add(add(0x20, data), dataLength)
let dataEndValue := mload(dataEnd) // Cache the value at the `dataEnd` slot.
mstore(dataEnd, 0x00) // Zeroize the `dataEnd` slot to clear dirty bits.
// Run over the input, 3 bytes at a time.
for {} 1 {} {
data := add(data, 3) // Advance 3 bytes.
let input := mload(data)
// Write 4 bytes. Optimized for fewer stack operations.
mstore8(0, mload(and(shr(18, input), 0x3F)))
mstore8(1, mload(and(shr(12, input), 0x3F)))
mstore8(2, mload(and(shr(6, input), 0x3F)))
mstore8(3, mload(and(input, 0x3F)))
mstore(ptr, mload(0x00))
ptr := add(ptr, 4) // Advance 4 bytes.
if iszero(lt(ptr, end)) { break }
}
mstore(dataEnd, dataEndValue) // Restore the cached value at `dataEnd`.
mstore(0x40, add(end, 0x20)) // Allocate the memory.
// Equivalent to `o = [0, 2, 1][dataLength % 3]`.
let o := div(2, mod(dataLength, 3))
// Offset `ptr` and pad with '='. We can simply write over the end.
mstore(sub(ptr, o), shl(240, 0x3d3d))
// Set `o` to zero if there is padding.
o := mul(iszero(iszero(noPadding)), o)
mstore(sub(ptr, o), 0) // Zeroize the slot after the string.
mstore(result, sub(encodedLength, o)) // Store the length.
}
}
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// Equivalent to `encode(data, false, false)`.
function encode(bytes memory data) internal pure returns (string memory result) {
result = encode(data, false, false);
}
/// @dev Encodes `data` using the base64 encoding described in RFC 4648.
/// Equivalent to `encode(data, fileSafe, false)`.
function encode(bytes memory data, bool fileSafe)
internal
pure
returns (string memory result)
{
result = encode(data, fileSafe, false);
}
/// @dev Decodes base64 encoded `data`.
///
/// Supports:
/// - RFC 4648 (both standard and file-safe mode).
/// - RFC 3501 (63: ',').
///
/// Does not support:
/// - Line breaks.
///
/// Note: For performance reasons,
/// this function will NOT revert on invalid `data` inputs.
/// Outputs for invalid inputs will simply be undefined behaviour.
/// It is the user's responsibility to ensure that the `data`
/// is a valid base64 encoded string.
function decode(string memory data) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
let dataLength := mload(data)
if dataLength {
let decodedLength := mul(shr(2, dataLength), 3)
for {} 1 {} {
// If padded.
if iszero(and(dataLength, 3)) {
let t := xor(mload(add(data, dataLength)), 0x3d3d)
// forgefmt: disable-next-item
decodedLength := sub(
decodedLength,
add(iszero(byte(30, t)), iszero(byte(31, t)))
)
break
}
// If non-padded.
decodedLength := add(decodedLength, sub(and(dataLength, 3), 1))
break
}
result := mload(0x40)
// Write the length of the bytes.
mstore(result, decodedLength)
// Skip the first slot, which stores the length.
let ptr := add(result, 0x20)
let end := add(ptr, decodedLength)
// Load the table into the scratch space.
// Constants are optimized for smaller bytecode with zero gas overhead.
// `m` also doubles as the mask of the upper 6 bits.
let m := 0xfc000000fc00686c7074787c8084888c9094989ca0a4a8acb0b4b8bcc0c4c8cc
mstore(0x5b, m)
mstore(0x3b, 0x04080c1014181c2024282c3034383c4044484c5054585c6064)
mstore(0x1a, 0xf8fcf800fcd0d4d8dce0e4e8ecf0f4)
for {} 1 {} {
// Read 4 bytes.
data := add(data, 4)
let input := mload(data)
// Write 3 bytes.
// forgefmt: disable-next-item
mstore(ptr, or(
and(m, mload(byte(28, input))),
shr(6, or(
and(m, mload(byte(29, input))),
shr(6, or(
and(m, mload(byte(30, input))),
shr(6, mload(byte(31, input)))
))
))
))
ptr := add(ptr, 3)
if iszero(lt(ptr, end)) { break }
}
mstore(0x40, add(end, 0x20)) // Allocate the memory.
mstore(end, 0) // Zeroize the slot after the bytes.
mstore(0x60, 0) // Restore the zero slot.
}
}
}
}
lib/solady/src/utils/LibBytes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for byte related operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBytes.sol)
library LibBytes {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated bytes storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native bytes storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct BytesStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the bytes.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the bytes storage `$` to `s`.
function set(BytesStorage storage $, bytes memory s) internal {
/// @solidity memory-safe-assembly
assembly {
let n := mload(s)
let packed := or(0xff, shl(8, n))
for { let i := 0 } 1 {} {
if iszero(gt(n, 0xfe)) {
i := 0x1f
packed := or(n, shl(8, mload(add(s, i))))
if iszero(gt(n, i)) { break }
}
let o := add(s, 0x20)
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), mload(add(o, i)))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to `s`.
function setCalldata(BytesStorage storage $, bytes calldata s) internal {
/// @solidity memory-safe-assembly
assembly {
let packed := or(0xff, shl(8, s.length))
for { let i := 0 } 1 {} {
if iszero(gt(s.length, 0xfe)) {
i := 0x1f
packed := or(s.length, shl(8, shr(8, calldataload(s.offset))))
if iszero(gt(s.length, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
sstore(add(p, shr(5, i)), calldataload(add(s.offset, i)))
i := add(i, 0x20)
if iszero(lt(i, s.length)) { break }
}
break
}
sstore($.slot, packed)
}
}
/// @dev Sets the value of the bytes storage `$` to the empty bytes.
function clear(BytesStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty bytes "".
function isEmpty(BytesStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(BytesStorage storage $) internal view returns (uint256 result) {
result = uint256($._spacer);
/// @solidity memory-safe-assembly
assembly {
let n := and(0xff, result)
result := or(mul(shr(8, result), eq(0xff, n)), mul(n, iszero(eq(0xff, n))))
}
}
/// @dev Returns the value stored in `$`.
function get(BytesStorage storage $) internal view returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
let packed := sload($.slot)
let n := shr(8, packed)
for { let i := 0 } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
mstore(o, packed)
n := and(0xff, packed)
i := 0x1f
if iszero(gt(n, i)) { break }
}
mstore(0x00, $.slot)
for { let p := keccak256(0x00, 0x20) } 1 {} {
mstore(add(o, i), sload(add(p, shr(5, i))))
i := add(i, 0x20)
if iszero(lt(i, n)) { break }
}
break
}
mstore(result, n) // Store the length of the memory.
mstore(add(o, n), 0) // Zeroize the slot after the bytes.
mstore(0x40, add(add(o, n), 0x20)) // Allocate memory.
}
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(BytesStorage storage $, uint256 i) internal view returns (uint8 result) {
/// @solidity memory-safe-assembly
assembly {
for { let packed := sload($.slot) } 1 {} {
if iszero(eq(or(packed, 0xff), packed)) {
if iszero(gt(i, 0x1e)) {
result := byte(i, packed)
break
}
if iszero(gt(i, and(0xff, packed))) {
mstore(0x00, $.slot)
let j := sub(i, 0x1f)
result := byte(and(j, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, j))))
}
break
}
if iszero(gt(i, shr(8, packed))) {
mstore(0x00, $.slot)
result := byte(and(i, 0x1f), sload(add(keccak256(0x00, 0x20), shr(5, i))))
}
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTES OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(bytes memory subject, bytes memory needle, bytes memory replacement)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let needleLen := mload(needle)
let replacementLen := mload(replacement)
let d := sub(result, subject) // Memory difference.
let i := add(subject, 0x20) // Subject bytes pointer.
mstore(0x00, add(i, mload(subject))) // End of subject.
if iszero(gt(needleLen, mload(subject))) {
let subjectSearchEnd := add(sub(mload(0x00), needleLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(needleLen, 0x20)) { h := keccak256(add(needle, 0x20), needleLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(needleLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `needleLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, needleLen), h)) {
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(add(i, d), j), mload(add(add(replacement, 0x20), j)))
j := add(j, 0x20)
if iszero(lt(j, replacementLen)) { break }
}
d := sub(add(d, replacementLen), needleLen)
if needleLen {
i := add(i, needleLen)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(add(i, d), t)
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
}
let end := mload(0x00)
let n := add(sub(d, add(result, 0x20)), end)
// Copy the rest of the bytes one word at a time.
for {} lt(i, end) { i := add(i, 0x20) } { mstore(add(i, d), mload(i)) }
let o := add(i, d)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
for { let subjectLen := mload(subject) } 1 {} {
if iszero(mload(needle)) {
result := from
if iszero(gt(from, subjectLen)) { break }
result := subjectLen
break
}
let needleLen := mload(needle)
let subjectStart := add(subject, 0x20)
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLen), needleLen), 1)
let m := shl(3, sub(0x20, and(needleLen, 0x1f)))
let s := mload(add(needle, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLen))) { break }
if iszero(lt(needleLen, 0x20)) {
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0) // Initialize to `NOT_FOUND`.
if gt(mload(subject), from) {
let start := add(subject, 0x20)
let end := add(start, mload(subject))
let m := div(not(0), 255) // `0x0101 ... `.
let h := mul(byte(0, needle), m) // Replicating needle mask.
m := not(shl(7, m)) // `0x7f7f ... `.
for { let i := add(start, from) } 1 {} {
let c := xor(mload(i), h) // Load 32-byte chunk and xor with mask.
c := not(or(or(add(and(c, m), m), c), m)) // Each needle byte will be `0x80`.
if c {
c := and(not(shr(shl(3, sub(end, i)), not(0))), c) // Truncate bytes past the end.
if c {
let r := shl(7, lt(0x8421084210842108cc6318c6db6d54be, c)) // Save bytecode.
r := or(shl(6, lt(0xffffffffffffffff, shr(r, c))), r)
// forgefmt: disable-next-item
result := add(sub(i, start), shr(3, xor(byte(and(0x1f, shr(byte(24,
mul(0x02040810204081, shr(r, c))), 0x8421084210842108cc6318c6db6d54be)),
0xc0c8c8d0c8e8d0d8c8e8e0e8d0d8e0f0c8d0e8d0e0e0d8f0d0d0e0d8f8f8f8f8), r)))
break
}
}
i := add(i, 0x20)
if iszero(lt(i, end)) { break }
}
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right. Optimized for byte needles.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOfByte(bytes memory subject, bytes1 needle)
internal
pure
returns (uint256 result)
{
return indexOfByte(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(bytes memory subject, bytes memory needle) internal pure returns (uint256) {
return indexOf(subject, needle, 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let needleLen := mload(needle)
if gt(needleLen, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), needleLen)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(needle, 0x20), needleLen) } 1 {} {
if eq(keccak256(subject, needleLen), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256)
{
return lastIndexOf(subject, needle, type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(bytes memory subject, bytes memory needle) internal pure returns (bool) {
return indexOf(subject, needle) != NOT_FOUND;
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
// Just using keccak256 directly is actually cheaper.
let t := eq(keccak256(add(subject, 0x20), n), keccak256(add(needle, 0x20), n))
result := lt(gt(n, mload(subject)), t)
}
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(bytes memory subject, bytes memory needle)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(needle)
let notInRange := gt(n, mload(subject))
// `subject + 0x20 + max(subject.length - needle.length, 0)`.
let t := add(add(subject, 0x20), mul(iszero(notInRange), sub(mload(subject), n)))
// Just using keccak256 directly is actually cheaper.
result := gt(eq(keccak256(t, n), keccak256(add(needle, 0x20), n)), notInRange)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(bytes memory subject, uint256 times)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(or(iszero(times), iszero(l))) {
result := mload(0x40)
subject := add(subject, 0x20)
let o := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let j := 0 } 1 {} {
mstore(add(o, j), mload(add(subject, j)))
j := add(j, 0x20)
if iszero(lt(j, l)) { break }
}
o := add(o, l)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(bytes memory subject, uint256 start, uint256 end)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
let l := mload(subject) // Subject length.
if iszero(gt(l, end)) { end := l }
if iszero(gt(l, start)) { start := l }
if lt(start, end) {
result := mload(0x40)
let n := sub(end, start)
let i := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let j := and(add(n, 0x1f), w) } 1 {} {
mstore(add(result, j), mload(add(i, j)))
j := add(j, w) // `sub(j, 0x20)`.
if iszero(j) { break }
}
let o := add(add(result, 0x20), n)
mstore(o, 0) // Zeroize the slot after the bytes.
mstore(0x40, add(o, 0x20)) // Allocate memory.
mstore(result, n) // Store the length.
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset.
function slice(bytes memory subject, uint256 start)
internal
pure
returns (bytes memory result)
{
result = slice(subject, start, type(uint256).max);
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start, uint256 end)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
end := xor(end, mul(xor(end, subject.length), lt(subject.length, end)))
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, end), sub(end, start))
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the bytes.
/// `start` is a byte offset. Faster than Solidity's native slicing.
function sliceCalldata(bytes calldata subject, uint256 start)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
start := xor(start, mul(xor(start, subject.length), lt(subject.length, start)))
result.offset := add(subject.offset, start)
result.length := mul(lt(start, subject.length), sub(subject.length, start))
}
}
/// @dev Reduces the size of `subject` to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncate(bytes memory subject, uint256 n)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := subject
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Returns a copy of `subject`, with the length reduced to `n`.
/// If `n` is greater than the size of `subject`, this will be a no-op.
function truncatedCalldata(bytes calldata subject, uint256 n)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
result.offset := subject.offset
result.length := xor(n, mul(xor(n, subject.length), lt(subject.length, n)))
}
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(bytes memory subject, bytes memory needle)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLen := mload(needle)
if iszero(gt(searchLen, mload(subject))) {
result := mload(0x40)
let i := add(subject, 0x20)
let o := add(result, 0x20)
let subjectSearchEnd := add(sub(add(i, mload(subject)), searchLen), 1)
let h := 0 // The hash of `needle`.
if iszero(lt(searchLen, 0x20)) { h := keccak256(add(needle, 0x20), searchLen) }
let s := mload(add(needle, 0x20))
for { let m := shl(3, sub(0x20, and(searchLen, 0x1f))) } 1 {} {
let t := mload(i)
// Whether the first `searchLen % 32` bytes of `subject` and `needle` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(i, searchLen), h)) {
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
mstore(o, sub(i, add(subject, 0x20))) // Append to `result`.
o := add(o, 0x20)
i := add(i, searchLen) // Advance `i` by `searchLen`.
if searchLen {
if iszero(lt(i, subjectSearchEnd)) { break }
continue
}
}
i := add(i, 1)
if iszero(lt(i, subjectSearchEnd)) { break }
}
mstore(result, shr(5, sub(o, add(result, 0x20)))) // Store the length of `result`.
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(o, 0x20))
}
}
}
/// @dev Returns an arrays of bytess based on the `delimiter` inside of the `subject` bytes.
function split(bytes memory subject, bytes memory delimiter)
internal
pure
returns (bytes[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
for { let prevIndex := 0 } 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let l := sub(index, prevIndex)
mstore(element, l) // Store the length of the element.
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(l, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(add(element, 0x20), l), 0) // Zeroize the slot after the bytes.
// Allocate memory for the length and the bytes, rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(l, 0x3f), w)))
mstore(indexPtr, element) // Store the `element` into the array.
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated bytes of `a` and `b`.
/// Cheaper than `bytes.concat()` and does not de-align the free memory pointer.
function concat(bytes memory a, bytes memory b) internal pure returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let w := not(0x1f)
let aLen := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(aLen, 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLen := mload(b)
let output := add(result, aLen)
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLen, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLen := add(aLen, bLen)
let last := add(add(result, 0x20), totalLen)
mstore(last, 0) // Zeroize the slot after the bytes.
mstore(result, totalLen) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(bytes memory a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small bytes.
function eqs(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(bytes memory a, bytes memory b) internal pure returns (int256 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
let bLen := mload(b)
let n := and(xor(aLen, mul(xor(aLen, bLen), lt(bLen, aLen))), not(0x1f))
if n {
for { let i := 0x20 } 1 {} {
let x := mload(add(a, i))
let y := mload(add(b, i))
if iszero(or(xor(x, y), eq(i, n))) {
i := add(i, 0x20)
continue
}
result := sub(gt(x, y), lt(x, y))
break
}
}
// forgefmt: disable-next-item
if iszero(result) {
let l := 0x201f1e1d1c1b1a191817161514131211100f0e0d0c0b0a090807060504030201
let x := and(mload(add(add(a, 0x20), n)), shl(shl(3, byte(sub(aLen, n), l)), not(0)))
let y := and(mload(add(add(b, 0x20), n)), shl(shl(3, byte(sub(bLen, n), l)), not(0)))
result := sub(gt(x, y), lt(x, y))
if iszero(result) { result := sub(gt(aLen, bLen), lt(aLen, bLen)) }
}
}
}
/// @dev Directly returns `a` without copying.
function directReturn(bytes memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the bytes does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the bytes is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the bytes.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
/// @dev Directly returns `a` with minimal copying.
function directReturn(bytes[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a) // `a.length`.
let o := add(a, 0x20) // Start of elements in `a`.
let u := a // Highest memory slot.
let w := not(0x1f)
for { let i := 0 } iszero(eq(i, n)) { i := add(i, 1) } {
let c := add(o, shl(5, i)) // Location of pointer to `a[i]`.
let s := mload(c) // `a[i]`.
let l := mload(s) // `a[i].length`.
let r := and(l, 0x1f) // `a[i].length % 32`.
let z := add(0x20, and(l, w)) // Offset of last word in `a[i]` from `s`.
// If `s` comes before `o`, or `s` is not zero right padded.
if iszero(lt(lt(s, o), or(iszero(r), iszero(shl(shl(3, r), mload(add(s, z))))))) {
let m := mload(0x40)
mstore(m, l) // Copy `a[i].length`.
for {} 1 {} {
mstore(add(m, z), mload(add(s, z))) // Copy `a[i]`, backwards.
z := add(z, w) // `sub(z, 0x20)`.
if iszero(z) { break }
}
let e := add(add(m, 0x20), l)
mstore(e, 0) // Zeroize the slot after the copied bytes.
mstore(0x40, add(e, 0x20)) // Allocate memory.
s := m
}
mstore(c, sub(s, o)) // Convert to calldata offset.
let t := add(l, add(s, 0x20))
if iszero(lt(t, u)) { u := t }
}
let retStart := add(a, w) // Assumes `a` doesn't start from scratch space.
mstore(retStart, 0x20) // Store the return offset.
return(retStart, add(0x40, sub(u, retStart))) // End the transaction.
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function load(bytes memory a, uint256 offset) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), offset))
}
}
/// @dev Returns the word at `offset`, without any bounds checks.
function loadCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
result := calldataload(add(a.offset, offset))
}
}
/// @dev Returns a slice representing a static struct in the calldata. Performs bounds checks.
function staticStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
result.offset := add(a.offset, offset)
result.length := sub(a.length, offset)
if or(shr(64, or(l, a.offset)), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns a slice representing a dynamic struct in the calldata. Performs bounds checks.
function dynamicStructInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(a.offset, s)
result.length := sub(a.length, s)
if or(shr(64, or(s, or(l, a.offset))), gt(offset, l)) { revert(l, 0x00) }
}
}
/// @dev Returns bytes in calldata. Performs bounds checks.
function bytesInCalldata(bytes calldata a, uint256 offset)
internal
pure
returns (bytes calldata result)
{
/// @solidity memory-safe-assembly
assembly {
let l := sub(a.length, 0x20)
let s := calldataload(add(a.offset, offset)) // Relative offset of `result` from `a.offset`.
result.offset := add(add(a.offset, s), 0x20)
result.length := calldataload(add(a.offset, s))
// forgefmt: disable-next-item
if or(shr(64, or(result.length, or(s, or(l, a.offset)))),
or(gt(add(s, result.length), l), gt(offset, l))) { revert(l, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
if or(
or(lt(x.offset, a.offset), gt(add(x.offset, x.length), add(a.length, a.offset))),
shr(64, or(x.length, x.offset))
) { revert(0x00, 0x00) }
}
}
/// @dev Checks if `x` is in `a`. Assumes `a` has been checked.
function checkInCalldata(bytes[] calldata x, bytes calldata a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let e := sub(add(a.length, a.offset), 0x20)
if or(lt(x.offset, a.offset), shr(64, x.offset)) { revert(0x00, 0x00) }
for { let i := 0 } iszero(eq(x.length, i)) { i := add(i, 1) } {
let o := calldataload(add(x.offset, shl(5, i)))
let t := add(o, x.offset)
let l := calldataload(t)
if or(shr(64, or(l, o)), gt(add(t, l), e)) { revert(0x00, 0x00) }
}
}
}
/// @dev Returns empty calldata bytes. For silencing the compiler.
function emptyCalldata() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.length := 0
}
}
/// @dev Returns the most significant 20 bytes as an address.
function msbToAddress(bytes32 x) internal pure returns (address) {
return address(bytes20(x));
}
/// @dev Returns the least significant 20 bytes as an address.
function lsbToAddress(bytes32 x) internal pure returns (address) {
return address(uint160(uint256(x)));
}
}
lib/solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {LibBytes} from "./LibBytes.sol";
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
///
/// @dev Note:
/// For performance and bytecode compactness, most of the string operations are restricted to
/// byte strings (7-bit ASCII), except where otherwise specified.
/// Usage of byte string operations on charsets with runes spanning two or more bytes
/// can lead to undefined behavior.
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Goated string storage struct that totally MOGs, no cap, fr.
/// Uses less gas and bytecode than Solidity's native string storage. It's meta af.
/// Packs length with the first 31 bytes if <255 bytes, so it’s mad tight.
struct StringStorage {
bytes32 _spacer;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The length of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/// @dev The length of the string is more than 32 bytes.
error TooBigForSmallString();
/// @dev The input string must be a 7-bit ASCII.
error StringNot7BitASCII();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant ALPHANUMERIC_7_BIT_ASCII = 0x7fffffe07fffffe03ff000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant LETTERS_7_BIT_ASCII = 0x7fffffe07fffffe0000000000000000;
/// @dev Lookup for 'abcdefghijklmnopqrstuvwxyz'.
uint128 internal constant LOWERCASE_7_BIT_ASCII = 0x7fffffe000000000000000000000000;
/// @dev Lookup for 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
uint128 internal constant UPPERCASE_7_BIT_ASCII = 0x7fffffe0000000000000000;
/// @dev Lookup for '0123456789'.
uint128 internal constant DIGITS_7_BIT_ASCII = 0x3ff000000000000;
/// @dev Lookup for '0123456789abcdefABCDEF'.
uint128 internal constant HEXDIGITS_7_BIT_ASCII = 0x7e0000007e03ff000000000000;
/// @dev Lookup for '01234567'.
uint128 internal constant OCTDIGITS_7_BIT_ASCII = 0xff000000000000;
/// @dev Lookup for '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'.
uint128 internal constant PRINTABLE_7_BIT_ASCII = 0x7fffffffffffffffffffffff00003e00;
/// @dev Lookup for '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.
uint128 internal constant PUNCTUATION_7_BIT_ASCII = 0x78000001f8000001fc00fffe00000000;
/// @dev Lookup for ' \t\n\r\x0b\x0c'.
uint128 internal constant WHITESPACE_7_BIT_ASCII = 0x100003e00;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRING STORAGE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sets the value of the string storage `$` to `s`.
function set(StringStorage storage $, string memory s) internal {
LibBytes.set(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to `s`.
function setCalldata(StringStorage storage $, string calldata s) internal {
LibBytes.setCalldata(bytesStorage($), bytes(s));
}
/// @dev Sets the value of the string storage `$` to the empty string.
function clear(StringStorage storage $) internal {
delete $._spacer;
}
/// @dev Returns whether the value stored is `$` is the empty string "".
function isEmpty(StringStorage storage $) internal view returns (bool) {
return uint256($._spacer) & 0xff == uint256(0);
}
/// @dev Returns the length of the value stored in `$`.
function length(StringStorage storage $) internal view returns (uint256) {
return LibBytes.length(bytesStorage($));
}
/// @dev Returns the value stored in `$`.
function get(StringStorage storage $) internal view returns (string memory) {
return string(LibBytes.get(bytesStorage($)));
}
/// @dev Returns the uint8 at index `i`. If out-of-bounds, returns 0.
function uint8At(StringStorage storage $, uint256 i) internal view returns (uint8) {
return LibBytes.uint8At(bytesStorage($), i);
}
/// @dev Helper to cast `$` to a `BytesStorage`.
function bytesStorage(StringStorage storage $)
internal
pure
returns (LibBytes.BytesStorage storage casted)
{
/// @solidity memory-safe-assembly
assembly {
casted.slot := $.slot
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end of the memory to calculate the length later.
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 1)`.
// Store the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(result, add(48, mod(temp, 10)))
temp := div(temp, 10) // Keep dividing `temp` until zero.
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20) // Move the pointer 32 bytes back to make room for the length.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory result) {
if (value >= 0) return toString(uint256(value));
unchecked {
result = toString(~uint256(value) + 1);
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let n := mload(result) // Load the string length.
mstore(result, 0x2d) // Store the '-' character.
result := sub(result, 1) // Move back the string pointer by a byte.
mstore(result, add(n, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2 + 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value, byteCount);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `byteCount` bytes.
/// The output is not prefixed with "0x" and is encoded using 2 hexadecimal digits per byte,
/// giving a total length of `byteCount * 2` bytes.
/// Reverts if `byteCount` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 byteCount)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `byteCount * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
result := add(mload(0x40), and(add(shl(1, byteCount), 0x42), not(0x1f)))
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(result, add(byteCount, byteCount))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(result, start)) { break }
}
if temp {
mstore(0x00, 0x2194895a) // `HexLengthInsufficient()`.
revert(0x1c, 0x04)
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x".
/// The output excludes leading "0" from the `toHexString` output.
/// `0x00: "0x0", 0x01: "0x1", 0x12: "0x12", 0x123: "0x123"`.
function toMinimalHexString(uint256 value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := add(mload(result), 2) // Compute the length.
mstore(add(result, o), 0x3078) // Store the "0x" prefix, accounting for leading zero.
result := sub(add(result, o), 2) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output excludes leading "0" from the `toHexStringNoPrefix` output.
/// `0x00: "0", 0x01: "1", 0x12: "12", 0x123: "123"`.
function toMinimalHexStringNoPrefix(uint256 value)
internal
pure
returns (string memory result)
{
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let o := eq(byte(0, mload(add(result, 0x20))), 0x30) // Whether leading zero is present.
let n := mload(result) // Get the length.
result := add(result, o) // Move the pointer, accounting for leading zero.
mstore(result, sub(n, o)) // Store the length, accounting for leading zero.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
result := add(mload(0x40), 0x80)
mstore(0x40, add(result, 0x20)) // Allocate memory.
mstore(result, 0) // Zeroize the slot after the string.
let end := result // Cache the end to calculate the length later.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
result := add(result, w) // `sub(result, 2)`.
mstore8(add(result, 1), mload(and(temp, 15)))
mstore8(result, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
let n := sub(end, result)
result := sub(result, 0x20)
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory result) {
result = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(result, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory result) {
result = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Allocate memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(result, 0x80))
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
result := add(result, 2)
mstore(result, 40) // Store the length.
let o := add(result, 0x20)
mstore(add(o, 40), 0) // Zeroize the slot after the string.
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory result) {
result = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let n := add(mload(result), 2) // Compute the length.
mstore(result, 0x3078) // Store the "0x" prefix.
result := sub(result, 2) // Move the pointer.
mstore(result, n) // Store the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
let n := mload(raw)
result := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(result, add(n, n)) // Store the length of the output.
mstore(0x0f, 0x30313233343536373839616263646566) // Store the "0123456789abcdef" lookup.
let o := add(result, 0x20)
let end := add(raw, n)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
let mask := shl(7, div(not(0), 255))
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string,
/// AND all characters are in the `allowed` lookup.
/// Note: If `s` is empty, returns true regardless of `allowed`.
function is7BitASCII(string memory s, uint128 allowed) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if mload(s) {
let allowed_ := shr(128, shl(128, allowed))
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := and(result, shr(byte(0, mload(o)), allowed_))
o := add(o, 1)
if iszero(and(result, lt(o, end))) { break }
}
}
}
}
/// @dev Converts the bytes in the 7-bit ASCII string `s` to
/// an allowed lookup for use in `is7BitASCII(s, allowed)`.
/// To save runtime gas, you can cache the result in an immutable variable.
function to7BitASCIIAllowedLookup(string memory s) internal pure returns (uint128 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
let o := add(s, 0x20)
for { let end := add(o, mload(s)) } 1 {} {
result := or(result, shl(byte(0, mload(o)), 1))
o := add(o, 1)
if iszero(lt(o, end)) { break }
}
if shr(128, result) {
mstore(0x00, 0xc9807e0d) // `StringNot7BitASCII()`.
revert(0x1c, 0x04)
}
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, byte string operations are restricted
// to 7-bit ASCII strings. All offsets are byte offsets, not UTF character offsets.
// Usage of byte string operations on charsets with runes spanning two or more bytes
// can lead to undefined behavior.
/// @dev Returns `subject` all occurrences of `needle` replaced with `replacement`.
function replace(string memory subject, string memory needle, string memory replacement)
internal
pure
returns (string memory)
{
return string(LibBytes.replace(bytes(subject), bytes(needle), bytes(replacement)));
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.indexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function indexOf(string memory subject, string memory needle) internal pure returns (uint256) {
return LibBytes.indexOf(bytes(subject), bytes(needle), 0);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle, uint256 from)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), from);
}
/// @dev Returns the byte index of the first location of `needle` in `subject`,
/// needleing from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `needle` is not found.
function lastIndexOf(string memory subject, string memory needle)
internal
pure
returns (uint256)
{
return LibBytes.lastIndexOf(bytes(subject), bytes(needle), type(uint256).max);
}
/// @dev Returns true if `needle` is found in `subject`, false otherwise.
function contains(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.contains(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` starts with `needle`.
function startsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.startsWith(bytes(subject), bytes(needle));
}
/// @dev Returns whether `subject` ends with `needle`.
function endsWith(string memory subject, string memory needle) internal pure returns (bool) {
return LibBytes.endsWith(bytes(subject), bytes(needle));
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times) internal pure returns (string memory) {
return string(LibBytes.repeat(bytes(subject), times));
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory)
{
return string(LibBytes.slice(bytes(subject), start, end));
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start) internal pure returns (string memory) {
return string(LibBytes.slice(bytes(subject), start, type(uint256).max));
}
/// @dev Returns all the indices of `needle` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory needle)
internal
pure
returns (uint256[] memory)
{
return LibBytes.indicesOf(bytes(subject), bytes(needle));
}
/// @dev Returns an arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
bytes[] memory a = LibBytes.split(bytes(subject), bytes(delimiter));
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(LibBytes.concat(bytes(a), bytes(b)));
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let n := mload(subject)
if n {
result := mload(0x40)
let o := add(result, 0x20)
let d := sub(subject, result)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
for { let end := add(o, n) } 1 {} {
let b := byte(0, mload(add(d, o)))
mstore8(o, xor(and(shr(b, flags), 0x20), b))
o := add(o, 1)
if eq(o, end) { break }
}
mstore(result, n) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
}
/// @dev Returns a string from a small bytes32 string.
/// `s` must be null-terminated, or behavior will be undefined.
function fromSmallString(bytes32 s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let n := 0
for {} byte(n, s) { n := add(n, 1) } {} // Scan for '\0'.
mstore(result, n) // Store the length.
let o := add(result, 0x20)
mstore(o, s) // Store the bytes of the string.
mstore(add(o, n), 0) // Zeroize the slot after the string.
mstore(0x40, add(result, 0x40)) // Allocate memory.
}
}
/// @dev Returns the small string, with all bytes after the first null byte zeroized.
function normalizeSmallString(bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
for {} byte(result, s) { result := add(result, 1) } {} // Scan for '\0'.
mstore(0x00, s)
mstore(result, 0x00)
result := mload(0x00)
}
}
/// @dev Returns the string as a normalized null-terminated small string.
function toSmallString(string memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(s)
if iszero(lt(result, 33)) {
mstore(0x00, 0xec92f9a3) // `TooBigForSmallString()`.
revert(0x1c, 0x04)
}
result := shl(shl(3, sub(32, result)), mload(add(s, result)))
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(s, mload(s))
let o := add(result, 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
for {} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(o, c)
o := add(o, 1)
continue
}
let t := shr(248, mload(c))
mstore(o, mload(and(t, 0x1f)))
o := add(o, shr(5, t))
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
/// If `addDoubleQuotes` is true, the result will be enclosed in double-quotes.
function escapeJSON(string memory s, bool addDoubleQuotes)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let o := add(result, 0x20)
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(o, c)
o := add(o, 1)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), c)
o := add(o, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(o, mload(0x19)) // "\\u00XX".
o := add(o, 6)
continue
}
mstore8(o, 0x5c) // "\\".
mstore8(add(o, 1), mload(add(c, 8)))
o := add(o, 2)
}
if addDoubleQuotes {
mstore8(o, 34)
o := add(1, o)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
result = escapeJSON(s, false);
}
/// @dev Encodes `s` so that it can be safely used in a URI,
/// just like `encodeURIComponent` in JavaScript.
/// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
/// See: https://datatracker.ietf.org/doc/html/rfc2396
/// See: https://datatracker.ietf.org/doc/html/rfc3986
function encodeURIComponent(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
// Store "0123456789ABCDEF" in scratch space.
// Uppercased to be consistent with JavaScript's implementation.
mstore(0x0f, 0x30313233343536373839414243444546)
let o := add(result, 0x20)
for { let end := add(s, mload(s)) } iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// If not in `[0-9A-Z-a-z-_.!~*'()]`.
if iszero(and(1, shr(c, 0x47fffffe87fffffe03ff678200000000))) {
mstore8(o, 0x25) // '%'.
mstore8(add(o, 1), mload(and(shr(4, c), 15)))
mstore8(add(o, 2), mload(and(c, 15)))
o := add(o, 3)
continue
}
mstore8(o, c)
o := add(o, 1)
}
mstore(result, sub(o, add(result, 0x20))) // Store the length.
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Returns whether `a` equals `b`, where `b` is a null-terminated small string.
function eqs(string memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// These should be evaluated on compile time, as far as possible.
let m := not(shl(7, div(not(iszero(b)), 255))) // `0x7f7f ...`.
let x := not(or(m, or(b, add(m, and(b, m)))))
let r := shl(7, iszero(iszero(shr(128, x))))
r := or(r, shl(6, iszero(iszero(shr(64, shr(r, x))))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
result := gt(eq(mload(a), add(iszero(x), xor(31, shr(3, r)))),
xor(shr(add(8, r), b), shr(add(8, r), mload(add(a, 0x20)))))
}
}
/// @dev Returns 0 if `a == b`, -1 if `a < b`, +1 if `a > b`.
/// If `a` == b[:a.length]`, and `a.length < b.length`, returns -1.
function cmp(string memory a, string memory b) internal pure returns (int256) {
return LibBytes.cmp(bytes(a), bytes(b));
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behavior is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40) // Grab the free memory pointer.
mstore(0x40, add(result, 0x40)) // Allocate 2 words (1 for the length, 1 for the bytes).
mstore(result, 0) // Zeroize the length slot.
mstore(add(result, 0x1f), packed) // Store the length and bytes.
mstore(add(add(result, 0x20), mload(result)), 0) // Right pad with zeroes.
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLen := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
or( // Load the length and the bytes of `a` and `b`.
shl(shl(3, sub(0x1f, aLen)), mload(add(a, aLen))), mload(sub(add(b, 0x1e), aLen))),
// `totalLen != 0 && totalLen < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLen, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behavior is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
resultA := mload(0x40) // Grab the free memory pointer.
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retUnpaddedSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retUnpaddedSize), 0)
mstore(retStart, 0x20) // Store the return offset.
// End the transaction, returning the string.
return(retStart, and(not(0x1f), add(0x1f, retUnpaddedSize)))
}
}
}
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/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,
SourceRangeMismatch
} from "../lib/Errors.sol";
error InvalidTokenId();
error InvalidMimeType();
error InvalidSize();
error LengthMismatch();
error InvalidReferenceManifest();
error InvalidReferenceHashPatch();
error InvalidArchiveInfoPointer();
error InvalidArchiveJournalPointer();
error UnauthorizedPartnerWriter();
error InvalidPartnerSlot();
error InvalidPartner();
error PartnerSlotTaken();
/**
* @title AssetStore (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;
uint8 public constant PARTNER_SLOTS = 3;
uint256 public constant MAX_ARCHIVE_INFO_BYTES = 2048;
uint256 public constant MAX_ARCHIVE_JOURNAL_BYTES = 24_570;
// ── 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 public constant TABLE_TOKEN_REFERENCE_HASHES = 6;
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 (indexed by TABLE_* constants 1-12) ──
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;
// ── Collection Archive Record ──
// Points to the same compact SSTORE2 JSON registered by TorchPlatform.
// Replacing a correction pointer preserves every prior payload onchain.
address public archiveInfoPointer;
// Optional single-page gzip UTF-8 conservation journal. It is deliberately
// independent from ArchiveInfo so either record can be corrected alone.
address public archiveJournalPointer;
// ── Frozen Reference Image Provenance ──
// These four values pack into one storage slot. The table range remains
// discoverable from tokenIdStart/maxTokenId and SourceInfo for table 6.
uint64 public referenceSourceChainId;
address public referenceOriginalCollection;
uint8 public referenceHashKind; // 1=canonical RGBA visual SHA-256, 2=original-file SHA-256
uint8 public referenceHashVersion;
// Optional aggregate over the current effective Table 6 rows; zero means unpublished.
bytes32 public referenceCollectionHash;
// ── Write-once Preservation Credits ──
address public partnerWriter;
address[3] public onchainPartners;
// ── Events ──
event SourceSet(uint8 indexed tableKind, address ptr, uint32 stride, uint32 count);
event PatchSet(uint8 indexed tableKind, uint256 indexed id, bool active);
event PartnerWriterSet(address indexed oldWriter, address indexed newWriter);
event OnchainPartnerRecorded(uint8 indexed slot, address indexed partner);
event ReferenceManifestSet(
uint64 sourceChainId,
address indexed originalCollection,
uint8 hashKind,
uint8 hashVersion,
bytes32 collectionHash
);
event ArchiveInfoPointerSet(address indexed pointer);
event ArchiveJournalPointerSet(address indexed pointer);
// ═══════════════════════════════════════════════════════════
// CONSTRUCTOR
// ═══════════════════════════════════════════════════════════
constructor(address partnerWriter_) {
_initializeOwner(msg.sender);
partnerWriter = partnerWriter_;
baseName = "On-Chain NFT";
baseDescription = "Fully on-chain composable NFT";
}
/// @notice Update only the automation writer for still-empty Partner slots.
/// @dev This never changes an address already recorded in a slot.
function setPartnerWriter(address newWriter) external onlyOwner {
address oldWriter = partnerWriter;
partnerWriter = newWriter;
emit PartnerWriterSet(oldWriter, newWriter);
}
/// @notice Permanently fill one Onchain Partner slot.
/// @dev A nonzero slot can never be replaced or cleared, including by the owner.
function recordOnchainPartner(uint8 slot, address partner) external {
if (msg.sender != partnerWriter && msg.sender != owner()) revert UnauthorizedPartnerWriter();
if (slot >= PARTNER_SLOTS) revert InvalidPartnerSlot();
if (partner == address(0)) revert InvalidPartner();
if (onchainPartners[slot] != address(0)) revert PartnerSlotTaken();
onchainPartners[slot] = partner;
emit OnchainPartnerRecorded(slot, partner);
}
function getOnchainPartners() external view returns (address[3] memory partners) {
return onchainPartners;
}
// ═══════════════════════════════════════════════════════════
// OWNERSHIP
// ═══════════════════════════════════════════════════════════
// ═══════════════════════════════════════════════════════════
// SOURCE CONFIGURATION
// ═══════════════════════════════════════════════════════════
/// @notice Unified source setter. tableKind: 1-6 visual, 7-12 metadata.
function setSource(uint8 tableKind, address ptr) external onlyOwner notFrozen {
// 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_REFERENCE_HASHES) {
if (src.stride != 32) revert StrideMismatch(32, src.stride);
if (maxTokenId > type(uint32).max || tokenIdStart > type(uint32).max || maxTokenId < tokenIdStart) {
revert InvalidSize();
}
uint32 expectedIdStart = uint32(tokenIdStart);
uint32 expectedCount = uint32(maxTokenId - tokenIdStart + 1);
if (src.idStart != expectedIdStart || src.count != expectedCount) {
revert SourceRangeMismatch(expectedIdStart, expectedCount, src.idStart, src.count);
}
} 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;
if (tableKind == TABLE_TOKEN_REFERENCE_HASHES) {
referenceSourceChainId = 0;
referenceOriginalCollection = address(0);
referenceHashKind = 0;
referenceHashVersion = 0;
referenceCollectionHash = bytes32(0);
}
// 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 (ids.length != data.length) revert LengthMismatch();
bool isReferencePatch = tableKind == TABLE_TOKEN_REFERENCE_HASHES;
if (isReferencePatch && _sources[TABLE_TOKEN_REFERENCE_HASHES].ptr == address(0)) {
revert MissingRequiredSource("token-reference-hashes");
}
bool anySet;
for (uint256 i; i < ids.length;) {
if (isReferencePatch) {
_validateTokenId(ids[i]);
if (data[i].length == 0) {
delete _patches[tableKind][ids[i]];
} else if (data[i].length != 32) {
revert InvalidReferenceHashPatch();
} else {
_patches[tableKind][ids[i]] = data[i];
anySet = true;
}
} else 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;
}
if (isReferencePatch && ids.length != 0) {
referenceCollectionHash = bytes32(0);
}
}
/// @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 Source provenance and aggregate commitment for the effective Table 6 rows.
function setReferenceManifest(
uint64 sourceChainId,
address originalCollection,
uint8 hashKind,
uint8 hashVersion,
bytes32 collectionHash
) external onlyOwner notFrozen {
if (_sources[TABLE_TOKEN_REFERENCE_HASHES].ptr == address(0)) {
revert MissingRequiredSource("token-reference-hashes");
}
if (
sourceChainId == 0 || originalCollection == address(0) || hashKind < 1 || hashKind > 2 || hashVersion != 1
|| collectionHash == bytes32(0)
) {
revert InvalidReferenceManifest();
}
referenceSourceChainId = sourceChainId;
referenceOriginalCollection = originalCollection;
referenceHashKind = hashKind;
referenceHashVersion = hashVersion;
referenceCollectionHash = collectionHash;
emit ReferenceManifestSet(sourceChainId, originalCollection, hashKind, hashVersion, collectionHash);
}
/// @notice Return source provenance and logical table range in one read.
function getReferenceManifest()
external
view
returns (
uint64 sourceChainId,
address originalCollection,
uint32 referenceTokenIdStart,
uint32 referenceTokenCount,
uint8 hashKind,
uint8 hashVersion,
bytes32 collectionHash
)
{
SourceInfo storage src = _sources[TABLE_TOKEN_REFERENCE_HASHES];
sourceChainId = referenceSourceChainId;
originalCollection = referenceOriginalCollection;
referenceTokenIdStart = src.idStart;
referenceTokenCount = src.count;
hashKind = referenceHashKind;
hashVersion = referenceHashVersion;
collectionHash = referenceCollectionHash;
}
/// @notice Return one expected canonical RGBA visual or original-file SHA-256.
function getTokenReferenceHash(uint256 tokenId) external view returns (bytes32 expectedHash) {
_validateTokenId(tokenId);
bytes memory row = _readRow(TABLE_TOKEN_REFERENCE_HASHES, tokenId);
if (row.length != 32) return bytes32(0);
assembly ("memory-safe") {
expectedHash := mload(add(row, 32))
}
}
/// @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;
}
/// @notice Set the collection-level archive provenance record.
/// @dev Corrections replace only the current pointer; every prior SSTORE2
/// payload remains permanently available onchain.
function setArchiveInfoPointer(address pointer) external onlyOwner {
uint256 codeLength = pointer.code.length;
if (pointer == address(0) || codeLength <= 1 || codeLength > MAX_ARCHIVE_INFO_BYTES + 1) {
revert InvalidArchiveInfoPointer();
}
bytes memory info = SSTORE2.read(pointer);
if (info.length < 2 || info[0] != bytes1("{") || info[info.length - 1] != bytes1("}")) {
revert InvalidArchiveInfoPointer();
}
archiveInfoPointer = pointer;
emit ArchiveInfoPointerSet(pointer);
}
/// @notice Return the compact collection archive record stored in SSTORE2.
function archiveInfo() external view returns (string memory) {
address pointer = archiveInfoPointer;
if (pointer == address(0)) return "";
return string(SSTORE2.read(pointer));
}
/// @notice Set the optional collection-level gzip UTF-8 conservation journal.
/// @dev A zero pointer clears the current reference without deleting prior SSTORE2 payloads.
/// Nonzero journals must fit in one SSTORE2 page and begin with the gzip/deflate signature.
function setArchiveJournalPointer(address pointer) external onlyOwner {
if (pointer != address(0)) {
uint256 codeLength = pointer.code.length;
if (codeLength < 4 || codeLength > MAX_ARCHIVE_JOURNAL_BYTES + 1) {
revert InvalidArchiveJournalPointer();
}
bytes memory signature = SSTORE2.read(pointer, 0, 3);
if (signature[0] != 0x1f || signature[1] != 0x8b || signature[2] != 0x08) {
revert InvalidArchiveJournalPointer();
}
}
archiveJournalPointer = pointer;
emit ArchiveJournalPointerSet(pointer);
}
/// @notice Return the collection conservation journal as its original gzip bytes.
function archiveJournal() external view returns (bytes memory) {
address pointer = archiveJournalPointer;
if (pointer == address(0)) return "";
return SSTORE2.read(pointer);
}
// ═══════════════════════════════════════════════════════════
// 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];
bytes memory layerRow = _readRow(TABLE_TOKEN_ASSET_IDS, _assetIds, tokenId);
uint256 maxLayers = _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);
// 1. Name is semantic UTF-8; the Renderer escapes it at the JSON boundary.
// TABLE 10 row = [nameLength:u8][raw name bytes][zero padding].
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));
}
// 2. Description is semantic UTF-8; the Renderer escapes it at the JSON boundary.
// An empty/missing TABLE 11 row falls back to the base description.
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();
}
// Appended so existing read-path storage slots remain unchanged.
bool public frozen;
error ContentFrozen();
event ContentFrozenPermanently();
modifier notFrozen() {
if (frozen) revert ContentFrozen();
_;
}
/// @notice Irreversibly lock artwork; archive records and Partner credits stay editable.
function freeze() external onlyOwner notFrozen {
frozen = true;
emit ContentFrozenPermanently();
}
}
src/legacy/LayeredRendererBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {LibString} from "solady/src/utils/LibString.sol";
import {DynamicBufferLibEx} from "../lib/DynamicBufferLibEx.sol";
import {LibRenderStream} from "../lib/LibRenderStream.sol";
import {StreamingRendererBase} from "./StreamingRendererBase.sol";
/// @notice Shared layered SVG renderer with front scratch and tail output.
abstract contract LayeredRendererBase is StreamingRendererBase {
using LibString for uint256;
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
using LibRenderStream for LibRenderStream.Stream;
uint8 public constant ROUND_SEPARATE_V1 = 0;
uint8 public constant SINGLE_ROUND_V1 = 1;
error InvalidCompositionMethod();
error InvalidAssetStorageMode();
uint8 public immutable compositionMethod;
constructor(address store_, uint8 method_, address conservation_)
StreamingRendererBase(store_, conservation_)
{
if (method_ > SINGLE_ROUND_V1) revert InvalidCompositionMethod();
compositionMethod = method_;
}
function _payloadMode(uint8 flags) internal pure virtual returns (uint8);
function renderImage(uint256 tokenId) external view override returns (string memory) {
(uint16 w, uint16 h,, bytes memory packed) = assetStore.getTokenRenderBundle(tokenId);
LibRenderStream.Stream memory s = LibRenderStream.create(packed, false, true);
_svg(s, w, h, packed, false);
_returnResult(s.output.data);
}
function _tokenURIString(uint256 tokenId) internal view virtual override returns (string memory) {
(uint16 w, uint16 h,, bytes memory packed) = assetStore.getTokenRenderBundle(tokenId);
DynamicBufferLibEx.DynamicBuffer memory head;
_appendMetadataFromBundle(head, tokenId);
head.p(bytes(",\"image\":\"data:image/svg+xml,"));
return _uriFromHead(w, h, packed, head.data);
}
function _uriFromHead(uint16 w, uint16 h, bytes memory packed, bytes memory head)
private view returns (string memory)
{
LibRenderStream.Stream memory s = LibRenderStream.create(packed, true, true);
s.outer = false;
s.literal("data:application/json;base64,", 29);
s.outer = true;
s.write(head);
_svg(s, w, h, packed, true);
s.literal("\"}", 2);
s.finish();
_returnResult(s.output.data);
}
function _mirrorTokenURIString(uint256 tokenId) internal view virtual override returns (string memory) {
return _tokenURIString(tokenId);
}
function _buildTokenJSON(uint256 tokenId)
internal view override returns (DynamicBufferLibEx.DynamicBuffer memory)
{ return _json(tokenId, "", false); }
function _buildTokenJSONWithDescription(uint256 tokenId, string memory description)
internal view override returns (DynamicBufferLibEx.DynamicBuffer memory)
{ return _json(tokenId, description, true); }
function _json(uint256 tokenId, string memory description, bool overridden)
private view returns (DynamicBufferLibEx.DynamicBuffer memory)
{
(uint16 w, uint16 h,, bytes memory packed) = assetStore.getTokenRenderBundle(tokenId);
DynamicBufferLibEx.DynamicBuffer memory head;
if (overridden) _appendMetadataFromBundleWithDescription(head, tokenId, description);
else _appendMetadataFromBundle(head, tokenId);
head.p(bytes(",\"image\":\"data:image/svg+xml,"));
LibRenderStream.Stream memory s = LibRenderStream.create(packed, false, true);
s.write(head.data);
_svg(s, w, h, packed, true);
s.literal("\"}", 2);
s.finish();
return s.output;
}
function _svg(LibRenderStream.Stream memory s, uint16 w, uint16 h, bytes memory packed, bool utf8)
private view
{
s.begin();
_appendSVGStart(s.temp, w, h, utf8);
s.end();
for (uint256 i; i < packed.length; i += 32) {
uint256 word;
assembly ("memory-safe") { word := mload(add(add(packed, 32), i)) }
uint8 flags = uint8(word >> 64);
uint8 mode = _payloadMode(flags);
s.begin();
_appendImageStart(s.temp, uint8(word >> 72), flags, uint8(word >> 56), utf8);
s.end();
s.asset(address(uint160(word >> 96)), flags, uint32(word), mode);
if (utf8) s.literal("'/%3E", 5);
else s.literal("'/>", 3);
}
if (utf8) s.literal("%3C/svg%3E", 10);
else s.literal("</svg>", 6);
s.assertTail();
}
function _appendSVGStart(DynamicBufferLibEx.DynamicBuffer memory buffer, uint16 width, uint16 height, bool utf8)
private
view
{
if (utf8) {
buffer.p(bytes("%3Csvg%20xmlns='http://www.w3.org/2000/svg'"));
buffer.p(_svgCompositionAttribute(true));
buffer.p(bytes("%20viewBox='0%200%20"));
buffer.p(bytes(uint256(width).toString()));
buffer.p(bytes("%20"));
buffer.p(bytes(uint256(height).toString()));
buffer.p(bytes("'%20width='100%25'%20height='100%25'%3E"));
} else {
buffer.p(bytes("<svg xmlns='http://www.w3.org/2000/svg'"));
buffer.p(_svgCompositionAttribute(false));
buffer.p(bytes(" viewBox='0 0 "));
buffer.p(bytes(uint256(width).toString()));
buffer.p(bytes(" "));
buffer.p(bytes(uint256(height).toString()));
buffer.p(bytes("' width='100%' height='100%'>"));
}
}
function _appendImageStart(
DynamicBufferLibEx.DynamicBuffer memory buffer,
uint8 mimeTypeId,
uint8 flags,
uint8 opacity,
bool utf8
) private pure {
buffer.p(
utf8 ? bytes("%3Cimage%20width='100%25'%20height='100%25'") : bytes("<image width='100%' height='100%'")
);
if ((flags & FLAG_LAYER_PIXELATED) != 0) {
buffer.p(utf8 ? bytes("%20style='image-rendering:pixelated'") : bytes(" style='image-rendering:pixelated'"));
}
if (opacity < 255) {
buffer.p(utf8 ? bytes("%20opacity='") : bytes(" opacity='"));
_appendOpacityValue(buffer, opacity);
buffer.p(bytes("'"));
}
buffer.p(utf8 ? bytes("%20href='data:") : bytes(" href='data:"));
buffer.p(_imageMimeBytes(mimeTypeId));
buffer.p(bytes(";base64,"));
}
function _svgCompositionAttribute(bool utf8) private view returns (bytes memory) {
bytes memory value =
compositionMethod == SINGLE_ROUND_V1 ? bytes("single-round-v1") : bytes("round-separate-v1");
return utf8
? abi.encodePacked("%20data-oncave-composition-method='", value, "'")
: abi.encodePacked(" data-oncave-composition-method='", value, "'");
}
function _imageMimeBytes(uint8 id) internal pure override returns (bytes memory) {
if (id == 0) return bytes("image/png");
if (id == 1) return bytes("image/webp");
if (id == 2) return bytes("image/svg+xml");
if (id == 3) return bytes("image/avif");
if (id == 4) return bytes("image/gif");
if (id == 5) return bytes("image/jpeg");
if (id == 6) return bytes("application/octet-stream");
if (id == 7) return bytes("application/x-onchain-rgba");
revert("invalid mimeTypeId");
}
}
src/legacy/LibMetadataReader.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {LibString} from "solady/src/utils/LibString.sol";
import {DynamicBufferLibEx} from "../lib/DynamicBufferLibEx.sol";
import "./AssetStore.sol";
/// @notice Metadata helpers for building JSON (excluding image rendering).
/// @dev All functions are internal → inlined at compile time, zero gas overhead.
library LibMetadataReader {
error InvalidOriginalMetadata();
using LibString for string;
using LibString for uint256;
using LibString for address;
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
// ============================================================
// BUNDLE-BASED FUNCTIONS
// ============================================================
/// @notice Fetch metadata bundle and append partial JSON (no closing brace).
/// @dev Caller appends ,"image":"..." and closing "}" after this.
function appendMetadataFromBundle(
DynamicBufferLibEx.DynamicBuffer memory buffer,
AssetStore assetStore,
uint256 tokenId
) internal view {
// Table 12 is an explicit schema; historical tables 7/8 retain their semantics.
// This retains original numbers, booleans, display_type, order and optional fields.
bytes memory original = assetStore.getRow(12, tokenId);
if (original.length != 0) {
assetStore.requireValidToken(tokenId);
if (original.length < 3 || original[0] != "{" || original[original.length - 1] != "}") {
revert InvalidOriginalMetadata();
}
assembly ("memory-safe") { mstore(original, sub(mload(original), 1)) }
buffer.p(original);
return;
}
(
string memory name,
string memory description,
string memory externalUrl,
string memory animationUrl,
string memory backgroundColor,
string[] memory traitTypes,
string[] memory traitValues,,,
string memory jsonExtra
) = assetStore.getTokenMetadataBundle(tokenId);
appendMetadataFields(
buffer,
name,
description,
externalUrl,
animationUrl,
backgroundColor,
traitTypes,
traitValues,
jsonExtra
);
}
/// @notice Fetch metadata bundle and append partial JSON with a replacement description.
/// @dev Used by Mirror output so it can avoid scanning/copying a completed token JSON blob.
function appendMetadataFromBundleWithDescription(
DynamicBufferLibEx.DynamicBuffer memory buffer,
AssetStore assetStore,
uint256 tokenId,
string memory descriptionOverride
) internal view {
(
string memory name,
string memory projectDescription,
string memory externalUrl,
string memory animationUrl,
string memory backgroundColor,
string[] memory traitTypes,
string[] memory traitValues,,,
string memory jsonExtra
) = assetStore.getTokenMetadataBundle(tokenId);
appendMetadataFields(
buffer,
name,
_joinDescriptions(descriptionOverride, projectDescription),
externalUrl,
animationUrl,
backgroundColor,
traitTypes,
traitValues,
jsonExtra
);
}
/// @notice Append partial metadata JSON from pre-fetched fields (no closing brace).
function appendMetadataFields(
DynamicBufferLibEx.DynamicBuffer memory buffer,
string memory name,
string memory description,
string memory externalUrl,
string memory animationUrl,
string memory backgroundColor,
string[] memory traitTypes,
string[] memory traitValues,
string memory jsonExtra
) internal pure {
buffer.p(bytes('{"name":"'));
buffer.p(bytes(name.escapeJSON()));
buffer.p(bytes('"'));
if (bytes(jsonExtra).length > 0) {
buffer.p(bytes(","));
buffer.p(bytes(jsonExtra));
}
if (bytes(description).length > 0) {
buffer.p(bytes(',"description":"'));
buffer.p(bytes(description.escapeJSON()));
buffer.p(bytes('"'));
}
if (bytes(externalUrl).length > 0) {
buffer.p(bytes(',"external_url":"'));
buffer.p(bytes(externalUrl.escapeJSON()));
buffer.p(bytes('"'));
}
if (bytes(backgroundColor).length > 0) {
buffer.p(bytes(',"background_color":"'));
buffer.p(bytes(backgroundColor.escapeJSON()));
buffer.p(bytes('"'));
}
if (bytes(animationUrl).length > 0) {
buffer.p(bytes(',"animation_url":"'));
buffer.p(bytes(animationUrl.escapeJSON()));
buffer.p(bytes('"'));
}
buffer.p(bytes(',"attributes":'));
_buildAttributesJSON(buffer, traitTypes, traitValues);
}
// ============================================================
// PRIVATE HELPERS
// ============================================================
function _joinDescriptions(string memory first, string memory second) private pure returns (string memory) {
if (bytes(first).length == 0) return second;
if (bytes(second).length == 0) return first;
return string.concat(first, "\n\n", second);
}
/// @dev Build attributes JSON array from dictionary traits only.
function _buildAttributesJSON(
DynamicBufferLibEx.DynamicBuffer memory buffer,
string[] memory traitTypes,
string[] memory traitValues
) private pure {
buffer.p(bytes("["));
bool hasItem = false;
for (uint256 i = 0; i < traitTypes.length; i++) {
hasItem = _appendAttr(buffer, traitTypes[i], traitValues[i], hasItem);
}
buffer.p(bytes("]"));
}
function _appendAttr(
DynamicBufferLibEx.DynamicBuffer memory buffer,
string memory traitType,
string memory value,
bool needsComma
) private pure returns (bool) {
if (needsComma) {
buffer.p(bytes(","));
}
buffer.p(bytes('{"trait_type":"'));
buffer.p(bytes(traitType.escapeJSON()));
buffer.p(bytes('","value":"'));
buffer.p(bytes(value.escapeJSON()));
buffer.p(bytes('"'));
buffer.p(bytes("}"));
return true;
}
}
src/legacy/RendererBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Base64} from "solady/src/utils/Base64.sol";
import {LibString} from "solady/src/utils/LibString.sol";
import {DynamicBufferLibEx} from "../lib/DynamicBufferLibEx.sol";
import "./AssetStore.sol";
import "./LibMetadataReader.sol";
/// @title RendererBase
/// @notice Abstract base for rendering contracts. Shared token and mirror metadata entry points.
/// @dev Subclasses override _buildTokenJSON and renderImage for format-specific rendering.
abstract contract RendererBase {
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
using LibString for address;
using LibString for string;
using LibString for uint256;
error InvalidConservationRenderer();
// ============ State ============
AssetStore public immutable assetStore;
address public immutable conservationRenderer;
// ============ Constructor ============
constructor(address _store, address _conservationRenderer) {
if (_conservationRenderer == address(0)) revert InvalidConservationRenderer();
assetStore = AssetStore(_store);
conservationRenderer = _conservationRenderer;
}
/// @dev Return a bytes payload as a top-level ABI dynamic value without copying
/// it into a second return buffer. We reuse the preceding word as the ABI
/// offset slot because the function returns immediately.
function _returnResult(bytes memory result) internal pure {
assembly ("memory-safe") {
let out := sub(result, 0x20)
mstore(out, 0x20)
return(out, add(0x40, and(add(mload(result), 0x1f), not(0x1f))))
}
}
// ============ Virtual ============
function _buildTokenJSON(uint256 tokenId)
internal
view
virtual
returns (DynamicBufferLibEx.DynamicBuffer memory buffer);
function _buildTokenJSONWithDescription(uint256 tokenId, string memory descriptionOverride)
internal
view
virtual
returns (DynamicBufferLibEx.DynamicBuffer memory buffer);
function renderImage(uint256 tokenId) external view virtual returns (string memory);
// ============ Entry Points ============
/// @notice Get raw JSON bytes for a token (web3:// primary endpoint).
function tokenJSON(uint256 tokenId) external view returns (bytes memory) {
_returnResult(_buildTokenJSON(tokenId).data);
}
/// @notice Get raw Mirror JSON for TorchMirrorNFT (web3:// primary endpoint).
function mirrorTokenJSON(uint256 tokenId) external view returns (bytes memory) {
_returnResult(_buildMirrorTokenJSON(tokenId));
}
/// @notice Get base64-wrapped token URI (ERC-721 compatibility endpoint).
function tokenURI(uint256 tokenId) external view returns (string memory) {
return _tokenURIString(tokenId);
}
/// @notice Base64-wrapped Mirror tokenURI for compatibility callers.
function mirrorTokenURI(uint256 tokenId) external view returns (string memory) {
return _mirrorTokenURIString(tokenId);
}
/// @notice ERC-7572 collection metadata for the station's Mirror NFT.
/// @dev Uses the first valid token as a fully onchain collection image.
function mirrorContractURI() external view returns (string memory) {
string memory collName = assetStore.collectionName();
string memory title = string.concat("Oncave Mirror: ", collName);
string memory description = string.concat(
"Public, wallet-visible Mirrors of the fully onchain archive for ",
collName,
". Each Mirror is non-transferable and follows the current owner of its original NFT. "
"Preserved fully onchain by Oncave."
);
string memory image = string.concat(
"data:image/svg+xml;base64,", Base64.encode(bytes(this.renderImage(assetStore.tokenIdStart())))
);
bytes memory json = abi.encodePacked(
'{"name":"',
title.escapeJSON(),
'","description":"',
description.escapeJSON(),
'","image":"',
image.escapeJSON(),
'"}'
);
return string.concat("data:application/json;base64,", Base64.encode(json));
}
/// @notice Return the canonical ERC-4804 route for this token's self-contained Conservation File.
/// @dev The heavy HTML assembly remains in the shared OncaveConservationRenderer and is not
/// executed by this lightweight discovery getter.
function conservationFileURI(uint256 tokenId) external view returns (string memory) {
return string.concat(
"web3://",
conservationRenderer.toHexString(),
"/file/",
address(this).toHexString(),
"/",
tokenId.toString()
);
}
/// @dev Build the full tokenURI data string. Override in subclasses for streaming optimization.
function _tokenURIString(uint256 tokenId) internal view virtual returns (string memory) {
return string.concat("data:application/json;base64,", Base64.encode(_buildTokenJSON(tokenId).data));
}
/// @dev Build the full Mirror tokenURI data string. Override in subclasses for streaming optimization.
function _mirrorTokenURIString(uint256 tokenId) internal view virtual returns (string memory) {
return string.concat("data:application/json;base64,", Base64.encode(_buildMirrorTokenJSON(tokenId)));
}
/// @notice Get metadata JSON without image (lightweight query).
function renderMetadata(uint256 tokenId) external view returns (string memory) {
DynamicBufferLibEx.DynamicBuffer memory buf;
_appendMetadataFromBundle(buf, tokenId);
buf.p(bytes("}"));
_returnResult(buf.data);
}
function _appendMetadataFromBundle(DynamicBufferLibEx.DynamicBuffer memory buffer, uint256 tokenId) internal view {
LibMetadataReader.appendMetadataFromBundle(buffer, assetStore, tokenId);
}
function _appendMetadataFromBundleWithDescription(
DynamicBufferLibEx.DynamicBuffer memory buffer,
uint256 tokenId,
string memory descriptionOverride
) internal view {
LibMetadataReader.appendMetadataFromBundleWithDescription(buffer, assetStore, tokenId, descriptionOverride);
}
// ============ Mirror metadata ============
function _buildMirrorTokenJSON(uint256 tokenId) internal view returns (bytes memory) {
return _buildTokenJSON(tokenId).data;
}
function _mirrorDescription() internal view virtual returns (string memory) {
string memory collName = assetStore.collectionName();
return string.concat(
"This Oncave Mirror displays the fully onchain archive of the original ",
collName,
" NFT. It is non-transferable, follows the current owner of the original NFT, and cannot be traded separately. "
"Use the original collection token for trading."
);
}
}
src/legacy/StreamingRendererBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {LibString} from "solady/src/utils/LibString.sol";
import {DynamicBufferLibEx} from "../lib/DynamicBufferLibEx.sol";
import "./RendererBase.sol";
/// @notice Shared streaming helpers for Renderer and PixelRenderer.
abstract contract StreamingRendererBase is RendererBase {
using LibString for uint256;
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
uint8 internal constant FLAG_MULTIPART = 0x01;
uint8 internal constant FLAG_SLICED = 0x02;
uint8 internal constant FLAG_DATA_IS_BASE64 = 0x04;
uint8 internal constant FLAG_LAYER_PIXELATED = 0x10; // per-layer: add style='image-rendering:pixelated'
constructor(address _store, address _conservationRenderer) RendererBase(_store, _conservationRenderer) {}
function _imageMimeBytes(uint8 id) internal pure virtual returns (bytes memory);
function _layerByteSize(uint8 flags, uint32 dataParam) internal pure returns (uint256) {
if ((flags & FLAG_SLICED) != 0) {
return uint16(dataParam);
}
return dataParam;
}
function _appendOpacityValue(DynamicBufferLibEx.DynamicBuffer memory buffer, uint8 opacity) internal pure {
if (opacity == 0) {
buffer.p(bytes("0"));
} else {
uint256 percentage = (uint256(opacity) * 1000) / 255;
buffer.p(bytes("0."));
if (percentage < 100) buffer.p(bytes("0"));
if (percentage < 10) buffer.p(bytes("0"));
buffer.p(bytes(percentage.toString()));
}
}
}
src/lib/DynamicBufferLibEx.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice DynamicBufferLib with reservePtr/commit extensions for zero-copy writes
/// @author Based on Solady DynamicBufferLib (vectorized)
/// @dev Extended with reserve/commit pattern for direct EXTCODECOPY into buffer
library DynamicBufferLibEx {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
struct DynamicBuffer {
bytes data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Shorthand for `buffer.data.length`.
function length(DynamicBuffer memory buffer) internal pure returns (uint256) {
return buffer.data.length;
}
/// @dev Appends `data` to `buffer`.
function p(DynamicBuffer memory buffer, bytes memory data) internal pure returns (DynamicBuffer memory result) {
_deallocate(result);
result = buffer;
if (data.length == uint256(0)) return result;
assembly ("memory-safe") {
let w := not(0x1f)
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newBufDataLen := add(mload(data), bufDataLen)
let prime := 1621250193422201
let cap := mload(add(bufData, w))
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
for {} iszero(lt(newBufDataLen, cap)) {} {
let newCap := and(add(cap, add(or(cap, newBufDataLen), 0x20)), w)
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap)))
break
}
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap)))
mstore(buffer, newBufData)
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w)
if iszero(o) { break }
}
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData
break
}
for { let o := and(add(mload(data), 0x20), w) } 1 {} {
mstore(add(add(bufData, bufDataLen), o), mload(add(data, o)))
o := add(o, w)
if iszero(o) { break }
}
mstore(add(add(bufData, 0x20), newBufDataLen), 0)
mstore(bufData, newBufDataLen)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RESERVE/COMMIT EXTENSIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Reserve capacity for `size` additional logical bytes, return write pointer.
/// The allocator keeps one physical guard word after the logical capacity.
/// Together with the strict `newLen < cap` check, this lets streaming
/// writers use a final unaligned `mstore` without reserving 32 fake bytes.
/// @param buffer The buffer to reserve in
/// @param size Number of bytes to reserve
/// @return ptr Pointer where caller can write `size` bytes
function reservePtr(DynamicBuffer memory buffer, uint256 size) internal pure returns (uint256 ptr) {
assembly ("memory-safe") {
let w := not(0x1f)
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newLen := add(bufDataLen, size)
let prime := 1621250193422201
let cap := mload(add(bufData, w))
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand if needed
for {} iszero(lt(newLen, cap)) {} {
let newCap := and(add(cap, add(or(cap, newLen), 0x20)), w)
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap)))
break
}
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap)))
mstore(buffer, newBufData)
// Copy existing data (backwards, word by word)
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w)
if iszero(o) { break }
}
// Copy length field (the loop above doesn't copy offset 0)
mstore(newBufData, bufDataLen)
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData
break
}
// Return write pointer: bufData + 32 (length slot) + current length
ptr := add(add(bufData, 32), bufDataLen)
}
}
/// @dev Commit `size` logical bytes that were written at the pointer from reservePtr.
/// The trailing zero-word write is covered by reservePtr's guard word.
/// @param buffer The buffer to commit to
/// @param size Number of bytes written
function commit(DynamicBuffer memory buffer, uint256 size) internal pure {
assembly ("memory-safe") {
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newLen := add(bufDataLen, size)
mstore(bufData, newLen)
mstore(add(add(bufData, 0x20), newLen), 0) // Zero word after buffer
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _deallocate(DynamicBuffer memory result) private pure {
assembly ("memory-safe") {
mstore(0x40, result)
}
}
}
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/LibAssetReader.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {SSTORE2} from "solady/src/utils/SSTORE2.sol";
import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
/**
* @title LibAssetReader
* @notice Handles SSTORE2 slice and multipart reads for renderers.
*
* @dev dataParam encoding:
* - SLICED: (offset << 16) | length
* - MULTIPART: elementByteSize (total size of all chunks)
* - SINGLE: elementByteSize
* Streaming renderers read single-file payloads using code length and reserve
* one fixed page (MULTIPART_CHUNK_BYTES) of raw scratch, independent of this
* field. Historical records may use 0 (e.g. Quirkies asset #6475).
* PixelRenderer still relies on this field for whole-layer scratch sizing;
* current S1 single-file pixel layers were checked against actual lengths.
* Do not restore dataParam-based scratch sizing in streaming renderers.
*/
library LibAssetReader {
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
uint8 internal constant FLAG_MULTIPART = 0x01;
uint8 internal constant FLAG_SLICED = 0x02;
uint8 internal constant FLAG_DATA_IS_BASE64 = 0x04;
uint8 internal constant FLAG_RESERVED_0X08 = 0x08;
uint8 internal constant FLAG_LAYER_PIXELATED = 0x10; // Renderer: add style='image-rendering:pixelated' to this <image>
/// @notice Fixed chunk size for multipart data (24570 = 27×910 = 3³×910, supports 1/2/3-layer chunk-level base64 streaming without carry)
uint256 internal constant MULTIPART_CHUNK_BYTES = 24570;
error BadFlags();
error InvalidSlice();
error InvalidMultipartIndex();
function read(address pointer, uint8 flags, uint32 dataParam) internal view returns (bytes memory) {
bool isMultipart = (flags & FLAG_MULTIPART) != 0;
bool isSliced = (flags & FLAG_SLICED) != 0;
if (isMultipart && isSliced) revert BadFlags();
// 1. Direct read.
if (!isMultipart && !isSliced) {
return SSTORE2.read(pointer);
}
// 2. Slice read: dataParam = (offset << 16) | length
if (isSliced) {
uint256 offset = uint256(dataParam >> 16);
uint256 length = uint256(uint16(dataParam));
if (length == 0) revert InvalidSlice();
return SSTORE2.read(pointer, offset, offset + length);
}
// 3. Multipart read: dataParam = total byte size (knownLength)
// Uses pure assembly for O(n) performance instead of O(n²) bytes.concat loop.
return _readMultipart(pointer, dataParam);
}
/**
* @dev Pure assembly multipart read for maximum gas efficiency.
* Uses fixed chunk size (24570) to avoid extcodesize calls per chunk.
* @param indexPointer SSTORE2 pointer to the index table (32-byte addresses)
* @param knownLength Total byte size of all chunks combined
*/
function _readMultipart(address indexPointer, uint256 knownLength) private view returns (bytes memory result) {
// Guard: validate index pointer has valid SSTORE2 data
uint256 codeSize = indexPointer.code.length;
if (codeSize < 2) revert InvalidMultipartIndex(); // Need at least STOP byte + 1 address
uint256 indexLen = codeSize - 1;
if (indexLen == 0 || indexLen % 32 != 0) revert InvalidMultipartIndex();
uint256 chunkSize = MULTIPART_CHUNK_BYTES;
assembly ("memory-safe") {
// Allocate result buffer with known length
result := mload(0x40)
mstore(result, knownLength)
let resultData := add(result, 32)
// Update free memory pointer (word-aligned)
mstore(0x40, add(resultData, and(add(knownLength, 31), not(31))))
// Calculate chunk count (32-byte addresses in index)
let count := div(indexLen, 32)
let last := sub(count, 1)
// Fixed chunk size, last chunk = knownLength - (count-1) * chunkSize
let lastLen := sub(knownLength, mul(last, chunkSize))
let offset := 0
// Iterate chunks and EXTCODECOPY directly into result
for { let i := 0 } lt(i, count) { i := add(i, 1) } {
// Read 32-byte entry directly to scratch space
extcodecopy(indexPointer, 0x00, add(1, mul(i, 32)), 32)
let chunkPtr := and(mload(0x00), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// Chunk length: chunkSize for all except last
let chunkLen := chunkSize
if eq(i, last) { chunkLen := lastLen }
// EXTCODECOPY chunk directly into result
extcodecopy(chunkPtr, add(resultData, offset), 1, chunkLen)
offset := add(offset, chunkLen)
}
}
}
/**
* @notice Append asset data directly to buffer (zero-copy for B2 mode)
* @dev Uses reserve/commit pattern to avoid intermediate memory allocation.
* For B2 mode (FLAG_DATA_IS_BASE64), data is already Base64 ASCII.
* @param buffer DynamicBuffer to append to
* @param pointer SSTORE2 pointer
* @param flags Element flags
* @param dataParam Data parameter (size or slice info)
*/
function appendToBuffer(
DynamicBufferLibEx.DynamicBuffer memory buffer,
address pointer,
uint8 flags,
uint32 dataParam
) internal view {
bool isMultipart = (flags & FLAG_MULTIPART) != 0;
bool isSliced = (flags & FLAG_SLICED) != 0;
if (isMultipart && isSliced) revert BadFlags();
if (isSliced) {
// Sliced: dataParam = (offset << 16) | length
uint256 sliceOffset = uint256(dataParam >> 16);
uint256 sliceLength = uint256(uint16(dataParam));
if (sliceLength == 0) revert InvalidSlice();
_appendSliced(buffer, pointer, sliceOffset, sliceLength);
} else if (isMultipart) {
// Multipart: dataParam = total size
_appendMultipart(buffer, pointer, dataParam);
} else {
// Single: read entire blob
_appendSingle(buffer, pointer);
}
}
/// @dev Append single blob directly to buffer
function _appendSingle(DynamicBufferLibEx.DynamicBuffer memory buffer, address pointer) private view {
assembly ("memory-safe") {
let dataLen := sub(extcodesize(pointer), 1)
if gt(dataLen, 0) {
// Get buffer info
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newLen := add(bufDataLen, dataLen)
let prime := 1621250193422201
let w := not(0x1f)
let cap := mload(add(bufData, w))
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand if needed
for {} iszero(lt(newLen, cap)) {} {
let newCap := and(add(cap, add(or(cap, newLen), 0x20)), w)
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap)))
break
}
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap)))
mstore(buffer, newBufData)
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w)
if iszero(o) { break }
}
mstore(newBufData, bufDataLen)
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData
break
}
// Write pointer
let writePtr := add(add(bufData, 32), bufDataLen)
// EXTCODECOPY directly into buffer
extcodecopy(pointer, writePtr, 1, dataLen)
// Update length
mstore(bufData, newLen)
mstore(add(add(bufData, 0x20), newLen), 0)
}
}
}
/// @dev Append sliced data directly to buffer
function _appendSliced(
DynamicBufferLibEx.DynamicBuffer memory buffer,
address pointer,
uint256 sliceOffset,
uint256 sliceLength
) private view {
assembly ("memory-safe") {
// Get buffer info
let bufData := mload(buffer)
let bufDataLen := mload(bufData)
let newLen := add(bufDataLen, sliceLength)
let prime := 1621250193422201
let w := not(0x1f)
let cap := mload(add(bufData, w))
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand if needed
for {} iszero(lt(newLen, cap)) {} {
let newCap := and(add(cap, add(or(cap, newLen), 0x20)), w)
if iszero(or(xor(mload(0x40), add(bufData, add(0x40, cap))), iszero(cap))) {
mstore(add(bufData, w), mul(prime, newCap))
mstore(0x40, add(bufData, add(0x40, newCap)))
break
}
let newBufData := add(mload(0x40), 0x20)
mstore(0x40, add(newBufData, add(0x40, newCap)))
mstore(buffer, newBufData)
for { let o := and(add(bufDataLen, 0x20), w) } 1 {} {
mstore(add(newBufData, o), mload(add(bufData, o)))
o := add(o, w)
if iszero(o) { break }
}
mstore(newBufData, bufDataLen)
mstore(add(newBufData, w), mul(prime, newCap))
bufData := newBufData
break
}
// Write pointer
let writePtr := add(add(bufData, 32), bufDataLen)
// EXTCODECOPY slice directly into buffer (offset + 1 for SSTORE2 prefix)
extcodecopy(pointer, writePtr, add(sliceOffset, 1), sliceLength)
// Update length
mstore(bufData, newLen)
mstore(add(add(bufData, 0x20), newLen), 0)
}
}
/// @dev Append multipart data directly to buffer
/// @notice Uses fixed chunk size (24570) to avoid extcodesize calls per chunk
function _appendMultipart(DynamicBufferLibEx.DynamicBuffer memory buffer, address indexPointer, uint256 totalSize)
private
view
{
// Guard: validate index pointer has valid SSTORE2 data
uint256 codeSize = indexPointer.code.length;
if (codeSize < 2) revert InvalidMultipartIndex();
uint256 indexLen = codeSize - 1;
if (indexLen == 0 || indexLen % 32 != 0) revert InvalidMultipartIndex();
// Reserve space first
uint256 writePtr = buffer.reservePtr(totalSize);
uint256 chunkSize = MULTIPART_CHUNK_BYTES;
assembly ("memory-safe") {
// Calculate chunk count (32-byte addresses in index)
let count := div(indexLen, 32)
let last := sub(count, 1)
// Fixed chunk size, last chunk = totalSize - (count-1) * chunkSize
let lastLen := sub(totalSize, mul(last, chunkSize))
let offset := 0
for { let i := 0 } lt(i, count) { i := add(i, 1) } {
// Read 32-byte entry directly to scratch space
extcodecopy(indexPointer, 0x00, add(1, mul(i, 32)), 32)
let chunkPtr := and(mload(0x00), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
// Chunk length: chunkSize for all except last
let chunkLen := chunkSize
if eq(i, last) { chunkLen := lastLen }
// EXTCODECOPY chunk directly into buffer
extcodecopy(chunkPtr, add(writePtr, offset), 1, chunkLen)
offset := add(offset, chunkLen)
}
}
// Commit written bytes
buffer.commit(totalSize);
}
/// @dev Base64-encode bytes that already live in memory and append directly to buffer.
/// `srcPtr` must point to the first data byte (not a bytes length slot).
function appendBase64Memory(DynamicBufferLibEx.DynamicBuffer memory buffer, uint256 srcPtr, uint256 dataLength)
internal
pure
{
if (dataLength == 0) return;
uint256 encodedLength = ((dataLength + 2) / 3) * 4;
// DynamicBufferLibEx provides a physical guard word after logical capacity,
// so the encoder's final word write must not inflate the logical reservation.
uint256 writePtr = buffer.reservePtr(encodedLength);
assembly ("memory-safe") {
let freePtr := mload(0x40)
// Base64 table at scratch space, shifted by -1 byte for mload(index).
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
let ptr := writePtr
let end := add(ptr, encodedLength)
// Match the existing bytes-encoding loop: the first mload() must end with
// the first 3 data bytes in the low 24 bits, so start 32 bytes behind.
let src := sub(srcPtr, 0x20)
let dataEnd := add(srcPtr, dataLength)
let dataEndValue := mload(dataEnd)
mstore(dataEnd, 0x00) // Clear dirty bits for final partial read.
// Borrow the zero slot (0x60..0x7f) to pack each output word.
// Do not read empty-array lengths or add Solidity memory operations
// while it is borrowed. Both loops share this layout; restore zero
// and the free pointer at the single assembly fallthrough below.
let blockEnd := add(ptr, and(encodedLength, not(31)))
for {} lt(ptr, blockEnd) {} {
{
src := add(src, 3)
let input := mload(src)
mstore8(0x60, mload(and(shr(18, input), 0x3F)))
mstore8(0x61, mload(and(shr(12, input), 0x3F)))
mstore8(0x62, mload(and(shr(6, input), 0x3F)))
mstore8(0x63, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x64, mload(and(shr(18, input), 0x3F)))
mstore8(0x65, mload(and(shr(12, input), 0x3F)))
mstore8(0x66, mload(and(shr(6, input), 0x3F)))
mstore8(0x67, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x68, mload(and(shr(18, input), 0x3F)))
mstore8(0x69, mload(and(shr(12, input), 0x3F)))
mstore8(0x6a, mload(and(shr(6, input), 0x3F)))
mstore8(0x6b, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x6c, mload(and(shr(18, input), 0x3F)))
mstore8(0x6d, mload(and(shr(12, input), 0x3F)))
mstore8(0x6e, mload(and(shr(6, input), 0x3F)))
mstore8(0x6f, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x70, mload(and(shr(18, input), 0x3F)))
mstore8(0x71, mload(and(shr(12, input), 0x3F)))
mstore8(0x72, mload(and(shr(6, input), 0x3F)))
mstore8(0x73, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x74, mload(and(shr(18, input), 0x3F)))
mstore8(0x75, mload(and(shr(12, input), 0x3F)))
mstore8(0x76, mload(and(shr(6, input), 0x3F)))
mstore8(0x77, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x78, mload(and(shr(18, input), 0x3F)))
mstore8(0x79, mload(and(shr(12, input), 0x3F)))
mstore8(0x7a, mload(and(shr(6, input), 0x3F)))
mstore8(0x7b, mload(and(input, 0x3F)))
}
{
src := add(src, 3)
let input := mload(src)
mstore8(0x7c, mload(and(shr(18, input), 0x3F)))
mstore8(0x7d, mload(and(shr(12, input), 0x3F)))
mstore8(0x7e, mload(and(shr(6, input), 0x3F)))
mstore8(0x7f, mload(and(input, 0x3F)))
}
mstore(ptr, mload(0x60))
ptr := add(ptr, 32)
}
for {} lt(ptr, end) {} {
src := add(src, 3)
let input := mload(src)
mstore8(0x60, mload(and(shr(18, input), 0x3F)))
mstore8(0x61, mload(and(shr(12, input), 0x3F)))
mstore8(0x62, mload(and(shr(6, input), 0x3F)))
mstore8(0x63, mload(and(input, 0x3F)))
mstore(ptr, mload(0x60))
ptr := add(ptr, 4)
}
mstore(dataEnd, dataEndValue)
// Equivalent to [0,2,1][dataLength % 3].
let o := div(2, mod(dataLength, 3))
mstore(sub(ptr, o), shl(240, 0x3d3d))
mstore(0x60, 0)
mstore(0x40, freePtr)
}
buffer.commit(encodedLength);
}
/// @dev Base64-encode `data` directly into buffer using reserve/commit.
function appendBase64Bytes(DynamicBufferLibEx.DynamicBuffer memory buffer, bytes memory data) internal pure {
uint256 dataLength = data.length;
if (dataLength == 0) return;
uint256 srcPtr;
assembly ("memory-safe") {
srcPtr := add(data, 0x20)
}
appendBase64Memory(buffer, srcPtr, dataLength);
}
}
src/lib/LibBase64Pair.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {LibBase64Tables} from "./LibBase64Tables.sol";
import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
// Ordinary Base64 with an 8KB, 12-bit pair lookup reused across pages.
// Packing writes backwards across 0x42..0x7f, borrowing the free pointer
// and zero slot. No allocation or Solidity operations before both restore.
library LibBase64Pair {
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
// Generate 64 rows of 64 character pairs. Four word writes per row;
// no external data contract and no 4096-iteration construction loop.
// Return a pointer biased by -30 so mload(table + 2*index) ends in the pair.
function createTable() internal pure returns (uint256 table) {
(table,) = LibBase64Tables.create(true, false);
}
function appendBase64Memory(DynamicBufferLibEx.DynamicBuffer memory buffer, uint256 srcPtr, uint256 dataLength, uint256 table)
internal
pure
{
if (dataLength == 0) return;
uint256 encodedLength = ((dataLength + 2) / 3) * 4;
// DynamicBufferLibEx provides a physical guard word after logical capacity,
// so the encoder's final word write must not inflate the logical reservation.
uint256 writePtr = buffer.reservePtr(encodedLength);
assembly ("memory-safe") {
let freePtr := mload(0x40)
let ptr := writePtr
let end := add(ptr, encodedLength)
// Match the existing bytes-encoding loop: the first mload() must end with
// the first 3 data bytes in the low 24 bits, so start 32 bytes behind.
let src := sub(srcPtr, 0x20)
let dataEnd := add(srcPtr, dataLength)
let dataEndValue := mload(dataEnd)
mstore(dataEnd, 0x00) // Clear dirty bits for final partial read.
// Borrow the zero slot (0x60..0x7f) to pack each output word.
// Do not read empty-array lengths or add Solidity memory operations
// while it is borrowed. Both loops share this layout; restore zero
// and the free pointer at the single assembly fallthrough below.
let blockEnd := add(ptr, and(encodedLength, not(31)))
for {} lt(ptr, blockEnd) {} {
// Read eight groups once; pack pairs backwards into the same scratch word.
let word := mload(add(src, 24))
mstore(0x60, mload(add(table, and(shl(1, word), 0x1ffe))))
mstore(0x5e, mload(add(table, and(shr(11, word), 0x1ffe))))
mstore(0x5c, mload(add(table, and(shr(23, word), 0x1ffe))))
mstore(0x5a, mload(add(table, and(shr(35, word), 0x1ffe))))
mstore(0x58, mload(add(table, and(shr(47, word), 0x1ffe))))
mstore(0x56, mload(add(table, and(shr(59, word), 0x1ffe))))
mstore(0x54, mload(add(table, and(shr(71, word), 0x1ffe))))
mstore(0x52, mload(add(table, and(shr(83, word), 0x1ffe))))
mstore(0x50, mload(add(table, and(shr(95, word), 0x1ffe))))
mstore(0x4e, mload(add(table, and(shr(107, word), 0x1ffe))))
mstore(0x4c, mload(add(table, and(shr(119, word), 0x1ffe))))
mstore(0x4a, mload(add(table, and(shr(131, word), 0x1ffe))))
mstore(0x48, mload(add(table, and(shr(143, word), 0x1ffe))))
mstore(0x46, mload(add(table, and(shr(155, word), 0x1ffe))))
mstore(0x44, mload(add(table, and(shr(167, word), 0x1ffe))))
mstore(0x42, mload(add(table, and(shr(179, word), 0x1ffe))))
src := add(src, 24)
mstore(ptr, mload(0x60))
ptr := add(ptr, 32)
}
for {} lt(ptr, end) {} {
src := add(src, 3)
let input := mload(src)
mstore(0x44, mload(add(table, shl(1, and(input, 0xfff)))))
mstore(0x42, mload(add(table, shl(1, and(shr(12, input), 0xfff)))))
mstore(ptr, mload(0x60))
ptr := add(ptr, 4)
}
mstore(dataEnd, dataEndValue)
// Equivalent to [0,2,1][dataLength % 3].
let o := div(2, mod(dataLength, 3))
mstore(sub(ptr, o), shl(240, 0x3d3d))
mstore(0x60, 0)
mstore(0x40, freePtr)
}
buffer.commit(encodedLength);
}
}
src/lib/LibBase64Tables.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Per-call 12-bit Base64 tables, allocated before scratch and output.
/// @dev Ordinary entries occupy 2 bytes; escaped entries hold up to 6 payload
/// bytes and a length. Fill both tables in the same 64-row loop when needed.
library LibBase64Tables {
function create(bool ordinary, bool escaped) internal pure returns (uint256 table, uint256 escapeTable) {
if (!ordinary && !escaped) return (0, 0);
bytes memory ordinaryData;
bytes memory escapedData;
if (ordinary) ordinaryData = new bytes(8192);
if (escaped) escapedData = new bytes(32768 + 32);
assembly ("memory-safe") {
let freePtr := mload(0x40)
let ordinaryStart := 0
if ordinary { ordinaryStart := add(ordinaryData, 32) table := sub(ordinaryStart, 30) }
if escaped { escapeTable := add(escapedData, 32) }
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
for { let i := 0 } lt(i, 64) { i := add(i, 1) } {
let ch := and(mload(i), 0xff)
if ordinary {
let hi := mul(ch, 0x0100010001000100010001000100010001000100010001000100010001000100)
let row := add(ordinaryStart, shl(7, i))
mstore(add(row, 0), or(hi, 0x004100420043004400450046004700480049004a004b004c004d004e004f0050))
mstore(add(row, 32), or(hi, 0x005100520053005400550056005700580059005a006100620063006400650066))
mstore(add(row, 64), or(hi, 0x006700680069006a006b006c006d006e006f0070007100720073007400750076))
mstore(add(row, 96), or(hi, 0x007700780079007a0030003100320033003400350036003700380039002b002f))
}
if escaped {
let hi := mul(ch, 0x0100000000000000010000000000000001000000000000000100000000000000)
let row := add(escapeTable, shl(9, i))
mstore(add(row, 0), or(hi, 0x0041000000000002004200000000000200430000000000020044000000000002))
mstore(add(row, 32), or(hi, 0x0045000000000002004600000000000200470000000000020048000000000002))
mstore(add(row, 64), or(hi, 0x0049000000000002004a000000000002004b000000000002004c000000000002))
mstore(add(row, 96), or(hi, 0x004d000000000002004e000000000002004f0000000000020050000000000002))
mstore(add(row, 128), or(hi, 0x0051000000000002005200000000000200530000000000020054000000000002))
mstore(add(row, 160), or(hi, 0x0055000000000002005600000000000200570000000000020058000000000002))
mstore(add(row, 192), or(hi, 0x0059000000000002005a00000000000200610000000000020062000000000002))
mstore(add(row, 224), or(hi, 0x0063000000000002006400000000000200650000000000020066000000000002))
mstore(add(row, 256), or(hi, 0x006700000000000200680000000000020069000000000002006a000000000002))
mstore(add(row, 288), or(hi, 0x006b000000000002006c000000000002006d000000000002006e000000000002))
mstore(add(row, 320), or(hi, 0x006f000000000002007000000000000200710000000000020072000000000002))
mstore(add(row, 352), or(hi, 0x0073000000000002007400000000000200750000000000020076000000000002))
mstore(add(row, 384), or(hi, 0x007700000000000200780000000000020079000000000002007a000000000002))
mstore(add(row, 416), or(hi, 0x0030000000000002003100000000000200320000000000020033000000000002))
mstore(add(row, 448), or(hi, 0x0034000000000002003500000000000200360000000000020037000000000002))
mstore(add(row, 480), or(hi, 0x00380000000000020039000000000002002b000000000002002f000000000002))
}
}
if escaped {
// Preserve the three following entries when replacing an eight-byte entry.
function patch8(p, word) {
mstore(p, or(and(mload(p), 0xffffffffffffffffffffffffffffffffffffffffffffffff), word))
}
for { let i := 0 } lt(i, 64) { i := add(i, 1) } {
let ch := and(mload(i), 0xff)
patch8(add(escapeTable, shl(3, add(shl(6, i), 62))),
or(or(shl(248, ch), shl(224, 0x253242)), shl(192, 4)))
patch8(add(escapeTable, shl(3, add(3968, i))),
or(or(shl(232, 0x253242), shl(224, ch)), shl(192, 4)))
}
patch8(add(escapeTable, 32240), or(shl(208, 0x253242253242), shl(192, 6)))
}
mstore(0x40, freePtr)
}
}
}
src/lib/LibBase64URI.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {LibBase64Tables} from "./LibBase64Tables.sol";
import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
// URI-safe 12-bit lookup: six left-aligned payload bytes, one unused byte,
// then length. Per-entry stores may overwrite future entries, with a final guard.
library LibBase64URI {
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
function createTable() internal pure returns (uint256 table) {
(, table) = LibBase64Tables.create(false, true);
}
// The caller reserves 3 * standard Base64 length. Each mstore writes a word,
// but advances only by its table entry's 2/4/6 bytes; the buffer has a guard.
function appendReserved(DynamicBufferLibEx.DynamicBuffer memory buffer,
uint256 srcPtr, uint256 length, uint256 table) internal pure
{
if (length == 0) return;
uint256 ptr = buffer.reservePtr(0);
assembly ("memory-safe") {
let dataEnd := add(srcPtr, length)
let dirty := mload(dataEnd)
mstore(dataEnd, 0)
let src := sub(srcPtr, 32)
let groups := div(add(length, 2), 3)
let blocks := div(groups, 8)
for { let n := 0 } lt(n, blocks) { n := add(n, 1) } {
// The low 24 bytes contain eight groups, consumed high to low.
// j=0 uses shl for the low pair; all offsets are compile-time constants.
let word := mload(add(src, 24))
{
let entry := mload(add(table, and(shr(177, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(165, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(153, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(141, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(129, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(117, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(105, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(93, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(81, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(69, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(57, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(45, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(33, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shr(21, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
{
let entry := mload(add(table, and(shr(9, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, and(shl(3, word), 0x7ff8)))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
src := add(src, 24)
}
for { let n := mod(groups, 8) } n { n := sub(n, 1) } {
src := add(src, 3)
let input := mload(src)
let entry := mload(add(table, shl(3, and(shr(12, input), 0xfff))))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
entry := mload(add(table, shl(3, and(input, 0xfff))))
mstore(ptr, entry)
ptr := add(ptr, byte(7, entry))
}
let padding := div(2, mod(length, 3))
mstore(sub(ptr, padding), shl(240, 0x3d3d))
mstore(dataEnd, dirty)
let data := mload(buffer)
mstore(data, sub(ptr, add(data, 32)))
mstore(ptr, 0)
}
}
}
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;
}
}
}
}
}
src/lib/LibRenderStream.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {DynamicBufferLibEx} from "./DynamicBufferLibEx.sol";
import {LibAssetReader} from "./LibAssetReader.sol";
import {LibBase64Tables} from "./LibBase64Tables.sol";
import {LibBase64Pair} from "./LibBase64Pair.sol";
import {LibBase64URI} from "./LibBase64URI.sol";
/// @notice Reusable front scratch and a growing tail output. No payload pre-scan.
/// @dev All persistent inputs/structs must precede create(). Formatting allocations
/// must run inside begin()/end(). Never restore an old output-end pointer after growth.
library LibRenderStream {
using DynamicBufferLibEx for DynamicBufferLibEx.DynamicBuffer;
uint256 internal constant PAGE = LibAssetReader.MULTIPART_CHUNK_BYTES;
error ScratchOverflow();
error OutputNotLast();
struct Stream {
DynamicBufferLibEx.DynamicBuffer output;
DynamicBufferLibEx.DynamicBuffer temp;
uint256 raw;
uint256 work;
uint256 limit;
uint256 saved;
uint24 carry;
uint8 carryLen;
bool outer;
uint256 table;
uint256 escapeTable;
}
function create(bytes memory packed, bool outer, bool escaped) internal pure returns (Stream memory s) {
bool needsEncoding;
for (uint256 i; i < packed.length; i += 32) {
uint256 word;
assembly ("memory-safe") { word := mload(add(add(packed, 32), i)) }
if ((uint8(word >> 64) & 4) == 0) needsEncoding = true;
}
// Pre-encoded payloads feed the outer stream directly from raw scratch;
// they only need the small formatting workspace, not an encoded page.
// Every streaming read is bounded by PAGE. Single-file reads use code size,
// so scratch capacity must not depend on potentially stale dataParam values.
s = allocate(PAGE, outer && needsEncoding, escaped && needsEncoding, outer || (!escaped && needsEncoding));
s.outer = outer;
}
function allocate(uint256 pageBytes, bool outer, bool escaped) internal pure returns (Stream memory s) {
return allocate(pageBytes, outer, escaped, outer || !escaped);
}
/// @dev Build tables once before scratch/output, according to encoding semantics.
/// Never select by payload size or allocate a table after output exists.
function allocate(uint256 pageBytes, bool outer, bool escaped, bool ordinary) internal pure returns (Stream memory s) {
s.output = DynamicBufferLibEx.DynamicBuffer(new bytes(0));
s.temp = DynamicBufferLibEx.DynamicBuffer(new bytes(0));
s.outer = outer;
(s.table, s.escapeTable) = LibBase64Tables.create(ordinary, escaped);
uint256 start;
assembly ("memory-safe") { start := mload(0x40) }
s.raw = start;
s.work = start + ((pageBytes + 63) & ~uint256(31));
uint256 workBytes = outer ? ((escaped ? 3 : 1) * b64Length(pageBytes) + 159) & ~uint256(31) : 0;
if (workBytes < 2048) workBytes = 2048;
s.limit = s.work + workBytes;
uint256 endPtr = s.limit;
assembly ("memory-safe") { mstore(0x40, endPtr) }
s.output.reservePtr(256);
}
function assertTail(Stream memory s) internal pure {
DynamicBufferLibEx.DynamicBuffer memory out = s.output;
bool valid;
assembly ("memory-safe") {
let data := mload(out)
let cap := div(mload(sub(data, 32)), 1621250193422201)
valid := eq(mload(0x40), add(data, add(64, cap)))
}
if (!valid) revert OutputNotLast();
}
/// @dev Start bounded formatting in the front workspace using s.temp.
function begin(Stream memory s) internal pure {
assertTail(s);
uint256 top;
assembly ("memory-safe") { top := mload(0x40) }
s.saved = top;
uint256 work = s.work;
DynamicBufferLibEx.DynamicBuffer memory temp = s.temp;
assembly ("memory-safe") { mstore(temp, 0x60) mstore(0x40, work) }
}
function end(Stream memory s) internal pure {
restore(s);
write(s, s.temp.data);
}
function restore(Stream memory s) private pure {
uint256 used;
assembly ("memory-safe") { used := mload(0x40) }
if (used > s.limit) revert ScratchOverflow();
uint256 top = s.saved;
assembly ("memory-safe") { mstore(0x40, top) }
}
/// @dev Small constant without a Solidity bytes allocation after output.
function literal(Stream memory s, bytes32 value, uint256 length) internal pure {
uint256 ptr = s.work;
assembly ("memory-safe") { mstore(ptr, value) }
writeMemory(s, ptr, length);
}
function write(Stream memory s, bytes memory data) internal pure {
uint256 ptr;
assembly ("memory-safe") { ptr := add(data, 32) }
writeMemory(s, ptr, data.length);
}
function writeMemory(Stream memory s, uint256 ptr, uint256 length) internal pure {
if (s.outer) streamBase64(s, ptr, length);
else copy(s.output, ptr, length);
}
function copy(DynamicBufferLibEx.DynamicBuffer memory out, uint256 src, uint256 length) internal pure {
if (length == 0) return;
uint256 dst = out.reservePtr(length);
assembly ("memory-safe") {
for { let i := 0 } lt(i, length) { i := add(i, 32) } {
mstore(add(dst, i), mload(add(src, i)))
}
}
out.commit(length);
}
/// @param mode 0=verbatim bytes, 1=ordinary Base64 (archive), 2=URI-safe Base64 (image).
function asset(Stream memory s, address pointer, uint8 flags, uint32 param, uint8 mode) internal view {
bool multipart = (flags & 1) != 0;
bool sliced = (flags & 2) != 0;
if (multipart && sliced) revert LibAssetReader.BadFlags();
uint256 codeSize = pointer.code.length;
uint256 size = multipart ? param : sliced ? uint16(param) : codeSize == 0 ? 0 : codeSize - 1;
if (sliced && size == 0) revert LibAssetReader.InvalidSlice();
uint256 count = (size + PAGE - 1) / PAGE;
if (multipart && (codeSize < 2 || (codeSize - 1) % 32 != 0 || (codeSize - 1) / 32 != count)) {
revert LibAssetReader.InvalidMultipartIndex();
}
for (uint256 i; i < count; ++i) {
uint256 len = i + 1 == count ? size - i * PAGE : PAGE;
address part = pointer;
uint256 offset = 1;
if (multipart) {
assembly ("memory-safe") {
extcodecopy(pointer, 0, add(1, mul(i, 32)), 32)
part := and(mload(0), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else offset += (sliced ? param >> 16 : 0) + i * PAGE;
if (!s.outer && mode == 0) {
uint256 dst = s.output.reservePtr(len);
assembly ("memory-safe") { extcodecopy(part, dst, offset, len) }
s.output.commit(len);
} else {
if (len + 32 > s.work - s.raw) revert ScratchOverflow();
uint256 src = s.raw;
assembly ("memory-safe") { extcodecopy(part, src, offset, len) }
if (mode == 0) writeMemory(s, src, len);
else if (s.outer) {
begin(s);
encode(s.temp, src, len, mode == 2, s.table, s.escapeTable);
end(s);
} else encode(s.output, src, len, mode == 2, s.table, s.escapeTable);
}
assertTail(s);
}
}
function encode(DynamicBufferLibEx.DynamicBuffer memory out, uint256 src, uint256 length, bool escaped, uint256 table, uint256 escapeTable)
internal pure
{
if (escaped) {
out.reservePtr(3 * b64Length(length));
LibBase64URI.appendReserved(out, src, length, escapeTable);
} else LibBase64Pair.appendBase64Memory(out, src, length, table);
}
/// @dev Encode an existing SVG/metadata value; outer streams reuse one page.
function base64(Stream memory s, bytes memory data) internal pure {
uint256 src;
assembly ("memory-safe") { src := add(data, 32) }
if (!s.outer) { LibBase64Pair.appendBase64Memory(s.output, src, data.length, s.table); return; }
for (uint256 i; i < data.length;) {
uint256 n = data.length - i;
if (n > PAGE) n = PAGE;
begin(s);
LibBase64Pair.appendBase64Memory(s.temp, src + i, n, s.table);
end(s);
i += n;
}
}
/// @dev Pixel decoders need one complete compressed layer, reused in front.
function load(Stream memory s, address pointer, uint8 flags, uint32 param)
internal view returns (bytes memory data)
{
assertTail(s);
uint256 top;
uint256 raw = s.raw;
assembly ("memory-safe") { top := mload(0x40) mstore(0x40, raw) }
data = LibAssetReader.read(pointer, flags, param);
uint256 used;
assembly ("memory-safe") { used := mload(0x40) }
if (used > s.work) revert ScratchOverflow();
assembly ("memory-safe") { mstore(0x40, top) }
}
function streamBase64(Stream memory s, uint256 ptr, uint256 length) private pure {
if (length == 0) return;
if (s.carryLen != 0) {
uint256 word;
assembly ("memory-safe") { word := mload(ptr) }
if (s.carryLen == 1 && length == 1) {
s.carry |= uint24(uint8(word >> 248)) << 8;
s.carryLen = 2;
return;
}
uint24 trio = s.carry;
if (s.carryLen == 1) {
trio |= uint24(uint8(word >> 248)) << 8;
trio |= uint24(uint8(word >> 240));
ptr += 2; length -= 2;
} else { trio |= uint24(uint8(word >> 248)); ++ptr; --length; }
appendTrio(s.output, trio, 3);
s.carry = 0; s.carryLen = 0;
}
uint256 aligned = length - length % 3;
if (aligned != 0) {
LibBase64Pair.appendBase64Memory(s.output, ptr, aligned, s.table);
ptr += aligned; length -= aligned;
}
if (length == 0) return;
uint256 tail;
assembly ("memory-safe") { tail := mload(ptr) }
s.carry = uint24(uint8(tail >> 248)) << 16;
if (length == 2) s.carry |= uint24(uint8(tail >> 240)) << 8;
s.carryLen = uint8(length);
}
function finish(Stream memory s) internal pure {
if (s.carryLen != 0) { appendTrio(s.output, s.carry, s.carryLen); s.carry = 0; s.carryLen = 0; }
assertTail(s);
}
function appendTrio(DynamicBufferLibEx.DynamicBuffer memory out, uint24 trio, uint8 length) private pure {
uint256 dst = out.reservePtr(4);
assembly ("memory-safe") {
let fp := mload(0x40)
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
mstore8(dst, mload(and(shr(18, trio), 63)))
mstore8(add(dst, 1), mload(and(shr(12, trio), 63)))
mstore8(add(dst, 2), mload(and(shr(6, trio), 63)))
mstore8(add(dst, 3), mload(and(trio, 63)))
if lt(length, 3) { mstore8(add(dst, 3), 0x3d) }
if lt(length, 2) { mstore8(add(dst, 2), 0x3d) }
mstore(0x40, fp)
}
out.commit(4);
}
function b64Length(uint256 n) internal pure returns (uint256) { return 4 * ((n + 2) / 3); }
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/",
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.