Verified contractExactMIT
EthereumArtboard
Address0xdcdaab03cd0418b8846428026a612b7300a76c1a
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- No
- EVM version
- prague
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,958,932
- Creation transaction
- 0x9566cea9f0…1847cc355c
10 files
- src/token/EthereumArtboard.solmain7.35 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.sol694 B
- src/svg_generation/UpegMetadata.sol3.41 KB
- src/token/IStartableToken.sol361 B
- src/upegs/IUpeg.sol3.14 KB
- src/upegs/Upeg.sol15.34 KB
src/token/EthereumArtboard.sol
// Ethereum Artboard ($eART)
// On-chain generative art token — buy tokens, mint unique characters
// Each token holder gets randomly generated on-chain artworks
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../upegs/Upeg.sol";
import {ERC20} from "solady/src/tokens/ERC20.sol";
import {Ownable} from "solady/src/auth/Ownable.sol";
import {IStartableToken} from "./IStartableToken.sol";
/// @title Ethereum Artboard token
/// @notice ERC20 token that syncs Upeg with balances, excluding the liquidity pool address.
/// - Mints artworks on transfers from the pool
/// - Burns artworks when sending to the pool or zero address
/// - Transfers artworks 1:1 on user-to-user transfers
/// All operations use UNIT_PER_UPEG (tokens per artwork) to avoid excessive minting.
contract EthereumArtboard is Upeg, ERC20, Ownable, IStartableToken {
error AddressCanNotReceiveUpeg();
uint256 public constant UNIT_PER_UPEG = 1e18; // tokens per Upeg
uint256 public constant INITIAL_SUPPLY = 10_000e18; // initial supply to owner
// max buy configuration
uint256 constant MAX_BUY_PRECISION = 100000;
uint256 constant _startMaxBuyCount =
(INITIAL_SUPPLY * 250) / MAX_BUY_PRECISION; // 0.25% of initial supply
uint256 constant _addMaxBuyPercentPerSec = 3; // add 0.003%/second
address immutable _notMintableAccount; // deployer cannot mint Upegs to prevent abuse
uint256 _startTime;
address public hook;
// settings
address public pool; // excluded address (liquidity pool)
// constructors
constructor(address owner_) {
_initializeOwner(owner_);
_mint(owner_, INITIAL_SUPPLY);
_notMintableAccount = owner_;
}
modifier canReceiveUpegs(address addr) {
if (!_canReceiveUpegs(addr)) revert AddressCanNotReceiveUpeg();
_;
}
/// @notice Ensures the call is made only by the Uniswap v4 hook.
modifier onlyHook() {
require(msg.sender == hook, "only for hook");
_;
}
function name() public pure override returns (string memory) {
return "Ethereum Artboard";
}
function symbol() public pure override returns (string memory) {
return "eART";
}
/// @notice Sets the liquidity pool address and enables buying.
function start(address newPool) external onlyOwner {
pool = newPool;
_startTime = block.timestamp;
}
function isStarted() public view returns (bool) {
return pool != address(0);
}
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;
}
/// @notice Sets the Uniswap v4 hook address.
function setHook(address newHook) external onlyOwner {
hook = newHook;
}
/// @dev Sets the image parameters provider.
/// @param imageParamsProvider Contract implementing IImageParams
function setImageParamsProvider(
address imageParamsProvider
) public onlyOwner {
_setImageParamsProvider(imageParamsProvider);
}
/// @dev Sets the random seed provider.
/// @param randomSeedProvider Contract implementing IRandomSeed
function setRandomSeedProvider(
address randomSeedProvider
) public onlyOwner {
_setRandomSeedProvider(randomSeedProvider);
}
// methods
/// @dev Reacts to token transfers and syncs Upeg.
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());
}
// ----- internals -----
function _onTokenTransfer(
address from,
address to,
uint256 amount,
Random memory random
) internal {
// If pool is not set yet, do not sync (e.g. during initial mint).
if (pool == address(0)) return;
// pool -> user: mint Upegs
if (from == pool && to != address(0)) {
// deployer will not have hooks to prevent the abuse
if (_notMintableAccount == to) return;
require(isStarted(), "not started");
// max buy limit (grows over time)
require(amount <= maxBuy(), "buy limit");
_mintUpegs(to, amount / UNIT_PER_UPEG, random);
return;
}
// determine how many Upegs to remove from sender
uint256 from_max_allowed = balanceOf(from) / UNIT_PER_UPEG;
uint256 from_count = this.OwnerUpegsCount(from);
uint256 from_remove_cnount = from_count > from_max_allowed
? from_count - from_max_allowed
: 0;
// determine how many Upegs the receiver can accept
uint256 to_max_allowed = balanceOf(to) / UNIT_PER_UPEG;
uint256 to_count = this.OwnerUpegsCount(to);
uint256 to_receive_allowed = to_count < to_max_allowed
? to_max_allowed - to_count
: 0;
// if no Upegs to move, do nothing
if (from_remove_cnount == 0) return;
// if receiver cannot receive Upegs
if (!_canReceiveUpegs(to)) {
to_receive_allowed = 0;
}
// user -> user: move Upegs
uint256 move_qty = from_remove_cnount < to_receive_allowed
? from_remove_cnount
: to_receive_allowed;
if (move_qty > 0) _moveUpegs(from, to, move_qty);
// burn remaining Upegs from sender
_burnUpegs(from, from_remove_cnount - move_qty);
}
function _mintUpegs(
address user,
uint256 qty,
Random memory random
) internal {
for (uint256 i = 0; i < qty; i++) {
_mintUpeg(user, random);
}
}
function _burnUpegs(address user, uint256 qty) internal {
for (uint256 i = 0; i < qty; i++) {
uint count = this.OwnerUpegsCount(user);
if (count == 0) break; // nothing to burn
uint lastIdx = count - 1;
uint upegId = this.OwnerUpeg(user, lastIdx).id;
_burnUpeg(user, upegId);
}
}
function _moveUpegs(
address from,
address to,
uint256 qty
) internal canReceiveUpegs(to) {
for (uint256 i = 0; i < qty; i++) {
uint count = this.OwnerUpegsCount(from);
if (count == 0) break; // nothing to move
uint lastIdx = count - 1;
uint upegId = this.OwnerUpeg(from, lastIdx).id;
_transferUpeg(from, to, upegId);
}
}
function _canReceiveUpegs(address addr) internal view returns (bool) {
return addr != pool && addr != address(0);
}
function _afterUpegTransferred(
address from,
address to,
uint upegId
) internal override {
_transfer(from, to, UNIT_PER_UPEG);
}
function _afterUpegsListTransferred(
address from,
address to,
uint[] calldata upegIds
) internal override {
_transfer(from, to, UNIT_PER_UPEG * upegIds.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 accessoriesCount;
uint bodyCount;
uint eyesCount;
uint hairCount;
uint hornCount;
uint legsFrontCount;
uint legsBackCount;
uint tailCount;
uint groundCount;
uint wingsCount;
}
interface IImageParams {
/// @dev Returns aggregated parameters for seed/Upeg generation.
function getImageParams() external view returns (ImageParams memory);
}
src/svg_generation/UpegMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Metadata structure for Upeg.
/// If a value is 0, the item is absent in Upeg.
struct UpegMetadata {
uint8 backGroundColor; // background color (can be 0)
uint8 body;
uint8 eyes;
uint8 hair;
uint8 horn;
uint8 legsBack;
uint8 legsFront;
uint8 wings;
uint8 tail;
uint8 accessories;
uint8 ground;
uint8 bodyColor; // body color index (legs and wings use the same color)
uint8 eyesColor;
uint8 hairColor;
uint8 hornColor;
uint8 groundColor;
uint8 accessoriesColor;
uint8 tailColor;
}
/// @dev Library for encoding/decoding UpegMetadata 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 UpegMetadataLibrary {
/// @dev Encodes UpegMetadata into uint256.
function encode(UpegMetadata memory seed) internal pure returns (uint256 result) {
result |= uint256(seed.backGroundColor) << 0;
result |= uint256(seed.horn) << 8;
result |= uint256(seed.accessories) << 16;
result |= uint256(seed.hair) << 24;
result |= uint256(seed.wings) << 32;
result |= uint256(seed.tail) << 40;
result |= uint256(seed.legsFront) << 48;
result |= uint256(seed.legsBack) << 56;
result |= uint256(seed.eyes) << 64;
result |= uint256(seed.body) << 72;
result |= uint256(seed.ground) << 80;
result |= uint256(seed.bodyColor) << 88;
result |= uint256(seed.eyesColor) << 96;
result |= uint256(seed.hairColor) << 104;
result |= uint256(seed.hornColor) << 112;
result |= uint256(seed.groundColor) << 120;
result |= uint256(seed.accessoriesColor) << 128;
result |= uint256(seed.tailColor) << 136;
}
/// @dev Decodes uint256 into UpegMetadata.
function decode(uint256 seed) internal pure returns (UpegMetadata memory) {
return
UpegMetadata({
backGroundColor: uint8(seed & 0xFF),
body: uint8((seed >> 72) & 0xFF),
eyes: uint8((seed >> 64) & 0xFF),
hair: uint8((seed >> 24) & 0xFF),
horn: uint8((seed >> 8) & 0xFF),
legsBack: uint8((seed >> 56) & 0xFF),
legsFront: uint8((seed >> 48) & 0xFF),
wings: uint8((seed >> 32) & 0xFF),
tail: uint8((seed >> 40) & 0xFF),
accessories: uint8((seed >> 16) & 0xFF),
ground: uint8((seed >> 80) & 0xFF),
bodyColor: uint8((seed >> 88) & 0xFF),
eyesColor: uint8((seed >> 96) & 0xFF),
hairColor: uint8((seed >> 104) & 0xFF),
hornColor: uint8((seed >> 112) & 0xFF),
groundColor: uint8((seed >> 120) & 0xFF),
accessoriesColor: uint8((seed >> 128) & 0xFF),
tailColor: 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/IUpeg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Upeg data structure.
struct UpegSeedData {
/// @dev Upeg ID.
uint256 id;
/// @dev Upeg seed.
uint256 seed;
}
/// @dev Upeg collection interface.
/// Each owner has a list of Upegs with unique IDs and seed values.
interface IUpeg {
/// @dev Error when the caller doesn't own the Upeg.
error NotUpegOwner();
/// @dev Error when Upeg index is out of range.
error UpegIndexOutOfRange();
/// @dev Upeg mint event.
event OnUpegMinted(address indexed owner, uint upegId);
/// @dev Upeg burn event.
event OnUpegBurned(address indexed owner, uint upegId);
/// @dev Upeg transfer event.
event OnUpegTransfer(address indexed from, address indexed to, uint upegId);
/// @dev Total Upeg count.
function UpegsTotalCount() external view returns (uint);
/// @dev Total holder count.
function HoldersCount() external view returns (uint);
/// @dev Upeg count for an owner.
function OwnerUpegsCount(address owner) external view returns (uint);
/// @dev Returns a paginated list of Upegs.
/// @param owner Owner address
/// @param page Page number
/// @param pageSize Page size
function OwnerUpegsPage(address owner, uint page, uint pageSize) external view returns (UpegSeedData[] memory upegs);
/// @dev Upeg for an owner by index.
/// @param owner Owner address
/// @param index Upeg index
function OwnerUpeg(address owner, uint index) external view returns (UpegSeedData memory);
/// @dev Upeg index for an owner by ID.
/// @param owner Owner address
/// @param upegId Upeg ID
function OwnerUpegIndex(address owner, uint upegId) external view returns (uint index);
/// @dev Reorders the caller's Upeg. Shifts all items left/right (may be gas-inefficient).
/// @param upegId Upeg ID to reorder
/// @param newIndex New index
function ReorderUpeg(uint upegId, uint newIndex) external;
/// @dev Reorders the caller's Upeg. Gas-optimized swap without shifting.
/// @param upegId Upeg ID to reorder
/// @param newIndex New index or swap index
function ReorderUpegPair(uint upegId, uint newIndex) external;
/// @dev Checks if the owner owns a Upeg by ID.
function OwnerOwns(address owner, uint upegId) 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 Upeg to an address. One token is transferred with the Upeg.
/// @param to Recipient address
/// @param upegId Upeg ID
function transferUpeg(address to, uint upegId) external;
/// @dev Transfers multiple Upegs. Transfers the same number of tokens.
/// @param to Recipient address
/// @param upegIds Array of Upeg IDs
function transferUpegsList(
address to,
uint[] calldata upegIds
) external;
}src/upegs/Upeg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./IUpeg.sol";
import "../svg_generation/UpegMetadata.sol";
import "../svg_generation/IImageParams.sol";
import "../library/RandomLib.sol";
import "../library/IRandomSeedProvider.sol";
/// @dev Allows creating and storing Upegs by owner address.
/// @notice Upeg is a set of data that defines the token appearance.
/// @notice To save storage, Upeg is stored as an encoded uint256 (non-zero).
/// @notice A list of Upeg holders is maintained.
/// Each Upeg has a unique non-zero ID.
/// By ID you can get the encoded Upeg and decode it into UpegMetadata.
contract Upeg is IUpeg {
using RandomLibrary for Random;
// all Upegs
mapping(uint upegId => uint256 seed) _upegs; // encoded Upegs by ID
// Upegs for each owner
mapping(address owner => uint) _counts; // Upeg count per owner
mapping(address owner => mapping(uint index => uint256 upegId)) _ownedUpegs; // Upeg by owner index
mapping(address owner => mapping(uint upegId => uint index)) _ownedUpegsIndexes; // Upeg indices by ID
mapping(address owner => mapping(uint upegId => bool isOwn)) _owns; // ownership by Upeg ID
// Upeg holders list
mapping(uint index => address user) _holderList;
mapping(address user => uint index) _holderListNumbers; // holder number in list (0 means not a holder)
uint _upegsTotalCount; // total Upeg 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 Upeg (by upegId) into the owner's list.
/// @notice Seed must already exist in _upegs[upegId].
function _insertExistingUpegToOwner(address owner, uint upegId) internal {
// add to owner's list
_ownedUpegs[owner][_counts[owner]] = upegId;
_ownedUpegsIndexes[owner][upegId] = _counts[owner];
_counts[owner]++;
_owns[owner][upegId] = true;
// add owner to holder list if not present
if (!IsHolder(owner)) {
_holderList[_holdersCount] = owner;
_holderListNumbers[owner] = ++_holdersCount;
}
}
/// @dev Removes Upeg from owner's list (but does NOT delete the seed).
function _removeUpegFromOwner(address owner, uint upegId) internal {
// index of the removed item
uint idx = _ownedUpegsIndexes[owner][upegId];
uint lastIdx = _counts[owner] - 1;
if (idx != lastIdx) {
// swap-with-last to keep list compact
uint256 lastId = _ownedUpegs[owner][lastIdx];
_ownedUpegs[owner][idx] = lastId;
_ownedUpegsIndexes[owner][lastId] = idx;
}
// clear last slot and indices
delete _ownedUpegs[owner][lastIdx];
delete _ownedUpegsIndexes[owner][upegId];
_counts[owner]--;
_owns[owner][upegId] = false;
// remove owner from holder list if they own none
if (_counts[owner] == 0 && IsHolder(owner)) {
_removeHolder(owner);
}
}
/// @dev Restricts function to the Upeg owner.
modifier onlyUpegOwner(uint upegId) {
if (!_owns[msg.sender][upegId]) revert NotUpegOwner();
_;
}
/// @dev Ensures index is valid for the caller's Upeg list.
modifier onlyMyUpegIndex(uint index) {
if (index >= _counts[msg.sender]) revert UpegIndexOutOfRange();
_;
}
/// @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 UpegsTotalCount() external view returns (uint) {
return _upegsTotalCount;
}
function HoldersCount() external view returns (uint) {
return _holdersCount;
}
function OwnerUpegsCount(address owner) public view returns (uint) {
return _counts[owner];
}
function OwnerUpeg(
address owner,
uint index
) external view returns (UpegSeedData memory) {
if (index >= _counts[owner]) revert UpegIndexOutOfRange();
uint256 id = _ownedUpegs[owner][index];
return UpegSeedData({id: id, seed: _upegs[id]});
}
function OwnerUpegIndex(
address owner,
uint upegId
) external view returns (uint index) {
if (!_owns[owner][upegId]) revert NotUpegOwner();
return _ownedUpegsIndexes[owner][upegId];
}
function OwnerOwns(
address owner,
uint upegId
) external view returns (bool) {
return _owns[owner][upegId];
}
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 upeg 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 OwnerUpegsPage(
address owner,
uint page,
uint pageSize
) external view override returns (UpegSeedData[] memory upegs) {
uint count = _counts[owner];
if (pageSize == 0) return new UpegSeedData[](0);
uint start = page * pageSize;
if (start >= count) return new UpegSeedData[](0);
uint end = start + pageSize;
if (end > count) end = count;
uint len = end - start;
upegs = new UpegSeedData[](len);
for (uint i = 0; i < len; i++) {
uint idx = start + i;
uint256 inscId = _ownedUpegs[owner][idx];
upegs[i] = UpegSeedData({id: inscId, seed: _upegs[inscId]});
}
}
/// @dev Reorders caller's Upeg: upegId goes to newIndex, others shift.
function ReorderUpeg(
uint upegId,
uint newIndex
) external override onlyUpegOwner(upegId) onlyMyUpegIndex(newIndex) {
uint currentIndex = _ownedUpegsIndexes[msg.sender][upegId];
if (newIndex == currentIndex) return;
// take out element
uint256 id = _ownedUpegs[msg.sender][currentIndex];
// shift based on direction
if (newIndex < currentIndex) {
// shift right: [newIndex .. currentIndex-1] -> +1
for (uint i = currentIndex; i > newIndex; i--) {
_ownedUpegs[msg.sender][i] = _ownedUpegs[msg.sender][i - 1];
_ownedUpegsIndexes[msg.sender][_ownedUpegs[msg.sender][i]] = i;
}
} else {
// newIndex > currentIndex: shift left: [currentIndex+1 .. newIndex] -> -1
for (uint i = currentIndex; i < newIndex; i++) {
_ownedUpegs[msg.sender][i] = _ownedUpegs[msg.sender][i + 1];
_ownedUpegsIndexes[msg.sender][_ownedUpegs[msg.sender][i]] = i;
}
}
// place element into new slot
_ownedUpegs[msg.sender][newIndex] = id;
_ownedUpegsIndexes[msg.sender][id] = newIndex;
}
/// @dev Swaps upegId with the element at newIndex without shifting (gas-optimized).
function ReorderUpegPair(
uint upegId,
uint newIndex
) external override onlyUpegOwner(upegId) onlyMyUpegIndex(newIndex) {
uint currentIndex = _ownedUpegsIndexes[msg.sender][upegId];
if (newIndex == currentIndex) return;
uint256 otherId = _ownedUpegs[msg.sender][newIndex];
// swap in array
_ownedUpegs[msg.sender][newIndex] = upegId;
_ownedUpegs[msg.sender][currentIndex] = otherId;
// update indices
_ownedUpegsIndexes[msg.sender][upegId] = newIndex;
_ownedUpegsIndexes[msg.sender][otherId] = currentIndex;
}
/// @notice Creates a new Upeg for the owner.
/// @param owner Owner address
/// @param seed Encoded Upeg value
function _mintUpeg(address owner, uint256 seed) internal {
UpegSeedData memory seedData = _createUpeg(owner, seed);
emit OnUpegMinted(owner, seedData.id);
}
/// @notice Creates a new Upeg for the owner.
/// @param owner Owner address
function _mintUpeg(address owner, Random memory random) internal {
_mintUpeg(owner, _nextUpeg(random));
}
function _createUpeg(
address owner,
uint256 seed
) private returns (UpegSeedData memory seedData) {
uint upegId = ++_upegsTotalCount;
_upegs[upegId] = seed;
_insertExistingUpegToOwner(owner, upegId);
return UpegSeedData({id: upegId, seed: seed});
}
/// @notice Generates a random Upeg.
/// @param random Generator state struct
function _nextUpeg(
Random memory random
) internal view returns (uint256 seed) {
// get aggregated parameters (element counts and palette sizes)
ImageParams memory p = imageParams.getImageParams();
UpegMetadata 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.horn = _pickId(p.hornCount, random);
if (s.horn > 0) {
s.hornColor = _pickColor(p.colorsCount, random);
}
}
// accessories (30%)
if (_chance(30, random)) {
s.accessories = _pickId(p.accessoriesCount, random);
if (s.accessories > 0) {
s.accessoriesColor = _pickColor(p.colorsCount, random);
}
}
// hair (80%)
if (_chance(80, random)) {
s.hair = _pickId(p.hairCount, random);
if (s.hair > 0) {
s.hairColor = _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.tail = _pickId(p.tailCount, random);
if (s.tail > 0) {
s.tailColor = _pickColor(p.colorsCount, random);
}
}
// front legs (100%)
s.legsFront = _pickId(p.legsFrontCount, random);
// back legs (100%)
s.legsBack = _pickId(p.legsBackCount, random);
// eyes (100%)
s.eyes = _pickId(p.eyesCount, random);
if (s.eyes > 0) {
s.eyesColor = _pickColor(p.colorsCount, random);
}
// body (100%)
s.body = _pickId(p.bodyCount, random);
if (s.body > 0) {
s.bodyColor = _pickColor(p.colorsCount, random);
}
// ground (100%)
s.ground = _pickId(p.groundCount, random);
if (s.ground > 0) {
s.groundColor = _pickColor(p.colorsCount, random);
}
// encode struct into uint256
seed = UpegMetadataLibrary.encode(s);
return seed;
}
/// @notice Removes a Upeg from the owner.
/// @param owner Owner address
/// @param upegId Upeg ID
function _burnUpeg(
address owner,
uint upegId
) internal returns (uint256 seed) {
uint256 deletedSeed = _deleteUpeg(owner, upegId);
emit OnUpegBurned(owner, upegId);
return deletedSeed;
}
function _deleteUpeg(
address owner,
uint upegId
) internal returns (uint256 seed) {
// remove ownership and delete from owner's list
_removeUpegFromOwner(owner, upegId);
// delete seed
seed = _upegs[upegId];
delete _upegs[upegId];
return seed;
}
/// @notice Transfers a Upeg from one owner to another.
/// @param from Sender address
/// @param to Recipient address
/// @param upegId Upeg ID
function _transferUpeg(address from, address to, uint upegId) internal {
// remove upegId from sender list, keep seed
_removeUpegFromOwner(from, upegId);
// insert same upegId into receiver list (ID preserved)
_insertExistingUpegToOwner(to, upegId);
emit OnUpegTransfer(from, to, upegId);
}
/// @notice Removes a holder from the global holder list.
/// @param owner Owner address
function _removeHolder(address owner) internal {
// _holderListNumbers is 1-based; _holderList indices are 0-based
uint idx = _holderListNumbers[owner] - 1;
uint lastIdx = _holdersCount - 1;
// fill the gap: move the last entry into the removed slot (swap-with-last)
if (idx != lastIdx) {
address lastHolder = _holderList[lastIdx];
_holderList[idx] = lastHolder;
_holderListNumbers[lastHolder] = idx + 1; // update 1-based slot number
}
delete _holderList[lastIdx];
delete _holderListNumbers[owner];
_holdersCount--;
}
function transferUpeg(
address to,
uint upegId
) external override onlyUpegOwner(upegId) {
_transferUpeg(msg.sender, to, upegId);
_afterUpegTransferred(msg.sender, to, upegId);
}
function transferUpegsList(
address to,
uint[] calldata upegIds
) external override {
uint len = upegIds.length;
if (len == 0) return;
for (uint i = 0; i < len; ++i) {
if (!_owns[msg.sender][upegIds[i]]) revert NotUpegOwner();
_transferUpeg(msg.sender, to, upegIds[i]);
}
_afterUpegsListTransferred(msg.sender, to, upegIds);
}
function _afterUpegTransferred(
address from,
address to,
uint upegId
) internal virtual {}
function _afterUpegsListTransferred(
address from,
address to,
uint[] calldata upegIds
) internal virtual {}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": false
},
"evmVersion": "prague",
"remappings": [
"solady/=lib/solady/",
"forge-std/=lib/forge-std/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.