Verified contractExactMIT
LayeredOnchainArtThumbnailV2
Address0x11032ba2d6adc5b23b86ebdaefd68c5586a6516f
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.17
- Same code
Only this contract
Details
- Compiler
- solc 0.8.17+commit.8df45f5f
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,219,412
- Creation transaction
- 0xdc0bbfffa8…50bd8b1655
9 files
- src/layered/v2/LayeredOnchainArtThumbnailV2.solmain6.8 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol2.78 KB
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol12.79 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- lib/solmate/src/utils/SSTORE2.sol5.46 KB
- src/layered/v2/DynamicBuffer.sol11.07 KB
- src/layered/v2/LayeredInterfacesV2.sol1.33 KB
- src/layered/v2/LayeredPayloadV2.sol6.21 KB
- src/layered/v2/LayeredRenderUtilsV2.sol4.17 KB
src/layered/v2/LayeredOnchainArtThumbnailV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {SSTORE2} from "solmate/utils/SSTORE2.sol";
import {DynamicBuffer} from "./DynamicBuffer.sol";
import {ILayeredSourceV2} from "./LayeredInterfacesV2.sol";
import {LayeredPayloadV2} from "./LayeredPayloadV2.sol";
import {LayeredRenderUtilsV2} from "./LayeredRenderUtilsV2.sol";
contract LayeredOnchainArtThumbnailV2 {
using DynamicBuffer for bytes;
bytes private constant MARKER = bytes("<!--{{SVG_LAYERS}}-->");
bytes private constant IMAGE_A = bytes('<image href="');
bytes private constant DATA = bytes("data:");
bytes private constant BASE64 = bytes(";base64,");
bytes private constant IMAGE_B = bytes('" x="0" y="0" width="800" height="800" preserveAspectRatio="xMidYMid meet" data-layer-index="');
bytes private constant IMAGE_C = bytes('" data-kind="');
bytes private constant IMAGE_D = bytes('" data-idx="');
bytes private constant IMAGE_E = bytes('" data-z="');
bytes private constant IMAGE_F = bytes('" data-name="');
bytes private constant IMAGE_G = bytes('"/>');
address public immutable thumbnailPtr;
uint256 public immutable markerOffset;
uint256 public immutable templateLength;
error ZeroAddress();
error EmptyTemplatePointer(address pointer);
error MissingTemplateMarker(string marker);
constructor(address thumbnailPtr_) {
if (thumbnailPtr_ == address(0)) revert ZeroAddress();
if (thumbnailPtr_.code.length <= 1) revert EmptyTemplatePointer(thumbnailPtr_);
bytes memory template = SSTORE2.read(thumbnailPtr_);
uint256 offset = _find(template, MARKER);
if (offset == type(uint256).max) revert MissingTemplateMarker("SVG_LAYERS");
thumbnailPtr = thumbnailPtr_;
markerOffset = offset;
templateLength = template.length;
}
function thumbnailSvg(address nft, uint256 tokenId) external view returns (string memory) {
ILayeredSourceV2 source = ILayeredSourceV2(nft);
(uint256 capacity, uint256 count) = _renderLength(source, tokenId);
bytes memory out = DynamicBuffer.allocate(capacity);
LayeredPayloadV2.appendSSTORE2Range(out, thumbnailPtr, 0, markerOffset);
for (uint256 i; i < count; ++i) {
(
string memory layerName,
string memory traitType,
,
address dataPointer,
string memory mimetype,
uint16 z,
bool visible,
uint8 blinkMode
) = source.layerAt(tokenId, i);
blinkMode;
if (!visible || dataPointer == address(0)) continue;
_appendImage(out, i, layerName, traitType, dataPointer, mimetype, z);
}
uint256 suffixOffset = markerOffset + MARKER.length;
LayeredPayloadV2.appendSSTORE2Range(out, thumbnailPtr, suffixOffset, templateLength - suffixOffset);
assert(out.length == capacity);
return string(out);
}
/// @notice Exact output size without reading PNG payload bytes.
function thumbnailSvgLength(address nft, uint256 tokenId) external view returns (uint256 capacity) {
(capacity,) = _renderLength(ILayeredSourceV2(nft), tokenId);
}
function _renderLength(ILayeredSourceV2 source, uint256 tokenId)
private
view
returns (uint256 capacity, uint256 count)
{
count = source.layerCount(tokenId);
capacity = templateLength - MARKER.length;
// This pass reads only metadata and extcodesize/descriptor headers; no
// PNG bytes are copied into memory.
for (uint256 i; i < count; ++i) {
(
string memory layerName,
string memory traitType,
,
address dataPointer,
string memory mimetype,
uint16 z,
bool visible,
uint8 blinkMode
) = source.layerAt(tokenId, i);
blinkMode;
if (!visible || dataPointer == address(0)) continue;
capacity += _imageLength(i, layerName, traitType, dataPointer, mimetype, z);
}
}
function _imageLength(
uint256 index,
string memory layerName,
string memory traitType,
address dataPointer,
string memory mimetype,
uint16 z
) private view returns (uint256 length) {
LayeredPayloadV2.Info memory payload = LayeredPayloadV2.inspect(dataPointer);
uint256 mimeLength = bytes(mimetype).length == 0 ? 9 : bytes(mimetype).length;
length = IMAGE_A.length + DATA.length + mimeLength + BASE64.length
+ LayeredPayloadV2.encodedLength(payload.length) + IMAGE_B.length
+ LayeredRenderUtilsV2.decimalLength(index) + IMAGE_C.length
+ LayeredRenderUtilsV2.escapedLength(traitType, LayeredRenderUtilsV2.ESCAPE_XML) + IMAGE_D.length
+ LayeredRenderUtilsV2.decimalLength(index) + IMAGE_E.length
+ LayeredRenderUtilsV2.decimalLength(uint256(z)) + IMAGE_F.length
+ LayeredRenderUtilsV2.escapedLength(layerName, LayeredRenderUtilsV2.ESCAPE_XML) + IMAGE_G.length;
}
function _appendImage(
bytes memory out,
uint256 index,
string memory layerName,
string memory traitType,
address dataPointer,
string memory mimetype,
uint16 z
) private view {
out.appendSafe(IMAGE_A);
out.appendSafe(DATA);
out.appendSafe(bytes(bytes(mimetype).length == 0 ? "image/png" : mimetype));
out.appendSafe(BASE64);
LayeredPayloadV2.appendBase64(out, dataPointer);
out.appendSafe(IMAGE_B);
LayeredRenderUtilsV2.appendUint(out, index);
out.appendSafe(IMAGE_C);
LayeredRenderUtilsV2.appendEscaped(out, traitType, LayeredRenderUtilsV2.ESCAPE_XML);
out.appendSafe(IMAGE_D);
LayeredRenderUtilsV2.appendUint(out, index);
out.appendSafe(IMAGE_E);
LayeredRenderUtilsV2.appendUint(out, uint256(z));
out.appendSafe(IMAGE_F);
LayeredRenderUtilsV2.appendEscaped(out, layerName, LayeredRenderUtilsV2.ESCAPE_XML);
out.appendSafe(IMAGE_G);
}
function _find(bytes memory data, bytes memory needle) private pure returns (uint256) {
if (needle.length == 0 || data.length < needle.length) return type(uint256).max;
for (uint256 i; i <= data.length - needle.length; ++i) {
bool equal = true;
for (uint256 j; j < needle.length; ++j) {
if (data[i + j] != needle[j]) {
equal = false;
break;
}
}
if (equal) return i;
}
return type(uint256).max;
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/solmate/src/utils/SSTORE2.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
library SSTORE2 {
uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.
/*//////////////////////////////////////////////////////////////
WRITE LOGIC
//////////////////////////////////////////////////////////////*/
function write(bytes memory data) internal returns (address pointer) {
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex"00", data);
bytes memory creationCode = abi.encodePacked(
//---------------------------------------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//---------------------------------------------------------------------------------------------------------------//
// 0x60 | 0x600B | PUSH1 11 | codeOffset //
// 0x59 | 0x59 | MSIZE | 0 codeOffset //
// 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset //
// 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset //
// 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset //
// 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset //
// 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) //
// 0xf3 | 0xf3 | RETURN | //
//---------------------------------------------------------------------------------------------------------------//
hex"60_0B_59_81_38_03_80_92_59_39_F3", // Returns all code in the contract except for the first 11 (0B in hex) bytes.
runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.
);
/// @solidity memory-safe-assembly
assembly {
// Deploy a new contract with the generated creation code.
// We start 32 bytes into the code to avoid copying the byte length.
pointer := create(0, add(creationCode, 32), mload(creationCode))
}
require(pointer != address(0), "DEPLOYMENT_FAILED");
}
/*//////////////////////////////////////////////////////////////
READ LOGIC
//////////////////////////////////////////////////////////////*/
function read(address pointer) internal view returns (bytes memory) {
return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
}
function read(address pointer, uint256 start) internal view returns (bytes memory) {
start += DATA_OFFSET;
return readBytecode(pointer, start, pointer.code.length - start);
}
function read(
address pointer,
uint256 start,
uint256 end
) internal view returns (bytes memory) {
start += DATA_OFFSET;
end += DATA_OFFSET;
require(pointer.code.length >= end, "OUT_OF_BOUNDS");
return readBytecode(pointer, start, end - start);
}
/*//////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function readBytecode(
address pointer,
uint256 start,
uint256 size
) private view returns (bytes memory data) {
/// @solidity memory-safe-assembly
assembly {
// Get a pointer to some free memory.
data := mload(0x40)
// Update the free memory pointer to prevent overriding our data.
// We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).
// Adding 31 to size and running the result through the logic above ensures
// the memory pointer remains word-aligned, following the Solidity convention.
mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
// Store the size of the data in the first 32 byte chunk of free memory.
mstore(data, size)
// Copy the code into memory right after the 32 bytes we used to store the size.
extcodecopy(pointer, add(data, 32), start, size)
}
}
}
src/layered/v2/DynamicBuffer.sol
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 the ethier authors (github.com/divergencetech/ethier)
//
// Vendored from intartnft/scripty.sol at commit
// 13085e6851e72eb72df93c539afa8cae63c87954:
// contracts/scripty/utils/DynamicBuffer.sol
//
// Local compatibility/safety changes and extensions: allocation is rounded to
// a word so Solidity's free-memory pointer remains aligned; Base64 masks the
// unused bytes in its final partial quantum; checked slice append/encoding is
// supported without temporary allocations; and large callers may reuse a
// bounded 12-bit Base64 pair table. The logical capacity stored by the upstream
// container layout is not rounded, so checked appends still enforce the
// caller-requested bound. The upstream routines, MIT license, copyright and
// attribution are retained.
pragma solidity ^0.8.17;
/// @title DynamicBuffer
/// @author David Huber (@cxkoda) and Simon Fremaux (@dievardump). See also
/// https://raw.githubusercontent.com/dievardump/solidity-dynamic-buffer
/// @notice Preallocates a bounded memory buffer for subsequent appends.
library DynamicBuffer {
uint256 internal constant BASE64_PAIR_TABLE_LENGTH = 8_192;
function allocate(uint256 capacity_) internal pure returns (bytes memory buffer) {
// Checked Solidity arithmetic deliberately precedes assembly.
uint256 rawSize = capacity_ + 0x60;
uint256 allocationSize = (rawSize + 0x1f) & ~uint256(0x1f);
assembly {
let container := mload(0x40)
mstore(0x40, add(container, allocationSize))
// Upstream layout: [container length][buffer length][buffer data].
// The final word of allocation is safety space for word-copy tails.
mstore(container, add(capacity_, 0x40))
buffer := add(container, 0x20)
mstore(buffer, 0)
}
}
function appendUnchecked(bytes memory buffer, bytes memory data) internal pure {
assembly {
let length := mload(data)
for {
data := add(data, 0x20)
let dataEnd := add(data, length)
let copyTo := add(buffer, add(mload(buffer), 0x20))
} lt(data, dataEnd) {
data := add(data, 0x20)
copyTo := add(copyTo, 0x20)
} {
// May copy up to 31 bytes past the logical end. allocate()
// reserves at least one complete safety word for this tail.
mstore(copyTo, mload(data))
}
mstore(buffer, add(mload(buffer), length))
}
}
function appendSafe(bytes memory buffer, bytes memory data) internal pure {
checkOverflow(buffer, data.length);
appendUnchecked(buffer, data);
}
/// @notice Appends a checked slice without allocating a temporary bytes value.
function appendSafeRange(
bytes memory buffer,
bytes memory data,
uint256 offset,
uint256 length
) internal pure {
if (offset > data.length || length > data.length - offset) {
revert("DynamicBuffer: Source range out of bounds.");
}
if (length == 0) return;
checkOverflow(buffer, length);
assembly {
let source := add(add(data, 0x20), offset)
let sourceEnd := add(source, length)
let destination := add(add(buffer, 0x20), mload(buffer))
for {} lt(source, sourceEnd) {
source := add(source, 0x20)
destination := add(destination, 0x20)
} {
// The destination buffer's safety word covers the final
// partial copy. Source bytes past the requested range are not
// observable because the logical destination length is exact.
mstore(destination, mload(source))
}
mstore(buffer, add(mload(buffer), length))
}
}
/// @notice Appends RFC 4648 Base64 directly into the destination buffer.
/// @dev This is the checked upstream routine. It temporarily uses the
/// scratch/free-pointer slots for the lookup table, then restores 0x40.
function appendSafeBase64(
bytes memory buffer,
bytes memory data,
bool fileSafe,
bool noPadding
) internal pure {
appendSafeBase64Range(buffer, data, 0, data.length, fileSafe, noPadding);
}
/// @notice Base64-encodes a checked source slice directly into buffer.
/// @dev The implementation is the same pinned upstream encoder used by
/// appendSafeBase64; only the starting pointer and logical end differ.
function appendSafeBase64Range(
bytes memory buffer,
bytes memory data,
uint256 offset,
uint256 dataLength,
bool fileSafe,
bool noPadding
) internal pure {
if (offset > data.length || dataLength > data.length - offset) {
revert("DynamicBuffer: Source range out of bounds.");
}
if (dataLength == 0) return;
uint256 encodedLength;
uint256 r;
assembly {
encodedLength := shl(2, div(add(dataLength, 2), 3))
r := mod(dataLength, 3)
if noPadding {
encodedLength := sub(encodedLength, add(iszero(iszero(r)), eq(r, 1)))
}
}
checkOverflow(buffer, encodedLength);
assembly {
let nextFree := mload(0x40)
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(
0x3f,
sub(
"ghijklmnopqrstuvwxyz0123456789-_",
mul(iszero(fileSafe), 0x0230)
)
)
let ptr := add(add(buffer, 0x20), mload(buffer))
// The upstream loop uses an intentionally unaligned load whose
// low 24 bits are the next three bytes. Starting at data+offset
// preserves that invariant for a slice.
data := add(data, offset)
let end := add(data, dataLength)
for {} 1 {} {
data := add(data, 3)
let input := mload(data)
// The three encoded input bytes occupy the low 24 bits of this
// deliberately unaligned load. A normal Solidity bytes value
// commonly has zeroed tail padding, but callers may provide a
// bounded scratch allocation whose following bytes are dirty.
// Clear those bytes in the last partial quantum so padding is
// canonical and cannot depend on adjacent memory.
if iszero(lt(data, end)) {
switch r
case 1 { input := and(input, 0xff0000) }
case 2 { input := and(input, 0xffff00) }
}
mstore8(ptr, mload(and(shr(18, input), 0x3f)))
mstore8(add(ptr, 1), mload(and(shr(12, input), 0x3f)))
mstore8(add(ptr, 2), mload(and(shr(6, input), 0x3f)))
mstore8(add(ptr, 3), mload(and(input, 0x3f)))
ptr := add(ptr, 4)
if iszero(lt(data, end)) { break }
}
if iszero(noPadding) {
mstore8(sub(ptr, iszero(iszero(r))), 0x3d)
mstore8(sub(ptr, shl(1, eq(r, 1))), 0x3d)
}
mstore(buffer, add(mload(buffer), encodedLength))
mstore(0x40, nextFree)
}
}
/// @notice Builds a dense table mapping each 12-bit value to two standard
/// Base64 bytes. A caller can reuse it across many large encodes.
function allocateBase64PairTable() internal pure returns (bytes memory table) {
table = new bytes(BASE64_PAIR_TABLE_LENGTH);
assembly {
let nextFree := mload(0x40)
mstore(0x1f, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
mstore(0x3f, "ghijklmnopqrstuvwxyz0123456789+/")
let tableData := add(table, 0x20)
for { let i := 0 } lt(i, 0x1000) { i := add(i, 1) } {
let destination := add(tableData, shl(1, i))
mstore8(destination, mload(shr(6, i)))
mstore8(add(destination, 1), mload(and(i, 0x3f)))
}
mstore(0x40, nextFree)
}
}
/// @notice Standard Base64 using a caller-reused 12-bit pair table.
/// @dev Like appendSafeBase64Range, final partial input bytes are masked.
/// Each output write may touch the destination safety word but the logical
/// length remains exact and is capacity checked before assembly.
function appendSafeBase64RangeWithTable(
bytes memory buffer,
bytes memory data,
uint256 offset,
uint256 dataLength,
bytes memory pairTable,
bool noPadding
) internal pure {
if (offset > data.length || dataLength > data.length - offset) {
revert("DynamicBuffer: Source range out of bounds.");
}
if (pairTable.length != BASE64_PAIR_TABLE_LENGTH) {
revert("DynamicBuffer: Invalid Base64 pair table.");
}
if (dataLength == 0) return;
uint256 encodedLength = 4 * ((dataLength + 2) / 3);
uint256 remainder = dataLength % 3;
if (noPadding && remainder != 0) encodedLength -= remainder == 1 ? 2 : 1;
checkOverflow(buffer, encodedLength);
assembly {
let ptr := add(add(buffer, 0x20), mload(buffer))
data := add(data, offset)
let end := add(data, dataLength)
let tableData := add(pairTable, 0x20)
let highMask := shl(240, 0xffff)
for {} 1 {} {
data := add(data, 3)
let input := mload(data)
if iszero(lt(data, end)) {
switch remainder
case 1 { input := and(input, 0xff0000) }
case 2 { input := and(input, 0xffff00) }
}
let highPair := mload(add(tableData, shl(1, and(shr(12, input), 0xfff))))
let lowPair := mload(add(tableData, shl(1, and(input, 0xfff))))
mstore(ptr, or(and(highPair, highMask), shr(16, and(lowPair, highMask))))
ptr := add(ptr, 4)
if iszero(lt(data, end)) { break }
}
if iszero(noPadding) {
mstore8(sub(ptr, iszero(iszero(remainder))), 0x3d)
mstore8(sub(ptr, shl(1, eq(remainder, 1))), 0x3d)
}
mstore(buffer, add(mload(buffer), encodedLength))
}
}
function capacity(bytes memory buffer) internal pure returns (uint256 cap) {
assembly {
cap := sub(mload(sub(buffer, 0x20)), 0x40)
}
}
function checkOverflow(bytes memory buffer, uint256 addedLength) internal pure {
uint256 newLength = buffer.length + addedLength;
if (capacity(buffer) < newLength) {
revert("DynamicBuffer: Appending out of bounds.");
}
}
}
src/layered/v2/LayeredInterfacesV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
interface ILayeredSourceV2 {
function ownerOf(uint256 tokenId) external view returns (address);
function artworkInfo(uint256 tokenId)
external
view
returns (
string memory artworkName,
string memory description,
address recipient,
bool finalized,
bool minted
);
function layerCount(uint256 tokenId) external view returns (uint256);
function layerAt(uint256 tokenId, uint256 layerIndex)
external
view
returns (
string memory layerName,
string memory traitType,
string memory traitValue,
address dataPointer,
string memory mimetype,
uint16 z,
bool visible,
uint8 blinkMode
);
}
interface ILayeredThumbnailV2 {
function thumbnailSvgLength(address nft, uint256 tokenId) external view returns (uint256);
function thumbnailSvg(address nft, uint256 tokenId) external view returns (string memory);
}
interface ILayeredAnimationV2 {
function animationHtmlLength(address nft, uint256 tokenId) external view returns (uint256);
function animationHtml(address nft, uint256 tokenId) external view returns (string memory);
}
src/layered/v2/LayeredPayloadV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {DynamicBuffer} from "./DynamicBuffer.sol";
/// @notice Reads legacy one-pointer SSTORE2 payloads and optional V2 chunk
/// descriptors without changing Layer or LayerInput.
library LayeredPayloadV2 {
using DynamicBuffer for bytes;
bytes8 internal constant CHUNK_MAGIC = 0x4c4f413243484e4b; // "LOA2CHNK"
uint8 internal constant CHUNK_VERSION = 1;
uint256 internal constant DESCRIPTOR_HEADER_BYTES = 15;
uint256 internal constant ADDRESS_BYTES = 20;
uint256 internal constant MAX_CHUNKS = 256;
struct Info {
uint256 length;
uint256 chunkCount;
}
error EmptyPayloadPointer(address pointer);
error InvalidChunkDescriptor(address pointer);
error EmptyChunkPointer(address descriptor, uint256 chunkIndex, address pointer);
error ChunkLengthMismatch(address pointer, uint256 declaredLength, uint256 actualLength);
error SSTORE2ReadOutOfBounds(address pointer, uint256 offset, uint256 length);
function encodedLength(uint256 length) internal pure returns (uint256) {
return 4 * ((length + 2) / 3);
}
/// @dev A raw SSTORE2 pointer is runtime byte 0 (STOP) followed by payload.
/// A descriptor payload is:
/// magic[8] | version[1] | chunkCount[2] | totalBytes[4] | addresses[20*n].
/// totalBytes is never trusted: inspect verifies it against every chunk's
/// actual extcodesize before it is used for allocation or writes.
function inspect(address pointer) internal view returns (Info memory info) {
uint256 codeSize = pointer.code.length;
if (pointer == address(0) || codeSize <= 1) revert EmptyPayloadPointer(pointer);
uint256 payloadBytes = codeSize - 1;
if (payloadBytes < DESCRIPTOR_HEADER_BYTES || _magic(pointer) != CHUNK_MAGIC) {
info.length = payloadBytes;
return info;
}
bytes memory header = new bytes(DESCRIPTOR_HEADER_BYTES);
assembly {
extcodecopy(pointer, add(header, 0x20), 1, DESCRIPTOR_HEADER_BYTES)
}
if (uint8(header[8]) != CHUNK_VERSION) revert InvalidChunkDescriptor(pointer);
uint256 count = (uint256(uint8(header[9])) << 8) | uint256(uint8(header[10]));
uint256 declared = (uint256(uint8(header[11])) << 24)
| (uint256(uint8(header[12])) << 16)
| (uint256(uint8(header[13])) << 8)
| uint256(uint8(header[14]));
if (
count == 0 || count > MAX_CHUNKS
|| payloadBytes != DESCRIPTOR_HEADER_BYTES + (ADDRESS_BYTES * count)
) revert InvalidChunkDescriptor(pointer);
uint256 actual;
for (uint256 i; i < count; ++i) {
address chunk = chunkAt(pointer, i);
uint256 chunkCodeSize = chunk.code.length;
if (chunk == address(0) || chunkCodeSize <= 1) {
revert EmptyChunkPointer(pointer, i, chunk);
}
actual += chunkCodeSize - 1;
}
if (actual != declared) revert ChunkLengthMismatch(pointer, declared, actual);
info.length = actual;
info.chunkCount = count;
}
/// @notice Reads one complete logical payload into reusable scratch memory
/// and appends one padded Base64 stream. Resetting 0x40 after encoding means
/// only one PNG scratch allocation is live at a time, even across layers.
function appendBase64(bytes memory buffer, address pointer) internal view {
Info memory info = inspect(pointer);
buffer.checkOverflow(encodedLength(info.length));
uint256 restoreFreeMemory;
bytes memory scratch;
uint256 rounded = (info.length + 0x1f) & ~uint256(0x1f);
assembly {
restoreFreeMemory := mload(0x40)
scratch := restoreFreeMemory
mstore(scratch, mload(info))
mstore(0x40, add(add(scratch, 0x20), rounded))
}
if (info.chunkCount == 0) {
assembly {
extcodecopy(pointer, add(scratch, 0x20), 1, mload(info))
}
} else {
uint256 cursor;
for (uint256 i; i < info.chunkCount; ++i) {
address chunk = chunkAt(pointer, i);
uint256 chunkLength = chunk.code.length - 1;
assembly {
extcodecopy(chunk, add(add(scratch, 0x20), cursor), 1, chunkLength)
}
cursor += chunkLength;
}
// inspect already established equality; retain an explicit local
// assertion at the memory-write boundary.
assert(cursor == info.length);
}
buffer.appendSafeBase64(scratch, false, false);
assembly {
mstore(0x40, restoreFreeMemory)
}
}
function appendSSTORE2Range(
bytes memory buffer,
address pointer,
uint256 payloadOffset,
uint256 length
) internal view {
uint256 payloadLength = pointer.code.length;
if (pointer == address(0) || payloadLength <= 1) revert EmptyPayloadPointer(pointer);
payloadLength -= 1;
if (payloadOffset > payloadLength || length > payloadLength - payloadOffset) {
revert SSTORE2ReadOutOfBounds(pointer, payloadOffset, length);
}
buffer.checkOverflow(length);
assembly {
let destination := add(add(buffer, 0x20), mload(buffer))
extcodecopy(pointer, destination, add(payloadOffset, 1), length)
mstore(buffer, add(mload(buffer), length))
}
}
function chunkAt(address descriptor, uint256 index) internal view returns (address chunk) {
uint256 codeOffset = 1 + DESCRIPTOR_HEADER_BYTES + (index * ADDRESS_BYTES);
assembly {
let scratch := mload(0x40)
extcodecopy(descriptor, scratch, codeOffset, ADDRESS_BYTES)
chunk := shr(96, mload(scratch))
}
}
function _magic(address pointer) private view returns (bytes8 magic) {
assembly {
let scratch := mload(0x40)
extcodecopy(pointer, scratch, 1, 8)
magic := mload(scratch)
}
}
}
src/layered/v2/LayeredRenderUtilsV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {DynamicBuffer} from "./DynamicBuffer.sol";
library LayeredRenderUtilsV2 {
using DynamicBuffer for bytes;
using Strings for uint256;
uint8 internal constant ESCAPE_JSON = 0;
uint8 internal constant ESCAPE_JS = 1;
uint8 internal constant ESCAPE_XML = 2;
uint8 internal constant ESCAPE_HTML = 3;
function decimalLength(uint256 value) internal pure returns (uint256 length) {
do {
++length;
value /= 10;
} while (value != 0);
}
function appendUint(bytes memory buffer, uint256 value) internal pure {
buffer.appendSafe(bytes(value.toString()));
}
function escapedLength(string memory value, uint8 mode) internal pure returns (uint256 length) {
bytes memory raw = bytes(value);
for (uint256 i; i < raw.length; ++i) {
bytes1 c = raw[i];
if (mode == ESCAPE_XML) {
if (c == "&") length += 5;
else if (c == '"') length += 6;
else if (c == "'") length += 6;
else if (c == "<" || c == ">") length += 4;
else ++length;
} else if (mode == ESCAPE_HTML) {
if (c == "&") length += 5;
else if (c == '"') length += 6;
else if (c == "'") length += 5;
else if (c == "<" || c == ">") length += 4;
else ++length;
} else {
// Legacy JSON and JS behavior: preserve UTF-8 and controls other
// than quote, slash, LF, CR and TAB byte-for-byte.
if (c == '"' || c == "\\" || c == "\n" || c == "\r" || c == "\t") length += 2;
else ++length;
}
}
}
function appendEscaped(bytes memory buffer, string memory value, uint8 mode) internal pure {
bytes memory raw = bytes(value);
uint256 runStart;
for (uint256 i; i < raw.length; ++i) {
bytes memory replacement = _replacement(raw[i], mode);
if (replacement.length == 0) continue;
_appendRange(buffer, raw, runStart, i - runStart);
buffer.appendSafe(replacement);
runStart = i + 1;
}
_appendRange(buffer, raw, runStart, raw.length - runStart);
}
function _replacement(bytes1 c, uint8 mode) private pure returns (bytes memory) {
if (mode == ESCAPE_XML) {
if (c == "&") return bytes("&");
if (c == '"') return bytes(""");
if (c == "'") return bytes("'");
if (c == "<") return bytes("<");
if (c == ">") return bytes(">");
return bytes("");
}
if (mode == ESCAPE_HTML) {
if (c == "&") return bytes("&");
if (c == '"') return bytes(""");
if (c == "'") return bytes("'");
if (c == "<") return bytes("<");
if (c == ">") return bytes(">");
return bytes("");
}
if (c == '"') return bytes("\\\"");
if (c == "\\") return bytes("\\\\");
if (c == "\n") return bytes("\\n");
if (c == "\r") return bytes("\\r");
if (c == "\t") return bytes("\\t");
return bytes("");
}
function _appendRange(bytes memory buffer, bytes memory data, uint256 offset, uint256 length) private pure {
if (length == 0) return;
if (offset > data.length || length > data.length - offset) revert("render range out of bounds");
buffer.checkOverflow(length);
assembly {
let source := add(add(data, 0x20), offset)
let sourceEnd := add(source, length)
let destination := add(add(buffer, 0x20), mload(buffer))
for {} lt(source, sourceEnd) {
source := add(source, 0x20)
destination := add(destination, 0x20)
} {
mstore(destination, mload(source))
}
mstore(buffer, add(mload(buffer), length))
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"@openzeppelin/=lib/openzeppelin-contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"seadrop/=lib/seadrop/",
"utility-contracts/=lib/seadrop/lib/utility-contracts/src/",
"ERC721A-Upgradeable/=lib/seadrop/lib/ERC721A-Upgradeable/contracts/",
"ERC721A/=lib/seadrop/lib/ERC721A/contracts/",
"create2-helpers/=lib/seadrop/lib/create2-helpers/",
"create2-scripts/=lib/seadrop/lib/create2-helpers/script/",
"ds-test/=lib/seadrop/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"murky/=lib/seadrop/lib/murky/src/",
"openzeppelin-contracts-upgradeable/=lib/seadrop/lib/openzeppelin-contracts-upgradeable/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"operator-filter-registry/=lib/seadrop/lib/operator-filter-registry/src/",
"solmate/=lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.