Проверенный контрактТочноеMIT
SqueekRenderer
Адрес0x082c1eb3c1f12e59fd0be8bb26df32ea7b536260
- Баланс
0 ETH
- Транзакций
1
- Компилятор
solc 0.8.36
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.36+commit.8a079791
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 238 139
- Транзакция создания
- 0xe65df01f7b…34d0380caf
10 файлов
- src/art/SqueekRenderer.solглавный25,8 КБ
- lib/openzeppelin-contracts/contracts/utils/Base64.sol5,21 КБ
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1,97 КБ
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3,93 КБ
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28,31 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2,61 КБ
- src/art/SqueekArtPage.sol13,14 КБ
- src/art/SqueekArtValidator.sol3,9 КБ
- src/interfaces/ISqueekRenderer.sol1,13 КБ
src/art/SqueekRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
import { Base64 } from "@openzeppelin/contracts/utils/Base64.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ISqueekArtValidator, ISqueekRenderer } from "../interfaces/ISqueekRenderer.sol";
import { ArtPage } from "./SqueekArtPage.sol";
import { SqueekArtValidator } from "./SqueekArtValidator.sol";
/// @dev Append-only byte buffer with preallocated capacity (avoids quadratic concatenation).
library Buf {
struct B {
bytes data;
uint256 len;
}
function init(uint256 capacity) internal pure returns (B memory b) {
b.data = new bytes(capacity);
}
function put(B memory b, bytes memory s) internal pure {
uint256 l = s.length;
if (l == 0) return;
require(b.len + l <= b.data.length, "buf overflow");
bytes memory data = b.data;
uint256 offset = b.len;
// SAFETY: bounds checked above; copies s into data at offset.
assembly ("memory-safe") {
mcopy(add(add(data, 0x20), offset), add(s, 0x20), l)
}
b.len = offset + l;
}
/// @dev Writes the decimal digits of `v` in place (no allocation).
function putUint(B memory b, uint256 v) internal pure {
uint256 digits = 1;
for (uint256 t = v; t >= 10; t /= 10) ++digits;
uint256 start = b.len;
uint256 end = start + digits;
require(end <= b.data.length, "buf overflow");
bytes memory data = b.data;
// SAFETY: writes `digits` ASCII bytes at data[start..end).
assembly ("memory-safe") {
let ptr := add(add(data, 0x20), end)
for { } true { } {
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(v, 10)))
v := div(v, 10)
if eq(ptr, add(add(data, 0x20), start)) { break }
}
}
b.len = end;
}
function putByte(B memory b, bytes1 c) internal pure {
uint256 offset = b.len;
require(offset < b.data.length, "buf overflow");
bytes memory data = b.data;
// SAFETY: single byte write inside capacity.
assembly ("memory-safe") {
mstore8(add(add(data, 0x20), offset), byte(0, c))
}
b.len = offset + 1;
}
function done(B memory b) internal pure returns (bytes memory data) {
data = b.data;
uint256 l = b.len;
// SAFETY: shrinks the length word to the written size.
assembly ("memory-safe") {
mstore(data, l)
}
}
}
/// @title SqueekRenderer ("sqk.dotgrid-renderer.v1")
/// @notice Fully on-chain dot-grid renderer. A Squeek is a 64x64 grid of glyph emitters on a 25088x25088
/// canvas; eleven traits drawn from `keccak256(collectionSeed, tokenId)` pick the palette, colour
/// pattern, body/face/eye/muzzle/ear glyphs, illumination, eyes, ears and background from the
/// vocabularies stored in the immutable art page.
contract SqueekRenderer is ISqueekRenderer {
string public constant web = "https://squeekchain.com/";
string public constant X = "https://x.com/squeekchain";
using Buf for Buf.B;
error InvalidValidator(address validator);
string private constant RENDERER_NAME = "sqk.dotgrid-renderer.v1";
bytes32 private constant RENDERER_ID = keccak256(bytes(RENDERER_NAME));
bytes32 private constant ASSET_SET_ID = keccak256("sqk.dotgrid-asset-set.v1");
uint256 private constant GRID = 64;
uint256 private constant PITCH = 392;
uint256 private constant CANVAS = 25_088;
uint256 private constant TRAITS = 11;
// trait indices
uint256 private constant T_PALETTE = 0;
uint256 private constant T_PATTERN = 1;
uint256 private constant T_BODY = 2;
uint256 private constant T_FACE = 3;
uint256 private constant T_EYE = 4;
uint256 private constant T_MUZZLE = 5;
uint256 private constant T_EAR = 6;
uint256 private constant T_ILLUMINATION = 7;
uint256 private constant T_EYES = 8;
uint256 private constant T_EARS = 9;
uint256 private constant T_BACKGROUND = 10;
address public immutable validator;
struct Scene {
uint8[TRAITS] trait;
uint64 field;
bytes3[3] colors;
uint256 emitters;
uint64 usedGlyphs; // bitmap over 52 (glyph, size) ids
bytes usePrefix; // '<use href="#'
bytes xAttr; // '" x="'
bytes yAttr; // '" y="'
bytes closeTag; // '"/>'
}
constructor(address validator_) {
if (validator_ == address(0) || validator_.code.length == 0) revert InvalidValidator(validator_);
if (ISqueekArtValidator(validator_).assetSetId() != ASSET_SET_ID) revert InvalidValidator(validator_);
validator = validator_;
}
// ---------------------------------------------------------------------------------------------
// Identity & page checks
// ---------------------------------------------------------------------------------------------
function rendererName() external pure returns (string memory) {
return RENDERER_NAME;
}
function rendererId() external pure returns (bytes32) {
return RENDERER_ID;
}
function validatePage(address artPage) external view returns (bytes32 pageHash, bytes32 assetSetHash) {
return ISqueekArtValidator(validator).validatePage(artPage);
}
// ---------------------------------------------------------------------------------------------
// Trait resolution
// ---------------------------------------------------------------------------------------------
/// @notice Packed trait word: byte i (0..10) is the index into trait vocabulary i, bytes 11..18 hold
/// the 64-bit field seed used for per-emitter noise.
function traitWord(address artPage, bytes32 collectionSeed, uint256 tokenId) public view returns (bytes32) {
ArtPage memory page = SqueekArtValidator(validator).readPage(artPage);
return _traitWord(page, collectionSeed, tokenId);
}
function resolvedFieldHash(address artPage, bytes32 collectionSeed, uint256 tokenId)
external
view
returns (bytes32)
{
(bytes32 pageHash,) = ISqueekArtValidator(validator).validatePage(artPage);
return keccak256(abi.encode(traitWord(artPage, collectionSeed, tokenId), pageHash, tokenId));
}
function _traitWord(ArtPage memory page, bytes32 collectionSeed, uint256 tokenId) private pure returns (bytes32) {
bytes32 entropy = keccak256(abi.encode(collectionSeed, tokenId));
uint256 word;
for (uint256 trait; trait < TRAITS; ++trait) {
uint256 count = page.traitValues[trait].length;
uint256 index = uint8(entropy[trait]) % count;
word |= index << (8 * trait);
}
uint64 field = uint64(uint256(keccak256(abi.encode(entropy, "field"))));
word |= uint256(field) << (8 * TRAITS);
return bytes32(word);
}
function _scene(ArtPage memory page, bytes32 word) private pure returns (Scene memory scene) {
uint256 w = uint256(word);
for (uint256 trait; trait < TRAITS; ++trait) {
scene.trait[trait] = uint8(w >> (8 * trait));
}
scene.field = uint64(w >> (8 * TRAITS));
scene.usePrefix = '<use href="#';
scene.xAttr = '" x="';
scene.yAttr = '" y="';
scene.closeTag = '"/>';
uint256 paletteOffset = uint256(scene.trait[T_PALETTE]) * 9;
bytes memory p = page.palettes;
for (uint256 color; color < 3; ++color) {
uint256 at = paletteOffset + color * 3;
scene.colors[color] = bytes3(bytes.concat(p[at], p[at + 1], p[at + 2]));
}
}
// ---------------------------------------------------------------------------------------------
// tokenURI
// ---------------------------------------------------------------------------------------------
function tokenURI(address artPage, bytes32 collectionSeed, uint256 tokenId) external view returns (string memory) {
ArtPage memory page = SqueekArtValidator(validator).readPage(artPage);
(bytes32 pageHash, bytes32 assetSetHash) = ISqueekArtValidator(validator).validatePage(artPage);
bytes32 word = _traitWord(page, collectionSeed, tokenId);
bytes32 fieldHash = keccak256(abi.encode(word, pageHash, tokenId));
Scene memory scene = _scene(page, word);
bytes memory svg = _svg(page, scene, tokenId, pageHash, word, fieldHash);
Buf.B memory json = Buf.init(svg.length * 4 / 3 + 4096);
json.put('{"name":"');
json.put(bytes(page.name));
json.put(" #");
json.putUint(tokenId);
json.put('","description":"');
json.put(bytes(page.description));
json.put('","image":"data:image/svg+xml;base64,');
json.put(bytes(Base64.encode(svg)));
json.put('","attributes":[');
for (uint256 trait; trait < TRAITS; ++trait) {
if (trait != 0) json.put(",");
json.put('{"trait_type":"');
json.put(bytes(page.traitNames[trait]));
json.put('","value":"');
json.put(bytes(page.traitValues[trait][scene.trait[trait]]));
json.put('"}');
}
json.put('],"properties":{"renderer":"');
json.put(bytes(RENDERER_NAME));
json.put('","rendererId":"');
json.put(bytes(Strings.toHexString(uint256(RENDERER_ID), 32)));
json.put('","pageHash":"');
json.put(bytes(Strings.toHexString(uint256(pageHash), 32)));
json.put('","assetSetHash":"');
json.put(bytes(Strings.toHexString(uint256(assetSetHash), 32)));
json.put('","traitWord":"');
json.put(bytes(Strings.toHexString(uint256(word), 32)));
json.put('","resolvedFieldHash":"');
json.put(bytes(Strings.toHexString(uint256(fieldHash), 32)));
json.put('","emitters":');
json.putUint(scene.emitters);
json.put("}}");
return string.concat("data:application/json;base64,", Base64.encode(json.done()));
}
// ---------------------------------------------------------------------------------------------
// SVG
// ---------------------------------------------------------------------------------------------
function _svg(
ArtPage memory page,
Scene memory scene,
uint256 tokenId,
bytes32 pageHash,
bytes32 word,
bytes32 fieldHash
) private pure returns (bytes memory) {
// character layers are rendered first so the glyph bitmap is known when the defs are written
Buf.B memory body = Buf.init(90_000);
_character(scene, body);
Buf.B memory out = Buf.init(body.len + 12_000);
out.put('<svg xmlns="http://www.w3.org/2000/svg" width="1568" height="1568" viewBox="0 0 25088 25088" role="img" aria-label="');
out.put(bytes(page.name));
out.put(" #");
out.putUint(tokenId);
out.put('"><title>');
out.put(bytes(page.name));
out.put(" #");
out.putUint(tokenId);
out.put("</title><desc>");
for (uint256 trait; trait < TRAITS; ++trait) {
if (trait != 0) out.put("; ");
out.put(bytes(page.traitNames[trait]));
out.put(": ");
out.put(bytes(page.traitValues[trait][scene.trait[trait]]));
}
out.put("</desc><metadata>{"renderer":"");
out.put(bytes(RENDERER_NAME));
out.put("","rendererId":"");
out.put(bytes(Strings.toHexString(uint256(RENDERER_ID), 32)));
out.put("","pageHash":"");
out.put(bytes(Strings.toHexString(uint256(pageHash), 32)));
out.put("","tokenId":"");
out.putUint(tokenId);
out.put("","traitWord":"");
out.put(bytes(Strings.toHexString(uint256(word), 32)));
out.put("","resolvedFieldHash":"");
out.put(bytes(Strings.toHexString(uint256(fieldHash), 32)));
out.put(""}</metadata><defs>");
_glyphDefs(page, scene, out);
_backgroundDefs(scene, out);
out.put('<g id="e">');
out.put(body.done());
out.put("</g></defs>");
out.put('<rect width="25088" height="25088" fill="#08080A"/><rect width="25088" height="25088" fill="url(#bg)"/>');
_illumination(scene, out);
out.put("</svg>");
return out.done();
}
/// @dev Emits one `<path>` per (glyph, size) id used by the scene. Ids are letters: A.. for glyph 0
/// sizes 0..3, E.. for glyph 1, and so on (52 ids: A-Z then a-z).
function _glyphDefs(ArtPage memory page, Scene memory scene, Buf.B memory out) private pure {
for (uint256 id; id < 52; ++id) {
if (scene.usedGlyphs & (uint64(1) << uint64(id)) == 0) continue;
out.put('<path id="');
out.putByte(_glyphId(id));
out.put('" d="');
out.put(bytes(page.glyphPaths[id]));
out.put('" fill="currentColor" transform="scale(16)"/>');
}
}
function _glyphId(uint256 id) private pure returns (bytes1) {
return id < 26 ? bytes1(uint8(65 + id)) : bytes1(uint8(97 + id - 26));
}
function _useGlyph(Scene memory scene, uint256 glyph, uint256 size) private pure returns (uint256 id) {
id = glyph * 4 + size;
scene.usedGlyphs |= uint64(1) << uint64(id);
}
function _backgroundDefs(Scene memory scene, Buf.B memory out) private pure {
uint8 background = scene.trait[T_BACKGROUND];
uint256 dot = _useGlyph(scene, 0, 0); // small circle
uint256 cells = background == 2 ? 2 : background == 4 ? 4 : 1;
uint256 span = cells * PITCH;
out.put('<pattern id="bg" patternUnits="userSpaceOnUse" width="');
out.putUint(span);
out.put('" height="');
out.putUint(background == 3 ? PITCH * 2 : span);
out.put('"><g color="#');
out.put(_hex3(scene.colors[0]));
out.put('" opacity="');
out.put(background == 1 ? bytes("0.16") : background == 0 ? bytes("0.28") : bytes("0.34"));
out.put('">');
if (background == 4) {
// cross grid: dots along the first row and the first column of a 4x4 block
for (uint256 i; i < 4; ++i) {
_use(scene, out, dot, i * PITCH + PITCH / 2, PITCH / 2);
if (i != 0) _use(scene, out, dot, PITCH / 2, i * PITCH + PITCH / 2);
}
} else if (background == 1) {
// micro dots: the small circle scaled down, four per cell
out.put('<g transform="scale(0.5)">');
_use(scene, out, dot, PITCH / 2, PITCH / 2);
_use(scene, out, dot, PITCH / 2 + PITCH, PITCH / 2);
_use(scene, out, dot, PITCH / 2, PITCH / 2 + PITCH);
_use(scene, out, dot, PITCH / 2 + PITCH, PITCH / 2 + PITCH);
out.put("</g>");
} else {
_use(scene, out, dot, PITCH / 2, PITCH / 2);
}
out.put("</g></pattern>");
}
function _illumination(Scene memory scene, Buf.B memory out) private pure {
uint8 mode = scene.trait[T_ILLUMINATION];
// (halo opacity 1, halo opacity 2, halo scale 1 in 1/1000, halo scale 2)
(bytes memory o1, bytes memory o2, uint256 s1, uint256 s2) = mode == 0
? (bytes("0.09"), bytes("0.215"), uint256(1060), uint256(1030))
: mode == 1
? (bytes("0.11"), bytes("0.26"), uint256(1080), uint256(1040))
: mode == 2
? (bytes("0.08"), bytes("0.18"), uint256(1040), uint256(1020))
: mode == 3
? (bytes("0.12"), bytes("0.30"), uint256(1070), uint256(1035))
: (bytes("0.16"), bytes("0.40"), uint256(1100), uint256(1050));
_halo(out, o1, s1);
_halo(out, o2, s2);
out.put('<use href="#e"/>');
}
function _halo(Buf.B memory out, bytes memory opacity, uint256 scale) private pure {
// scale about the canvas centre: translate(-c*(s-1)) scale(s)
uint256 shift = CANVAS * (scale - 1000) / 2000;
out.put('<use href="#e" opacity="');
out.put(opacity);
out.put('" transform="translate(-');
out.putUint(shift);
out.put(" -");
out.putUint(shift);
out.put(") scale(1.");
out.put(_milli(scale - 1000));
out.put(')"/>');
}
function _milli(uint256 v) private pure returns (bytes memory) {
bytes memory s = new bytes(3);
s[0] = bytes1(uint8(48 + v / 100));
s[1] = bytes1(uint8(48 + (v / 10) % 10));
s[2] = bytes1(uint8(48 + v % 10));
return s;
}
// ---------------------------------------------------------------------------------------------
// Character geometry (grid cells)
// ---------------------------------------------------------------------------------------------
function _character(Scene memory scene, Buf.B memory out) private pure {
_bodyLayer(scene, out);
_earsLayer(scene, out);
_faceLayer(scene, out);
_muzzleLayer(scene, out);
_eyesLayer(scene, out);
}
/// @dev Body: ellipse centred (32, 38), radii 15 x 18 cells; one colour group per palette colour.
function _bodyLayer(Scene memory scene, Buf.B memory out) private pure {
uint256 glyph = scene.trait[T_BODY];
for (uint256 color; color < 3; ++color) {
bool open;
for (uint256 row = 19; row <= 57; ++row) {
for (uint256 col = 16; col <= 48; ++col) {
if (!_inEllipse(col, row, 32, 38, 15, 18)) continue;
if (_bodyColor(scene, col, row) != color) continue;
if (!open) {
_openGroup(out, scene.colors[color]);
open = true;
}
uint256 size = _bodySize(scene, col, row);
_emit(scene, out, _useGlyph(scene, glyph, size), col, row);
}
}
if (open) out.put("</g>");
}
}
function _bodyColor(Scene memory scene, uint256 col, uint256 row) private pure returns (uint256) {
uint8 pattern = scene.trait[T_PATTERN];
if (pattern == 0) return 0;
if (pattern == 1) return col < 32 ? 0 : 1;
if (pattern == 2) return row < 38 ? 0 : 1;
if (pattern == 3) return _inEllipse(col, row, 32, 38, 7, 8) ? 1 : 0;
if (pattern == 4) return ((col / 2) + (row / 2)) % 2;
return uint256(keccak256(abi.encode(scene.field, col, row))) % 3;
}
function _bodySize(Scene memory scene, uint256 col, uint256 row) private pure returns (uint256) {
uint8 mode = scene.trait[T_ILLUMINATION];
if (mode == 0) return 1; // Balanced Field
if (mode == 1) return _inEllipse(col, row, 32, 38, 8, 10) ? 2 : 1; // Core Pulse
if (mode == 2) return _inEllipse(col, row, 32, 38, 13, 16) ? 0 : 2; // Rim Trace
if (mode == 3) return ((col + row) / 4) % 3; // Phase Sweep
return 2; // Overdrive
}
/// @dev Ears: two shapes centred (22, 17) and (42, 17) drawn with the ear glyph in the secondary colour.
function _earsLayer(Scene memory scene, Buf.B memory out) private pure {
uint256 glyph = scene.trait[T_EAR];
uint8 ears = scene.trait[T_EARS];
_openGroup(out, scene.colors[1]);
for (uint256 side; side < 2; ++side) {
uint256 cx = side == 0 ? 22 : 42;
for (uint256 row = 10; row <= 24; ++row) {
for (uint256 col = cx - 6; col <= cx + 6; ++col) {
if (!_inEar(ears, col, row, cx, 17)) continue;
_emit(scene, out, _useGlyph(scene, glyph, ears == 1 ? 1 : 2), col, row);
}
}
}
out.put("</g>");
}
function _inEar(uint8 ears, uint256 col, uint256 row, uint256 cx, uint256 cy) private pure returns (bool) {
uint256 d2 = _dist2(col, row, cx, cy);
if (ears == 0) return d2 <= 9; // Canonical Round r=3
if (ears == 1) return d2 <= 4; // Compact Round r=2
if (ears == 2) return d2 <= 16; // Wide Round r=4
if (ears == 3) return _absDiff(col, cx) <= 2 && _absDiff(row, cy) <= 2; // Soft Square 5x5
if (ears == 4) return d2 <= 12 && !(col > cx && row < cy && d2 >= 5); // Notched
return d2 >= 5 && d2 <= 16; // Hollow Ring
}
/// @dev Face: inner ellipse (32, 33) radii 9 x 7 cells in the accent colour, smallest face glyph.
function _faceLayer(Scene memory scene, Buf.B memory out) private pure {
uint256 glyph = scene.trait[T_FACE];
_openGroup(out, scene.colors[2]);
for (uint256 row = 26; row <= 40; ++row) {
for (uint256 col = 23; col <= 41; ++col) {
if (!_inEllipse(col, row, 32, 33, 9, 7)) continue;
_emit(scene, out, _useGlyph(scene, glyph, 0), col, row);
}
}
out.put("</g>");
}
/// @dev Muzzle: small disc centred (32, 40), muzzle glyph, accent colour.
function _muzzleLayer(Scene memory scene, Buf.B memory out) private pure {
uint256 glyph = scene.trait[T_MUZZLE];
_openGroup(out, scene.colors[1]);
for (uint256 row = 38; row <= 42; ++row) {
for (uint256 col = 29; col <= 35; ++col) {
if (_dist2(col, row, 32, 40) > 5) continue;
_emit(scene, out, _useGlyph(scene, glyph, 1), col, row);
}
}
out.put("</g>");
}
/// @dev Eyes: white eye-glyph emitters around (27, 32) and (37, 32), shape by the Eyes trait.
function _eyesLayer(Scene memory scene, Buf.B memory out) private pure {
uint256 glyph = scene.trait[T_EYE];
uint8 eyes = scene.trait[T_EYES];
out.put('<g color="#FFFFFF">');
for (uint256 side; side < 2; ++side) {
uint256 cx = side == 0 ? 27 : 37;
uint8 shape = eyes;
if (eyes == 10) shape = side == 0 ? 0 : 3; // Wink: capsule + sleepy bar
for (uint256 row = 29; row <= 35; ++row) {
for (uint256 col = cx - 3; col <= cx + 3; ++col) {
if (!_inEye(shape, col, row, cx, 32)) continue;
_emit(scene, out, _useGlyph(scene, glyph, shape == 2 || shape == 6 ? 0 : 1), col, row);
}
}
}
out.put("</g>");
}
function _inEye(uint8 shape, uint256 col, uint256 row, uint256 cx, uint256 cy) private pure returns (bool) {
uint256 dx = _absDiff(col, cx);
uint256 dy = _absDiff(row, cy);
bool above = row < cy;
bool below = row > cy;
if (shape == 0) return dx == 0 && dy <= 1; // Standard Capsules
if (shape == 1) return dx <= 1 && dy <= 1 && !(dy == 1 && below); // Wide Blocks 3x2
if (shape == 2) return dx == 0 && dy == 0; // Tiny Pixels
if (shape == 3) return dy == 0 && dx <= 1; // Sleepy Bars
if (shape == 4) return (dx == dy && dx <= 1); // X Expression
if (shape == 5) return (dx == 0 && dy == 0) || (dx + dy == 2 && dx != dy); // Reticle
if (shape == 6) return dx == 0 && dy <= 1; // Vertical Slits (small glyph)
if (shape == 7) return (dx == 0 && dy == 0) || (dx == 1 && dy == 1 && above); // Focused Chevrons
if (shape == 8) return (dx == 1 && dy == 0) || (dx == 0 && dy == 1 && above); // Happy Arcs
if (shape == 9) return dx == 0 && dy == 1; // Broken Signal
return dx <= 2 && dy <= 2 && dx + dy >= 2 && !(dx == 2 && dy == 2); // Orbit Rings
}
// ---------------------------------------------------------------------------------------------
// Emission helpers
// ---------------------------------------------------------------------------------------------
function _emit(Scene memory scene, Buf.B memory out, uint256 glyphId, uint256 col, uint256 row) private pure {
_use(scene, out, glyphId, col * PITCH + PITCH / 2, row * PITCH + PITCH / 2);
++scene.emitters;
}
function _use(Scene memory scene, Buf.B memory out, uint256 glyphId, uint256 x, uint256 y) private pure {
out.put(scene.usePrefix);
out.putByte(_glyphId(glyphId));
out.put(scene.xAttr);
out.putUint(x);
out.put(scene.yAttr);
out.putUint(y);
out.put(scene.closeTag);
}
function _openGroup(Buf.B memory out, bytes3 color) private pure {
out.put('<g color="#');
out.put(_hex3(color));
out.put('">');
}
function _hex3(bytes3 color) private pure returns (bytes memory s) {
bytes16 alphabet = "0123456789ABCDEF";
s = new bytes(6);
for (uint256 i; i < 3; ++i) {
uint8 b = uint8(color[i]);
s[i * 2] = alphabet[b >> 4];
s[i * 2 + 1] = alphabet[b & 0x0f];
}
}
function _inEllipse(uint256 col, uint256 row, uint256 cx, uint256 cy, uint256 rx, uint256 ry)
private
pure
returns (bool)
{
uint256 dx = _absDiff(col, cx);
uint256 dy = _absDiff(row, cy);
return dx * dx * ry * ry + dy * dy * rx * rx <= rx * rx * ry * ry;
}
function _dist2(uint256 col, uint256 row, uint256 cx, uint256 cy) private pure returns (uint256) {
uint256 dx = _absDiff(col, cx);
uint256 dy = _absDiff(row, cy);
return dx * dx + dy * dy;
}
function _absDiff(uint256 a, uint256 b) private pure returns (uint256) {
return a > b ? a - b : b - a;
}
}
lib/openzeppelin-contracts/contracts/utils/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Base64.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
* See sections 4 and 5 of https://datatracker.ietf.org/doc/html/rfc4648
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string internal constant _TABLE_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
return _encode(data, _TABLE, true);
}
/**
* @dev Converts a `bytes` to its Bytes64Url `string` representation.
* Output is not padded with `=` as specified in https://www.rfc-editor.org/rfc/rfc4648[rfc4648].
*/
function encodeURL(bytes memory data) internal pure returns (string memory) {
return _encode(data, _TABLE_URL, false);
}
/**
* @dev Internal table-agnostic conversion
*/
function _encode(bytes memory data, string memory table, bool withPadding) private pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// If padding is enabled, the final length should be `bytes` data length divided by 3 rounded up and then
// multiplied by 4 so that it leaves room for padding the last chunk
// - `data.length + 2` -> Prepare for division rounding up
// - `/ 3` -> Number of 3-bytes chunks (rounded up)
// - `4 *` -> 4 characters for each chunk
// This is equivalent to: 4 * Math.ceil(data.length / 3)
//
// If padding is disabled, the final length should be `bytes` data length multiplied by 4/3 rounded up as
// opposed to when padding is required to fill the last chunk.
// - `4 * data.length` -> 4 characters for each chunk
// - ` + 2` -> Prepare for division rounding up
// - `/ 3` -> Number of 3-bytes chunks (rounded up)
// This is equivalent to: Math.ceil((4 * data.length) / 3)
uint256 resultLength = withPadding ? 4 * ((data.length + 2) / 3) : (4 * data.length + 2) / 3;
string memory result = new string(resultLength);
assembly ("memory-safe") {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 0x20)
let dataPtr := data
let endPtr := add(data, mload(data))
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
// set it to zero to make sure no dirty bytes are read in that section.
let afterPtr := add(endPtr, 0x20)
let afterCache := mload(afterPtr)
mstore(afterPtr, 0x00)
// Run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 byte (24 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
// Use this as an index into the lookup table, mload an entire word
// so the desired character is in the least significant byte, and
// mstore8 this least significant byte into the result and continue.
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// Reset the value that was cached
mstore(afterPtr, afterCache)
if withPadding {
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
}
return result;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @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;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(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) {
uint256 localValue = value;
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] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
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 Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* 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²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
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²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_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.
uint256 twos = denominator & (0 - denominator);
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²⁵⁶ / 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²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
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⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// 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²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, 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;
}
}
/**
* @dev 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) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(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 {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/art/SqueekArtPage.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @notice Decoded immutable art page consumed by the dot-grid renderer.
struct ArtPage {
string name;
string description;
string[] traitNames;
string[][] traitValues;
string[] glyphPaths;
bytes palettes;
}
/// @title SqueekArtPage
/// @notice Builds the canonical "DGPG" (dot-grid page) bytes: collection name/description, the 11 trait
/// vocabularies, the 13 glyphs x 4 sizes SVG path set and the 17 three-colour palettes.
/// @dev The page is stored verbatim as the runtime code of an immutable data contract (see
/// `SqueekArtPageDeployer`) and is pinned by hash in every Squeek's metadata.
library SqueekArtPage {
bytes4 internal constant MAGIC = 0x44475047; // "DGPG"
function build() internal pure returns (bytes memory) {
ArtPage memory page;
page.name = "Squeek";
page.description = "Squeek is a dot-grid character rendered fully onchain from an immutable art page.";
page.traitNames = _traitNames();
page.traitValues = _traitValues();
page.glyphPaths = _glyphPaths();
page.palettes = _palettes();
return abi.encodePacked(MAGIC, abi.encode(page));
}
function _traitNames() private pure returns (string[] memory names) {
names = new string[](11);
names[0] = "Palette";
names[1] = "Color Pattern";
names[2] = "Body Glyph";
names[3] = "Face Glyph";
names[4] = "Eye Glyph";
names[5] = "Muzzle Glyph";
names[6] = "Ear Glyph";
names[7] = "Illumination";
names[8] = "Eyes";
names[9] = "Ears";
names[10] = "Background";
}
function _traitValues() private pure returns (string[][] memory values) {
values = new string[][](11);
values[0] = _palettesNames();
values[1] = _list6("Solid", "Vertical Split", "Horizontal Split", "Radial Core", "Checker", "Spectral Noise");
string[] memory glyphs = _glyphNames();
values[2] = glyphs;
values[3] = glyphs;
values[4] = glyphs;
values[5] = glyphs;
values[6] = glyphs;
values[7] = _list5("Balanced Field", "Core Pulse", "Rim Trace", "Phase Sweep", "Overdrive");
values[8] = _eyes();
values[9] = _list6("Canonical Round", "Compact Round", "Wide Round", "Soft Square", "Notched", "Hollow Ring");
values[10] = _list5("Dot Grid", "Micro Dots", "Wide Dots", "Scanlines", "Cross Grid");
}
function _palettesNames() private pure returns (string[] memory names) {
names = new string[](17);
names[0] = "Void Violet";
names[1] = "Electric Cyan";
names[2] = "Acid Lime";
names[3] = "Orange CRT";
names[4] = "Hot Magenta";
names[5] = "Reactor Red";
names[6] = "Ice White";
names[7] = "Spectral RGB";
names[8] = "Gold";
names[9] = "Spectral Void Violet";
names[10] = "Spectral Electric Cyan";
names[11] = "Spectral Acid Lime";
names[12] = "Spectral Orange CRT";
names[13] = "Spectral Hot Magenta";
names[14] = "Spectral Reactor Red";
names[15] = "Spectral Ice White";
names[16] = "Spectral Gold";
}
function _glyphNames() private pure returns (string[] memory names) {
names = new string[](13);
names[0] = "Circle";
names[1] = "Rounded Square";
names[2] = "Triangle";
names[3] = "Diamond";
names[4] = "Cross";
names[5] = "Sparkle";
names[6] = "Shield";
names[7] = "Capsule";
names[8] = "Crown";
names[9] = "Heart";
names[10] = "Teardrop";
names[11] = "Lightning Bolt";
names[12] = "Clover";
}
function _eyes() private pure returns (string[] memory names) {
names = new string[](12);
names[0] = "Standard Capsules";
names[1] = "Wide Blocks";
names[2] = "Tiny Pixels";
names[3] = "Sleepy Bars";
names[4] = "X Expression";
names[5] = "Reticle";
names[6] = "Vertical Slits";
names[7] = "Focused Chevrons";
names[8] = "Happy Arcs";
names[9] = "Broken Signal";
names[10] = "Wink";
names[11] = "Orbit Rings";
}
/// @dev 13 glyphs x 4 sizes, centred on the origin, drawn at `transform="scale(16)"`.
function _glyphPaths() private pure returns (string[] memory paths) {
paths = new string[](52);
// Circle
paths[0] = "M0-2.5A2.5 2.5 0 1 1 0 2.5A2.5 2.5 0 1 1 0-2.5Z";
paths[1] = "M0-4.5A4.5 4.5 0 1 1 0 4.5A4.5 4.5 0 1 1 0-4.5Z";
paths[2] = "M0-7A7 7 0 1 1 0 7A7 7 0 1 1 0-7Z";
paths[3] = "M0-9.5A9.5 9.5 0 1 1 0 9.5A9.5 9.5 0 1 1 0-9.5Z";
// Rounded Square
paths[4] = "M-1.136-2.272H1.136A1.136 1.136 0 0 1 2.272-1.136V1.136A1.136 1.136 0 0 1 1.136 2.272H-1.136A1.136 1.136 0 0 1-2.272 1.136V-1.136A1.136 1.136 0 0 1-1.136-2.272Z";
paths[5] = "M-2.045-4.089H2.045A2.045 2.045 0 0 1 4.089-2.045V2.045A2.045 2.045 0 0 1 2.045 4.089H-2.045A2.045 2.045 0 0 1-4.089 2.045V-2.045A2.045 2.045 0 0 1-2.045-4.089Z";
paths[6] = "M-3.18-6.361H3.18A3.18 3.18 0 0 1 6.361-3.18V3.18A3.18 3.18 0 0 1 3.18 6.361H-3.18A3.18 3.18 0 0 1-6.361 3.18V-3.18A3.18 3.18 0 0 1-3.18-6.361Z";
paths[7] = "M-4.316-8.633H4.316A4.316 4.316 0 0 1 8.633-4.316V4.316A4.316 4.316 0 0 1 4.316 8.633H-4.316A4.316 4.316 0 0 1-8.633 4.316V-4.316A4.316 4.316 0 0 1-4.316-8.633Z";
// Triangle
paths[8] = "M0-3.131L3.131 3.131L-3.131 3.131Z";
paths[9] = "M0-5.636L5.636 5.636L-5.636 5.636Z";
paths[10] = "M0-8.767L8.767 8.767L-8.767 8.767Z";
paths[11] = "M0-11.898L11.898 11.898L-11.898 11.898Z";
// Diamond
paths[12] = "M0-3.115L3.115 0L0 3.115L-3.115 0Z";
paths[13] = "M0-5.607L5.607 0L0 5.607L-5.607 0Z";
paths[14] = "M0-8.722L8.722 0L0 8.722L-8.722 0Z";
paths[15] = "M0-11.837L11.837 0L0 11.837L-11.837 0Z";
// Cross
paths[16] = "M-2.985-1H-1V-2.985H1V-1H2.985V1H1V2.985H-1V1H-2.985Z";
paths[17] = "M-5.373-1.791H-1.791V-5.373H1.791V-1.791H5.373V1.791H1.791V5.373H-1.791V1.791H-5.373Z";
paths[18] = "M-8.358-2.786H-2.786V-8.358H2.786V-2.786H8.358V2.786H2.786V8.358H-2.786V2.786H-8.358Z";
paths[19] = "M-11.343-3.781H-3.781V-11.343H3.781V-3.781H11.343V3.781H3.781V11.343H-3.781V3.781H-11.343Z";
// Sparkle
paths[20] = "M0-3.824L1.275-1.275L3.824 0L1.275 1.275L0 3.824L-1.275 1.275L-3.824 0L-1.275-1.275Z";
paths[21] = "M0-6.883L2.294-2.294L6.883 0L2.294 2.294L0 6.883L-2.294 2.294L-6.883 0L-2.294-2.294Z";
paths[22] = "M0-10.706L3.569-3.569L10.707 0L3.569 3.569L0 10.707L-3.569 3.569L-10.706 0L-3.569-3.569Z";
paths[23] = "M0-14.53L4.843-4.843L14.53 0L4.843 4.843L0 14.53L-4.843 4.843L-14.53 0L-4.843-4.843Z";
// Shield
paths[24] = "M-2.558-2.558H2.558V0L0 2.558L-2.558 0Z";
paths[25] = "M-4.605-4.605H4.605V0L0 4.605L-4.605 0Z";
paths[26] = "M-7.163-7.163H7.163V0L0 7.163L-7.163 0Z";
paths[27] = "M-9.721-9.721H9.721V0L0 9.721L-9.721 0Z";
// Capsule
paths[28] = "M-1.655-1.655H1.655A1.655 1.655 0 0 1 1.655 1.655H-1.655A1.655 1.655 0 0 1-1.655-1.655Z";
paths[29] = "M-2.979-2.979H2.979A2.979 2.979 0 0 1 2.979 2.979H-2.979A2.979 2.979 0 0 1-2.979-2.979Z";
paths[30] = "M-4.634-4.634H4.634A4.634 4.634 0 0 1 4.634 4.634H-4.634A4.634 4.634 0 0 1-4.634-4.634Z";
paths[31] = "M-6.289-6.289H6.289A6.289 6.289 0 0 1 6.289 6.289H-6.289A6.289 6.289 0 0 1-6.289-6.289Z";
// Crown
paths[32] = "M-2.427 2.427V-1L-2-2.427L-1-1L0-2.427L1-1L2-2.427L2.427-1V2.427Z";
paths[33] = "M-4.369 4.369V-1.456L-2.912-4.369L-1.456-1.456L0-4.369L1.456-1.456L2.912-4.369L4.369-1.456V4.369Z";
paths[34] = "M-6.796 6.796V-2.265L-4.53-6.796L-2.265-2.265L0-6.796L2.265-2.265L4.53-6.796L6.796-2.265V6.796Z";
paths[35] = "M-9.223 9.223V-3.074L-6.148-9.223L-3.074-3.074L0-9.223L3.074-3.074L6.148-9.223L9.223-3.074V9.223Z";
// Heart
paths[36] = "M0 3.008L-3.008 0Q-3.008-3.008 0-1.504Q3.008-3.008 3.008 0Z";
paths[37] = "M0 5.414L-5.413 0Q-5.413-5.413 0-2.707Q5.414-5.413 5.414 0Z";
paths[38] = "M0 8.421L-8.421 0Q-8.421-8.421 0-4.211Q8.421-8.421 8.421 0Z";
paths[39] = "M0 11.429L-11.429 0Q-11.429-11.429 0-5.714Q11.429-11.429 11.429 0Z";
// Teardrop
paths[40] = "M0-2.906Q2.906 0 1.453 2.906Q0 5.813-1.453 2.906Q-2.906 0 0-2.906Z";
paths[41] = "M0-5.231Q5.231 0 2.616 5.231Q0 10.463-2.616 5.231Q-5.231 0 0-5.231Z";
paths[42] = "M0-8.138Q8.138 0 4.069 8.138Q0 16.275-4.069 8.138Q-8.138 0 0-8.138Z";
paths[43] = "M0-11.044Q11.044 0 5.522 11.044Q0 22.088-5.522 11.044Q-11.044 0 0-11.044Z";
// Lightning Bolt
paths[44] = "M1.307-3.922L-3.922 1.307H-1.307L-1.961 3.923L3.923-1.307H1.307Z";
paths[45] = "M2.354-7.06L-7.06 2.354H-2.353L-3.53 7.06L7.06-2.353H2.354Z";
paths[46] = "M3.661-10.983L-10.983 3.661H-3.661L-5.491 10.983L10.983-3.661H3.661Z";
paths[47] = "M4.969-14.905L-14.905 4.969H-4.968L-7.453 14.906L14.906-4.968H4.969Z";
// Clover
paths[48] = "M0 0Q-2.73-2.73 0-2.73T0 0Q2.73-2.73 2.73 0T0 0Q2.73 2.73 0 2.73T0 0Q-2.73 2.73-2.73 0T0 0Z";
paths[49] = "M0 0Q-4.914-4.914 0-4.914T0 0Q4.914-4.914 4.914 0T0 0Q4.914 4.914 0 4.914T0 0Q-4.914 4.914-4.914 0T0 0Z";
paths[50] = "M0 0Q-7.644-7.644 0-7.644T0 0Q7.644-7.644 7.644 0T0 0Q7.644 7.644 0 7.644T0 0Q-7.644 7.644-7.644 0T0 0Z";
paths[51] = "M0 0Q-10.374-10.374 0-10.374T0 0Q10.374-10.374 10.374 0T0 0Q10.374 10.374 0 10.374T0 0Q-10.374 10.374-10.374 0T0 0Z";
}
/// @dev 17 palettes x 3 colours (primary, secondary, accent), 3 bytes each.
function _palettes() private pure returns (bytes memory) {
return abi.encodePacked(
hex"7C3AED_A78BFA_4C1D95", // Void Violet
hex"22D3EE_67E8F9_0E7490", // Electric Cyan
hex"A3E635_D9F99D_4D7C0F", // Acid Lime
hex"FB923C_FDBA74_C2410C", // Orange CRT
hex"F472B6_FBCFE8_BE185D", // Hot Magenta
hex"EF4444_FCA5A5_991B1B", // Reactor Red
hex"F8FAFC_CBD5E1_94A3B8", // Ice White
hex"FF3B30_34C759_0A84FF", // Spectral RGB
hex"F5C542_FFE08A_B8860B", // Gold
hex"7C3AED_22D3EE_F472B6", // Spectral Void Violet
hex"22D3EE_A3E635_7C3AED", // Spectral Electric Cyan
hex"A3E635_FB923C_22D3EE", // Spectral Acid Lime
hex"FB923C_F472B6_F5C542", // Spectral Orange CRT
hex"F472B6_7C3AED_22D3EE", // Spectral Hot Magenta
hex"EF4444_F5C542_7C3AED", // Spectral Reactor Red
hex"F8FAFC_22D3EE_F472B6", // Spectral Ice White
hex"F5C542_EF4444_A3E635" // Spectral Gold
);
}
function _list5(string memory a, string memory b, string memory c, string memory d, string memory e)
private
pure
returns (string[] memory list)
{
list = new string[](5);
list[0] = a;
list[1] = b;
list[2] = c;
list[3] = d;
list[4] = e;
}
function _list6(
string memory a,
string memory b,
string memory c,
string memory d,
string memory e,
string memory f
) private pure returns (string[] memory list) {
list = new string[](6);
list[0] = a;
list[1] = b;
list[2] = c;
list[3] = d;
list[4] = e;
list[5] = f;
}
}
/// @title SqueekArtPageDeployer
/// @notice Writes a page as the immutable runtime code of a data contract (STOP byte followed by the page),
/// so the renderer reads it with `EXTCODECOPY` and the collection can pin it by code hash.
contract SqueekArtPageDeployer {
string public constant web = "https://squeekchain.com/";
string public constant X = "https://x.com/squeekchain";
error PageTooLarge(uint256 length);
error DeploymentFailed();
event ArtPageDeployed(address indexed page, bytes32 indexed pageHash, uint256 length);
/// @notice Deploys the canonical Squeek art page.
function deployCanonical() external returns (address page) {
page = deploy(SqueekArtPage.build());
}
/// @notice Deploys an arbitrary page as a data contract.
function deploy(bytes memory data) public returns (address page) {
if (data.length > 24_575) revert PageTooLarge(data.length);
// 600B 59 81 38 03 80 92 59 39 F3 : copy everything after this 11-byte header and return it as code.
bytes memory initCode = abi.encodePacked(hex"600B5981380380925939F3", hex"00", data);
// SAFETY: plain CREATE of immutable data; failure is surfaced through DeploymentFailed.
assembly ("memory-safe") {
page := create(0, add(initCode, 0x20), mload(initCode))
}
if (page == address(0)) revert DeploymentFailed();
emit ArtPageDeployed(page, keccak256(data), data.length);
}
}
src/art/SqueekArtValidator.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
import { ISqueekArtValidator } from "../interfaces/ISqueekRenderer.sol";
import { ArtPage, SqueekArtPage } from "./SqueekArtPage.sol";
/// @title SqueekArtValidator
/// @notice Immutable format checks for "DGPG" art pages. Returns the page hash (keccak of the page bytes)
/// and the asset-set hash (keccak over the asset-set id, glyph paths and palettes).
contract SqueekArtValidator is ISqueekArtValidator {
string public constant web = "https://squeekchain.com/";
string public constant X = "https://x.com/squeekchain";
error EmptyPage(address page);
error InvalidMagic(bytes4 actual);
error InvalidTraitCount(uint256 actual);
error InvalidTraitValues(uint256 trait, uint256 actual);
error InvalidGlyphCount(uint256 actual);
error InvalidPaletteBytes(uint256 actual);
bytes32 private constant ASSET_SET_ID = keccak256("sqk.dotgrid-asset-set.v1");
uint256 private constant TRAIT_COUNT = 11;
uint256 private constant GLYPH_COUNT = 13;
uint256 private constant GLYPH_SIZES = 4;
uint256 private constant PALETTE_COUNT = 17;
function assetSetId() external pure returns (bytes32) {
return ASSET_SET_ID;
}
/// @notice Reads and validates a page, returning its commitments.
function validatePage(address artPage) external view returns (bytes32 pageHash, bytes32 assetSetHash) {
bytes memory raw = readRaw(artPage);
ArtPage memory page = _decode(raw);
_check(page);
pageHash = keccak256(raw);
assetSetHash = keccak256(abi.encode(ASSET_SET_ID, page.glyphPaths, page.palettes));
}
/// @notice Reads and decodes a page (reverts on malformed pages).
function readPage(address artPage) external view returns (ArtPage memory page) {
page = _decode(readRaw(artPage));
_check(page);
}
/// @notice Returns the raw page bytes (runtime code without the leading STOP byte).
function readRaw(address artPage) public view returns (bytes memory raw) {
uint256 size = artPage.code.length;
if (size < 2) revert EmptyPage(artPage);
raw = new bytes(size - 1);
// SAFETY: copies code[1..size) into the freshly allocated buffer.
assembly ("memory-safe") {
extcodecopy(artPage, add(raw, 0x20), 1, sub(size, 1))
}
}
function _decode(bytes memory raw) private pure returns (ArtPage memory page) {
if (raw.length < 4) revert InvalidMagic(bytes4(0));
bytes4 magic = bytes4(raw);
if (magic != SqueekArtPage.MAGIC) revert InvalidMagic(magic);
bytes memory body = new bytes(raw.length - 4);
// SAFETY: copies raw[4..] into body.
assembly ("memory-safe") {
mcopy(add(body, 0x20), add(raw, 0x24), mload(body))
}
page = abi.decode(body, (ArtPage));
}
function _check(ArtPage memory page) private pure {
if (page.traitNames.length != TRAIT_COUNT || page.traitValues.length != TRAIT_COUNT) {
revert InvalidTraitCount(page.traitNames.length);
}
for (uint256 trait; trait < TRAIT_COUNT; ++trait) {
uint256 count = page.traitValues[trait].length;
if (count == 0 || count > 255) revert InvalidTraitValues(trait, count);
}
if (page.traitValues[0].length != PALETTE_COUNT) revert InvalidTraitValues(0, page.traitValues[0].length);
for (uint256 trait = 2; trait <= 6; ++trait) {
if (page.traitValues[trait].length != GLYPH_COUNT) {
revert InvalidTraitValues(trait, page.traitValues[trait].length);
}
}
if (page.glyphPaths.length != GLYPH_COUNT * GLYPH_SIZES) revert InvalidGlyphCount(page.glyphPaths.length);
if (page.palettes.length != PALETTE_COUNT * 9) revert InvalidPaletteBytes(page.palettes.length);
}
}
src/interfaces/ISqueekRenderer.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.36;
/// @notice On-chain dot-grid renderer surface consumed by the collection.
interface ISqueekRenderer {
function rendererName() external pure returns (string memory);
function rendererId() external pure returns (bytes32);
function validator() external view returns (address);
function validatePage(address artPage) external view returns (bytes32 pageHash, bytes32 assetSetHash);
function traitWord(address artPage, bytes32 collectionSeed, uint256 tokenId) external view returns (bytes32);
function resolvedFieldHash(address artPage, bytes32 collectionSeed, uint256 tokenId)
external
view
returns (bytes32);
function tokenURI(address artPage, bytes32 collectionSeed, uint256 tokenId)
external
view
returns (string memory);
}
/// @notice Art page validator surface (immutable page format checks).
interface ISqueekArtValidator {
function assetSetId() external pure returns (bytes32);
function validatePage(address artPage) external view returns (bytes32 pageHash, bytes32 assetSetHash);
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@uniswap/v3-core/=lib/v3-core/",
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"v3-core/=lib/v3-core/contracts/"
],
"experimental": false
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.