Verified contractPartialMIT
UspegToken
Address0x63d74b2b0568c2a5ae8115d2b4cc2e710f4a4ac8
- Balance
0 ETH
- Transactions
32
- Compiler
solc 0.8.28
- Same code
3 more contracts
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 24,980,719
- Creation transaction
- 0x02d8c56f4b…8b616dde2a
- Main copy (most transactions)
- 0xf6eccbd9…42da2851
10 files
- src/contracts/token/UspegToken.solmain9.39 KB
- solady/src/auth/Ownable.sol12.55 KB
- solady/src/tokens/ERC20.sol31.12 KB
- src/contracts/token/IImageParams.sol752 B
- src/contracts/token/IRandomSeedProvider.sol259 B
- src/contracts/token/IStartableToken.sol471 B
- src/contracts/token/IUspeg.sol1.89 KB
- src/contracts/token/RandomLib.sol590 B
- src/contracts/token/Uspeg.sol10.53 KB
- src/contracts/token/UspegMetadata.sol1.38 KB
src/contracts/token/UspegToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/*
█ █ █████ ███████ ██████ ███████
█ █ ██ ██ ██ ██ ██
█ █ █████ ██████ █████ ██ ███
█ █ █ ██ ██ ██ ██
████ █████ ██ ███████ █████
USPEG — A Uniswap V4 hook collectible.
Minting $USPEG via Uniswap V4 creates a unique pixel collectible.
Common draw → no reason to keep → swapped back → burned. Rare draw →
worth keeping → withdrawn/held → permanently leaves the AMM.
Common draw → no reason to keep → swapped back → burned.
Rare draw → worth keeping → withdrawn → permanently leaves the AMM.
Website : https://uspeg.art
X : https://x.com/uspegv4
US + JPEG = USPEG.
*/
import {ERC20} from "solady/src/tokens/ERC20.sol";
import {Ownable} from "solady/src/auth/Ownable.sol";
import {Uspeg} from "./Uspeg.sol";
import {IStartableToken} from "./IStartableToken.sol";
import {Random} from "./RandomLib.sol";
/// @title UspegToken
/// @notice ERC20 (solady) bound 1:1 to Uspeg collectibles. Mints Uspegs on
/// transfers from the pool, burns Uspegs on transfers back into the
/// pool, and moves Uspeg identity along with whole-token user-to-user
contract UspegToken is Uspeg, ERC20, Ownable, IStartableToken {
/// @notice Canonical 1:1 ERC20 ↔ collectible ratio (Unipeg-equivalent).
uint256 public constant UNIT_PER_USPEG_LATE = 1e18;
/// @notice Early-phase 10:1 ratio. Mints one collectible per 10 whole
/// USPEG bought, so first buyers pay ~10x less gas. Tokens bought
/// during this phase that don't reach the next 10-token threshold
/// remain fungible-only (no NFT) for their lifetime.
uint256 public constant UNIT_PER_USPEG_EARLY = 10e18;
/// @notice Initial supply minted to the deployer at construction.
uint256 public constant INITIAL_SUPPLY = 10_000e18;
uint256 constant MAX_BUY_PRECISION = 100000;
uint256 constant _startMaxBuyCount = (INITIAL_SUPPLY * 450) / MAX_BUY_PRECISION; // 0.45%
uint256 constant _addMaxBuyPercentPerSec = 3; // 0.003% / sec
address immutable _notMintableAccount;
uint256 _startTime;
/// @notice The address authorized to call `start` — the V4 hook.
address public hook;
/// @notice The PoolManager singleton (set by the hook on initialize).
address public pool;
/// @notice True once the pool price has crossed the early-phase threshold
/// and the 10:1 discount has expired. One-way ratchet — only the
/// hook can set this and it never goes back to false.
bool public earlyPhaseEnded;
event EarlyPhaseEnded(uint256 timestamp);
constructor(address owner_) {
_initializeOwner(owner_);
_mint(owner_, INITIAL_SUPPLY);
_notMintableAccount = owner_;
}
modifier canReceiveUspegs(address addr) {
if (!_canReceiveUspegs(addr)) revert AddressCanNotReceiveUspeg();
_;
}
modifier onlyHook() {
require(msg.sender == hook, "only for hook");
_;
}
/* ------------------------------ ERC20 metadata ------------------------------ */
function name() public pure override returns (string memory) {
return "usPEG";
}
function symbol() public pure override returns (string memory) {
return "usPEG";
}
/* ------------------------------- Phase ratio ------------------------------- */
/// @notice Current ERC20-units required to mint one USPEG collectible.
/// Returns 10e18 (10 tokens per NFT) while early phase is active,
/// then 1e18 (Unipeg-equivalent) afterwards. The frontend reads
/// this to format estimates, and `_onTokenTransfer` uses it to
/// derive how many NFTs to mint/burn on each pool transfer.
function UNIT_PER_USPEG() public view returns (uint256) {
return earlyPhaseEnded ? UNIT_PER_USPEG_LATE : UNIT_PER_USPEG_EARLY;
}
/// @notice Called by the hook (and only the hook) when the pool's
/// sqrtPriceX96 crosses the early-phase threshold. One-way; later
/// calls are no-ops so the hook can call it on every swap without
/// needing its own ratchet.
function endEarlyPhase() external onlyHook {
if (earlyPhaseEnded) return;
earlyPhaseEnded = true;
emit EarlyPhaseEnded(block.timestamp);
}
/* --------------------------- Hook + pool admin --------------------------- */
/// @inheritdoc IStartableToken
function start(address newPool) external onlyHook {
pool = newPool;
_startTime = block.timestamp;
}
/// @inheritdoc IStartableToken
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;
}
function setHook(address newHook) external onlyOwner {
hook = newHook;
}
function setImageParamsProvider(address provider) external onlyOwner {
_setImageParamsProvider(provider);
}
function setRandomSeedProvider(address provider) external onlyOwner {
_setRandomSeedProvider(provider);
}
/* --------------------------- ERC20 lifecycle hook --------------------------- */
function _afterTokenTransfer(address from, address to, uint256 amount) internal override {
super._afterTokenTransfer(from, to, amount);
if (pool == address(0)) return;
// Mix the receiver's address into the seed so buyers in the same block
// get distinct traits. Without this, prevrandao+blockhash are block-level
// constants and all same-block mints would be identical.
Random memory rnd = createRandom();
rnd.seed = uint256(keccak256(abi.encodePacked(rnd.seed, to)));
_onTokenTransfer(from, to, amount, rnd);
}
/* ------------------------------- Internals ------------------------------- */
function _onTokenTransfer(address from, address to, uint256 amount, Random memory random)
internal
{
uint256 unit = UNIT_PER_USPEG();
// pool -> user: mint Uspegs.
if (from == pool && to != address(0)) {
if (_notMintableAccount == to) return;
require(isStarted(), "not started");
require(amount <= maxBuy(), "buy limit");
_mintUspegs(to, amount / unit, random);
return;
}
// sender's surplus over their whole-token balance must be released.
uint256 fromMaxAllowed = balanceOf(from) / unit;
uint256 fromCount = _counts[from];
uint256 fromRemoveCount = fromCount > fromMaxAllowed ? fromCount - fromMaxAllowed : 0;
if (fromRemoveCount == 0) return;
// receiver's room (whole-token balance minus current uspeg count).
uint256 toMaxAllowed = balanceOf(to) / unit;
uint256 toCount = _counts[to];
uint256 toReceiveAllowed = toCount < toMaxAllowed ? toMaxAllowed - toCount : 0;
if (!_canReceiveUspegs(to)) {
toReceiveAllowed = 0;
}
uint256 moveQuantity = fromRemoveCount < toReceiveAllowed ? fromRemoveCount : toReceiveAllowed;
if (moveQuantity > 0) _moveUspegs(from, to, moveQuantity);
// burn whatever the receiver couldn't take (sells, transfers to pool, etc.).
_burnUspegs(from, fromRemoveCount - moveQuantity);
}
function _mintUspegs(address account, uint256 quantity, Random memory random) internal {
for (uint256 i = 0; i < quantity; ++i) {
_mintUspeg(account, random);
}
}
function _burnUspegs(address account, uint256 quantity) internal {
for (uint256 i = 0; i < quantity; ++i) {
uint256 count = _counts[account];
if (count == 0) break;
uint256 uspegId = _ownedUspegs[account][count - 1];
_burnUspeg(account, uspegId);
}
}
function _moveUspegs(address from, address to, uint256 quantity)
internal
canReceiveUspegs(to)
{
for (uint256 i = 0; i < quantity; ++i) {
uint256 count = _counts[from];
if (count == 0) break;
uint256 uspegId = _ownedUspegs[from][count - 1];
_transferUspeg(from, to, uspegId);
}
}
function _canReceiveUspegs(address addr) internal view returns (bool) {
return addr != pool && addr != address(0);
}
/* ----------------------------- Uspeg → ERC20 ----------------------------- */
function _afterUspegTransferred(address from, address to, uint256) internal override {
_transfer(from, to, UNIT_PER_USPEG());
}
function _afterUspegsListTransferred(address from, address to, uint256[] calldata uspegIds)
internal
override
{
_transfer(from, to, UNIT_PER_USPEG() * uspegIds.length);
}
}
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();
_;
}
}
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/contracts/token/IImageParams.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @dev Generation parameters for Uspeg seed rolls. One count per visible
/// layer folder on the website. Each count tells the seed-roller how
/// many distinct sprites exist for that layer; the seed clamps the
/// trait byte to `value % count` accordingly.
struct ImageParams {
uint256 backgroundsCount; // 1. backgrounds
uint256 clothesCount; // 2. clothes
uint256 basesCount; // 3. bases
uint256 hatsCount; // 4. hats
uint256 propsCount; // 5. props
}
interface IImageParams {
/// @dev Returns aggregated layer counts for seed/Uspeg generation.
function getImageParams() external view returns (ImageParams memory);
}
src/contracts/token/IRandomSeedProvider.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title Interface for providing a random seed.
interface IRandomSeedProvider {
/// @dev Returns a seed for pseudo-random generation.
function randomSeed() external view returns (uint256);
}
src/contracts/token/IStartableToken.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @dev Interface for a token whose pool address is set by the v4 hook at
/// pool initialization time. Mirrors Unipeg/Punkpeg's `IStartableToken`.
interface IStartableToken {
/// @notice Sets the liquidity pool address and enables buying.
function start(address newPool) external;
/// @notice Returns true once `start` has been called.
function isStarted() external view returns (bool);
}
src/contracts/token/IUspeg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @dev Uspeg data structure — same shape as Unipeg's `UpegSeedData`.
struct UspegSeedData {
uint256 id;
uint256 seed;
}
/// @dev Uspeg collection interface — direct port of Unipeg's `IUpeg`,
/// renamed to USPEG and using camelCase to keep the existing frontend
/// ABI usable without changes.
interface IUspeg {
error NotUspegOwner();
error UspegIndexOutOfRange();
error AddressCanNotReceiveUspeg();
event UspegMinted(address indexed owner, uint256 uspegId);
event UspegBurned(address indexed owner, uint256 uspegId);
event UspegTransferred(address indexed from, address indexed to, uint256 uspegId);
function uspegsTotalCount() external view returns (uint256);
function holdersCount() external view returns (uint256);
function ownerUspegsCount(address owner) external view returns (uint256);
function ownerUspegsPage(address owner, uint256 page, uint256 pageSize)
external
view
returns (UspegSeedData[] memory uspegs);
function ownerUspeg(address owner, uint256 index)
external
view
returns (UspegSeedData memory);
function ownerUspegIndex(address owner, uint256 uspegId) external view returns (uint256);
function reorderUspeg(uint256 uspegId, uint256 newIndex) external;
function reorderUspegPair(uint256 uspegId, uint256 newIndex) external;
function ownerOwns(address owner, uint256 uspegId) external view returns (bool);
function isHolder(address owner) external view returns (bool);
function holder(uint256 index) external view returns (address);
function holderNumber(address owner) external view returns (uint256);
function transferUspeg(address to, uint256 uspegId) external;
function transferUspegsList(address to, uint256[] calldata uspegIds) external;
}
src/contracts/token/RandomLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @dev Pseudo-random generator state.
struct Random {
uint256 seed;
uint256 nonce;
}
/// @dev Library for pseudo-random number generation.
/// @notice Mirrors Unipeg/Punkpeg's `RandomLibrary` so the seed-rolling logic
/// in `Uspeg.sol` can be a 1:1 port.
library RandomLibrary {
/// @dev Generates the next pseudo-random number from the state.
function next(Random memory random) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(random.seed, ++random.nonce)));
}
}
src/contracts/token/Uspeg.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {IUspeg, UspegSeedData} from "./IUspeg.sol";
import {UspegMetadata, UspegMetadataLib} from "./UspegMetadata.sol";
import {IImageParams, ImageParams} from "./IImageParams.sol";
import {IRandomSeedProvider} from "./IRandomSeedProvider.sol";
import {Random, RandomLibrary} from "./RandomLib.sol";
/// @title Uspeg
/// @notice Direct port of Unipeg's `Upeg.sol` collectible registry, renamed
/// and slimmed for USPEG's 5-trait PNG layer system. Storage layout,
/// holder list logic, and pagination shape are 1:1 with Unipeg
/// (verified at 0x44b28991B167582F18BA0259e0173176ca125505).
contract Uspeg is IUspeg {
using RandomLibrary for Random;
using UspegMetadataLib for UspegMetadata;
// all Uspegs
mapping(uint256 uspegId => uint256 seed) _uspegs;
// Uspegs per owner
mapping(address owner => uint256) _counts;
mapping(address owner => mapping(uint256 index => uint256 uspegId)) _ownedUspegs;
mapping(address owner => mapping(uint256 uspegId => uint256 index)) _ownedUspegsIndexes;
mapping(address owner => mapping(uint256 uspegId => bool isOwn)) _owns;
// holders list
mapping(uint256 index => address user) _holderList;
mapping(address user => uint256 number) _holderListNumbers;
uint256 _uspegsTotalCount;
uint256 _holdersCount;
IRandomSeedProvider public randomSeedProvider;
IImageParams public imageParams;
modifier onlyUspegOwner(uint256 uspegId) {
if (!_owns[msg.sender][uspegId]) revert NotUspegOwner();
_;
}
modifier onlyMyUspegIndex(uint256 index) {
if (index >= _counts[msg.sender]) revert UspegIndexOutOfRange();
_;
}
/* ------------------------------ Provider setters ------------------------------ */
function _setRandomSeedProvider(address newProvider) internal {
randomSeedProvider = IRandomSeedProvider(newProvider);
}
function _setImageParamsProvider(address newProvider) internal {
imageParams = IImageParams(newProvider);
}
function createRandom() internal view returns (Random memory) {
return Random({seed: randomSeedProvider.randomSeed(), nonce: 0});
}
/* --------------------------------- Reads --------------------------------- */
function isHolder(address owner) public view returns (bool) {
return _holderListNumbers[owner] > 0;
}
function uspegsTotalCount() external view returns (uint256) {
return _uspegsTotalCount;
}
function holdersCount() external view returns (uint256) {
return _holdersCount;
}
function ownerUspegsCount(address owner) public view returns (uint256) {
return _counts[owner];
}
function ownerUspeg(address owner, uint256 index) external view returns (UspegSeedData memory) {
if (index >= _counts[owner]) revert UspegIndexOutOfRange();
uint256 id = _ownedUspegs[owner][index];
return UspegSeedData({id: id, seed: _uspegs[id]});
}
function ownerUspegIndex(address owner, uint256 uspegId) external view returns (uint256) {
if (!_owns[owner][uspegId]) revert NotUspegOwner();
return _ownedUspegsIndexes[owner][uspegId];
}
function ownerOwns(address owner, uint256 uspegId) external view returns (bool) {
return _owns[owner][uspegId];
}
function holder(uint256 index) external view returns (address) {
return _holderList[index];
}
function holderNumber(address owner) external view returns (uint256) {
return _holderListNumbers[owner];
}
function ownerUspegsPage(address owner, uint256 page, uint256 pageSize)
external
view
returns (UspegSeedData[] memory uspegs)
{
uint256 count = _counts[owner];
if (pageSize == 0) return new UspegSeedData[](0);
uint256 startIndex = page * pageSize;
if (startIndex >= count) return new UspegSeedData[](0);
uint256 endIndex = startIndex + pageSize;
if (endIndex > count) endIndex = count;
uspegs = new UspegSeedData[](endIndex - startIndex);
for (uint256 i = 0; i < uspegs.length; ++i) {
uint256 id = _ownedUspegs[owner][startIndex + i];
uspegs[i] = UspegSeedData({id: id, seed: _uspegs[id]});
}
}
/* ------------------------ List manipulation (internal) ------------------------ */
function _insertExistingUspegToOwner(address owner, uint256 uspegId) internal {
_ownedUspegs[owner][_counts[owner]] = uspegId;
_ownedUspegsIndexes[owner][uspegId] = _counts[owner];
_counts[owner]++;
_owns[owner][uspegId] = true;
if (!isHolder(owner)) {
_holderList[_holdersCount] = owner;
_holderListNumbers[owner] = ++_holdersCount;
}
}
function _removeUspegFromOwner(address owner, uint256 uspegId) internal {
uint256 idx = _ownedUspegsIndexes[owner][uspegId];
uint256 lastIdx = _counts[owner] - 1;
if (idx != lastIdx) {
uint256 lastId = _ownedUspegs[owner][lastIdx];
_ownedUspegs[owner][idx] = lastId;
_ownedUspegsIndexes[owner][lastId] = idx;
}
delete _ownedUspegs[owner][lastIdx];
delete _ownedUspegsIndexes[owner][uspegId];
_counts[owner]--;
_owns[owner][uspegId] = false;
if (_counts[owner] == 0 && isHolder(owner)) {
_removeHolder(owner);
}
}
function _removeHolder(address owner) internal {
uint256 idx = _holderListNumbers[owner] - 1;
uint256 lastIdx = _holdersCount - 1;
if (idx != lastIdx) {
address lastHolder = _holderList[lastIdx];
_holderList[idx] = lastHolder;
_holderListNumbers[lastHolder] = idx + 1;
}
delete _holderList[lastIdx];
delete _holderListNumbers[owner];
_holdersCount--;
}
/* --------------------------- Mint / burn / move --------------------------- */
function _mintUspeg(address owner, Random memory random) internal {
_mintUspeg(owner, _nextUspeg(random));
}
function _mintUspeg(address owner, uint256 seed) internal {
uint256 uspegId = ++_uspegsTotalCount;
_uspegs[uspegId] = seed;
_insertExistingUspegToOwner(owner, uspegId);
emit UspegMinted(owner, uspegId);
}
function _burnUspeg(address owner, uint256 uspegId) internal returns (uint256 seed) {
_removeUspegFromOwner(owner, uspegId);
seed = _uspegs[uspegId];
delete _uspegs[uspegId];
emit UspegBurned(owner, uspegId);
}
function _transferUspeg(address from, address to, uint256 uspegId) internal {
_removeUspegFromOwner(from, uspegId);
_insertExistingUspegToOwner(to, uspegId);
emit UspegTransferred(from, to, uspegId);
}
/* ------------------------------- Trait roll ------------------------------- */
/// @dev Generates a fresh trait byte for each visible PNG layer. Each
/// trait is a `random.next() % count` selection — flat distribution,
/// no probability gates, no color palettes (USPEG layers ship as
/// pre-rendered PNGs, not SVG primitives).
function _nextUspeg(Random memory random) internal view returns (uint256 seed) {
ImageParams memory p = imageParams.getImageParams();
UspegMetadata memory m;
m.backgrounds = p.backgroundsCount == 0 ? 0 : uint8(random.next() % p.backgroundsCount);
m.clothes = p.clothesCount == 0 ? 0 : uint8(random.next() % p.clothesCount);
m.bases = p.basesCount == 0 ? 0 : uint8(random.next() % p.basesCount);
m.hats = p.hatsCount == 0 ? 0 : uint8(random.next() % p.hatsCount);
m.props = p.propsCount == 0 ? 0 : uint8(random.next() % p.propsCount);
seed = m.encode();
}
/* -------------------------- Reorder (caller-only) -------------------------- */
function reorderUspeg(uint256 uspegId, uint256 newIndex)
external
onlyUspegOwner(uspegId)
onlyMyUspegIndex(newIndex)
{
uint256 currentIndex = _ownedUspegsIndexes[msg.sender][uspegId];
if (newIndex == currentIndex) return;
uint256 id = _ownedUspegs[msg.sender][currentIndex];
if (newIndex < currentIndex) {
for (uint256 i = currentIndex; i > newIndex; i--) {
_ownedUspegs[msg.sender][i] = _ownedUspegs[msg.sender][i - 1];
_ownedUspegsIndexes[msg.sender][_ownedUspegs[msg.sender][i]] = i;
}
} else {
for (uint256 i = currentIndex; i < newIndex; i++) {
_ownedUspegs[msg.sender][i] = _ownedUspegs[msg.sender][i + 1];
_ownedUspegsIndexes[msg.sender][_ownedUspegs[msg.sender][i]] = i;
}
}
_ownedUspegs[msg.sender][newIndex] = id;
_ownedUspegsIndexes[msg.sender][id] = newIndex;
}
function reorderUspegPair(uint256 uspegId, uint256 newIndex)
external
onlyUspegOwner(uspegId)
onlyMyUspegIndex(newIndex)
{
uint256 currentIndex = _ownedUspegsIndexes[msg.sender][uspegId];
if (newIndex == currentIndex) return;
uint256 otherId = _ownedUspegs[msg.sender][newIndex];
_ownedUspegs[msg.sender][newIndex] = uspegId;
_ownedUspegs[msg.sender][currentIndex] = otherId;
_ownedUspegsIndexes[msg.sender][uspegId] = newIndex;
_ownedUspegsIndexes[msg.sender][otherId] = currentIndex;
}
/* ---------------------------- External transfers ---------------------------- */
function transferUspeg(address to, uint256 uspegId) external onlyUspegOwner(uspegId) {
_transferUspeg(msg.sender, to, uspegId);
_afterUspegTransferred(msg.sender, to, uspegId);
}
function transferUspegsList(address to, uint256[] calldata uspegIds) external {
uint256 length = uspegIds.length;
if (length == 0) return;
for (uint256 i = 0; i < length; ++i) {
if (!_owns[msg.sender][uspegIds[i]]) revert NotUspegOwner();
_transferUspeg(msg.sender, to, uspegIds[i]);
}
_afterUspegsListTransferred(msg.sender, to, uspegIds);
}
function _afterUspegTransferred(address from, address to, uint256 uspegId) internal virtual {}
function _afterUspegsListTransferred(address from, address to, uint256[] calldata uspegIds)
internal
virtual
{}
}
src/contracts/token/UspegMetadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @dev Per-Uspeg trait selection. One field per visible layer folder.
/// Fields are encoded into the low 40 bits of the 256-bit seed; the
/// Uspeg ID is packed in via `(seed | (uspegId << 64))` by `Uspeg.sol`.
///
/// Bit layout (LSB first):
/// 0 backgrounds
/// 8 clothes
/// 16 bases
/// 24 hats
/// 32 props
///
/// The website's [renderer.js](src/frontend/renderer.js) reads the
/// same bit offsets to pick the matching PNG from each folder.
struct UspegMetadata {
uint8 backgrounds;
uint8 clothes;
uint8 bases;
uint8 hats;
uint8 props;
}
library UspegMetadataLib {
function encode(UspegMetadata memory metadata) internal pure returns (uint256 seed) {
seed |= uint256(metadata.backgrounds);
seed |= uint256(metadata.clothes) << 8;
seed |= uint256(metadata.bases) << 16;
seed |= uint256(metadata.hats) << 24;
seed |= uint256(metadata.props) << 32;
}
function decode(uint256 seed) internal pure returns (UspegMetadata memory metadata) {
metadata.backgrounds = uint8(seed);
metadata.clothes = uint8(seed >> 8);
metadata.bases = uint8(seed >> 16);
metadata.hats = uint8(seed >> 24);
metadata.props = uint8(seed >> 32);
}
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": []
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.