Verified contractPartialApache-2.0
KohiPiece
Address0xe56522ebaf8e19c7e2b9468cbef8af14773f5f18
- Balance
0 ETH
- Transactions
28
- Compiler
solc 0.8.37
- Same code
Only this contract
Details
- Compiler
- solc 0.8.37+commit.f401782d
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- Apache-2.0
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,122,885
- Creation transaction
- 0x33e76756d5…5f9bf6bdb6
16 files
- src/player/KohiPiece.solmain27.3 KB
- lib/openzeppelin/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin/contracts/utils/Context.sol963 B
- lib/solady/src/tokens/ERC2981.sol6.87 KB
- lib/solady/src/tokens/ERC721.sol40 KB
- lib/solady/src/utils/ECDSA.sol20.2 KB
- lib/solady/src/utils/EIP712.sol13.69 KB
- lib/solady/src/utils/SignatureCheckerLib.sol25.76 KB
- src/Attributes.sol16.46 KB
- src/IKVMTraitsRunner.sol2.25 KB
- src/RegistryOwnable.sol1.93 KB
- src/SSTORE2.sol2.02 KB
- src/StreamStore.sol5.22 KB
- src/player/IKohiPiece.sol5.84 KB
- src/player/IKohiTokenURI.sol2.51 KB
src/player/KohiPiece.sol
// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
pragma solidity ^0.8.24;
import {ERC721} from "solady/tokens/ERC721.sol";
import {ERC2981} from "solady/tokens/ERC2981.sol";
import {EIP712} from "solady/utils/EIP712.sol";
import {ECDSA} from "solady/utils/ECDSA.sol";
import {SignatureCheckerLib} from "solady/utils/SignatureCheckerLib.sol";
import "../RegistryOwnable.sol";
import "../StreamStore.sol";
import "../Attributes.sol";
import "../IKVMTraitsRunner.sol";
import {IKohiPiece, KohiRenderPath} from "./IKohiPiece.sol";
import {IKohiTokenURI} from "./IKohiTokenURI.sol";
/* =============================================================================
* KOHIPIECE · a generative artwork stored on chain as one program and its seeds
* =============================================================================
*
* THE PROBLEM. Many NFTs keep their artwork off chain. The token holds a link,
* and the link can break or change. A KohiPiece keeps the artwork itself on chain
* as a short program. Any reader can rebuild every image from chain state
* alone.
*
* HOW IT WORKS. The program is for the KVM, a bytecode virtual machine for
* generative art. This contract stores the program. Each token is that
* program run with one seed. A seed is a number that makes one run differ
* from another. The artist chooses all the seeds before any token exists, so
* every token is a chosen work. The supply is fixed at deployment.
*
* kohiProgram() returns the program. kohiSeed(id) returns the seed of one
* token. kohiRenderPath() names the contracts that make the image. The
* interpreter runs the program to a draw stream. The renderer of the piece's
* family turns the draw stream into pixels. Anyone can render any token with
* view calls.
*
* THE TRUST BOUNDARY. One account, the owner (the artist), controls the
* contract. Ownership moves in two steps and cannot be renounced. The locks
* below end each power for good.
*
* WHAT THE OWNER CAN DO, AND WHEN IT STOPS.
* - Before lockArt(): write the program, the params, the trait names and the
* description. lockArt() freezes all four forever.
* - Before lockSeeds(): set the seeds. lockSeeds() needs exactly maxSupply
* seeds. It freezes them forever.
* - mintTo() mints in token order (id 1 gets seed 1). It works only after
* both locks, so no token exists before its artwork and seed are final.
* The supply cannot grow.
* - Before lockTokenURI(): choose the tokenURI module. This is the contract
* that writes the metadata of each token. lockTokenURI() freezes the
* choice. A module changes how the metadata looks. It cannot change the
* artwork.
* - Before lockContractURI(): set the collection metadata (ERC-7572).
* lockContractURI() freezes it.
* - Once, after both locks: record the creator (ERC-7015). The creator signs
* the program hash and the seeds hash as EIP-712 typed data. The
* attribution therefore names this exact artwork. This contract checks the
* signature. A signature from the key of the account passes. If it does
* not match, the contract asks the account through ERC-1271. An account
* with an EIP-7702 delegation has code. Its own key still signs for it.
* - Set the default royalty (ERC-2981). This is never locked.
*
* WHAT IS PERMANENT. The constructor fixes the name, the symbol, the supply
* and the render path. The contract has no upgrade path and no self-destruct.
* The owner has no function that moves a token. Token holders move their own
* tokens under the ERC-721 rules.
*
* Every change to the tokenURI module emits the ERC-4906 BatchMetadataUpdate
* event, so marketplaces refresh the metadata.
*/
/// @title KohiPiece
/// @notice An ERC-721 collection whose artwork is a KVM program stored in the
/// contract, run once per token with a seed that the artist chose.
/// @dev Built on Solady ERC721, ERC2981 and EIP712 and on OpenZeppelin
/// Ownable2Step. The program is stored in SSTORE2 chunks. Locks are
/// one-way flags with no unlock function.
contract KohiPiece is ERC721, ERC2981, EIP712, RegistryOwnable, IKohiPiece {
/// @notice The number of tokens. It cannot change.
uint256 public immutable maxSupply;
/// @notice The rasterizer family the program is drawn for (0 to 5).
uint8 public immutable family;
/// @notice The noise kind the program uses: 0 NoiseV1, 1 GradNoise.
uint8 public immutable noiseKind;
/// @notice The EIP-712 type hash of the message that the creator signs for
/// ERC-7015.
bytes32 public constant ARTWORK_CREATION_TYPEHASH =
keccak256("ArtworkCreation(bytes32 programHash,bytes32 seedsHash)");
/// @notice The one-shot interpreter (KVMRunner).
address public immutable runner;
/// @notice The stepped interpreter, for renders larger than one call.
address public immutable stepRunner;
/// @notice The renderer of the piece's family.
address public immutable renderer;
/// @notice The traits-only interpreter that kohiAttributes reads.
address public immutable traitsRunner;
/// @dev The collection name. Also the EIP-712 domain name.
string internal _name;
/// @dev The collection symbol.
string internal _symbol;
/// @dev The SSTORE2 contracts that hold the program, in order.
address[] internal _programPtrs;
/// @dev The PARAM slot values. Slot i is _params[i].
int64[] internal _params;
/// @dev The display metadata of each trait.
Attributes.TraitMeta[] internal _traitMeta;
/// @dev The description of the piece.
string internal _description;
/// @dev The seeds. _seeds[i] is the seed of token i + 1.
int32[] internal _seeds;
/// @dev The collection metadata URI (ERC-7572).
string internal _contractURI;
/// @notice True after lockArt(): the program, params, traits and
/// description are final.
bool public artLocked;
/// @notice True after lockSeeds(): the seeds are final.
bool public seedsLocked;
/// @notice True after lockTokenURI(): the tokenURI module is final.
bool public tokenURILocked;
/// @notice True after lockContractURI(): the collection metadata is final.
bool public contractURILocked;
/// @notice keccak256 of the program, set by lockArt().
bytes32 public programHash;
/// @notice keccak256(abi.encodePacked(seeds)), set by lockSeeds().
bytes32 public seedsHash;
/// @notice The attributed creator (ERC-7015), or zero before attribution.
address public creator;
/// @notice The module that writes each token's metadata.
IKohiTokenURI public tokenURIModule;
/// @notice The number of tokens minted.
uint256 public totalSupply;
/// @notice Program bytes were added.
/// @param chunks The number of SSTORE2 contracts written.
/// @param bytesAdded The number of program bytes added.
event ProgramChunksAdded(uint256 chunks, uint256 bytesAdded);
/// @notice The program was removed.
event ProgramCleared();
/// @notice The PARAM slot values were set.
/// @param count The number of slot values.
event ParamsSet(uint256 count);
/// @notice The display metadata of a trait was added.
/// @param id The TRAIT record id.
/// @param name The trait name.
event TraitAdded(uint8 id, string name);
/// @notice All trait metadata was removed.
event TraitsCleared();
/// @notice The description was set.
/// @param description The description.
event DescriptionSet(string description);
/// @notice The program, params, traits and description are now final.
/// @param programHash The keccak256 of the program.
event ArtLocked(bytes32 programHash);
/// @notice The seed list was set.
/// @param count The number of seeds.
event SeedsSet(uint256 count);
/// @notice The seeds are now final.
/// @param seedsHash The keccak256 of the packed seeds.
event SeedsLocked(bytes32 seedsHash);
/// @notice The tokenURI module was set.
/// @param module The module address.
event TokenURIModuleSet(address module);
/// @notice The tokenURI module is now final.
/// @param module The module address.
event TokenURILocked(address module);
/// @notice The collection metadata URI changed (ERC-7572).
event ContractURIUpdated();
/// @notice The collection metadata URI is now final.
event ContractURILocked();
/// @notice The creator of the artwork was recorded (ERC-7015).
/// @param structHash The EIP-712 struct hash that the creator signed.
/// @param domainName The EIP-712 domain name, which is the collection name.
/// @param version The EIP-712 domain version.
/// @param creator The creator account.
/// @param signature The creator signature.
event CreatorAttribution(bytes32 structHash, string domainName, string version, address creator, bytes signature);
/// @notice The metadata of a range of tokens changed (ERC-4906).
/// @param _fromTokenId The first token of the range.
/// @param _toTokenId The last token of the range.
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
/// @notice The program, params, traits and description are final.
error ArtIsLocked();
/// @notice The art is not final yet.
error ArtNotLocked();
/// @notice The seeds are final.
error SeedsAreLocked();
/// @notice The seeds are not final yet.
error SeedsNotLocked();
/// @notice The seed count is wrong.
/// @param count The seed count that was found.
error BadSeedCount(uint256 count);
/// @notice The mint is past maxSupply.
error SupplyExceeded();
/// @notice The tokenURI module is final.
error TokenURIIsLocked();
/// @notice No tokenURI module is set.
error NoTokenURIModule();
/// @notice The program has no bytes.
error EmptyProgram();
/// @notice No trait metadata is set.
error NoTraits();
/// @notice The text has a quote, a backslash or a control byte.
error UnsafeText();
/// @notice The collection metadata URI is final.
error ContractURIIsLocked();
/// @notice The creator is already recorded.
error AlreadyAttributed();
/// @notice The creator signature is not valid, or the creator is zero.
error BadSignature();
/// @notice The constructor arguments are not valid.
error BadConfig();
/// @notice Deploy a piece with its name, supply and render path.
/// @dev Reverts BadConfig if maxSupply_ is zero, the family is above 5, or
/// the noise kind is above 1.
/// @param owner_ The owner (the artist).
/// @param name_ The collection name; token names are "<name> #<id>".
/// @param symbol_ The collection symbol.
/// @param maxSupply_ The number of tokens, and of seeds.
/// @param path The family, noise kind, interpreter, stepped
/// interpreter and renderer.
/// @param traitsRunner_ The traits-only interpreter.
constructor(
address owner_,
string memory name_,
string memory symbol_,
uint256 maxSupply_,
KohiRenderPath memory path,
address traitsRunner_
) RegistryOwnable(owner_) {
if (maxSupply_ == 0 || path.family > 5 || path.noiseKind > 1) revert BadConfig();
_name = name_;
_symbol = symbol_;
maxSupply = maxSupply_;
family = path.family;
noiseKind = path.noiseKind;
runner = path.runner;
stepRunner = path.stepRunner;
renderer = path.renderer;
traitsRunner = traitsRunner_;
}
/// @dev Reverts ArtIsLocked after lockArt().
modifier whileArtOpen() {
if (artLocked) revert ArtIsLocked();
_;
}
// ---- the artwork (owner, until lockArt) ---------------------------------
/// @notice Append bytes to the program.
/// @dev One SSTORE2 contract holds at most 24,575 bytes. This function
/// splits the bytes across as many contracts as it needs. Owner only.
/// Reverts ArtIsLocked after lockArt().
/// @param data The next part of the program.
function appendProgram(bytes calldata data) external onlyOwner whileArtOpen {
address[] memory ptrs = StreamStore.writeChunks(data);
for (uint256 i = 0; i < ptrs.length; i++) _programPtrs.push(ptrs[i]);
emit ProgramChunksAdded(ptrs.length, data.length);
}
/// @notice Remove the whole program, to write it again.
/// @dev Owner only. Reverts ArtIsLocked after lockArt().
function clearProgram() external onlyOwner whileArtOpen {
delete _programPtrs;
emit ProgramCleared();
}
/// @notice Set the PARAM slot values that the program reads.
/// @dev Owner only. Reverts ArtIsLocked after lockArt().
/// @param params The raw 64-bit slot values; slot i is params[i].
function setParams(int64[] calldata params) external onlyOwner whileArtOpen {
_params = params;
emit ParamsSet(params.length);
}
/// @notice Add the display metadata of one trait the program emits.
/// @dev Owner only. Reverts ArtIsLocked after lockArt(). Reverts UnsafeText
/// for a name or label with a quote, a backslash or a control byte.
/// @param id The TRAIT record id.
/// @param kind 0 number, 1 choice, 2 flag, 3 value.
/// @param hidden True to omit the trait from the attributes.
/// @param decimals The decimal places for kind 3.
/// @param traitName The trait name (trait_type).
/// @param labels The label of each value, for kinds 1 and 2.
function addTrait(
uint8 id,
uint8 kind,
bool hidden,
uint8 decimals,
string calldata traitName,
string[] calldata labels
) external onlyOwner whileArtOpen {
_requireSafeText(traitName);
Attributes.TraitMeta storage m = _traitMeta.push();
m.id = id;
m.kind = kind;
m.hidden = hidden;
m.decimals = decimals;
m.name = traitName;
for (uint256 i = 0; i < labels.length; i++) {
_requireSafeText(labels[i]);
m.labels.push(labels[i]);
}
emit TraitAdded(id, traitName);
}
/// @notice Remove every trait, to add them again.
/// @dev Owner only. Reverts ArtIsLocked after lockArt().
function clearTraits() external onlyOwner whileArtOpen {
delete _traitMeta;
emit TraitsCleared();
}
/// @notice Set the description of the piece.
/// @dev Owner only. Reverts ArtIsLocked after lockArt(). Reverts UnsafeText
/// for a quote, a backslash or a control byte.
/// @param description The description.
function setDescription(string calldata description) external onlyOwner whileArtOpen {
_requireSafeText(description);
_description = description;
emit DescriptionSet(description);
}
/// @notice Freeze the program, params, traits and description forever.
/// @dev Owner only. Reverts ArtIsLocked if the art is already locked.
/// Reverts EmptyProgram if no program is set. Reverts NoTraits if no
/// trait is set. The ArtLocked event carries the keccak256 of the
/// program.
function lockArt() external onlyOwner whileArtOpen {
if (_programPtrs.length == 0) revert EmptyProgram();
if (_traitMeta.length == 0) revert NoTraits();
artLocked = true;
programHash = keccak256(StreamStore.readChunks(_programPtrs));
emit ArtLocked(programHash);
}
// ---- the seeds (owner, until lockSeeds) ---------------------------------
/// @notice Set the curated seeds. seeds[i] is the seed of token i + 1.
/// @dev Owner only. Replaces any earlier list. Reverts SeedsAreLocked after
/// lockSeeds(). Reverts BadSeedCount for more than maxSupply seeds.
/// @param seedList The seeds, in token order.
function setSeeds(int32[] calldata seedList) external onlyOwner {
if (seedsLocked) revert SeedsAreLocked();
if (seedList.length > maxSupply) revert BadSeedCount(seedList.length);
_seeds = seedList;
emit SeedsSet(seedList.length);
}
/// @notice Freeze the seeds forever.
/// @dev Owner only. Reverts SeedsAreLocked if the seeds are already locked.
/// Reverts BadSeedCount unless exactly maxSupply seeds are set. The
/// SeedsLocked event carries keccak256(abi.encodePacked(seeds)).
function lockSeeds() external onlyOwner {
if (seedsLocked) revert SeedsAreLocked();
if (_seeds.length != maxSupply) revert BadSeedCount(_seeds.length);
seedsLocked = true;
seedsHash = keccak256(abi.encodePacked(_seeds));
emit SeedsLocked(seedsHash);
}
/// @notice The curated seed list, in token order.
/// @return The seeds. Entry i is the seed of token i + 1.
function seeds() external view returns (int32[] memory) {
return _seeds;
}
// ---- minting ------------------------------------------------------------
/// @notice Mint the next `count` tokens to `to`, in token order.
/// @dev Owner only. Reverts ArtNotLocked before lockArt(). Reverts
/// SeedsNotLocked before lockSeeds(). Reverts SupplyExceeded if the
/// mint passes maxSupply. The first token minted is id 1.
/// @param to The recipient.
/// @param count The number of tokens to mint.
function mintTo(address to, uint256 count) external onlyOwner {
if (!artLocked) revert ArtNotLocked();
if (!seedsLocked) revert SeedsNotLocked();
uint256 next = totalSupply;
if (next + count > maxSupply) revert SupplyExceeded();
for (uint256 i = 1; i <= count; i++) _mint(to, next + i);
totalSupply = next + count;
}
// ---- metadata -----------------------------------------------------------
/// @notice Choose the module that writes each token's metadata.
/// @dev Owner only. Reverts TokenURIIsLocked after lockTokenURI(). Emits
/// BatchMetadataUpdate for every token id, 1 to maxSupply. The owner
/// can set the zero address. tokenURI() then reverts NoTokenURIModule.
/// @param module The module.
function setTokenURIModule(IKohiTokenURI module) external onlyOwner {
if (tokenURILocked) revert TokenURIIsLocked();
tokenURIModule = module;
emit TokenURIModuleSet(address(module));
emit BatchMetadataUpdate(1, maxSupply);
}
/// @notice Freeze the tokenURI module forever.
/// @dev Owner only. Reverts TokenURIIsLocked if it is already locked.
/// Reverts NoTokenURIModule if no module is set.
function lockTokenURI() external onlyOwner {
if (tokenURILocked) revert TokenURIIsLocked();
if (address(tokenURIModule) == address(0)) revert NoTokenURIModule();
tokenURILocked = true;
emit TokenURILocked(address(tokenURIModule));
}
/// @notice Set the collection metadata URI (ERC-7572).
/// @dev Owner only. Reverts ContractURIIsLocked after lockContractURI().
/// Emits ContractURIUpdated.
/// @param uri The URI of the collection JSON.
function setContractURI(string calldata uri) external onlyOwner {
if (contractURILocked) revert ContractURIIsLocked();
_contractURI = uri;
emit ContractURIUpdated();
}
/// @notice Freeze the collection metadata URI forever.
/// @dev Owner only. Reverts ContractURIIsLocked if it is already locked.
function lockContractURI() external onlyOwner {
if (contractURILocked) revert ContractURIIsLocked();
contractURILocked = true;
emit ContractURILocked();
}
/// @notice The collection metadata URI (ERC-7572).
/// @return The URI of the collection JSON.
function contractURI() external view returns (string memory) {
return _contractURI;
}
/// @notice Record the creator of the artwork (ERC-7015). Once only.
/// @dev Owner only, after lockArt() and lockSeeds(). `signature` is the
/// EIP-712 signature of the creator for ArtworkCreation(programHash,
/// seedsHash). The domain is the name, "1", the chain id and the
/// address of this contract. The check first recovers the signer from
/// the signature. If that is not creator_, the check asks creator_
/// through ERC-1271. Reverts ArtNotLocked or SeedsNotLocked before
/// the locks. Reverts AlreadyAttributed if a creator is recorded.
/// Reverts BadSignature if creator_ is zero or the signature is not
/// valid.
/// @param creator_ The account of the creator.
/// @param signature The signature of the creator.
function attributeCreator(address creator_, bytes calldata signature) external onlyOwner {
if (!artLocked) revert ArtNotLocked();
if (!seedsLocked) revert SeedsNotLocked();
if (creator != address(0)) revert AlreadyAttributed();
if (creator_ == address(0)) revert BadSignature();
bytes32 structHash = keccak256(abi.encode(ARTWORK_CREATION_TYPEHASH, programHash, seedsHash));
bytes32 digest = _hashTypedData(structHash);
if (
ECDSA.tryRecoverCalldata(digest, signature) != creator_
&& !SignatureCheckerLib.isValidERC1271SignatureNowCalldata(creator_, digest, signature)
) revert BadSignature();
creator = creator_;
emit CreatorAttribution(structHash, _name, "1", creator_, signature);
}
/// @notice Set the default royalty (ERC-2981).
/// @dev Owner only. Nothing locks it. The Solady ERC2981 base reverts for
/// a zero receiver or a fee above 10,000.
/// @param receiver The royalty receiver.
/// @param feeNumerator The fee in basis points of 10,000.
function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
_setDefaultRoyalty(receiver, feeNumerator);
}
/// @notice The metadata URI of a token. The tokenURI module writes it.
/// @dev Reverts TokenDoesNotExist for a token that is not minted. Reverts
/// NoTokenURIModule if no module is set.
/// @param id The token.
/// @return The metadata URI.
function tokenURI(uint256 id) public view override returns (string memory) {
if (!_exists(id)) revert TokenDoesNotExist();
if (address(tokenURIModule) == address(0)) revert NoTokenURIModule();
return tokenURIModule.tokenURI(this, id);
}
/// @notice The collection name.
/// @return The name.
function name() public view override returns (string memory) {
return _name;
}
/// @notice The collection symbol.
/// @return The symbol.
function symbol() public view override returns (string memory) {
return _symbol;
}
/// @dev The EIP-712 domain name and version.
function _domainNameAndVersion() internal view override returns (string memory, string memory) {
return (_name, "1");
}
/// @dev The constructor body sets the name after the EIP712 constructor
/// would have cached it. The domain is therefore computed on each use.
function _domainNameAndVersionMayChange() internal pure override returns (bool) {
return true;
}
// ---- IKohiPiece ---------------------------------------------------------
/// @inheritdoc IKohiPiece
function kohiProgram() external view returns (bytes memory) {
return StreamStore.readChunks(_programPtrs);
}
/// @inheritdoc IKohiPiece
function kohiParams() external view returns (int64[] memory) {
return _params;
}
/// @inheritdoc IKohiPiece
function kohiSeed(uint256 tokenId) public view returns (int32) {
if (!_exists(tokenId)) revert KohiNoSuchToken(tokenId);
return _seeds[tokenId - 1];
}
/// @inheritdoc IKohiPiece
function kohiRenderPath() external view returns (KohiRenderPath memory) {
return KohiRenderPath({
family: family,
noiseKind: noiseKind,
runner: runner,
stepRunner: stepRunner,
renderer: renderer
});
}
/// @inheritdoc IKohiPiece
function kohiName(uint256 tokenId) external view returns (string memory) {
if (!_exists(tokenId)) revert KohiNoSuchToken(tokenId);
return string.concat(_name, " #", _decimal(tokenId));
}
/// @inheritdoc IKohiPiece
function kohiDescription() external view returns (string memory) {
return _description;
}
/// @inheritdoc IKohiPiece
/// @dev Runs the program on the traits-only interpreter. The run stops
/// after the last TRAIT record the traits metadata declares, before
/// the program draws, so it costs a small part of a full render.
function kohiAttributes(uint256 tokenId) external view returns (string memory) {
int32 seed = kohiSeed(tokenId);
bytes memory stream =
IKVMTraitsRunner(traitsRunner).traitsOf(StreamStore.readChunks(_programPtrs), seed, _params, _traitMeta.length);
return Attributes.toJson(Attributes.extractTraits(stream), _traitMeta);
}
// ---- ERC-165 ------------------------------------------------------------
/// @notice ERC-165 support: ERC-721, ERC-2981, ERC-4906 and IKohiPiece.
/// @param interfaceId The interface id.
/// @return True if the contract supports the interface.
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool) {
return interfaceId == type(IKohiPiece).interfaceId || interfaceId == 0x49064906
|| ERC721.supportsInterface(interfaceId) || ERC2981.supportsInterface(interfaceId);
}
// ---- helpers ------------------------------------------------------------
/// @dev Reverts UnsafeText for a quote, a backslash or a control byte.
/// Such text would break the JSON that it is written into.
function _requireSafeText(string calldata s) internal pure {
bytes calldata b = bytes(s);
for (uint256 i = 0; i < b.length; i++) {
bytes1 c = b[i];
if (c == '"' || c == "\\" || uint8(c) < 0x20 || uint8(c) == 0x7f) revert UnsafeText();
}
}
/// @dev The decimal text of a number.
function _decimal(uint256 v) internal pure returns (string memory) {
if (v == 0) return "0";
bytes memory b;
while (v != 0) {
b = abi.encodePacked(bytes1(uint8(48 + v % 10)), b);
v /= 10;
}
return string(b);
}
}
lib/openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/solady/src/tokens/ERC2981.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC2981 NFT Royalty Standard implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC2981.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/common/ERC2981.sol)
abstract contract ERC2981 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The royalty fee numerator exceeds the fee denominator.
error RoyaltyOverflow();
/// @dev The royalty receiver cannot be the zero address.
error RoyaltyReceiverIsZeroAddress();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default royalty info is given by:
/// ```
/// let packed := sload(_ERC2981_MASTER_SLOT_SEED)
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
///
/// The per token royalty info is given by.
/// ```
/// mstore(0x00, tokenId)
/// mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
/// let packed := sload(keccak256(0x00, 0x40))
/// let receiver := shr(96, packed)
/// let royaltyFraction := xor(packed, shl(96, receiver))
/// ```
uint256 private constant _ERC2981_MASTER_SLOT_SEED = 0xaa4ec00224afccfdb7;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC2981 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Checks that `_feeDenominator` is non-zero.
constructor() {
require(_feeDenominator() != 0, "Fee denominator cannot be zero.");
}
/// @dev Returns the denominator for the royalty amount.
/// Defaults to 10000, which represents fees in basis points.
/// Override this function to return a custom amount if needed.
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC2981: 0x2a55205a.
result := or(eq(s, 0x01ffc9a7), eq(s, 0x2a55205a))
}
}
/// @dev Returns the `receiver` and `royaltyAmount` for `tokenId` sold at `salePrice`.
function royaltyInfo(uint256 tokenId, uint256 salePrice)
public
view
virtual
returns (address receiver, uint256 royaltyAmount)
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
let packed := sload(keccak256(0x00, 0x40))
receiver := shr(96, packed)
if iszero(receiver) {
packed := sload(mload(0x20))
receiver := shr(96, packed)
}
let x := salePrice
let y := xor(packed, shl(96, receiver)) // `feeNumerator`.
// Overflow check, equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
// Out-of-gas revert. Should not be triggered in practice, but included for safety.
returndatacopy(returndatasize(), returndatasize(), mul(y, gt(x, div(not(0), y))))
royaltyAmount := div(mul(x, y), feeDenominator)
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
sstore(_ERC2981_MASTER_SLOT_SEED, or(packed, feeNumerator))
}
}
/// @dev Sets the default royalty `receiver` and `feeNumerator` to zero.
function _deleteDefaultRoyalty() internal virtual {
/// @solidity memory-safe-assembly
assembly {
sstore(_ERC2981_MASTER_SLOT_SEED, 0)
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId`.
///
/// Requirements:
/// - `receiver` must not be the zero address.
/// - `feeNumerator` must not be greater than the fee denominator.
function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator)
internal
virtual
{
uint256 feeDenominator = _feeDenominator();
/// @solidity memory-safe-assembly
assembly {
feeNumerator := shr(160, shl(160, feeNumerator))
if gt(feeNumerator, feeDenominator) {
mstore(0x00, 0x350a88b3) // `RoyaltyOverflow()`.
revert(0x1c, 0x04)
}
let packed := shl(96, receiver)
if iszero(packed) {
mstore(0x00, 0xb4457eaa) // `RoyaltyReceiverIsZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), or(packed, feeNumerator))
}
}
/// @dev Sets the royalty `receiver` and `feeNumerator` for `tokenId` to zero.
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, tokenId)
mstore(0x20, _ERC2981_MASTER_SLOT_SEED)
sstore(keccak256(0x00, 0x40), 0)
}
}
}
lib/solady/src/tokens/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC721 implementation with storage hitchhiking.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC721.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721/ERC721.sol)
///
/// @dev Note:
/// - The ERC721 standard allows for self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - For performance, methods are made payable where permitted by the ERC721 standard.
/// - The `safeTransfer` functions use the identity precompile (0x4)
/// to copy memory internally.
///
/// If you are overriding:
/// - NEVER violate the ERC721 invariant:
/// the balance of an owner MUST always be equal to their number of ownership slots.
/// The transfer functions do not have an underflow guard for user token balances.
/// - Make sure all variables written to storage are properly cleaned
/// (e.g. the bool value for `isApprovedForAll` MUST be either 1 or 0 under the hood).
/// - Check that the overridden function is actually used in the function you want to
/// change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC721 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev An account can hold up to 4294967295 tokens.
uint256 internal constant _MAX_ACCOUNT_BALANCE = 0xffffffff;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Only the token owner or an approved account can manage the token.
error NotOwnerNorApproved();
/// @dev The token does not exist.
error TokenDoesNotExist();
/// @dev The token already exists.
error TokenAlreadyExists();
/// @dev Cannot query the balance for the zero address.
error BalanceQueryForZeroAddress();
/// @dev Cannot mint or transfer to the zero address.
error TransferToZeroAddress();
/// @dev The token must be owned by `from`.
error TransferFromIncorrectOwner();
/// @dev The recipient's balance has overflowed.
error AccountBalanceOverflow();
/// @dev Cannot safely transfer to a contract that does not implement
/// the ERC721Receiver interface.
error TransferToNonERC721ReceiverImplementer();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when token `id` is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed id);
/// @dev Emitted when `owner` enables `account` to manage the `id` token.
event Approval(address indexed owner, address indexed account, uint256 indexed id);
/// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.
event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);
/// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
uint256 private constant _TRANSFER_EVENT_SIGNATURE =
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
/// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
uint256 private constant _APPROVAL_EVENT_SIGNATURE =
0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;
/// @dev `keccak256(bytes("ApprovalForAll(address,address,bool)"))`.
uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =
0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership data slot of `id` is given by:
/// ```
/// mstore(0x00, id)
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
/// ```
/// Bits Layout:
/// - [0..159] `addr`
/// - [160..255] `extraData`
///
/// The approved address slot is given by: `add(1, ownershipSlot)`.
///
/// See: https://notes.ethereum.org/%40vbuterin/verkle_tree_eip
///
/// The balance slot of `owner` is given by:
/// ```
/// mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x1c)
/// ```
/// Bits Layout:
/// - [0..31] `balance`
/// - [32..255] `aux`
///
/// The `operator` approval slot of `owner` is given by:
/// ```
/// mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
/// mstore(0x00, owner)
/// let operatorApprovalSlot := keccak256(0x0c, 0x30)
/// ```
uint256 private constant _ERC721_MASTER_SLOT_SEED = 0x7d8825530a5a2e7a << 192;
/// @dev Pre-shifted and pre-masked constant.
uint256 private constant _ERC721_MASTER_SLOT_SEED_MASKED = 0x0a5a2e7a00000000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the token collection name.
function name() public view virtual returns (string memory);
/// @dev Returns the token collection symbol.
function symbol() public view virtual returns (string memory);
/// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
function tokenURI(uint256 id) public view virtual returns (string memory);
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC721 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function ownerOf(uint256 id) public view virtual returns (address result) {
result = _ownerOf(id);
/// @solidity memory-safe-assembly
assembly {
if iszero(result) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns the number of tokens owned by `owner`.
///
/// Requirements:
/// - `owner` must not be the zero address.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Revert if the `owner` is the zero address.
if iszero(owner) {
mstore(0x00, 0x8f4eb604) // `BalanceQueryForZeroAddress()`.
revert(0x1c, 0x04)
}
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := and(sload(keccak256(0x0c, 0x1c)), _MAX_ACCOUNT_BALANCE)
}
}
/// @dev Returns the account approved to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
function getApproved(uint256 id) public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
if iszero(shl(96, sload(ownershipSlot))) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
result := sload(add(1, ownershipSlot))
}
}
/// @dev Sets `account` as the approved account to manage token `id`.
///
/// Requirements:
/// - Token `id` must exist.
/// - The caller must be the owner of the token,
/// or an approved operator for the token owner.
///
/// Emits an {Approval} event.
function approve(address account, uint256 id) public payable virtual {
_approve(msg.sender, account, id);
}
/// @dev Returns whether `operator` is approved to manage the tokens of `owner`.
function isApprovedForAll(address owner, address operator)
public
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x30))
}
}
/// @dev Sets whether `operator` is approved to manage the tokens of the caller.
///
/// Emits an {ApprovalForAll} event.
function setApprovalForAll(address operator, bool isApproved) public virtual {
/// @solidity memory-safe-assembly
assembly {
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`msg.sender`, `operator`).
mstore(0x1c, operator)
mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
// forgefmt: disable-next-item
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
}
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 id) public payable virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, caller()))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// Revert if the caller is not the owner, nor approved.
if iszero(or(eq(caller(), from), eq(caller(), approvedAddress))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `safeTransferFrom(from, to, id, "")`.
function safeTransferFrom(address from, address to, uint256 id) public payable virtual {
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
public
payable
virtual
{
transferFrom(from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Returns true if this contract implements the interface defined by `interfaceId`.
/// See: https://eips.ethereum.org/EIPS/eip-165
/// This function call must use less than 30000 gas.
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let s := shr(224, interfaceId)
// ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.
result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL QUERY FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if token `id` exists.
function _exists(uint256 id) internal view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := iszero(iszero(shl(96, sload(add(id, add(id, keccak256(0x00, 0x20)))))))
}
}
/// @dev Returns the owner of token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _ownerOf(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(96, shl(96, sload(add(id, add(id, keccak256(0x00, 0x20))))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL DATA HITCHHIKING FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance, no events are emitted for the hitchhiking setters.
// Please emit your own events if required.
/// @dev Returns the auxiliary data for `owner`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _getAux(address owner) internal view virtual returns (uint224 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
result := shr(32, sload(keccak256(0x0c, 0x1c)))
}
}
/// @dev Set the auxiliary data for `owner` to `value`.
/// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
/// Auxiliary data can be set for any address, even if it does not have any tokens.
function _setAux(address owner, uint224 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
mstore(0x00, owner)
let balanceSlot := keccak256(0x0c, 0x1c)
let packed := sload(balanceSlot)
sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
}
}
/// @dev Returns the extra data for token `id`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _getExtraData(uint256 id) internal view virtual returns (uint96 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := shr(160, sload(add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Sets the extra data for token `id` to `value`.
/// Minting, transferring, burning a token will not change the extra data.
/// The extra data can be set on a non-existent token.
function _setExtraData(uint256 id, uint96 value) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let packed := sload(ownershipSlot)
sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed)))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 id) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Revert if the token already exists.
if shl(96, ownershipPacked) {
mstore(0x00, 0xc991cbb1) // `TokenAlreadyExists()`.
revert(0x1c, 0x04)
}
// Update with the owner.
sstore(ownershipSlot, or(ownershipPacked, to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Mints token `id` to `to`, and updates the extra data for token `id` to `value`.
/// Does NOT check if token `id` already exists (assumes `id` is auto-incrementing).
///
/// Requirements:
///
/// - `to` cannot be the zero address.
///
/// Emits a {Transfer} event.
function _mintAndSetExtraDataUnchecked(address to, uint256 id, uint96 value) internal virtual {
_beforeTokenTransfer(address(0), to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
to := shr(96, shl(96, to))
// Update with the owner and extra data.
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
sstore(add(id, add(id, keccak256(0x00, 0x20))), or(shl(160, value), to))
// Increment the balance of the owner.
{
mstore(0x00, to)
let balanceSlot := keccak256(0x0c, 0x1c)
let balanceSlotPacked := add(sload(balanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(balanceSlot, balanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
}
_afterTokenTransfer(address(0), to, id);
}
/// @dev Equivalent to `_safeMint(to, id, "")`.
function _safeMint(address to, uint256 id) internal virtual {
_safeMint(to, id, "");
}
/// @dev Mints token `id` to `to`.
///
/// Requirements:
///
/// - Token `id` must not exist.
/// - `to` cannot be the zero address.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeMint(address to, uint256 id, bytes memory data) internal virtual {
_mint(to, id);
if (_hasCode(to)) _checkOnERC721Received(address(0), to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_burn(address(0), id)`.
function _burn(uint256 id) internal virtual {
_burn(address(0), id);
}
/// @dev Destroys token `id`, using `by`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _burn(address by, uint256 id) internal virtual {
address owner = ownerOf(id);
_beforeTokenTransfer(owner, address(0), id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
// Reload the owner in case it is changed in `_beforeTokenTransfer`.
owner := shr(96, shl(96, ownershipPacked))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Load and check the token approval.
{
mstore(0x00, owner)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Clear the owner.
sstore(ownershipSlot, xor(ownershipPacked, owner))
// Decrement the balance of `owner`.
{
let balanceSlot := keccak256(0x0c, 0x1c)
sstore(balanceSlot, sub(sload(balanceSlot), 1))
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id)
}
_afterTokenTransfer(owner, address(0), id);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL APPROVAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `account` is the owner of token `id`, or is approved to manage it.
///
/// Requirements:
/// - Token `id` must exist.
function _isApprovedOrOwner(address account, uint256 id)
internal
view
virtual
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := 1
// Clear the upper 96 bits.
account := shr(96, shl(96, account))
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, account))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := shr(96, shl(96, sload(ownershipSlot)))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// Check if `account` is the `owner`.
if iszero(eq(account, owner)) {
mstore(0x00, owner)
// Check if `account` is approved to manage the token.
if iszero(sload(keccak256(0x0c, 0x30))) {
result := eq(account, sload(add(1, ownershipSlot)))
}
}
}
}
/// @dev Returns the account approved to manage token `id`.
/// Returns the zero address instead of reverting if the token does not exist.
function _getApproved(uint256 id) internal view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, id)
mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
result := sload(add(1, add(id, add(id, keccak256(0x00, 0x20)))))
}
}
/// @dev Equivalent to `_approve(address(0), account, id)`.
function _approve(address account, uint256 id) internal virtual {
_approve(address(0), account, id);
}
/// @dev Sets `account` as the approved account to manage token `id`, using `by`.
///
/// Requirements:
/// - Token `id` must exist.
/// - If `by` is not the zero address, `by` must be the owner
/// or an approved operator for the token owner.
///
/// Emits a {Approval} event.
function _approve(address by, address account, uint256 id) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
account := and(bitmaskAddress, account)
by := and(bitmaskAddress, by)
// Load the owner of the token.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let owner := and(bitmaskAddress, sload(ownershipSlot))
// Revert if the token does not exist.
if iszero(owner) {
mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
revert(0x1c, 0x04)
}
// If `by` is not the zero address, do the authorization check.
// Revert if `by` is not the owner, nor approved.
if iszero(or(iszero(by), eq(by, owner))) {
mstore(0x00, owner)
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Sets `account` as the approved account to manage `id`.
sstore(add(1, ownershipSlot), account)
// Emit the {Approval} event.
log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, owner, account, id)
}
}
/// @dev Approve or remove the `operator` as an operator for `by`,
/// without authorization checks.
///
/// Emits an {ApprovalForAll} event.
function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
by := shr(96, shl(96, by))
operator := shr(96, shl(96, operator))
// Convert to 0 or 1.
isApproved := iszero(iszero(isApproved))
// Update the `isApproved` for (`by`, `operator`).
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
mstore(0x00, by)
sstore(keccak256(0x0c, 0x30), isApproved)
// Emit the {ApprovalForAll} event.
mstore(0x00, isApproved)
log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, by, operator)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `_transfer(address(0), from, to, id)`.
function _transfer(address from, address to, uint256 id) internal virtual {
_transfer(address(0), from, to, id);
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
///
/// Emits a {Transfer} event.
function _transfer(address by, address from, address to, uint256 id) internal virtual {
_beforeTokenTransfer(from, to, id);
/// @solidity memory-safe-assembly
assembly {
// Clear the upper 96 bits.
let bitmaskAddress := shr(96, not(0))
from := and(bitmaskAddress, from)
to := and(bitmaskAddress, to)
by := and(bitmaskAddress, by)
// Load the ownership data.
mstore(0x00, id)
mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
let ownershipPacked := sload(ownershipSlot)
let owner := and(bitmaskAddress, ownershipPacked)
// Revert if the token does not exist, or if `from` is not the owner.
if iszero(mul(owner, eq(owner, from))) {
// `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
revert(0x1c, 0x04)
}
// Load, check, and update the token approval.
{
mstore(0x00, from)
let approvedAddress := sload(add(1, ownershipSlot))
// If `by` is not the zero address, do the authorization check.
// Revert if the `by` is not the owner, nor approved.
if iszero(or(iszero(by), or(eq(by, from), eq(by, approvedAddress)))) {
if iszero(sload(keccak256(0x0c, 0x30))) {
mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
revert(0x1c, 0x04)
}
}
// Delete the approved address if any.
if approvedAddress { sstore(add(1, ownershipSlot), 0) }
}
// Update with the new owner.
sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
// Decrement the balance of `from`.
{
let fromBalanceSlot := keccak256(0x0c, 0x1c)
sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
}
// Increment the balance of `to`.
{
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x1c)
let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
// Revert if `to` is the zero address, or if the account balance overflows.
if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
// `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
mstore(shl(2, iszero(to)), 0xea553b3401336cea)
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceSlotPacked)
}
// Emit the {Transfer} event.
log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
}
_afterTokenTransfer(from, to, id);
}
/// @dev Equivalent to `_safeTransfer(from, to, id, "")`.
function _safeTransfer(address from, address to, uint256 id) internal virtual {
_safeTransfer(from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - The caller must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(address(0), from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/// @dev Equivalent to `_safeTransfer(by, from, to, id, "")`.
function _safeTransfer(address by, address from, address to, uint256 id) internal virtual {
_safeTransfer(by, from, to, id, "");
}
/// @dev Transfers token `id` from `from` to `to`.
///
/// Requirements:
///
/// - Token `id` must exist.
/// - `from` must be the owner of the token.
/// - `to` cannot be the zero address.
/// - If `by` is not the zero address,
/// it must be the owner of the token, or be approved to manage the token.
/// - If `to` refers to a smart contract, it must implement
/// {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
///
/// Emits a {Transfer} event.
function _safeTransfer(address by, address from, address to, uint256 id, bytes memory data)
internal
virtual
{
_transfer(by, from, to, id);
if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS FOR OVERRIDING */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any token transfers, including minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {}
/// @dev Hook that is called after any token transfers, including minting and burning.
function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns if `a` has bytecode of non-zero length.
function _hasCode(address a) private view returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := extcodesize(a) // Can handle dirty upper bits.
}
}
/// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.
/// Reverts if the target does not support the function correctly.
function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)
private
{
/// @solidity memory-safe-assembly
assembly {
// Prepare the calldata.
let m := mload(0x40)
let onERC721ReceivedSelector := 0x150b7a02
mstore(m, onERC721ReceivedSelector)
mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.
mstore(add(m, 0x40), shr(96, shl(96, from)))
mstore(add(m, 0x60), id)
mstore(add(m, 0x80), 0x80)
let n := mload(data)
mstore(add(m, 0xa0), n)
if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }
// Revert if the call reverts.
if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {
if returndatasize() {
// Bubble up the revert if the call reverts.
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
}
// Load the returndata and compare it.
if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {
mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.
revert(0x1c, 0x04)
}
}
}
}
lib/solady/src/utils/ECDSA.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Gas optimized ECDSA wrapper.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
///
/// @dev Note:
/// - The recovery functions use the ecrecover precompile (0x1).
/// - As of Solady version 0.0.68, the `recover` variants will revert upon recovery failure.
/// This is for more safety by default.
/// Use the `tryRecover` variants if you need to get the zero address back
/// upon recovery failure instead.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT directly use signatures as unique identifiers:
/// - The recovery operations do NOT check if a signature is non-malleable.
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// - If you need a unique hash from a signature, please use the `canonicalHash` functions.
library ECDSA {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The order of the secp256k1 elliptic curve.
uint256 internal constant N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141;
/// @dev `N/2 + 1`. Used for checking the malleability of the signature.
uint256 private constant _HALF_N_PLUS_1 =
0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The signature is invalid.
error InvalidSignature();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RECOVERY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recover(bytes32 hash, bytes memory signature) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { continue }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { continue }
mstore(0x00, hash)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* TRY-RECOVER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// WARNING!
// These functions will NOT revert upon recovery failure.
// Instead, they will return the zero address upon recovery failure.
// It is critical that the returned address is NEVER compared against
// a zero address (e.g. an uninitialized address variable).
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecover(bytes32 hash, bytes memory signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { break }
mstore(0x00, hash)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CANONICAL HASH FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// The following functions return the hash of the signature in its canonicalized format,
// which is the 65-byte `abi.encodePacked(r, s, uint8(v))`, where `v` is either 27 or 28.
// If `s` is greater than `N / 2` then it will be converted to `N - s`
// and the `v` value will be flipped.
// If the signature has an invalid length, or if `v` is invalid,
// a uniquely corrupt hash will be returned.
// These functions are useful for "poor-mans-VRF".
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes memory signature) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let l := mload(signature)
for {} 1 {} {
mstore(0x00, mload(add(signature, 0x20))) // `r`.
let s := mload(add(signature, 0x40))
let v := mload(add(signature, 0x41))
if eq(l, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(l, 64), 2)) {
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(add(signature, 0x20), l), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHashCalldata(bytes calldata signature)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
mstore(0x00, calldataload(signature.offset)) // `r`.
let s := calldataload(add(signature.offset, 0x20))
let v := calldataload(add(signature.offset, 0x21))
if eq(signature.length, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(signature.length, 64), 2)) {
calldatacopy(mload(0x40), signature.offset, signature.length)
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(mload(0x40), signature.length), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes32 r, bytes32 vs) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
let v := add(shr(255, vs), 27)
let s := shr(1, shl(1, vs))
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(uint8 v, bytes32 r, bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
lib/solady/src/utils/EIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Contract for EIP-712 typed structured data hashing and signing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EIP712.sol)
/// @author Modified from Solbase (https://github.com/Sol-DAO/solbase/blob/main/src/utils/EIP712.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol)
///
/// @dev Note, this implementation:
/// - Uses `address(this)` for the `verifyingContract` field.
/// - Does NOT use the optional EIP-712 salt.
/// - Does NOT use any EIP-712 extensions.
/// This is for simplicity and to save gas.
/// If you need to customize, please fork / modify accordingly.
abstract contract EIP712 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS AND IMMUTABLES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 internal constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("EIP712Domain(string name,string version,address verifyingContract)")`.
/// This is only used in `_hashTypedDataSansChainId`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_CHAIN_ID =
0x91ab3d17e3a50a9d89e63fd30b92be7f5336b03b287bb946787a83a9d62a2766;
/// @dev `keccak256("EIP712Domain(string name,string version)")`.
/// This is only used in `_hashTypedDataSansChainIdAndVerifyingContract`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_CHAIN_ID_AND_VERIFYING_CONTRACT =
0xb03948446334eb9b2196d5eb166f69b9d49403eb4a12f36de8d3f9f3cb8e15c3;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId)")`.
/// This is only used in `_hashTypedDataSansVerifyingContract`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_VERIFYING_CONTRACT =
0xc2f8787176b8ac6bf7215b4adcc1e069bf4ab82d9ab1df05a57a91d425935b6e;
uint256 private immutable _cachedThis;
uint256 private immutable _cachedChainId;
bytes32 private immutable _cachedNameHash;
bytes32 private immutable _cachedVersionHash;
bytes32 private immutable _cachedDomainSeparator;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTRUCTOR */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cache the hashes for cheaper runtime gas costs.
/// In the case of upgradeable contracts (i.e. proxies),
/// or if the chain id changes due to a hard fork,
/// the domain separator will be seamlessly calculated on-the-fly.
constructor() {
_cachedThis = uint256(uint160(address(this)));
_cachedChainId = block.chainid;
string memory name;
string memory version;
if (!_domainNameAndVersionMayChange()) (name, version) = _domainNameAndVersion();
bytes32 nameHash = _domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(name));
bytes32 versionHash =
_domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(version));
_cachedNameHash = nameHash;
_cachedVersionHash = versionHash;
bytes32 separator;
if (!_domainNameAndVersionMayChange()) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
_cachedDomainSeparator = separator;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* FUNCTIONS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Please override this function to return the domain name and version.
/// ```
/// function _domainNameAndVersion()
/// internal
/// pure
/// virtual
/// returns (string memory name, string memory version)
/// {
/// name = "Solady";
/// version = "1";
/// }
/// ```
///
/// Note: If the returned result may change after the contract has been deployed,
/// you must override `_domainNameAndVersionMayChange()` to return true.
function _domainNameAndVersion()
internal
view
virtual
returns (string memory name, string memory version);
/// @dev Returns if `_domainNameAndVersion()` may change
/// after the contract has been deployed (i.e. after the constructor).
/// Default: false.
function _domainNameAndVersionMayChange() internal pure virtual returns (bool result) {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _domainSeparator() internal view virtual returns (bytes32 separator) {
if (_domainNameAndVersionMayChange()) {
separator = _buildDomainSeparator();
} else {
separator = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) separator = _buildDomainSeparator();
}
}
/// @dev Returns the hash of the fully encoded EIP-712 message for this domain,
/// given `structHash`, as defined in
/// https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct.
///
/// The hash can be used together with {ECDSA-recover} to obtain the signer of a message:
/// ```
/// bytes32 digest = _hashTypedData(keccak256(abi.encode(
/// keccak256("Mail(address to,string contents)"),
/// mailTo,
/// keccak256(bytes(mailContents))
/// )));
/// address signer = ECDSA.recover(digest, signature);
/// ```
function _hashTypedData(bytes32 structHash) internal view virtual returns (bytes32 digest) {
// We will use `digest` to store the domain separator to save a bit of gas.
if (_domainNameAndVersionMayChange()) {
digest = _buildDomainSeparator();
} else {
digest = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) digest = _buildDomainSeparator();
}
/// @solidity memory-safe-assembly
assembly {
// Compute the digest.
mstore(0x00, 0x1901000000000000) // Store "\x19\x01".
mstore(0x1a, digest) // Store the domain separator.
mstore(0x3a, structHash) // Store the struct hash.
digest := keccak256(0x18, 0x42)
// Restore the part of the free memory slot that was overwritten.
mstore(0x3a, 0)
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID.
/// Included for the niche use case of cross-chain workflows.
function _hashTypedDataSansChainId(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_CHAIN_ID)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
mstore(0x60, address())
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x80)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID and verifying contract.
/// Included for the niche use case of cross-chain and multi-verifier workflows.
function _hashTypedDataSansChainIdAndVerifyingContract(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_CHAIN_ID_AND_VERIFYING_CONTRACT)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x60)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID and verifying contract.
/// Included for the niche use case of multi-verifier workflows.
function _hashTypedDataSansVerifyingContract(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_VERIFYING_CONTRACT)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
mstore(0x60, chainid())
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x80)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-5267 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev See: https://eips.ethereum.org/EIPS/eip-5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
fields = hex"0f"; // `0b01111`.
(name, version) = _domainNameAndVersion();
chainId = block.chainid;
verifyingContract = address(this);
salt = salt; // `bytes32(0)`.
extensions = extensions; // `new uint256[](0)`.
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _buildDomainSeparator() private view returns (bytes32 separator) {
// We will use `separator` to store the name hash to save a bit of gas.
bytes32 versionHash;
if (_domainNameAndVersionMayChange()) {
(string memory name, string memory version) = _domainNameAndVersion();
separator = keccak256(bytes(name));
versionHash = keccak256(bytes(version));
} else {
separator = _cachedNameHash;
versionHash = _cachedVersionHash;
}
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), separator) // Name hash.
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
/// @dev Returns if the cached domain separator has been invalidated.
function _cachedDomainSeparatorInvalidated() private view returns (bool result) {
uint256 cachedChainId = _cachedChainId;
uint256 cachedThis = _cachedThis;
/// @solidity memory-safe-assembly
assembly {
result := iszero(and(eq(chainid(), cachedChainId), eq(address(), cachedThis)))
}
}
}
lib/solady/src/utils/SignatureCheckerLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Signature verification helper that supports both ECDSA signatures from EOAs
/// and ERC1271 signatures from smart contract wallets like Argent and Gnosis safe.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SignatureCheckerLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/SignatureChecker.sol)
///
/// @dev Note:
/// - The signature checking functions use the ecrecover precompile (0x1).
/// - The `bytes memory signature` variants use the identity precompile (0x4)
/// to copy memory internally.
/// - Unlike ECDSA signatures, contract signatures are revocable.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT use signatures as unique identifiers:
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// This implementation does NOT check if a signature is non-malleable.
library SignatureCheckerLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIGNATURE CHECKING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
let copied := staticcall(gas(), 4, signature, n, add(m, 0x44), n)
isValid := staticcall(gas(), signer, m, add(returndatasize(), 0x44), d, 0x20)
isValid := and(eq(mload(d), f), and(isValid, copied))
break
}
}
}
/// @dev Returns whether `signature` is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNowCalldata(address signer, bytes32 hash, bytes calldata signature)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // `r`, `s`.
}
default { break }
mstore(0x00, hash)
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
isValid := staticcall(gas(), signer, m, add(signature.length, 0x64), d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), shr(1, shl(1, vs))) // `s`.
mstore8(add(m, 0xa4), add(shr(255, vs), 27)) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `signer` and `hash`.
/// If `signer.code.length == 0`, then validate with `ecrecover`, else
/// it will validate with ERC1271 on `signer`.
function isValidSignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
if (signer == address(0)) return isValid;
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
for {} 1 {} {
if iszero(extcodesize(signer)) {
mstore(0x00, hash)
mstore(0x20, and(v, 0xff)) // `v`.
mstore(0x40, r) // `r`.
mstore(0x60, s) // `s`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC1271 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note: These ERC1271 operations do NOT have an ECDSA fallback.
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
// Copy the `signature` over.
let n := add(0x20, mload(signature))
let copied := staticcall(gas(), 4, signature, n, add(m, 0x44), n)
isValid := staticcall(gas(), signer, m, add(returndatasize(), 0x44), d, 0x20)
isValid := and(eq(mload(d), f), and(isValid, copied))
}
}
/// @dev Returns whether `signature` is valid for `hash` for an ERC1271 `signer` contract.
function isValidERC1271SignatureNowCalldata(
address signer,
bytes32 hash,
bytes calldata signature
) internal view returns (bool isValid) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), signature.length)
// Copy the `signature` over.
calldatacopy(add(m, 0x64), signature.offset, signature.length)
isValid := staticcall(gas(), signer, m, add(signature.length, 0x64), d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/// @dev Returns whether the signature (`r`, `vs`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), shr(1, shl(1, vs))) // `s`.
mstore8(add(m, 0xa4), add(shr(255, vs), 27)) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/// @dev Returns whether the signature (`v`, `r`, `s`) is valid for `hash`
/// for an ERC1271 `signer` contract.
function isValidERC1271SignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
let f := shl(224, 0x1626ba7e)
mstore(m, f) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m, 0x04), hash)
let d := add(m, 0x24)
mstore(d, 0x40) // The offset of the `signature` in the calldata.
mstore(add(m, 0x44), 65) // Length of the signature.
mstore(add(m, 0x64), r) // `r`.
mstore(add(m, 0x84), s) // `s`.
mstore8(add(m, 0xa4), v) // `v`.
isValid := staticcall(gas(), signer, m, 0xa5, d, 0x20)
isValid := and(eq(mload(d), f), isValid)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC6492 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Note: These ERC6492 operations now include an ECDSA fallback at the very end.
// The calldata variants are excluded for brevity.
/// @dev Returns whether `signature` is valid for `hash`.
/// If the signature is postfixed with the ERC6492 magic number, it will attempt to
/// deploy / prepare the `signer` smart account before doing a regular ERC1271 check.
/// Note: This function is NOT reentrancy safe.
/// The verifier must be deployed.
/// Otherwise, the function will return false if `signer` is not yet deployed / prepared.
/// See: https://gist.github.com/Vectorized/011d6becff6e0a73e42fe100f8d7ef04
/// With a dedicated verifier, this function is safe to use in contracts
/// that have been granted special permissions.
function isValidERC6492SignatureNowAllowSideEffects(
address signer,
bytes32 hash,
bytes memory signature
) internal returns (bool isValid) {
/// @solidity memory-safe-assembly
assembly {
function callIsValidSignature(signer_, hash_, signature_) -> _isValid {
let m_ := mload(0x40)
let f_ := shl(224, 0x1626ba7e)
mstore(m_, f_) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m_, 0x04), hash_)
let d_ := add(m_, 0x24)
mstore(d_, 0x40) // The offset of the `signature` in the calldata.
let n_ := add(0x20, mload(signature_))
let copied_ := staticcall(gas(), 4, signature_, n_, add(m_, 0x44), n_)
_isValid := staticcall(gas(), signer_, m_, add(returndatasize(), 0x44), d_, 0x20)
_isValid := and(eq(mload(d_), f_), and(_isValid, copied_))
}
let noCode := iszero(extcodesize(signer))
let n := mload(signature)
for {} 1 {} {
if iszero(eq(mload(add(signature, n)), mul(0x6492, div(not(isValid), 0xffff)))) {
if iszero(noCode) { isValid := callIsValidSignature(signer, hash, signature) }
break
}
if iszero(noCode) {
let o := add(signature, 0x20) // Signature bytes.
isValid := callIsValidSignature(signer, hash, add(o, mload(add(o, 0x40))))
if isValid { break }
}
let m := mload(0x40)
mstore(m, signer)
mstore(add(m, 0x20), hash)
pop(
call(
gas(), // Remaining gas.
0x0000bc370E4DC924F427d84e2f4B9Ec81626ba7E, // Non-reverting verifier.
0, // Send zero ETH.
m, // Start of memory.
add(returndatasize(), 0x40), // Length of calldata in memory.
staticcall(gas(), 4, add(signature, 0x20), n, add(m, 0x40), n), // 1.
0x00 // Length of returndata to write.
)
)
isValid := returndatasize()
break
}
// Do `ecrecover` fallback if `noCode && !isValid`.
for {} gt(noCode, isValid) {} {
switch n
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Returns whether `signature` is valid for `hash`.
/// If the signature is postfixed with the ERC6492 magic number, it will attempt
/// to use a reverting verifier to deploy / prepare the `signer` smart account
/// and do a `isValidSignature` check via the reverting verifier.
/// Note: This function is reentrancy safe.
/// The reverting verifier must be deployed.
/// Otherwise, the function will return false if `signer` is not yet deployed / prepared.
/// See: https://gist.github.com/Vectorized/846a474c855eee9e441506676800a9ad
function isValidERC6492SignatureNow(address signer, bytes32 hash, bytes memory signature)
internal
returns (bool isValid)
{
/// @solidity memory-safe-assembly
assembly {
function callIsValidSignature(signer_, hash_, signature_) -> _isValid {
let m_ := mload(0x40)
let f_ := shl(224, 0x1626ba7e)
mstore(m_, f_) // `bytes4(keccak256("isValidSignature(bytes32,bytes)"))`.
mstore(add(m_, 0x04), hash_)
let d_ := add(m_, 0x24)
mstore(d_, 0x40) // The offset of the `signature` in the calldata.
let n_ := add(0x20, mload(signature_))
let copied_ := staticcall(gas(), 4, signature_, n_, add(m_, 0x44), n_)
_isValid := staticcall(gas(), signer_, m_, add(returndatasize(), 0x44), d_, 0x20)
_isValid := and(eq(mload(d_), f_), and(_isValid, copied_))
}
let noCode := iszero(extcodesize(signer))
let n := mload(signature)
for {} 1 {} {
if iszero(eq(mload(add(signature, n)), mul(0x6492, div(not(isValid), 0xffff)))) {
if iszero(noCode) { isValid := callIsValidSignature(signer, hash, signature) }
break
}
if iszero(noCode) {
let o := add(signature, 0x20) // Signature bytes.
isValid := callIsValidSignature(signer, hash, add(o, mload(add(o, 0x40))))
if isValid { break }
}
let m := mload(0x40)
mstore(m, signer)
mstore(add(m, 0x20), hash)
let willBeZeroIfRevertingVerifierExists :=
call(
gas(), // Remaining gas.
0x00007bd799e4A591FeA53f8A8a3E9f931626Ba7e, // Reverting verifier.
0, // Send zero ETH.
m, // Start of memory.
add(returndatasize(), 0x40), // Length of calldata in memory.
staticcall(gas(), 4, add(signature, 0x20), n, add(m, 0x40), n), // 1.
0x00 // Length of returndata to write.
)
isValid := gt(returndatasize(), willBeZeroIfRevertingVerifierExists)
break
}
// Do `ecrecover` fallback if `noCode && !isValid`.
for {} gt(noCode, isValid) {} {
switch n
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
let m := mload(0x40)
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
let recovered := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
isValid := gt(returndatasize(), shl(96, xor(signer, recovered)))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://eth.wiki/json-rpc/API#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
src/Attributes.sol
// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
pragma solidity ^0.8.13;
/* =============================================================================
* ATTRIBUTES · a token's traits, derived from its draw stream
* =============================================================================
*
* Attributes computes the `attributes` array of a token's tokenURI. It is the
* default path for a piece that supplies no attributes logic. It works in
* two steps:
*
* 1. extractTraits reads a canonical draw-instruction stream (the stream
* format the renderer consumes). It collects the payload of each trait
* record: a one-byte trait id and an 8-byte signed integer value (9 bytes
* in total). It skips every other record by its exact byte width, so a
* trait-record marker byte inside coordinate data is never read as a
* trait. The scanner depends only on this record format, not on how the
* stream was produced.
* 2. toJson maps the extracted records through the trait metadata of the
* piece into the `attributes` array of the tokenURI:
* `[{"trait_type":"...","value":...}, ...]`.
*
* VALUE FORMAT. Every trait value is a Q31.32 fixed-point number (a "Fix64"):
* the real number x is stored as the integer x * 2^32. A whole-number trait,
* such as an index into a small set of options, is an exact multiple of 2^32.
* A fractional trait, such as a lightness or hue in [0, 1), keeps bits below
* that point. A numeric trait (kind number or value) renders `value` as a
* signed decimal, unquoted, as its `decimals` field says:
* - `decimals == 0` (the default): the output is the integer part only,
* from the arithmetic right shift `value >> 32` (it floors toward
* negative infinity). This matches the conversion in the off-chain
* renderer exactly.
* - `decimals == N > 0`: the output has N fractional digits, from
* `_fixedDecimal`. It rounds half-up on the last kept digit (with integer
* carry), signs the result as sign-and-magnitude, and suppresses a
* negative zero such as `-0.000`. Use it for traits that are fractional,
* for example the lightness, chroma or hue of a color, or a knob in
* [0, 1). The off-chain renderer has an equivalent routine, and tests
* verify that the two agree over a broad range of values. `N` should
* stay in [1, 6], the range of fractional digits that a Q31.32 value
* shows without rounding artifacts. This contract does not enforce that
* range. It is a rule for the trait metadata. (The name and label
* safety described below is enforced where traits are added.)
* - kind choice or flag: the value selects a label, `labels[value >> 32]`,
* quoted as a JSON string. If the index is out of range or negative, the
* output is the numeric rendering above.
*
* NAME AND LABEL SAFETY. `name` and each entry in `labels` come from the
* trait metadata the owner adds. The code splices them into the JSON WITHOUT
* escaping, so they must be valid JSON string contents: no quote, no
* backslash, no control character. A quote ends the JSON string early. The
* token document then fails to parse for every token, permanently, because
* the trait metadata is frozen.
*
* KohiPiece ENFORCES this when a trait is added: a control byte, a quote or a
* backslash in a trait name or label is refused.
*
* As an extra safeguard for data URIs, `_san` percent-encodes `#` to `%23`
* and `%` to `%25` in every name and label it emits. An unescaped `#` starts
* the URI fragment early and truncates the JSON after it. A stray `%` can be
* misread during URI decoding.
*
* UNCHECKED ARITHMETIC. The scan and format bodies run `unchecked`. An
* in-memory array length bounds each counter and offset (it cannot reach
* 2^64, because memory cost grows quadratically in gas), and each steps by
* small constants. The overflow checks would be dead code that costs bytes of
* the contract-size budget. `unchecked` does not affect array-index
* BOUNDS checks: they all still fire. `_fixedDecimal` stays checked: its
* `10 ** dec` can overflow for an out-of-range `decimals`, and the arithmetic
* panic there is intended.
*/
library Attributes {
/// Per-piece trait metadata: for each trait id that the program of a
/// piece can emit, how to label and render it in the `attributes` array
/// of the tokenURI. An off-chain manifest entry can name an arbitrary
/// formatting function. On-chain, the `kind` and `labels` fields replace
/// it and cover every format in use.
struct TraitMeta {
uint8 id; // trait record id this entry describes
uint8 kind; // 0 number, 1 choice, 2 flag, 3 value
bool hidden; // omit from display (still recorded in the stream)
// Numeric kinds: how many fractional digits to render (0 = integer
// part only, the default; N > 0 = a fixed N-digit decimal; see
// _fixedDecimal and VALUE FORMAT above). It shares a storage slot
// with id, kind and hidden. An entry that never sets it reads 0.
uint8 decimals;
string name; // trait_type
string[] labels; // choice/flag: index -> label; empty for number/value
}
// ---- extract ------------------------------------------------------------
/// Concatenate the (id, value) payload of every trait record (tag byte
/// 0x02) in a canonical draw-instruction stream. Each trait yields 9
/// bytes of output: a 1-byte unsigned id and an 8-byte signed
/// (big-endian) value. The function skips every other record by its exact
/// byte width, so a 0x02 byte inside unrelated data (such as coordinate
/// data) is never read as a trait record.
function extractTraits(bytes memory stream) internal pure returns (bytes memory out) {
unchecked {
uint256 n = 0;
uint256 i = 0;
while (i < stream.length) {
uint8 tag = uint8(stream[i]);
if (tag == 0x02) {
n++;
i += 10;
} else {
i = _skip(stream, i, tag);
}
}
out = new bytes(n * 9);
uint256 w = 0;
i = 0;
while (i < stream.length) {
uint8 tag = uint8(stream[i]);
if (tag == 0x02) {
// id + i64 value
for (uint256 j = 0; j < 9; j++) out[w + j] = stream[i + 1 + j];
w += 9;
i += 10;
} else {
i = _skip(stream, i, tag);
}
}
}
}
/// Return the offset after one non-trait record that starts at `i` (the
/// caller already read the tag).
function _skip(bytes memory stream, uint256 i, uint8 tag) private pure returns (uint256) {
unchecked {
if (tag == 0xb0) return i + 5; // begin: u16 w | u16 h
if (tag == 0x00) return i + 5; // background: u32 argb
if (tag == 0xb1) return stream.length; // end
if (tag == 0x06) {
// field: u8 kind | u32 | u32
// (+ kind 1: i64 scale | i64 warp | i32 seed)
return i + (uint8(stream[i + 1]) == 1 ? 30 : 10);
}
if (tag == 0x07) return i + 2; // aliased: u8
if (tag == 0x04) return i + 55; // stamp: u32 | u8 | u8 | 6*i64
if (tag == 0x08) return i + 25; // cam: 3*i64
if (tag == 0x09) return i + 50; // light: u8 | 6*i64
if (tag == 0x0a) return i + 161; // mesh: 18*i64 | u32 | u32 | i64
if (tag == 0x01) return _skipPaint(stream, i);
revert("Attributes: unknown stream tag");
}
}
/// Paint (0x01): u8 hasFill | u32 | u8 hasStroke | u32 | i64 strokeW |
/// u8 flags | (u8 cap, u8 join if bit1) | (u8 blend if bit2) | (u8 kind |
/// 4*i64 | u8 n | 6n stop bytes if bit3, a gradient fill) | (u8 kind |
/// 2*i64 | 2*u32 | i32 = 29 bytes if bit4, a field fill) | u8 hasClip |
/// (8*i64 if clip) | u16 segCount | segs.
function _skipPaint(bytes memory stream, uint256 i) private pure returns (uint256) {
unchecked {
uint256 p = i + 1 + 1 + 4 + 1 + 4 + 8; // at the flags byte
uint8 flags = uint8(stream[p]);
p += 1; // past flags: at cap/blend/gradient/field/hasClip
// An unrecognized paint-flag bit is a hard error, not a silent
// misparse: a format extension must fail here, not read as valid
// data. Bits 5..7 (mask 0xe0) are unrecognized. The code below
// handles bit4 (the field-fill extension).
if (flags & 0xe0 != 0) revert("Attributes: unknown paint flags");
if (flags & 2 != 0) p += 2; // skip cap + join
if (flags & 4 != 0) p += 1; // skip blend
// skip the GFILL ext
if (flags & 8 != 0) p += 34 + uint256(uint8(stream[p + 33])) * 6;
// skip the FFILL field ext (bit3/bit4 exclusive)
if (flags & 16 != 0) p += 29;
uint8 hasClip = uint8(stream[p]);
p += 1;
if (hasClip == 1) p += 64; // 8 * i64
uint256 segCount = (uint256(uint8(stream[p])) << 8) | uint256(uint8(stream[p + 1]));
p += 2;
for (uint256 s = 0; s < segCount; s++) {
uint8 seg = uint8(stream[p]);
if (seg == 0x01 || seg == 0x02) p += 17; // M/L: tag + 2*i64
else if (seg == 0x03) p += 49; // C: tag + 6*i64
else if (seg == 0x04) p += 1; // Z
else revert("Attributes: bad seg tag");
}
return p;
}
}
// ---- json ---------------------------------------------------------------
/// Map the extracted (id|value) records through `meta` into the tokenURI
/// `attributes` array. A record is omitted if its id has no metadata
/// entry or its entry is `hidden`. Reads storage, so it is `view`.
function toJson(bytes memory records, TraitMeta[] storage meta) internal view returns (string memory) {
unchecked {
bytes memory out = "[";
bool first = true;
// Each record is 9 bytes (u8 id | i64 value).
for (uint256 off = 0; off + 9 <= records.length; off += 9) {
(bool found, uint256 mi) = _find(meta, uint8(records[off]));
if (!found || meta[mi].hidden) continue;
// The per-entry JSON has its own frame (_entryJson), so its
// locals do not share the stack with the loop locals.
bytes memory entry = _entryJson(meta[mi], _readI64(records, off + 1));
out = abi.encodePacked(out, first ? "" : ",", entry);
first = false;
}
return string(abi.encodePacked(out, "]"));
}
}
/// One `{"trait_type":"...","value":...}` object.
function _entryJson(TraitMeta storage m, int64 value) private view returns (bytes memory) {
bytes memory nameJson = _san(m.name);
bytes memory valueJson = _valueJson(m, value);
return abi.encodePacked('{"trait_type":"', nameJson, '","value":', valueJson, "}");
}
/// The JSON `value` token for one record: a quoted label for a
/// choice/flag with an in-range index. Otherwise the unquoted decimal
/// (number/value, or a label with an out-of-range or negative index).
function _valueJson(TraitMeta storage m, int64 value) private view returns (bytes memory) {
int64 idx = value >> 32; // Fix64 -> integer part (floor)
if ((m.kind == 1 || m.kind == 2) && idx >= 0 && uint256(uint64(idx)) < m.labels.length) {
bytes memory label = _san(m.labels[uint256(uint64(idx))]);
return abi.encodePacked('"', label, '"');
}
if (m.decimals > 0) return bytes(_fixedDecimal(value, m.decimals));
return bytes(_i64ToString(idx));
}
/// Linear scan for the metadata entry with trait id `id`. A piece
/// declares few traits.
function _find(TraitMeta[] storage meta, uint8 id) private view returns (bool, uint256) {
unchecked {
for (uint256 k = 0; k < meta.length; k++) {
if (meta[k].id == id) return (true, k);
}
return (false, 0);
}
}
/// Read a big-endian i64 at `off` from a 9-byte-record buffer.
function _readI64(bytes memory b, uint256 off) private pure returns (int64) {
unchecked {
uint64 u = 0;
for (uint256 i = 0; i < 8; i++) {
u = (u << 8) | uint8(b[off + i]);
}
return int64(u);
}
}
/// Percent-encode the `;utf8,` URI hazards `#`->`%23` and `%`->`%25` in a
/// controlled name or label. JSON-string safety is enforced where traits
/// are added.
function _san(string memory s) private pure returns (bytes memory) {
unchecked {
bytes memory b = bytes(s);
uint256 extra = 0;
for (uint256 i = 0; i < b.length; i++) {
if (b[i] == "#" || b[i] == "%") extra += 2;
}
if (extra == 0) return b;
bytes memory o = new bytes(b.length + extra);
uint256 w = 0;
for (uint256 i = 0; i < b.length; i++) {
if (b[i] == "#") {
o[w++] = "%";
o[w++] = "2";
o[w++] = "3";
} else if (b[i] == "%") {
o[w++] = "%";
o[w++] = "2";
o[w++] = "5";
} else {
o[w++] = b[i];
}
}
return o;
}
}
/// Signed base-10 decimal of an int64.
function _i64ToString(int64 v) private pure returns (string memory) {
unchecked {
if (v == 0) return "0";
bool neg = v < 0;
uint256 u = neg ? uint256(-int256(v)) : uint256(int256(v));
bytes memory tmp = new bytes(20);
uint256 n = 0;
while (u != 0) {
tmp[n++] = bytes1(uint8(48 + (u % 10)));
u /= 10;
}
bytes memory out = new bytes(n + (neg ? 1 : 0));
uint256 j = 0;
if (neg) out[j++] = "-";
for (uint256 k = 0; k < n; k++) {
out[j++] = tmp[n - 1 - k];
}
return string(out);
}
}
/// Render a Fix64 (Q31.32) `value` as a decimal string with `dec`
/// fractional digits. It rounds half-up on the last kept digit (with
/// integer carry), signs the result as sign-and-magnitude, and renders a
/// negative zero such as `-0.000` as a clean zero. `dec` should stay in
/// [1, 6]. This function does not enforce that range; it is a rule for
/// the published trait metadata. The off-chain renderer has an equivalent
/// routine, and tests verify that the two agree over a range of values.
function _fixedDecimal(int64 value, uint8 dec) private pure returns (string memory) {
bool neg = value < 0;
uint64 mag = neg ? uint64(uint256(-int256(value))) : uint64(uint256(int256(value)));
uint256 intPart = mag >> 32; // integer part
uint256 frac = mag & 0xffffffff; // Q0.32 fraction
uint256 pow = 10 ** dec;
// `1 << 31` is half of 2^32, so the `>> 32` rounds to nearest
// (half-up on the last kept digit). `scaled` is the fraction as an
// integer in [0, 10^dec).
uint256 scaled = (frac * pow + (1 << 31)) >> 32;
if (scaled >= pow) {
intPart += 1; // carry: 0.9996 -> 1.000
scaled = 0;
}
bool isZero = intPart == 0 && scaled == 0;
// Left-zero-pad `scaled` to `dec` digits.
bytes memory fracStr = new bytes(dec);
for (uint256 k = dec; k > 0; k--) {
fracStr[k - 1] = bytes1(uint8(48 + (scaled % 10)));
scaled /= 10;
}
// Suppress a lone `-` on a value that rounded to zero (e.g. -0.00001).
bytes memory sign = (neg && !isZero) ? bytes("-") : bytes("");
return string(abi.encodePacked(sign, _i64ToString(int64(uint64(intPart))), ".", fracStr));
}
}
src/IKVMTraitsRunner.sol
// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
pragma solidity ^0.8.13;
/// @notice The traits-only reader. It is the surface of KVMTraitsRunner, an
/// interpreter fork that reads a token's TRAIT records and draws
/// nothing.
/// @dev The interface is small and standalone. A contract can read traits
/// without importing the interpreter. KVMTraitsRunner enforces
/// the surface (`is IKVMTraitsRunner`).
interface IKVMTraitsRunner {
/// @notice Read a token's (id, value) TRAIT records and stop when the
/// K-th record is written.
/// @dev KVMTraitsRunner reverts with KVMError on a malformed container
/// or a faulting program.
/// @param program A KVM1 container. KVMRunner.execute runs the same bytes.
/// @param seed The int32 run seed.
/// @param params Values for the program's PARAM ops. A missing index
/// reads 0.
/// @param K The piece's declared trait count (0 = run to HALT).
/// For K >= the true count, the trait values are
/// byte-exact. For a smaller K, the result holds only the
/// first K records.
/// @return The canonical draw stream with all drawing removed: begin,
/// any background records, the TRAIT (0x02 | u8 id | i64 value)
/// records in order, then end. The 0x02 records are
/// byte-identical to those in a full KVMRunner.execute stream
/// for the same inputs.
function traitsOf(bytes calldata program, int32 seed, int64[] calldata params, uint256 K)
external
view
returns (bytes memory);
}
src/RegistryOwnable.sol
// SPDX-License-Identifier: MIT
/* Copyright (c) wattsy */
pragma solidity ^0.8.24;
import {Ownable} from "openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "openzeppelin/contracts/access/Ownable2Step.sol";
/* =============================================================================
* REGISTRYOWNABLE · two-step ownership with renouncing disabled
* =============================================================================
*
* A single-owner access-control base. It adds one safety property to the
* `Ownable2Step` contract of OpenZeppelin.
*
* Ownership changes in two steps. The owner calls `transferOwnership` to
* nominate a successor. Nothing changes until the nominee calls
* `acceptOwnership`. A mistyped or unreachable address cannot lock the
* contract out: the owner stays in control until a working address accepts.
*
* Ownership cannot be renounced. `renounceOwnership` always reverts. Plain
* `Ownable` lets the owner set the owner to the zero address, and then nobody
* can administer the contract again. Every governance action on a contract
* that uses this base is one-way or timelocked, so a dropped owner would
* strand that governance with no path back.
*/
abstract contract RegistryOwnable is Ownable2Step {
/// Thrown by `renounceOwnership`, always.
error RenounceDisabled();
/// @notice Deploys with `initialOwner` as the owner.
/// @param initialOwner The first owner. The `Ownable` constructor
/// reverts if this is the zero address.
constructor(address initialOwner) Ownable(initialOwner) {}
/// @notice Always reverts with `RenounceDisabled`.
/// @dev A contract that must stop being administrable freezes its own
/// powers through its one-way locks. It does not discard its owner.
function renounceOwnership() public view override onlyOwner {
revert RenounceDisabled();
}
}
src/SSTORE2.sol
// SPDX-License-Identifier: MIT
// Copyright (c) Solady authors (https://github.com/Vectorized/solady), MIT.
// Adapted from Solady's SSTORE2 (src/utils/SSTORE2.sol): shares the same
// 10-byte PUSH2 creation prologue, the RETURNDATASIZE-as-zero trick, the 0x0A
// runtime offset, and the DeploymentFailed() error name; the opcodes are
// reordered and the API is narrowed.
pragma solidity ^0.8.13;
/*
* SSTORE2: minimal contract-code-as-storage. Writes `data` as the runtime
* code of a fresh contract prefixed with a STOP (0x00) byte so it can never
* be executed, and reads it back with EXTCODECOPY.
*
* Creation code layout (10 bytes) followed by the runtime:
* 61 XXXX PUSH2 runtime length
* 3D RETURNDATASIZE (0)
* 81 DUP2
* 60 0A PUSH1 10 (offset of runtime within creation code)
* 3D RETURNDATASIZE (0)
* 39 CODECOPY
* F3 RETURN
*/
library SSTORE2 {
error DataTooLarge();
error DeploymentFailed();
function write(bytes memory data) internal returns (address pointer) {
// 1 byte STOP prefix + data must fit in the EIP-170 runtime limit.
if (data.length + 1 > 24576) revert DataTooLarge();
// creation code | STOP prefix | data
bytes memory creation = abi.encodePacked(
hex"61",
uint16(data.length + 1),
hex"3d81600a3d39f3",
hex"00",
data
);
assembly {
pointer := create(0, add(creation, 0x20), mload(creation))
}
if (pointer == address(0)) revert DeploymentFailed();
}
function read(address pointer) internal view returns (bytes memory data) {
uint256 size;
assembly {
size := extcodesize(pointer)
}
if (size == 0) return data = new bytes(0);
unchecked {
size -= 1; // skip the STOP prefix
}
data = new bytes(size);
assembly {
extcodecopy(pointer, add(data, 0x20), 1, size)
}
}
}
src/StreamStore.sol
// SPDX-License-Identifier: MIT
/* Copyright (c) wattsy */
pragma solidity ^0.8.13;
import "./SSTORE2.sol";
/* =============================================================================
* STREAMSTORE · large payloads as chunked SSTORE2 pointers
* =============================================================================
*
* StreamStore writes a large binary payload (an image, a wasm module) as a
* sequence of SSTORE2 contracts. It reads back the exact original bytes.
*
* SSTORE2 deploys the data as the runtime code of a small contract. This is
* cheaper to write than storage, and a read copies the code with EXTCODECOPY.
* EIP-170 limits runtime code to 24,576 bytes. SSTORE2 puts one STOP guard
* byte first, so a call to the contract does nothing. StreamStore keeps this
* convention. A pointer holds at most 24,575 data bytes (`MAX_CHUNK`), and
* the data starts at code offset 1.
*
* On write, StreamStore splits a payload across as many pointers as it needs.
* On read, it joins the chunks into one buffer. The `extcodesize` of a chunk
* is its data length plus one. `readChunks` copies from code offset 1 and
* skips the guard byte of each chunk. An error of one byte here shifts every
* byte after it.
*
* The reader copies each chunk with EXTCODECOPY straight into one
* preallocated buffer. It makes no intermediate allocation per chunk. A chunk
* boundary can fall inside a logical record. This is safe: the reader drops
* only the guard byte of each chunk, so the output is byte-exact wherever a
* boundary falls.
*/
library StreamStore {
/// Maximum data bytes per chunk. The guard byte plus the data equal the
/// 24,576-byte runtime cap. A payload of one chunk is written exactly as
/// a bare SSTORE2.write writes it.
uint256 internal constant MAX_CHUNK = 24575;
/// Split `data` into the fewest pointers (chunk size `MAX_CHUNK`).
function writeChunks(bytes memory data) internal returns (address[] memory ptrs) {
return writeChunks(data, MAX_CHUNK);
}
/// Split `data` across SSTORE2 pointers of at most `chunkSize` data
/// bytes. A `chunkSize` of 0 or above MAX_CHUNK becomes MAX_CHUNK.
/// Empty input gives one empty pointer.
function writeChunks(bytes memory data, uint256 chunkSize) internal returns (address[] memory ptrs) {
if (chunkSize == 0 || chunkSize > MAX_CHUNK) chunkSize = MAX_CHUNK;
uint256 len = data.length;
uint256 n = len == 0 ? 1 : (len + chunkSize - 1) / chunkSize;
ptrs = new address[](n);
uint256 off = 0;
for (uint256 i = 0; i < n; i++) {
uint256 clen = len - off;
if (clen > chunkSize) clen = chunkSize;
ptrs[i] = SSTORE2.write(_slice(data, off, clen));
off += clen;
}
}
/// Join the data of a pointer set into one buffer. EXTCODECOPY copies
/// each chunk from code offset 1 (after the STOP guard) into place.
function readChunks(address[] memory ptrs) internal view returns (bytes memory out) {
uint256 n = ptrs.length;
uint256 total = 0;
for (uint256 i = 0; i < n; i++) {
address p = ptrs[i];
uint256 sz;
assembly {
sz := extcodesize(p)
}
if (sz > 1) total += sz - 1;
}
out = new bytes(total);
uint256 w;
assembly {
w := add(out, 0x20)
}
for (uint256 i = 0; i < n; i++) {
address p = ptrs[i];
uint256 sz;
assembly {
sz := extcodesize(p)
}
if (sz > 1) {
uint256 dlen = sz - 1;
assembly {
extcodecopy(p, w, 1, dlen)
w := add(w, dlen)
}
}
}
}
/// keccak256 of the reassembled payload. Use it to check the bytes.
function hashOf(address[] memory ptrs) internal view returns (bytes32) {
return keccak256(readChunks(ptrs));
}
/// Total data bytes of a pointer set: the sum of `extcodesize` minus one
/// guard byte per chunk.
function sizeOf(address[] memory ptrs) internal view returns (uint256 total) {
for (uint256 i = 0; i < ptrs.length; i++) {
address p = ptrs[i];
uint256 sz;
assembly {
sz := extcodesize(p)
}
if (sz > 1) total += sz - 1;
}
}
/// Copy `len` bytes of `data` from `off` into a new buffer. The copy
/// works in words. It can write up to 31 bytes into the padding of `out`
/// (inside its allocation) and read past the end of `data` (a memory read
/// never faults). SSTORE2.write packs exactly `len` bytes, so the padding
/// is never deployed.
function _slice(bytes memory data, uint256 off, uint256 len) private pure returns (bytes memory out) {
out = new bytes(len);
assembly {
let src := add(add(data, 0x20), off)
let dst := add(out, 0x20)
for { let i := 0 } lt(i, len) { i := add(i, 0x20) } {
mstore(add(dst, i), mload(add(src, i)))
}
}
}
}
src/player/IKohiPiece.sol
// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
pragma solidity ^0.8.13;
/* =============================================================================
* IKOHIPIECE · the interface of a piece whose artwork is a KVM program
* =============================================================================
*
* THE PROBLEM. A token of generative art is only as durable as the way to
* rebuild its image. Each collection could answer that question in its own
* way. A player page, a command-line renderer and a marketplace would then
* need custom code for each collection. This interface gives one answer for
* every piece.
*
* HOW IT WORKS. A Kohi piece stores its artwork as a program for the KVM, a
* bytecode virtual machine for generative art. A token is the program plus
* the seed of that token. A seed is a number that makes one run of the
* program differ from another. This interface tells a reader where these
* inputs are and which contracts turn them into the image. Every reader gets
* the same answers, so every reader renders the same artwork.
*
* THE RENDER PATH IS THE PROVENANCE STATEMENT. kohiRenderPath names the
* contracts that make the image. The interpreter turns (program, params,
* seed) into a draw stream. The renderer turns the draw stream into pixels.
* The image of a token is what these contracts compute from these inputs. A
* player page that shows the image in a browser is a convenience. It is
* never part of this path.
*
* THE TRUST BOUNDARY. Every function is a view over chain state. Nothing
* points off chain. The interface has no function that writes state. Each
* implementation states what its owner can change and until when.
*
* ERC-165. A piece contract declares support through
* supportsInterface(type(IKohiPiece).interfaceId), which returns true.
*/
/// @notice The contracts that render a piece, and the inputs that they need.
/// @dev The field order is part of the ABI. Do not change it.
struct KohiRenderPath {
/// The rasterizer family: 0 GraphicsV1, 1 AGG (hard strokes),
/// 2 AGG (blended strokes), 3 stamp, 4 mesh, 5 traced mesh.
uint8 family;
/// The noise kind the program uses: 0 NoiseV1, 1 GradNoise.
uint8 noiseKind;
/// The one-shot interpreter. execute(program, seed, params) returns the
/// draw stream (the IKVMExec surface).
address runner;
/// The stepped interpreter. It runs a program that does not fit in one
/// call, in chunks, and gives the same draw stream. It is address(0) if
/// the piece always fits in one call.
address stepRunner;
/// The renderer of the family. It turns the draw stream into pixels.
address renderer;
}
/// @title IKohiPiece
/// @notice The read interface of a piece whose artwork is a KVM program.
/// @dev Every function is a view. An implementation declares the interface
/// through ERC-165.
interface IKohiPiece {
/// @notice The token does not exist.
/// @param tokenId The token that was asked for.
error KohiNoSuchToken(uint256 tokenId);
/// @notice The KVM container (the program) of the piece.
/// @dev The bytes are the same for every token. A piece that locks its
/// program returns the same bytes forever after the lock.
/// @return program The container bytes.
function kohiProgram() external view returns (bytes memory program);
/// @notice The PARAM slot values that the program reads.
/// @dev Slot i is params[i]. An empty array means that the program reads
/// no slot.
/// @return params The raw 64-bit slot values.
function kohiParams() external view returns (int64[] memory params);
/// @notice The seed of a token.
/// @dev Reverts KohiNoSuchToken for a token that does not exist.
/// @param tokenId The token.
/// @return seed The seed that the interpreter gets.
function kohiSeed(uint256 tokenId) external view returns (int32 seed);
/// @notice The contracts that render the piece.
/// @return path The family, the noise kind, and the addresses of the
/// interpreters and the renderer.
function kohiRenderPath() external view returns (KohiRenderPath memory path);
/// @notice The display name of a token, for example "Rakel #42".
/// @dev The text is JSON-safe: it has no quote, backslash or control byte.
/// Reverts KohiNoSuchToken for a token that does not exist.
/// @param tokenId The token.
/// @return name The name.
function kohiName(uint256 tokenId) external view returns (string memory name);
/// @notice The description of the piece.
/// @dev The text is JSON-safe: it has no quote, backslash or control byte.
/// @return description The description.
function kohiDescription() external view returns (string memory description);
/// @notice The attributes of a token, as a JSON array of
/// {"trait_type": ..., "value": ...} objects.
/// @dev The text is JSON-safe. It is "[]" if the piece has no attributes.
/// Reverts KohiNoSuchToken for a token that does not exist.
/// @param tokenId The token.
/// @return attributes The JSON array.
function kohiAttributes(uint256 tokenId) external view returns (string memory attributes);
}
src/player/IKohiTokenURI.sol
// SPDX-License-Identifier: Apache-2.0
/* Copyright (c) wattsy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
pragma solidity ^0.8.13;
import {IKohiPiece} from "./IKohiPiece.sol";
/* =============================================================================
* IKOHITOKENURI · a module that writes the tokenURI of a Kohi piece
* =============================================================================
*
* THE PROBLEM. Marketplaces want metadata in many shapes: a page, an image, a
* hosted copy. The artwork must stay the same in all of them.
*
* HOW IT WORKS. A piece contract does not build its own metadata. It holds
* the address of a module and calls it. The module reads everything that it
* needs from the piece through IKohiPiece, so one module serves any number of
* pieces.
*
* THE TRUST BOUNDARY. The module decides how the metadata looks: which
* fields, which page, which image. It does not decide what the artwork is.
* The artwork is the program of the piece and the seed of the token, rendered
* by the contracts that the piece names in kohiRenderPath. The piece owner
* can replace the module until the piece locks it. After the lock, the module
* is fixed.
*
* PiecePlayer is one module. It writes an animation_url page that renders the
* token in the browser. Other modules can add an image, or a hosted copy of
* the page, without any change to the piece.
*/
/// @title IKohiTokenURI
/// @notice The interface of a module that writes the tokenURI of a token of a
/// Kohi piece.
/// @dev One module can serve many pieces. It reads the piece through
/// IKohiPiece.
interface IKohiTokenURI {
/// @notice The tokenURI of a token of a piece.
/// @dev Reverts for a token that the piece does not have.
/// @param piece The piece contract.
/// @param tokenId The token.
/// @return The metadata URI of the token.
function tokenURI(IKohiPiece piece, uint256 tokenId) external view returns (string memory);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"openzeppelin/=lib/openzeppelin/",
"ds-test/=lib/forge-std/lib/ds-test/src/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.