Verified contractExactMIT
Spawns
Address0xfdc1afdcdd6f4c6263e6e68ccdf696cd8801636e
- Balance
0 ETH
- Transactions
29
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,893,667
- Creation transaction
- 0xefb29a10fa…91ad001b34
10 files
- src/token/Spawns.solmain6.54 KB
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/tokens/ERC20.sol31.12 KB
- src/library/IRandomSeedProvider.sol257 B
- src/library/RandomLib.sol498 B
- src/svg_generation/IImageParams.sol693 B
- src/svg_generation/SpawnMetadata.sol3.4 KB
- src/token/IStartableToken.sol361 B
- src/upegs/ISpawn.sol3.3 KB
- src/upegs/Spawn.sol15.02 KB
src/token/Spawns.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../upegs/Spawn.sol";
import {ERC20} from "solady/src/tokens/ERC20.sol";
import {Ownable} from "solady/src/auth/Ownable.sol";
import {IStartableToken} from "./IStartableToken.sol";
interface ISvgRenderer {
function generate(uint256 seed) external view returns (string memory);
}
// $SPAWN — the first living token on Ethereum.
//
// Every buy spawns a unique on-chain creature. Every sell kills it forever.
// No two Spawns are alike. Each one is generated the moment you swap,
// rendered entirely on-chain as pixel art — no IPFS, no metadata server,
// no external dependency. Your Spawn lives and dies by the chain alone.
//
// Built on Uniswap v4 hooks. The contract watches every swap through the
// PoolManager and reacts in real-time: buy = birth, sell = death,
// transfer = your creature follows you.
//
// 10,000 tokens. 10,000 possible creatures. Fully on-chain.
contract Spawns is Spawn, ERC20, Ownable, IStartableToken {
error AddressCanNotReceiveSpawn();
uint256 public constant UNIT_PER_SPAWN = 1e18;
uint256 public constant INITIAL_SUPPLY = 10_000e18;
uint256 constant MAX_BUY_PRECISION = 100000;
uint256 constant _startMaxBuyCount =
(INITIAL_SUPPLY * 1000) / MAX_BUY_PRECISION;
uint256 constant _addMaxBuyPercentPerSec = 30;
address immutable _notMintableAccount;
uint256 _startTime;
address public hook;
address public pool;
constructor(address owner_) {
_initializeOwner(owner_);
_mint(owner_, INITIAL_SUPPLY);
_notMintableAccount = owner_;
}
modifier canReceiveSpawns(address addr) {
if (!_canReceiveSpawns(addr)) revert AddressCanNotReceiveSpawn();
_;
}
modifier onlyHook() {
require(msg.sender == hook, "only for hook");
_;
}
function name() public pure override returns (string memory) {
return "Spawns";
}
function symbol() public pure override returns (string memory) {
return "SPAWN";
}
function start(address newPool) external onlyHook {
pool = newPool;
_startTime = block.timestamp;
}
function isStarted() public view returns (bool) {
return pool != address(0);
}
function spawnArt(uint256 spawnId) external view returns (string memory) {
uint256 seed = _spawns[spawnId];
require(seed != 0, "spawn does not exist");
return ISvgRenderer(hook).generate(seed);
}
function maxBuy() public view returns (uint256) {
if (!isStarted()) return 0;
uint256 count = _startMaxBuyCount +
(INITIAL_SUPPLY *
(block.timestamp - _startTime) *
_addMaxBuyPercentPerSec) /
MAX_BUY_PRECISION;
if (count > INITIAL_SUPPLY) count = INITIAL_SUPPLY;
return count;
}
function setHook(address newHook) external onlyOwner {
hook = newHook;
}
function setImageParamsProvider(
address imageParamsProvider
) public onlyOwner {
_setImageParamsProvider(imageParamsProvider);
}
function setRandomSeedProvider(
address randomSeedProvider
) public onlyOwner {
_setRandomSeedProvider(randomSeedProvider);
}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal override {
super._afterTokenTransfer(from, to, amount);
if (pool == address(0)) return;
_onTokenTransfer(from, to, amount, createRandom());
}
function _onTokenTransfer(
address from,
address to,
uint256 amount,
Random memory random
) internal {
if (pool == address(0)) return;
if (from == pool && to != address(0)) {
if (_notMintableAccount == to) return;
require(isStarted(), "not started");
require(amount <= maxBuy(), "buy limit");
_mintSpawns(to, amount / UNIT_PER_SPAWN, random);
return;
}
uint256 from_max_allowed = balanceOf(from) / UNIT_PER_SPAWN;
uint256 from_count = this.OwnerSpawnsCount(from);
uint256 from_remove_cnount = from_count > from_max_allowed
? from_count - from_max_allowed
: 0;
uint256 to_max_allowed = balanceOf(to) / UNIT_PER_SPAWN;
uint256 to_count = this.OwnerSpawnsCount(to);
uint256 to_receive_allowed = to_count < to_max_allowed
? to_max_allowed - to_count
: 0;
if (from_remove_cnount == 0) return;
if (!_canReceiveSpawns(to)) {
to_receive_allowed = 0;
}
uint256 move_qty = from_remove_cnount < to_receive_allowed
? from_remove_cnount
: to_receive_allowed;
if (move_qty > 0) _moveSpawns(from, to, move_qty);
_burnSpawns(from, from_remove_cnount - move_qty);
}
function _mintSpawns(
address user,
uint256 qty,
Random memory random
) internal {
for (uint256 i = 0; i < qty; i++) {
_mintSpawn(user, random);
}
}
function _burnSpawns(address user, uint256 qty) internal {
for (uint256 i = 0; i < qty; i++) {
uint count = this.OwnerSpawnsCount(user);
if (count == 0) break;
uint lastIdx = count - 1;
uint spawnId = this.OwnerSpawn(user, lastIdx).id;
_burnSpawn(user, spawnId);
}
}
function _moveSpawns(
address from,
address to,
uint256 qty
) internal canReceiveSpawns(to) {
for (uint256 i = 0; i < qty; i++) {
uint count = this.OwnerSpawnsCount(from);
if (count == 0) break;
uint lastIdx = count - 1;
uint spawnId = this.OwnerSpawn(from, lastIdx).id;
_transferSpawn(from, to, spawnId);
}
}
function _canReceiveSpawns(address addr) internal view returns (bool) {
return addr != pool && addr != address(0);
}
function _afterSpawnTransferred(
address from,
address to,
uint spawnId
) internal override {
_transfer(from, to, UNIT_PER_SPAWN);
}
function _afterSpawnsListTransferred(
address from,
address to,
uint[] calldata spawnIds
) internal override {
_transfer(from, to, UNIT_PER_SPAWN * spawnIds.length);
}
}
lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
lib/solady/src/tokens/ERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple ERC20 + EIP-2612 implementation.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol)
///
/// @dev Note:
/// - The ERC20 standard allows minting and transferring to and from the zero address,
/// minting and transferring zero tokens, as well as self-approvals.
/// For performance, this implementation WILL NOT revert for such actions.
/// Please add any checks with overrides if desired.
/// - The `permit` function uses the ecrecover precompile (0x1).
///
/// If you are overriding:
/// - NEVER violate the ERC20 invariant:
/// the total sum of all balances must be equal to `totalSupply()`.
/// - 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 ERC20 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The total supply has overflowed.
error TotalSupplyOverflow();
/// @dev The allowance has overflowed.
error AllowanceOverflow();
/// @dev The allowance has underflowed.
error AllowanceUnderflow();
/// @dev Insufficient balance.
error InsufficientBalance();
/// @dev Insufficient allowance.
error InsufficientAllowance();
/// @dev The permit is invalid.
error InvalidPermit();
/// @dev The permit has expired.
error PermitExpired();
/// @dev The allowance of Permit2 is fixed at infinity.
error Permit2AllowanceIsFixedAtInfinity();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when `amount` tokens is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @dev Emitted when `amount` tokens is approved by `owner` to be used by `spender`.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @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;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The storage slot for the total supply.
uint256 private constant _TOTAL_SUPPLY_SLOT = 0x05345cdf77eb68f44c;
/// @dev The balance slot of `owner` is given by:
/// ```
/// mstore(0x0c, _BALANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let balanceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _BALANCE_SLOT_SEED = 0x87a211a2;
/// @dev The allowance slot of (`owner`, `spender`) is given by:
/// ```
/// mstore(0x20, spender)
/// mstore(0x0c, _ALLOWANCE_SLOT_SEED)
/// mstore(0x00, owner)
/// let allowanceSlot := keccak256(0x0c, 0x34)
/// ```
uint256 private constant _ALLOWANCE_SLOT_SEED = 0x7f5e9f20;
/// @dev The nonce slot of `owner` is given by:
/// ```
/// mstore(0x0c, _NONCES_SLOT_SEED)
/// mstore(0x00, owner)
/// let nonceSlot := keccak256(0x0c, 0x20)
/// ```
uint256 private constant _NONCES_SLOT_SEED = 0x38377508;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `(_NONCES_SLOT_SEED << 16) | 0x1901`.
uint256 private constant _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX = 0x383775081901;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 private constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("1")`.
/// If you need to use a different version, override `_versionHash`.
bytes32 private constant _DEFAULT_VERSION_HASH =
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6;
/// @dev `keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")`.
bytes32 private constant _PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @dev The canonical Permit2 address.
/// For signature-based allowance granting for single transaction ERC20 `transferFrom`.
/// Enabled by default. To disable, override `_givePermit2InfiniteAllowance()`.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 METADATA */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the name of the token.
function name() public view virtual returns (string memory);
/// @dev Returns the symbol of the token.
function symbol() public view virtual returns (string memory);
/// @dev Returns the decimals places of the token.
function decimals() public view virtual returns (uint8) {
return 18;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the amount of tokens in existence.
function totalSupply() public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_TOTAL_SUPPLY_SLOT)
}
}
/// @dev Returns the amount of tokens owned by `owner`.
function balanceOf(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns the amount of tokens that `spender` can spend on behalf of `owner`.
function allowance(address owner, address spender)
public
view
virtual
returns (uint256 result)
{
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return type(uint256).max;
}
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x34))
}
}
/// @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
///
/// Emits a {Approval} event.
function approve(address spender, uint256 amount) public virtual returns (bool) {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, caller(), shr(96, mload(0x2c)))
}
return true;
}
/// @dev Transfer `amount` tokens from the caller to `to`.
///
/// Requirements:
/// - `from` must at least have `amount`.
///
/// Emits a {Transfer} event.
function transfer(address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(msg.sender, to, amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, caller())
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, caller(), shr(96, mload(0x0c)))
}
_afterTokenTransfer(msg.sender, to, amount);
return true;
}
/// @dev Transfers `amount` tokens from `from` to `to`.
///
/// Note: Does not update the allowance if it is the maximum uint256 value.
///
/// Requirements:
/// - `from` must at least have `amount`.
/// - The caller must have at least `amount` of allowance to transfer the tokens of `from`.
///
/// Emits a {Transfer} event.
function transferFrom(address from, address to, uint256 amount) public virtual returns (bool) {
_beforeTokenTransfer(from, to, amount);
// Code duplication is for zero-cost abstraction if possible.
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
if iszero(eq(caller(), _PERMIT2)) {
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the allowance slot and load its value.
mstore(0x20, caller())
mstore(0x0c, or(from_, _ALLOWANCE_SLOT_SEED))
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
}
_afterTokenTransfer(from, to, amount);
return true;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-2612 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For more performance, override to return the constant value
/// of `keccak256(bytes(name()))` if `name()` will never change.
function _constantNameHash() internal view virtual returns (bytes32 result) {}
/// @dev If you need a different value, override this function.
function _versionHash() internal view virtual returns (bytes32 result) {
result = _DEFAULT_VERSION_HASH;
}
/// @dev For inheriting contracts to increment the nonce.
function _incrementNonce(address owner) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
sstore(nonceSlot, add(1, sload(nonceSlot)))
}
}
/// @dev Returns the current nonce for `owner`.
/// This value is used to compute the signature for EIP-2612 permit.
function nonces(address owner) public view virtual returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
// Compute the nonce slot and load its value.
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Sets `value` as the allowance of `spender` over the tokens of `owner`,
/// authorized by a signed approval by `owner`.
///
/// Emits a {Approval} event.
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && value != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(value)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
// Revert if the block timestamp is greater than `deadline`.
if gt(timestamp(), deadline) {
mstore(0x00, 0x1a15a3cc) // `PermitExpired()`.
revert(0x1c, 0x04)
}
let m := mload(0x40) // Grab the free memory pointer.
// Clean the upper 96 bits.
owner := shr(96, shl(96, owner))
spender := shr(96, shl(96, spender))
// Compute the nonce slot and load its value.
mstore(0x0e, _NONCES_SLOT_SEED_WITH_SIGNATURE_PREFIX)
mstore(0x00, owner)
let nonceSlot := keccak256(0x0c, 0x20)
let nonceValue := sload(nonceSlot)
// Prepare the domain separator.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
mstore(0x2e, keccak256(m, 0xa0))
// Prepare the struct hash.
mstore(m, _PERMIT_TYPEHASH)
mstore(add(m, 0x20), owner)
mstore(add(m, 0x40), spender)
mstore(add(m, 0x60), value)
mstore(add(m, 0x80), nonceValue)
mstore(add(m, 0xa0), deadline)
mstore(0x4e, keccak256(m, 0xc0))
// Prepare the ecrecover calldata.
mstore(0x00, keccak256(0x2c, 0x42))
mstore(0x20, and(0xff, v))
mstore(0x40, r)
mstore(0x60, s)
let t := staticcall(gas(), 1, 0x00, 0x80, 0x20, 0x20)
// If the ecrecover fails, the returndatasize will be 0x00,
// `owner` will be checked if it equals the hash at 0x00,
// which evaluates to false (i.e. 0), and we will revert.
// If the ecrecover succeeds, the returndatasize will be 0x20,
// `owner` will be compared against the returned address at 0x20.
if iszero(eq(mload(returndatasize()), owner)) {
mstore(0x00, 0xddafbaef) // `InvalidPermit()`.
revert(0x1c, 0x04)
}
// Increment and store the updated nonce.
sstore(nonceSlot, add(nonceValue, t)) // `t` is 1 if ecrecover succeeds.
// Compute the allowance slot and store the value.
// The `owner` is already at slot 0x20.
mstore(0x40, or(shl(160, _ALLOWANCE_SLOT_SEED), spender))
sstore(keccak256(0x2c, 0x34), value)
// Emit the {Approval} event.
log3(add(m, 0x60), 0x20, _APPROVAL_EVENT_SIGNATURE, owner, spender)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Returns the EIP-712 domain separator for the EIP-2612 permit.
function DOMAIN_SEPARATOR() public view virtual returns (bytes32 result) {
bytes32 nameHash = _constantNameHash();
// We simply calculate it on-the-fly to allow for cases where the `name` may change.
if (nameHash == bytes32(0)) nameHash = keccak256(bytes(name()));
bytes32 versionHash = _versionHash();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Grab 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())
result := keccak256(m, 0xa0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL MINT FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Mints `amount` tokens to `to`, increasing the total supply.
///
/// Emits a {Transfer} event.
function _mint(address to, uint256 amount) internal virtual {
_beforeTokenTransfer(address(0), to, amount);
/// @solidity memory-safe-assembly
assembly {
let totalSupplyBefore := sload(_TOTAL_SUPPLY_SLOT)
let totalSupplyAfter := add(totalSupplyBefore, amount)
// Revert if the total supply overflows.
if lt(totalSupplyAfter, totalSupplyBefore) {
mstore(0x00, 0xe5cfe957) // `TotalSupplyOverflow()`.
revert(0x1c, 0x04)
}
// Store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, totalSupplyAfter)
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, 0, shr(96, mload(0x0c)))
}
_afterTokenTransfer(address(0), to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL BURN FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Burns `amount` tokens from `from`, reducing the total supply.
///
/// Emits a {Transfer} event.
function _burn(address from, uint256 amount) internal virtual {
_beforeTokenTransfer(from, address(0), amount);
/// @solidity memory-safe-assembly
assembly {
// Compute the balance slot and load its value.
mstore(0x0c, _BALANCE_SLOT_SEED)
mstore(0x00, from)
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Subtract and store the updated total supply.
sstore(_TOTAL_SUPPLY_SLOT, sub(sload(_TOTAL_SUPPLY_SLOT), amount))
// Emit the {Transfer} event.
mstore(0x00, amount)
log3(0x00, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, shl(96, from)), 0)
}
_afterTokenTransfer(from, address(0), amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL TRANSFER FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Moves `amount` of tokens from `from` to `to`.
function _transfer(address from, address to, uint256 amount) internal virtual {
_beforeTokenTransfer(from, to, amount);
/// @solidity memory-safe-assembly
assembly {
let from_ := shl(96, from)
// Compute the balance slot and load its value.
mstore(0x0c, or(from_, _BALANCE_SLOT_SEED))
let fromBalanceSlot := keccak256(0x0c, 0x20)
let fromBalance := sload(fromBalanceSlot)
// Revert if insufficient balance.
if gt(amount, fromBalance) {
mstore(0x00, 0xf4d678b8) // `InsufficientBalance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated balance.
sstore(fromBalanceSlot, sub(fromBalance, amount))
// Compute the balance slot of `to`.
mstore(0x00, to)
let toBalanceSlot := keccak256(0x0c, 0x20)
// Add and store the updated balance of `to`.
// Will not overflow because the sum of all user balances
// cannot exceed the maximum uint256 value.
sstore(toBalanceSlot, add(sload(toBalanceSlot), amount))
// Emit the {Transfer} event.
mstore(0x20, amount)
log3(0x20, 0x20, _TRANSFER_EVENT_SIGNATURE, shr(96, from_), shr(96, mload(0x0c)))
}
_afterTokenTransfer(from, to, amount);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL ALLOWANCE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Updates the allowance of `owner` for `spender` based on spent `amount`.
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
if (spender == _PERMIT2) return; // Do nothing, as allowance is infinite.
}
/// @solidity memory-safe-assembly
assembly {
// Compute the allowance slot and load its value.
mstore(0x20, spender)
mstore(0x0c, _ALLOWANCE_SLOT_SEED)
mstore(0x00, owner)
let allowanceSlot := keccak256(0x0c, 0x34)
let allowance_ := sload(allowanceSlot)
// If the allowance is not the maximum uint256 value.
if not(allowance_) {
// Revert if the amount to be transferred exceeds the allowance.
if gt(amount, allowance_) {
mstore(0x00, 0x13be252b) // `InsufficientAllowance()`.
revert(0x1c, 0x04)
}
// Subtract and store the updated allowance.
sstore(allowanceSlot, sub(allowance_, amount))
}
}
}
/// @dev Sets `amount` as the allowance of `spender` over the tokens of `owner`.
///
/// Emits a {Approval} event.
function _approve(address owner, address spender, uint256 amount) internal virtual {
if (_givePermit2InfiniteAllowance()) {
/// @solidity memory-safe-assembly
assembly {
// If `spender == _PERMIT2 && amount != type(uint256).max`.
if iszero(or(xor(shr(96, shl(96, spender)), _PERMIT2), iszero(not(amount)))) {
mstore(0x00, 0x3f68539a) // `Permit2AllowanceIsFixedAtInfinity()`.
revert(0x1c, 0x04)
}
}
}
/// @solidity memory-safe-assembly
assembly {
let owner_ := shl(96, owner)
// Compute the allowance slot and store the amount.
mstore(0x20, spender)
mstore(0x0c, or(owner_, _ALLOWANCE_SLOT_SEED))
sstore(keccak256(0x0c, 0x34), amount)
// Emit the {Approval} event.
mstore(0x00, amount)
log3(0x00, 0x20, _APPROVAL_EVENT_SIGNATURE, shr(96, owner_), shr(96, mload(0x2c)))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HOOKS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Hook that is called before any transfer of tokens.
/// This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/// @dev Hook that is called after any transfer of tokens.
/// This includes minting and burning.
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PERMIT2 */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns whether to fix the Permit2 contract's allowance at infinity.
///
/// This value should be kept constant after contract initialization,
/// or else the actual allowance values may not match with the {Approval} events.
/// For best performance, return a compile-time constant for zero-cost abstraction.
function _givePermit2InfiniteAllowance() internal view virtual returns (bool) {
return true;
}
}
src/library/IRandomSeedProvider.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Interface for providing a random seed.
interface IRandomSeedProvider {
/// @dev Returns a seed for pseudo-random generation.
function randomSeed() external view returns (uint256);
}src/library/RandomLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Structure for pseudo-random generator state.
struct Random {
uint seed;
uint nonce;
}
/// @dev Library for pseudo-random number generation.
library RandomLibrary {
/// @dev Generates the next pseudo-random number.
/// @param random Generator state struct.
function next(Random memory random) internal pure returns (uint) {
return uint(keccak256(abi.encodePacked(random.seed, ++random.nonce)));
}
}
src/svg_generation/IImageParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Generation parameters (element counts and palette sizes).
struct ImageParams {
// palette sizes
uint8 colorsCount; // full color palette
uint8 backgroundColorsCount; // background palette
// element counts per layer
uint relicCount;
uint coreCount;
uint gazeCount;
uint crownCount;
uint tusksCount;
uint clawsFrontCount;
uint clawsBackCount;
uint trailCount;
uint realmCount;
uint wingsCount;
}
interface IImageParams {
/// @dev Returns aggregated parameters for seed/Spawn generation.
function getImageParams() external view returns (ImageParams memory);
}
src/svg_generation/SpawnMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Metadata structure for Spawn.
/// If a value is 0, the item is absent in Spawn.
struct SpawnMetadata {
uint8 backGroundColor; // background color (can be 0)
uint8 core;
uint8 gaze;
uint8 crown;
uint8 tusks;
uint8 clawsBack;
uint8 clawsFront;
uint8 wings;
uint8 trail;
uint8 relic;
uint8 realm;
uint8 coreColor; // body color index (legs and wings use the same color)
uint8 gazeColor;
uint8 crownColor;
uint8 tusksColor;
uint8 realmColor;
uint8 relicColor;
uint8 trailColor;
}
/// @dev Library for encoding/decoding SpawnMetadata into uint256.
/// Each item is omitted if its value is 0.
/// 1 byte - background color (can be 0)
/// 2 byte - horn
/// 3 byte - accessories
/// 4 byte - hair
/// 5 byte - wings
/// 6 byte - tail
/// 7 byte - front legs
/// 8 byte - back legs
/// 9 byte - eyes
/// 10 byte - body
/// 11 byte - ground
/// 12 byte - body color (legs and wings use the same color)
/// 13 byte - eyes color
/// 14 byte - hair color
/// 15 byte - horn color
/// 16 byte - ground color
/// 17 byte - accessories color
/// 18 byte - tail color
library SpawnMetadataLibrary {
/// @dev Encodes SpawnMetadata into uint256.
function encode(SpawnMetadata memory seed) internal pure returns (uint256 result) {
result |= uint256(seed.backGroundColor) << 0;
result |= uint256(seed.tusks) << 8;
result |= uint256(seed.relic) << 16;
result |= uint256(seed.crown) << 24;
result |= uint256(seed.wings) << 32;
result |= uint256(seed.trail) << 40;
result |= uint256(seed.clawsFront) << 48;
result |= uint256(seed.clawsBack) << 56;
result |= uint256(seed.gaze) << 64;
result |= uint256(seed.core) << 72;
result |= uint256(seed.realm) << 80;
result |= uint256(seed.coreColor) << 88;
result |= uint256(seed.gazeColor) << 96;
result |= uint256(seed.crownColor) << 104;
result |= uint256(seed.tusksColor) << 112;
result |= uint256(seed.realmColor) << 120;
result |= uint256(seed.relicColor) << 128;
result |= uint256(seed.trailColor) << 136;
}
/// @dev Decodes uint256 into SpawnMetadata.
function decode(uint256 seed) internal pure returns (SpawnMetadata memory) {
return
SpawnMetadata({
backGroundColor: uint8(seed & 0xFF),
core: uint8((seed >> 72) & 0xFF),
gaze: uint8((seed >> 64) & 0xFF),
crown: uint8((seed >> 24) & 0xFF),
tusks: uint8((seed >> 8) & 0xFF),
clawsBack: uint8((seed >> 56) & 0xFF),
clawsFront: uint8((seed >> 48) & 0xFF),
wings: uint8((seed >> 32) & 0xFF),
trail: uint8((seed >> 40) & 0xFF),
relic: uint8((seed >> 16) & 0xFF),
realm: uint8((seed >> 80) & 0xFF),
coreColor: uint8((seed >> 88) & 0xFF),
gazeColor: uint8((seed >> 96) & 0xFF),
crownColor: uint8((seed >> 104) & 0xFF),
tusksColor: uint8((seed >> 112) & 0xFF),
realmColor: uint8((seed >> 120) & 0xFF),
relicColor: uint8((seed >> 128) & 0xFF),
trailColor: uint8((seed >> 136) & 0xFF)
});
}
}
src/token/IStartableToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Interface for a token with a start action.
interface IStartableToken {
/// @notice Sets the liquidity pool address and enables buying.
function start(address newPool) external;
/// @notice Checks whether the token is started.
function isStarted() external view returns (bool);
}src/upegs/ISpawn.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Spawn data structure.
struct SpawnSeedData {
/// @dev Spawn ID.
uint256 id;
/// @dev Spawn seed.
uint256 seed;
}
/// @dev Spawn collection interface.
/// Each owner has a list of Spawns with unique IDs and seed values.
interface ISpawn {
/// @dev Error when the caller doesn't own the Spawn.
error NotSpawnOwner();
/// @dev Error when Spawn index is out of range.
error SpawnIndexOutOfRange();
/// @dev Spawn mint event.
event OnSpawnMinted(address indexed owner, uint spawnId);
/// @dev Spawn burn event.
event OnSpawnBurned(address indexed owner, uint spawnId);
/// @dev Spawn transfer event.
event OnSpawnTransfer(address indexed from, address indexed to, uint spawnId);
/// @dev Total Spawn count.
function SpawnsTotalCount() external view returns (uint);
/// @dev Total holder count.
function HoldersCount() external view returns (uint);
/// @dev Spawn count for an owner.
function OwnerSpawnsCount(address owner) external view returns (uint);
/// @dev Returns a paginated list of Spawns.
/// @param owner Owner address
/// @param page Page number
/// @param pageSize Page size
function OwnerSpawnsPage(address owner, uint page, uint pageSize) external view returns (SpawnSeedData[] memory spawns);
/// @dev Spawn for an owner by index.
/// @param owner Owner address
/// @param index Spawn index
function OwnerSpawn(address owner, uint index) external view returns (SpawnSeedData memory);
/// @dev Spawn index for an owner by ID.
/// @param owner Owner address
/// @param spawnId Spawn ID
function OwnerSpawnIndex(address owner, uint spawnId) external view returns (uint index);
/// @dev Reorders a Spawn for an owner. Shifts all items left/right (may be gas-inefficient).
/// @param owner Owner address
/// @param spawnId Spawn ID to reorder
/// @param newIndex New index
function ReorderSpawn(address owner, uint spawnId, uint newIndex) external;
/// @dev Reorders a Spawn for an owner. Gas-optimized swap without shifting.
/// @param owner Owner address
/// @param spawnId Spawn ID to reorder
/// @param newIndex New index or swap index
function ReorderSpawnPair(address owner, uint spawnId, uint newIndex) external;
/// @dev Checks if the owner owns a Spawn by ID.
function OwnerOwns(address owner, uint spawnId) external view returns (bool);
/// @dev Checks if the owner is a holder.
function IsHolder(address owner) external view returns (bool);
/// @dev Holder by index.
function Holder(uint index) external view returns (address);
/// @dev Holder number by address.
function HolderNumber(address owner) external view returns (uint);
/// @dev Transfers a Spawn to an address. One token is transferred with the Spawn.
/// @param to Recipient address
/// @param spawnId Spawn ID
function transferSpawn(address to, uint spawnId) external;
/// @dev Transfers multiple Spawns. Transfers the same number of tokens.
/// @param to Recipient address
/// @param spawnIds Array of Spawn IDs
function transferSpawnsList(
address to,
uint[] calldata spawnIds
) external;
}src/upegs/Spawn.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./ISpawn.sol";
import "../svg_generation/SpawnMetadata.sol";
import "../svg_generation/IImageParams.sol";
import "../library/RandomLib.sol";
import "../library/IRandomSeedProvider.sol";
/// @dev Allows creating and storing Spawns by owner address.
/// @notice Spawn is a set of data that defines the token appearance.
/// @notice To save storage, Spawn is stored as an encoded uint256 (non-zero).
/// @notice A list of Spawn holders is maintained.
/// Each Spawn has a unique non-zero ID.
/// By ID you can get the encoded Spawn and decode it into SpawnMetadata.
contract Spawn is ISpawn {
using RandomLibrary for Random;
// all Spawns
mapping(uint spawnId => uint256 seed) _spawns; // encoded Spawns by ID
// Spawns for each owner
mapping(address owner => uint) _counts; // Spawn count per owner
mapping(address owner => mapping(uint index => uint256 spawnId)) _ownedSpawns; // Spawn by owner index
mapping(address owner => mapping(uint spawnId => uint index)) _ownedSpawnsIndexes; // Spawn indices by ID
mapping(address owner => mapping(uint spawnId => bool isOwn)) _owns; // ownership by Spawn ID
// Spawn holders list
mapping(uint index => address user) _holderList;
mapping(address user => uint index) _holderListNumbers; // holder number in list (0 means not a holder)
uint _spawnsTotalCount; // total Spawn count
uint _holdersCount; // total holder count
IRandomSeedProvider public randomSeedProvider; // random seed provider
/// @dev Image parameters provider (element counts and palette sizes).
IImageParams public imageParams;
/// @dev Inserts an existing Spawn (by spawnId) into the owner's list.
/// @notice Seed must already exist in _spawns[spawnId].
function _insertExistingSpawnToOwner(address owner, uint spawnId) internal {
// add to owner's list
_ownedSpawns[owner][_counts[owner]] = spawnId;
_ownedSpawnsIndexes[owner][spawnId] = _counts[owner];
_counts[owner]++;
_owns[owner][spawnId] = true;
// add owner to holder list if not present
if (!IsHolder(owner)) {
_holderList[_holdersCount] = owner;
_holderListNumbers[owner] = ++_holdersCount;
}
}
/// @dev Removes Spawn from owner's list (but does NOT delete the seed).
function _removeSpawnFromOwner(address owner, uint spawnId) internal {
// index of the removed item
uint idx = _ownedSpawnsIndexes[owner][spawnId];
uint lastIdx = _counts[owner] - 1;
if (idx != lastIdx) {
// swap-with-last to keep list compact
uint256 lastId = _ownedSpawns[owner][lastIdx];
_ownedSpawns[owner][idx] = lastId;
_ownedSpawnsIndexes[owner][lastId] = idx;
}
// clear last slot and indices
delete _ownedSpawns[owner][lastIdx];
delete _ownedSpawnsIndexes[owner][spawnId];
_counts[owner]--;
_owns[owner][spawnId] = false;
// remove owner from holder list if they own none
if (_counts[owner] == 0 && IsHolder(owner)) {
_removeHolder(owner);
}
}
/// @dev Restricts function to the Spawn owner.
modifier onlySpawnOwner(uint spawnId) {
if (!_owns[msg.sender][spawnId]) revert NotSpawnOwner();
_;
}
/// @dev Ensures Spawn index is within bounds.
modifier onlySpawnIndex(address owner, uint index) {
if (index >= _counts[owner]) revert SpawnIndexOutOfRange();
_;
}
/// @dev Sets the random seed provider.
/// @param newRandomSeedProvider Contract implementing IRandomSeedProvider
function _setRandomSeedProvider(address newRandomSeedProvider) internal {
randomSeedProvider = IRandomSeedProvider(newRandomSeedProvider);
}
/// @dev Creates a random generator state struct.
function createRandom() internal view returns (Random memory) {
return Random(randomSeedProvider.randomSeed(), 0);
}
/// @dev Sets the image parameters provider.
/// @param imageParamsProvider Contract implementing IImageParams
function _setImageParamsProvider(address imageParamsProvider) internal {
imageParams = IImageParams(imageParamsProvider);
}
/// @dev Returns true with probability prob% (0..100).
function _chance(
uint prob,
Random memory random
) internal pure returns (bool) {
return (random.next() % 100) < prob;
}
/// @dev Picks id in 1..count (0 if count == 0).
function _pickId(
uint count,
Random memory random
) internal pure returns (uint8) {
if (count == 0) return 0;
return uint8((random.next() % count) + 1);
}
/// @dev Picks a color index in 0..(max-1).
function _pickColor(
uint8 max,
Random memory random
) internal pure returns (uint8) {
if (max == 0) return 0;
return uint8(random.next() % max);
}
function IsHolder(address owner) public view returns (bool) {
return _holderListNumbers[owner] > 0;
}
function SpawnsTotalCount() external view returns (uint) {
return _spawnsTotalCount;
}
function HoldersCount() external view returns (uint) {
return _holdersCount;
}
function OwnerSpawnsCount(address owner) public view returns (uint) {
return _counts[owner];
}
function OwnerSpawn(
address owner,
uint index
) external view returns (SpawnSeedData memory) {
if (index >= _counts[owner]) revert SpawnIndexOutOfRange();
uint256 id = _ownedSpawns[owner][index];
return SpawnSeedData({id: id, seed: _spawns[id]});
}
function OwnerSpawnIndex(
address owner,
uint spawnId
) external view returns (uint index) {
if (!_owns[owner][spawnId]) revert NotSpawnOwner();
return _ownedSpawnsIndexes[owner][spawnId];
}
function OwnerOwns(
address owner,
uint spawnId
) external view returns (bool) {
return _owns[owner][spawnId];
}
function Holder(uint index) external view returns (address) {
return _holderList[index];
}
function HolderNumber(address owner) external view returns (uint) {
return _holderListNumbers[owner];
}
/// @notice returns a page of spawn IDs and seeds for a given owner
/// @param owner owner address
/// @param page zero-based page index
/// @param pageSize number of items per page
function OwnerSpawnsPage(
address owner,
uint page,
uint pageSize
) external view override returns (SpawnSeedData[] memory spawns) {
uint count = _counts[owner];
if (pageSize == 0) return new SpawnSeedData[](0);
uint start = page * pageSize;
if (start >= count) return new SpawnSeedData[](0);
uint end = start + pageSize;
if (end > count) end = count;
uint len = end - start;
spawns = new SpawnSeedData[](len);
for (uint i = 0; i < len; i++) {
uint idx = start + i;
uint256 inscId = _ownedSpawns[owner][idx];
spawns[i] = SpawnSeedData({id: inscId, seed: _spawns[inscId]});
}
}
/// @dev Reorders owner's Spawn: spawnId goes to newIndex, others shift.
function ReorderSpawn(
address owner,
uint spawnId,
uint newIndex
) external override onlySpawnOwner(spawnId) onlySpawnIndex(owner, newIndex) {
uint currentIndex = _ownedSpawnsIndexes[owner][spawnId];
if (newIndex == currentIndex) return;
// take out element
uint256 id = _ownedSpawns[owner][currentIndex];
// shift based on direction
if (newIndex < currentIndex) {
// shift right: [newIndex .. currentIndex-1] -> +1
for (uint i = currentIndex; i > newIndex; i--) {
_ownedSpawns[owner][i] = _ownedSpawns[owner][i - 1];
_ownedSpawnsIndexes[owner][_ownedSpawns[owner][i]] = i;
}
} else {
// newIndex > currentIndex: shift left: [currentIndex+1 .. newIndex] -> -1
for (uint i = currentIndex; i < newIndex; i++) {
_ownedSpawns[owner][i] = _ownedSpawns[owner][i + 1];
_ownedSpawnsIndexes[owner][_ownedSpawns[owner][i]] = i;
}
}
// place element into new slot
_ownedSpawns[owner][newIndex] = id;
_ownedSpawnsIndexes[owner][id] = newIndex;
}
/// @dev Swaps spawnId with the element at newIndex without shifting (gas-optimized).
function ReorderSpawnPair(
address owner,
uint spawnId,
uint newIndex
) external override onlySpawnOwner(spawnId) onlySpawnIndex(owner, newIndex) {
uint currentIndex = _ownedSpawnsIndexes[owner][spawnId];
if (newIndex == currentIndex) return;
uint256 otherId = _ownedSpawns[owner][newIndex];
// swap in array
_ownedSpawns[owner][newIndex] = spawnId;
_ownedSpawns[owner][currentIndex] = otherId;
// update indices
_ownedSpawnsIndexes[owner][spawnId] = newIndex;
_ownedSpawnsIndexes[owner][otherId] = currentIndex;
}
/// @notice Creates a new Spawn for the owner.
/// @param owner Owner address
/// @param seed Encoded Spawn value
function _mintSpawn(address owner, uint256 seed) internal {
SpawnSeedData memory seedData = _createSpawn(owner, seed);
emit OnSpawnMinted(owner, seedData.id);
}
/// @notice Creates a new Spawn for the owner.
/// @param owner Owner address
function _mintSpawn(address owner, Random memory random) internal {
_mintSpawn(owner, _nextSpawn(random));
}
function _createSpawn(
address owner,
uint256 seed
) private returns (SpawnSeedData memory seedData) {
uint spawnId = ++_spawnsTotalCount;
_spawns[spawnId] = seed;
_insertExistingSpawnToOwner(owner, spawnId);
return SpawnSeedData({id: spawnId, seed: seed});
}
/// @notice Generates a random Spawn.
/// @param random Generator state struct
function _nextSpawn(
Random memory random
) internal view returns (uint256 seed) {
// get aggregated parameters (element counts and palette sizes)
ImageParams memory p = imageParams.getImageParams();
SpawnMetadata memory s;
// background (100%) — index in 0..backgroundColorsCount-1
s.backGroundColor = p.backgroundColorsCount == 0
? 0
: uint8(random.next() % p.backgroundColorsCount);
// horn (20%)
if (_chance(20, random)) {
s.tusks = _pickId(p.tusksCount, random);
if (s.tusks > 0) {
s.tusksColor = _pickColor(p.colorsCount, random);
}
}
// accessories (30%)
if (_chance(30, random)) {
s.relic = _pickId(p.relicCount, random);
if (s.relic > 0) {
s.relicColor = _pickColor(p.colorsCount, random);
}
}
// hair (80%)
if (_chance(80, random)) {
s.crown = _pickId(p.crownCount, random);
if (s.crown > 0) {
s.crownColor = _pickColor(p.colorsCount, random);
}
}
// wings (30%) — use body color, no separate color
if (_chance(30, random)) {
s.wings = _pickId(p.wingsCount, random);
}
// tail (80%)
if (_chance(80, random)) {
s.trail = _pickId(p.trailCount, random);
if (s.trail > 0) {
s.trailColor = _pickColor(p.colorsCount, random);
}
}
// front legs (100%)
s.clawsFront = _pickId(p.clawsFrontCount, random);
// back legs (100%)
s.clawsBack = _pickId(p.clawsBackCount, random);
// eyes (100%)
s.gaze = _pickId(p.gazeCount, random);
if (s.gaze > 0) {
s.gazeColor = _pickColor(p.colorsCount, random);
}
// body (100%)
s.core = _pickId(p.coreCount, random);
if (s.core > 0) {
s.coreColor = _pickColor(p.colorsCount, random);
}
// ground (100%)
s.realm = _pickId(p.realmCount, random);
if (s.realm > 0) {
s.realmColor = _pickColor(p.colorsCount, random);
}
// encode struct into uint256
seed = SpawnMetadataLibrary.encode(s);
return seed;
}
/// @notice Removes a Spawn from the owner.
/// @param owner Owner address
/// @param spawnId Spawn ID
function _burnSpawn(
address owner,
uint spawnId
) internal returns (uint256 seed) {
uint256 deletedSeed = _deleteSpawn(owner, spawnId);
emit OnSpawnBurned(owner, spawnId);
return deletedSeed;
}
function _deleteSpawn(
address owner,
uint spawnId
) internal returns (uint256 seed) {
// remove ownership and delete from owner's list
_removeSpawnFromOwner(owner, spawnId);
// delete seed
seed = _spawns[spawnId];
delete _spawns[spawnId];
return seed;
}
/// @notice Transfers a Spawn from one owner to another.
/// @param from Sender address
/// @param to Recipient address
/// @param spawnId Spawn ID
function _transferSpawn(address from, address to, uint spawnId) internal {
// remove spawnId from sender list, keep seed
_removeSpawnFromOwner(from, spawnId);
// insert same spawnId into receiver list (ID preserved)
_insertExistingSpawnToOwner(to, spawnId);
emit OnSpawnTransfer(from, to, spawnId);
}
/// @notice Removes holder from the holder list.
/// @param owner Owner address
function _removeHolder(address owner) internal {
delete _holderList[_holderListNumbers[owner]];
delete _holderListNumbers[owner];
_holdersCount--;
}
function transferSpawn(
address to,
uint spawnId
) external override onlySpawnOwner(spawnId) {
_transferSpawn(msg.sender, to, spawnId);
_afterSpawnTransferred(msg.sender, to, spawnId);
}
function transferSpawnsList(
address to,
uint[] calldata spawnIds
) external override {
uint len = spawnIds.length;
if (len == 0) return;
for (uint i = 0; i < len; ++i) {
if (!_owns[msg.sender][spawnIds[i]]) revert NotSpawnOwner();
_transferSpawn(msg.sender, to, spawnIds[i]);
}
_afterSpawnsListTransferred(msg.sender, to, spawnIds);
}
function _afterSpawnTransferred(
address from,
address to,
uint spawnId
) internal virtual {}
function _afterSpawnsListTransferred(
address from,
address to,
uint[] calldata spawnIds
) internal virtual {}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/contracts/=lib/uniswap-hooks/lib/openzeppelin-contracts/contracts/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/uniswap-hooks/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"uniswap-hooks/=lib/uniswap-hooks/src/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.