Verified contractExactGPL-3.0
PunkGames
Address0xf4ab7aa42367af2a2139602425fde7f425cc7b82
- Balance
0 ETH
- Transactions
324
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- shanghai
- Via IR
- yes
- License
- GPL-3.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,239,008
- Creation transaction
- 0x3718ba1986…7759c2fd28
21 files
- src/PunkGames.solmain68.7 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol872 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.53 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol17.7 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol4.93 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol995 B
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol7.29 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol1.04 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol792 B
- lib/openzeppelin-contracts/contracts/utils/Base64.sol3.86 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.24 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol3.1 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol911 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol15.12 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol1.26 KB
- src/PunkGamesAfterGames.sol6.29 KB
- src/PunkGamesRenderer.sol16.86 KB
- src/PunkTraits.sol9.2 KB
src/PunkGames.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./PunkGamesRenderer.sol";
import "./PunkGamesAfterGames.sol";
/*
* █▄─▄▄─█▄─██─▄█▄─▀█▄─▄█▄─█─▄█─▄▄▄▄██▀▄─██▄─▀█▀─▄█▄─▄▄─█─▄▄▄▄█
* ██─▄▄▄██─██─███─█▄▀─███─▄▀██─██▄─██─▀─███─█▄█─███─▄█▀█▄▄▄▄─█
* ▀▄▄▄▀▀▀▀▄▄▄▄▀▀▄▄▄▀▀▄▄▀▄▄▀▄▄▀▄▄▄▄▄▀▄▄▀▄▄▀▄▄▄▀▄▄▄▀▄▄▄▄▄▀▄▄▄▄▄▀
*
* 10,000 on-chain punks. Survive the rounds. Last ones standing
* split the prize pool. Eliminated punks live on as "After Games"
* NFTs carrying their full OG CryptoPunks trait set.
*/
/**
* @title PunkGames
* @notice 10,000 ERC-721 punks fight through bot-driven elimination rounds
* until 1 winner remains. Holders may cash out for a fixed multiple of
* mint price during rounds 3-9. Top-3 finishers split a frozen prize
* snapshot. Eliminated punks are burned and re-minted into the
* PunkGamesAfterGames secondary collection with placement metadata.
*
* @dev Burn-and-remint elimination flow, fixed-multiplier cash-outs, top-3
* placement payouts, future-blockhash randomness via lockRandomness(),
* chunked on-chain trait + anchor storage, and bot-tip round execution.
* Deploy params (mainnet vs Sepolia rehearsal) differ only by constructor
* values — same bytecode on both. License + attribution at end of file.
*/
contract PunkGames is ERC721, ERC721Enumerable, Ownable, ReentrancyGuard, IERC2981 {
/*//////////////////////////////////////////////////////////////
ENUMS
//////////////////////////////////////////////////////////////*/
/// CANCELED is a safety-net terminal state, reachable only via
/// cancelGameAndRefund() after a 60-day stall. Alive holders refund their
/// mint price; cashed-out and eliminated players receive nothing (they
/// already had their outcome). After another 30-day timelock, leftover
/// funds become sweepable via emergencyWithdraw.
enum Stage { PRESALE, MAIN_SALE, COMPLETE, ARENA, FINISHED, CANCELED }
/*//////////////////////////////////////////////////////////////
IMMUTABLE CONFIG (deploy params)
//////////////////////////////////////////////////////////////*/
uint256 public immutable TOKEN_LIMIT; // 10_000 mainnet, 100 test
uint256 public immutable MINT_PRICE; // 0.0044 ether mainnet
uint256 public immutable MAX_PER_TX; // 10 mainnet — wallets can call mint() multiple times to remint, no per-wallet cap
uint256 public immutable ROUND_INTERVAL; // mass phase interval (8 hours mainnet)
uint256 public immutable ENDGAME_INTERVAL; // endgame interval (24 hours mainnet) — slower for build-up
uint256 public immutable RUN_ROUND_TIP; // 0.001 ether mainnet — caller incentive
uint256 public immutable BATCH_SIZE; // max eliminations per runRoundBatch call
// Each elimination ~200k gas (burn + AfterGames mint),
// so keep BATCH_SIZE * 200k under the block gas limit.
// Cash-out payout cap (in mint-price units). v2 model uses share-of-pool
// (cashOutReserve / aliveCount) clamped by this cap. At 200x:
// • $5 mint → $1000 cap (well below 3rd place ~$2,300 at $42.5k pool)
// • $1 mint → $200 cap (below 3rd place ~$467 at $8.5k pool)
// • $25 mint → $5000 cap (below 3rd place ~$11.6k)
// Brand-safety invariant validated across royalty inflows, mint prices,
// player cohorts, and edge cases in sim3.py. See project_cashout_v2_spec.md.
uint256 public constant CASHOUT_CAP_MULT = 200;
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
uint256 public constant MAX_ROUND = 14; // mass phase (1-11) + endgame (12-14)
uint256 public immutable ARENA_ANCHOR_HOUR_UTC; // hour (UTC, 0-23) at which the arena opens the day after mint completes
uint256 public immutable ARENA_DELAY_OVERRIDE_SEC; // test shortcut: if non-zero, arenaStartTime = mintComplete + this; else next-day-at-anchor-hour
uint256 public constant CASH_OUT_OPENS_ROUND = 3;
uint256 public constant CASH_OUT_CLOSES_ROUND = 10; // closes at round 10 (9 alive)
uint256 public constant ENDGAME_TRIGGER = 4; // when aliveCount <= 4, switch to 1-per-round
uint256 public constant ELIMINATION_PERCENT = 50;
// Mint split — basis points (10000 = 100%)
uint256 public constant PRIZE_BPS = 8500;
uint256 public constant CREATOR_BPS = 1000;
uint256 public constant OPS_BPS = 500;
// Pool split — basis points of prize pool
uint256 public constant CASHOUT_RESERVE_BPS = 5000; // 50%
uint256 public constant WINNER_RESERVE_BPS = 5000; // 50%
// Placement payouts — basis points of winner pool
// 1st = 60%, 2nd = 22%, 3rd = 10%, remainder rolls to 1st
// ($28.9k / $9.35k / $4.25k for $85k pool at 50/50 split, scales with rollover)
uint256 public constant PLACE_1_BPS = 6000;
uint256 public constant PLACE_2_BPS = 2200;
uint256 public constant PLACE_3_BPS = 1000;
// Remaining 800bp gets added to 1st place
// Royalty
uint96 public constant ROYALTY_BPS_GAME = 690; // 6.9% during game
uint96 public constant ROYALTY_BPS_POST = 500; // 5% after
// Royalty income split (4.2% pool / 2.7% creator out of 6.9%)
uint256 public constant ROYALTY_TO_POOL_BPS = 4200; // out of 6900
uint256 public constant ROYALTY_TO_CREATOR_BPS = 2700; // out of 6900
/*//////////////////////////////////////////////////////////////
SAFETY NET (cancel + keeper bounty)
//////////////////////////////////////////////////////////////*/
/// @notice After this many seconds of on-chain inactivity, anyone can
/// trigger cancelGameAndRefund(). Picked at 60d so transient outages,
/// gas-spike days, and the operator's vacation don't accidentally trip it,
/// but a truly abandoned game can still be unwound.
uint256 public constant CANCEL_STALL_DELAY = 60 days;
/// @notice After a cancel, owner must wait this long before sweeping
/// unclaimed funds via emergencyWithdraw. Mirrors the FINISHED-stage
/// timelock so the rules are the same regardless of why the game ended.
uint256 public constant CANCEL_TIMELOCK = 30 days;
/// @notice If a round becomes more than this overdue, the next caller of
/// runRoundBatch earns a one-time KEEPER_BOUNTY. Picked at 1h so a slow
/// block or a brief gas spike doesn't pay out, but a stalled bot does.
uint256 public constant KEEPER_BOUNTY_DELAY = 1 hours;
/// @notice Per-round bounty paid to whoever fires a delayed round. Sized
/// at ~$2 worth of ETH at deploy-era prices ($2k ETH ≈ 0.001 ETH).
uint256 public constant KEEPER_BOUNTY = 0.001 ether;
/// @notice Hard lifetime cap on total bounties paid in this game. ~$50
/// worth at deploy-era prices. Sized comfortably above worst-case
/// (every one of the 14 rounds delayed = 14 × KEEPER_BOUNTY = 0.014 ETH).
uint256 public constant KEEPER_BOUNTY_CAP = 0.025 ether;
/// @notice H-3 fix: 12-second cooldown after _finalizeGame — exactly one
/// mainnet block. The H-3 attack vector is same-block ordering (a bot
/// orders its finalize tx right before a royalty tx in one block);
/// 12 sec covers that and the next-block first half as a small buffer.
/// During the window, royalty still flows into winnerReserve AND
/// finalPrizeSnapshot. After the window: 100% to creator (normal
/// post-game behavior). Winners wait one block (~12 sec) to claim —
/// indistinguishable from normal network latency.
uint256 public constant FINALIZE_GRACE = 12 seconds;
/*//////////////////////////////////////////////////////////////
CORE STATE
//////////////////////////////////////////////////////////////*/
Stage public stage;
PunkGamesRenderer public immutable renderer;
PunkGamesAfterGames public immutable afterGames;
// Anti-grind randomness: seed is derived from a FUTURE blockhash captured
// after deploy. Owner can't predict it at deploy, can't grind the timing,
// can't influence it — anyone can call `lockRandomness()` once the target
// block has passed. Used to seed elimination randomness during the arena.
uint256 public immutable DEPLOY_BLOCK;
uint256 public constant RANDOMNESS_DELAY_BLOCKS = 32; // ≈ 6.4 min mainnet (= 1 PoS epoch, post-finality)
uint256 public randomSeed; // 0 = not yet locked. nonzero once lockRandomness() fires.
address public creator;
address public ops;
/*//////////////////////////////////////////////////////////////
POOLS
//////////////////////////////////////////////////////////////*/
uint256 public prizePool; // current total (visible in UI)
uint256 public cashOutReserve; // capped at 50% of prize pool at game start
uint256 public winnerReserve; // capped at 50% — eventually paid to top 3
uint256 public creatorBalance;
uint256 public opsBalance;
// Lifetime royalty inflow counters. UI reads these to show "secondary
// trades contributed X ETH to the prize pool" without scanning event logs.
uint256 public totalRoyaltyToPool;
uint256 public totalRoyaltyToCreator;
/// @notice Snapshot of total winner pool at game end. Fixed at FINISHED stage.
/// Used for winner payout calculations to prevent claim-order dependency.
uint256 public finalPrizeSnapshot;
/// @notice Timestamp when game finished. Used for emergency withdraw timelock.
uint256 public finishedAt;
/// @notice Timestamp when cancelGameAndRefund() fired. 0 if not canceled.
uint256 public canceledAt;
/// @notice aliveCount snapshot at cancel time — denominator for pro-rata
/// refunds if refundPoolAtCancel is short of (alive × MINT_PRICE).
uint256 public aliveCountAtCancel;
/// @notice Refundable balance snapshot at cancel time (contract balance
/// minus creator/ops balances). Refunds drain from here.
uint256 public refundPoolAtCancel;
/// @notice Per-token refund-claimed flag (CANCELED stage only).
mapping(uint256 => bool) public refundClaimed;
/// @notice Running total of keeper bounties paid; capped at KEEPER_BOUNTY_CAP.
uint256 public totalBountiesPaid;
/// @notice Count of tokens with winnerFlag set via endgame elimination
/// (i.e., 2nd + 3rd place). Used by cancelGameAndRefund so crowned-but-
/// not-finalized holders aren't trapped — they were on track to win and
/// deserve at least their mint price back if the game stalls before
/// finalize. Their PunkGames token is burned, so the alive-only refund
/// path can't reach them; this counter widens the denominator.
uint256 public crownedCount;
/// @notice One bounty per round-start, even if the round takes multiple
/// runRoundBatch calls to drain (BATCH_SIZE limit).
mapping(uint256 => bool) public roundBountyPaid;
/// @notice One RUN_ROUND_TIP per round-start, regardless of how many
/// runRoundBatch calls execute it. H-1 fix: without this, a caller could
/// pass _maxCount = 1 and earn one tip per single elimination, draining
/// up to ~27% of the prize pool. Mainnet currently sets RUN_ROUND_TIP = 0
/// so the exploit is neutralized at deploy time, but this guard removes
/// the dependency on that config choice. Indexed by currentRound; the
/// reduction==0 finalize path also writes here so it can't earn a second
/// tip beyond the last round's allowance.
mapping(uint256 => bool) public tipPaidThisRound;
/// @notice The interval pinned at the START of the current/last round.
/// M-3 fix (audit pass-4): without pinning, cashouts that pushed aliveCount
/// from above ENDGAME_TRIGGER to at-or-below mid-round would flip the
/// timing check to ENDGAME_INTERVAL, stalling the round if endgame ≠ mass
/// interval. Mainnet uses equal 8h intervals so the bug is currently
/// neutralized, but this defends against any future config that re-enables
/// different intervals. 0 = no round has started yet (use computed value).
uint256 public currentRoundInterval;
/// @notice Timestamp the main sale opened. Anchor for the cancel-stall
/// clock during MAIN_SALE if no mints have happened.
uint256 public mainSaleStartedAt;
/// @notice Timestamp of the most recent mint. Anchor for the cancel-stall
/// clock during MAIN_SALE after some buying has happened.
uint256 public lastMintTime;
/*//////////////////////////////////////////////////////////////
GAME STATE
//////////////////////////////////////////////////////////////*/
uint256 public currentRound;
uint256 public lastRoundTimestamp; // schedule anchor; advanced by interval each round (drift-free)
uint256 public arenaStartTime; // Unix timestamp when arena unlocks (next 14:00 UTC after mint completes)
uint256 public eliminationsThisRound; // eliminations so far this round (display only post audit pass-7)
/// @notice Monotonic per-selection counter used in `_selectVictim` entropy.
/// Pass-7 audit (codex M-1) flagged that the prior salt input
/// `eliminationsThisRound` was incremented by the caller-chosen batch size
/// before victim selection, so a builder/keeper could pick a `_maxCount`
/// value that produced a favorable victim sequence. `selectionCounter`
/// increments exactly once per selection inside `_selectVictim` itself,
/// independent of how many batches the round is split across.
uint256 public selectionCounter;
uint256 public roundTargetAlive; // aliveCount the round drives down to
bool public roundInProgress; // true while a round is mid-execution
// Token state — eliminationRound: 0 = alive, 1-5 = eliminated in that round
mapping(uint256 => uint8) public eliminationRound;
mapping(uint256 => bool) public winnerFlag; // alive at end → crowned
mapping(uint256 => uint8) public placement; // 1, 2, or 3 for top finishers
mapping(uint256 => bool) public cashedOut;
mapping(uint256 => bool) public claimedPrize;
// Lazy-init alive tracking — no upfront 10k loop
uint256 public aliveCount;
uint256 public arenaSnapshotSupply; // totalSupply at openArena
// Virtual dense alive list — O(1) victim selection (C2 fix)
// Lazy-initialized: if _aliveList[i] == 0, token at index i is tokenId i.
// Non-zero stores tokenId+1 (so 0 stays as the "identity" sentinel).
mapping(uint256 => uint256) private _aliveList;
mapping(uint256 => uint256) private _aliveIndex;
// Lazy Fisher-Yates pool — random token ID assignment at mint time.
// _remainingTokens: how many IDs are still available (decrements each mint).
// _availableTokens[i]: 0 means slot i holds tokenId i; non-zero stores the actual tokenId.
uint256 private _remainingTokens;
mapping(uint256 => uint256) private _availableTokens;
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event StageChanged(Stage newStage);
event Minted(address indexed to, uint256 indexed tokenId);
event ArenaOpened(uint256 timestamp, uint256 supply);
event ArenaStartTimeSet(uint256 arenaStartTime);
event RandomnessLocked(uint256 targetBlock, uint256 seed);
event RoundExecuted(uint256 indexed round, uint256 eliminated, uint256 remaining);
event Eliminated(uint256 indexed tokenId, uint256 indexed round, address indexed owner);
event CashedOut(uint256 indexed tokenId, address indexed owner, uint256 amount, uint8 round);
event WinnerCrowned(uint256 indexed tokenId, uint8 placement, address indexed owner);
event PrizeClaimed(uint256 indexed tokenId, address indexed owner, uint256 amount);
event RoyaltyReceived(uint256 amount, uint256 toPool, uint256 toCreator);
event TipPaid(address indexed caller, uint256 amount);
event CreatorWithdrawn(uint256 amount);
event OpsWithdrawn(uint256 amount);
event EmergencyWithdrawn(uint256 amount);
event FinalPrizeSnapshot(uint256 amount);
event GameCanceled(uint256 timestamp, uint256 aliveCount, uint256 refundPool);
event RefundClaimed(uint256 indexed tokenId, address indexed owner, uint256 amount);
event KeeperBountyPaid(address indexed caller, uint256 indexed round, uint256 amount);
/*//////////////////////////////////////////////////////////////
ERRORS
//////////////////////////////////////////////////////////////*/
error WrongStage();
error SoldOut();
error InsufficientPayment();
error TooManyAtOnce();
error AlreadyClaimed();
error NotTokenOwner();
error NotEligible();
error AlreadyEliminated();
error AlreadyCashedOut();
error CashOutNotYetAvailable();
error CashOutClosed();
error SlippageExceeded();
error RoundTooEarly();
error RoundComplete();
error TooEarly();
error ZeroSupply();
error GameNotEnded();
error RandomnessNotLocked();
error RandomnessNotYetAvailable();
error RandomnessAlreadyLocked();
error BlockhashUnavailable();
error GameNotStalled();
error NotCanceled();
error AlreadyRefunded();
error NotRefundEligible();
/*//////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
struct DeployConfig {
uint256 tokenLimit;
uint256 mintPrice;
uint256 maxPerTx;
uint256 roundInterval; // mass-phase round interval
uint256 endgameInterval; // endgame round interval (triggers when aliveCount <= ENDGAME_TRIGGER)
uint256 arenaAnchorHourUtc; // 0-23: hour-of-day the arena opens (day after mint completes)
uint256 arenaDelayOverrideSec; // 0 = use next-day-at-anchor-hour logic (mainnet). Non-zero = use mintCompleteTime + this many seconds (test shortcut).
uint256 runRoundTip;
uint256 batchSize;
}
constructor(
string memory _name,
string memory _symbol,
DeployConfig memory _cfg,
address _renderer,
address _afterGames,
address _creator,
address _ops
) ERC721(_name, _symbol) Ownable(msg.sender) {
TOKEN_LIMIT = _cfg.tokenLimit;
MINT_PRICE = _cfg.mintPrice;
MAX_PER_TX = _cfg.maxPerTx;
ROUND_INTERVAL = _cfg.roundInterval;
ENDGAME_INTERVAL = _cfg.endgameInterval == 0 ? _cfg.roundInterval : _cfg.endgameInterval;
require(_cfg.arenaAnchorHourUtc < 24, "anchor hour out of range");
ARENA_ANCHOR_HOUR_UTC = _cfg.arenaAnchorHourUtc;
ARENA_DELAY_OVERRIDE_SEC = _cfg.arenaDelayOverrideSec;
RUN_ROUND_TIP = _cfg.runRoundTip;
BATCH_SIZE = _cfg.batchSize;
// Anchor for future-blockhash randomness — see lockRandomness().
DEPLOY_BLOCK = block.number;
renderer = PunkGamesRenderer(_renderer);
afterGames = PunkGamesAfterGames(_afterGames);
creator = _creator;
ops = _ops;
// PRESALE here just means "deployed, public mint not yet open". The
// merkle-root presale path was removed pre-mainnet — there is no
// allowlist mint, no claim() function. Owner calls startMainSale()
// (after lockRandomness fires) to open public mint to everyone.
stage = Stage.PRESALE;
_remainingTokens = _cfg.tokenLimit;
}
/*//////////////////////////////////////////////////////////////
MINTING
//////////////////////////////////////////////////////////////*/
function mint(uint256 _amount) external payable nonReentrant {
if (stage != Stage.MAIN_SALE) revert WrongStage();
if (_amount > MAX_PER_TX) revert TooManyAtOnce();
uint256 cost = MINT_PRICE * _amount;
if (msg.value < cost) revert InsufficientPayment();
if (totalSupply() + _amount > TOKEN_LIMIT) revert SoldOut();
_splitMintPayment(cost);
for (uint256 i = 0; i < _amount; i++) {
_mintWarrior(msg.sender);
}
// Auto-close mint when sold out — no manual completeSale() needed
if (totalSupply() == TOKEN_LIMIT) {
_completeSale();
}
// Refund any overpayment (H2 fix)
uint256 excess = msg.value - cost;
if (excess > 0) {
(bool ok,) = payable(msg.sender).call{value: excess}("");
require(ok, "refund failed");
}
}
/// @dev Single-tx mint with rarity-grinding risk accepted (codex pass-7
/// audit H-1). Reasoning: this is a 10k survival raffle where 9,999 punks
/// are eliminated. Winning the prize pool dominates rare-trait secondary
/// value, so the grinding incentive is bounded. The UX cost of commit-
/// reveal (2 txs, wallet compatibility issues, bot mass-mint friction)
/// outweighs the marginal protection for this product. See
/// CONSOLIDATED_FINAL.md for the full risk-acceptance rationale.
function _mintWarrior(address _to) internal {
// Lazy Fisher-Yates: pick a random slot from the remaining pool,
// swap it with the last slot, then shrink the pool by 1.
uint256 remaining = _remainingTokens;
uint256 rand = uint256(keccak256(abi.encodePacked(
randomSeed, block.prevrandao, block.timestamp, msg.sender, remaining
))) % remaining;
// slot rand → tokenId (0 means identity: tokenId == rand)
uint256 tokenId = _availableTokens[rand] == 0 ? rand : _availableTokens[rand];
// Move last slot into the gap
uint256 lastIdx = remaining - 1;
uint256 lastVal = _availableTokens[lastIdx] == 0 ? lastIdx : _availableTokens[lastIdx];
if (rand != lastIdx) {
_availableTokens[rand] = lastVal;
}
delete _availableTokens[lastIdx];
_remainingTokens = lastIdx;
// _mint instead of _safeMint blocks the in-flight onERC721Received
// callback grinding shape. The full grinding attack (call mint(), wait
// for return, inspect tokenId, revert whole tx) remains possible
// because the contract caller can read state after _mint returns —
// accepted risk per CONSOLIDATED_FINAL.md / codex pass-7 H-1.
_mint(_to, tokenId);
lastMintTime = block.timestamp;
emit Minted(_to, tokenId);
}
function _splitMintPayment(uint256 _amount) internal {
uint256 toPrize = (_amount * PRIZE_BPS) / 10000;
uint256 toCreator = (_amount * CREATOR_BPS) / 10000;
uint256 toOps = _amount - toPrize - toCreator;
prizePool += toPrize;
creatorBalance += toCreator;
opsBalance += toOps;
}
/*//////////////////////////////////////////////////////////////
ROYALTY INCOME (receive)
//////////////////////////////////////////////////////////////*/
/// @notice Routes incoming ETH (royalties from secondary trades) into pools.
/// Active windows (4.2% pool / 2.7% creator split out of 6.9% royalty):
/// • ARENA stage
/// • FINISHED stage during the 12-second FINALIZE_GRACE window
/// Outside those: 100% to creator. The grace window blocks the H-3
/// front-running attack — see comment on FINALIZE_GRACE constant.
receive() external payable {
bool inArena = stage == Stage.ARENA;
bool inGrace = stage == Stage.FINISHED && block.timestamp < finishedAt + FINALIZE_GRACE;
if (inArena || inGrace) {
uint256 toPool = (msg.value * ROYALTY_TO_POOL_BPS) / 6900;
uint256 toCreator = msg.value - toPool;
prizePool += toPool;
creatorBalance += toCreator;
// Lifetime running totals — read by the UI to show "secondary sales
// contributed X ETH to the prize pool" without paying for getLogs.
totalRoyaltyToPool += toPool;
totalRoyaltyToCreator += toCreator;
if (inArena) {
// Split new pool money between cashout and winner reserves
uint256 toCashout = toPool / 2;
cashOutReserve += toCashout;
winnerReserve += (toPool - toCashout);
} else {
// Same-block-after-finalize royalty: cashouts are closed, so
// all pool money goes to winnerReserve. Grow finalPrizeSnapshot
// too so winners' computed payouts include the late royalty.
// The matching FINALIZE_GRACE require in claimWinnerPrize
// keeps claim-order fair (no one claims during the 12 sec).
winnerReserve += toPool;
finalPrizeSnapshot += toPool;
}
emit RoyaltyReceived(msg.value, toPool, toCreator);
} else {
creatorBalance += msg.value;
totalRoyaltyToCreator += msg.value;
emit RoyaltyReceived(msg.value, 0, msg.value);
}
}
/*//////////////////////////////////////////////////////////////
SALE STAGE MANAGEMENT
//////////////////////////////////////////////////////////////*/
function startMainSale() external onlyOwner {
if (stage != Stage.PRESALE) revert WrongStage();
// Mint must not open until randomness is locked, otherwise the
// tokenId-draw randomness lacks the anti-grind seed.
if (randomSeed == 0) revert RandomnessNotLocked();
stage = Stage.MAIN_SALE;
// Seed the cancel-stall anchor so a never-bought-into game can still
// be unwound after 60 days. lastMintTime ticks forward on each mint.
mainSaleStartedAt = block.timestamp;
lastMintTime = block.timestamp;
emit StageChanged(stage);
}
function completeSale() external onlyOwner {
_completeSale();
}
/// @notice Owner can cut the mint short if the field clearly won't sell out.
/// The game proceeds with whatever totalSupply has minted by this point —
/// no need to reach TOKEN_LIMIT. Arena still opens at the anchored time.
function cutSupplyAndComplete() external onlyOwner {
if (totalSupply() == 0) revert ZeroSupply();
_completeSale();
}
function _completeSale() internal {
if (stage != Stage.MAIN_SALE) revert WrongStage();
stage = Stage.COMPLETE;
if (ARENA_DELAY_OVERRIDE_SEC > 0) {
// Test shortcut: arena opens mintCompleteTime + override seconds.
// Used for Sepolia rehearsals so we don't have to wait until the
// next ARENA_ANCHOR_HOUR_UTC slot. Mainnet sets this to 0.
arenaStartTime = block.timestamp + ARENA_DELAY_OVERRIDE_SEC;
} else {
// Mainnet behavior: anchor to the next ARENA_ANCHOR_HOUR_UTC the
// day AFTER mint completes. Mint sells out at any odd hour; the
// game still kicks off at a clean, marketable time of day.
uint256 currentDay = block.timestamp / 86400;
arenaStartTime = (currentDay + 1) * 86400 + ARENA_ANCHOR_HOUR_UTC * 3600;
}
emit StageChanged(stage);
emit ArenaStartTimeSet(arenaStartTime);
}
/// @notice Permissionless: lock the random seed from a FUTURE blockhash.
/// Owner can't predict the seed at deploy, can't grind the call timing,
/// can't influence which block hash is used. Anyone calls this once 64
/// blocks have passed since deploy (~6.4 min on mainnet). After this fires,
/// `startMainSale` can open and minting may begin.
function lockRandomness() external {
if (randomSeed != 0) revert RandomnessAlreadyLocked();
uint256 targetBlock = DEPLOY_BLOCK + RANDOMNESS_DELAY_BLOCKS;
if (block.number < targetBlock) revert RandomnessNotYetAvailable();
// blockhash() is only available for the last 256 blocks. If the lock
// hasn't been called within ~50 min of the target, the hash is zero
// and we'd lock in an unsafe seed — explicit revert so a bot or the
// owner can call again on a fresh deploy.
bytes32 bh = blockhash(targetBlock);
if (bh == bytes32(0)) revert BlockhashUnavailable();
randomSeed = uint256(keccak256(abi.encodePacked(bh, address(this))));
emit RandomnessLocked(targetBlock, randomSeed);
}
/*//////////////////////////////////////////////////////////////
ARENA / GAMEPLAY
//////////////////////////////////////////////////////////////*/
/// @notice Open the arena. Permissionless after arenaStartTime — anyone
/// can fire it (bots will sweep it instantly). The owner has no discretion
/// on round timing once mint completes.
function openArena() external {
if (randomSeed == 0) revert RandomnessNotLocked();
if (stage != Stage.COMPLETE) revert WrongStage();
if (block.timestamp < arenaStartTime) revert TooEarly();
uint256 supply = totalSupply();
arenaSnapshotSupply = supply;
aliveCount = supply;
// Split prize pool at this moment into cashout vs winner reserves
cashOutReserve = (prizePool * CASHOUT_RESERVE_BPS) / 10000;
winnerReserve = prizePool - cashOutReserve;
stage = Stage.ARENA;
// Schedule pinning: round 1 must be eligible exactly at arenaStartTime,
// so we set lastRoundTimestamp = arenaStartTime - ROUND_INTERVAL.
// The _runRound gate is `block.timestamp >= lastRoundTimestamp + interval`,
// which becomes `block.timestamp >= arenaStartTime`. ✓
lastRoundTimestamp = arenaStartTime - ROUND_INTERVAL;
emit ArenaOpened(block.timestamp, supply);
emit StageChanged(stage);
}
/// @notice Run a batch of eliminations for the current round.
/// Anyone can call. Caller receives RUN_ROUND_TIP from prize pool as bot incentive.
/// Each call processes up to BATCH_SIZE eliminations.
/// @notice Run eliminations for the current round using the full BATCH_SIZE cap.
function runRoundBatch() external nonReentrant {
_runRound(BATCH_SIZE);
}
/// @notice Run eliminations with a custom per-tx limit (capped at BATCH_SIZE).
/// Pass a smaller value if gas prices spike or you hit block gas limits.
function runRoundBatch(uint256 _maxCount) external nonReentrant {
uint256 cap = (_maxCount == 0 || _maxCount > BATCH_SIZE) ? BATCH_SIZE : _maxCount;
_runRound(cap);
}
function _runRound(uint256 _batchCap) internal {
if (stage != Stage.ARENA) revert WrongStage();
if (currentRound >= MAX_ROUND) revert WrongStage();
// M-3 fix (audit pass-4): use the interval pinned at the start of the
// current round if one is in progress; otherwise compute fresh. Without
// this, mid-round cashouts that push aliveCount into the endgame zone
// would flip the interval mid-round (relevant only when ENDGAME_INTERVAL
// != ROUND_INTERVAL — neutralized on mainnet's 8h/8h config but
// defended structurally regardless).
uint256 currentInterval = roundInProgress
? currentRoundInterval
: (aliveCount <= ENDGAME_TRIGGER ? ENDGAME_INTERVAL : ROUND_INTERVAL);
if (block.timestamp < lastRoundTimestamp + currentInterval) revert RoundTooEarly();
// Start a new round if one isn't already running.
if (!roundInProgress) {
// Reduction = how many to remove this round (50% mass / 1 endgame / 0 winner).
uint256 reduction = _eliminationTargetForRound(currentRound);
// reduction == 0 means aliveCount <= 1 — the winner is decided.
// Pass-8 fix (rehearsal #5 finding): do NOT pay the tip on a
// finalize-only call. _payTip drains winnerReserve AFTER
// _finalizeGame snapshotted it, leaving the 3rd-place reserve
// short by exactly the tip and the claim L-4 require to revert.
// The keeper got tips for the real elimination work — this call
// is bookkeeping only, no tip owed.
if (reduction == 0) {
_finalizeGame();
return;
}
// Keeper bounty: if this round is starting late (>1h after the
// scheduled eligibility), pay a one-time bounty to whoever finally
// fired it. One bounty per round even if the round takes multiple
// batches. Drawn from cashOutReserve — note this reduces the final
// prize snapshot (winners see the smaller pool). Accounting is
// clean: bounty is paid out immediately, not tracked separately.
// The bounty is the safety net for "what if the operator's bot dies
// and nobody runs the game" — random keepers get a small profit
// motive to keep things moving.
uint256 nextRound = currentRound + 1;
if (
!roundBountyPaid[nextRound]
&& totalBountiesPaid < KEEPER_BOUNTY_CAP
&& block.timestamp >= lastRoundTimestamp + currentInterval + KEEPER_BOUNTY_DELAY
) {
_payKeeperBounty(nextRound);
}
currentRound++;
// Floor we drive aliveCount down to. Always >= 1, so the last
// survivor can never be eliminated by a round.
roundTargetAlive = aliveCount - reduction;
eliminationsThisRound = 0;
roundInProgress = true;
// M-3 fix: pin the interval at round-start so mid-round cashouts
// can't flip the timing math.
currentRoundInterval = currentInterval;
}
// Eliminations still needed to reach the floor. Cashouts during the
// round have already lowered aliveCount, counting toward this round —
// so total removed (cashouts + eliminations) equals the reduction and
// the field can never be over-drained below the floor.
uint256 needed = aliveCount > roundTargetAlive ? aliveCount - roundTargetAlive : 0;
uint256 batchSize = needed > _batchCap ? _batchCap : needed;
// CEI: bump the counter before the external calls in _eliminateBatch (H1 fix).
eliminationsThisRound += batchSize;
if (batchSize > 0) {
_eliminateBatch(batchSize);
}
// Round complete once aliveCount has reached the floor.
bool justFinalized = false;
if (aliveCount <= roundTargetAlive) {
emit RoundExecuted(currentRound, eliminationsThisRound, aliveCount);
roundInProgress = false;
// Drift-free schedule: advance the anchor by exactly this round's
// interval. If the round fires late (delayed bot, gas spike, etc.)
// the NEXT round's eligibility is still anchored to the schedule,
// not pushed further out. Rounds stay on their 14:00/22:00/06:00 UTC
// slots even if individual rounds run a little late.
lastRoundTimestamp += currentInterval;
// Last survivor → finalize and crown 1st place.
if (aliveCount <= 1) {
_finalizeGame();
justFinalized = true;
}
}
// Pass-8 fix (rehearsal #5): skip the tip on the call that finalized
// the game. _payTip would drain winnerReserve AFTER finalPrizeSnapshot
// was locked in, leaving the 3rd-place claim short by exactly the
// tip amount and the L-4 require to revert. The eliminations this
// call DID do are real work — the keeper got tips for them via prior
// batches. Skipping this last tip costs them 1× RUN_ROUND_TIP at most
// and preserves winner payouts exactly.
if (!justFinalized) _payTip();
}
/// @notice Survivor voluntarily exits. Pays a share of the cashout
/// reserve (cashOutReserve / aliveCount), capped by CASHOUT_CAP_MULT.
/// Burns the clothed PunkGames token and mints a matching After Games
/// keepsake (with wasCashOut=true) so the wallet retains a visible record
/// of having walked away.
/// @dev Mandatory slippage protection: callers MUST pass `_minPayout`.
/// Share-of-pool payout is computed at include-time (not submit-time), so
/// other cashouts landing first can shift the value. The bare
/// cashOut(uint256) overload was REMOVED (pre-mainnet hardening) so stale
/// clients revert loudly instead of getting sandwich-rugged silently.
/// Pass `_minPayout = 0` to opt out (not recommended).
function cashOut(uint256 _tokenId, uint256 _minPayout) external nonReentrant {
_cashOut(_tokenId, _minPayout);
}
function _cashOut(uint256 _tokenId, uint256 _minPayout) internal {
// Explicit stage gate: post-cancel cashOuts must not drain the refund pool.
if (stage != Stage.ARENA) revert WrongStage();
if (ownerOf(_tokenId) != msg.sender) revert NotTokenOwner();
if (eliminationRound[_tokenId] != 0) revert AlreadyEliminated();
if (cashedOut[_tokenId]) revert AlreadyCashedOut();
if (currentRound < CASH_OUT_OPENS_ROUND) revert CashOutNotYetAvailable();
if (currentRound >= CASH_OUT_CLOSES_ROUND) revert CashOutClosed();
// Lock in the final 4 — once we reach the endgame zone, nobody can cash
// out. This guarantees the endgame always has its contestants to crown
// 4th/3rd/2nd/1st, even if mass cashouts shrank the field early.
if (aliveCount <= ENDGAME_TRIGGER) revert CashOutClosed();
// v2 share-of-pool: payout is computed from current reserve / alive,
// capped by CASHOUT_CAP_MULT. Can only be 0 if the reserve is fully
// drained — treat that as window-closed rather than a failing tx.
uint256 payout = _cashOutPayoutForRound(currentRound);
if (payout == 0) revert CashOutClosed();
// M-1 fix (audit pass-4): slippage floor. Default is 0 (no floor) so
// pre-M-1 callers see no change. Callers using the new overload get
// protection against the actual payout being lower than what they
// signed against.
if (payout < _minPayout) revert SlippageExceeded();
eliminationRound[_tokenId] = uint8(currentRound);
cashedOut[_tokenId] = true;
cashOutReserve -= payout;
prizePool -= payout;
_removeFromAlive(_tokenId);
aliveCount--;
claimedPrize[_tokenId] = true;
// Burn the clothed token and mint the After Games keepsake. Marked
// wasCashOut=true so the renderer reaches for the dedicated cash-out
// art (different outfit from the bruised eliminated punks).
_burn(_tokenId);
afterGames.mintCashOut(msg.sender, _tokenId, uint8(currentRound));
(bool ok, ) = payable(msg.sender).call{value: payout}("");
require(ok, "transfer failed");
emit CashedOut(_tokenId, msg.sender, payout, uint8(currentRound));
}
/// @notice Winner claims their placement prize after game ends. Subject
/// to a 12-second grace window after finalize (= 1 mainnet block) so
/// same-block royalty income lands in the snapshot before payouts are
/// computed. See FINALIZE_GRACE comment for the H-3 attack rationale.
function claimWinnerPrize(uint256 _tokenId) external nonReentrant {
if (stage != Stage.FINISHED) revert GameNotEnded();
require(block.timestamp >= finishedAt + FINALIZE_GRACE, "finalize grace");
// Clothed punk (1st place) is still alive — check PunkGames ownership.
// Burned winners (2nd/3rd) received an After Games punk — check that instead.
address tokenOwner = _ownerOf(_tokenId) != address(0)
? ownerOf(_tokenId)
: afterGames.ownerOf(_tokenId);
if (tokenOwner != msg.sender) revert NotTokenOwner();
if (!winnerFlag[_tokenId]) revert NotEligible();
if (claimedPrize[_tokenId]) revert AlreadyClaimed();
uint256 amount = _winnerPayout(_tokenId);
claimedPrize[_tokenId] = true;
// L-4 fix: fail loud if reserves can't cover the computed amount. The
// function previously fell through to address(this).balance which
// silently dipped into creator/ops accounting. With the M-5 fix in
// place this should never trigger; the require makes any future
// accounting desync surface as a revert instead of fund loss.
require(winnerReserve + cashOutReserve >= amount, "reserves desync");
// Drain from reserves and prizePool together — keep accounting consistent.
// Pull from winnerReserve first, then cashOutReserve if needed.
uint256 remaining = amount;
if (winnerReserve >= remaining) {
winnerReserve -= remaining;
remaining = 0;
} else {
remaining -= winnerReserve;
winnerReserve = 0;
}
if (remaining > 0 && cashOutReserve >= remaining) {
cashOutReserve -= remaining;
remaining = 0;
}
prizePool -= (amount - remaining);
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "transfer failed");
emit PrizeClaimed(_tokenId, msg.sender, amount);
}
/*//////////////////////////////////////////////////////////////
INTERNAL ELIMINATION LOGIC
//////////////////////////////////////////////////////////////*/
function _eliminateBatch(uint256 _count) internal {
for (uint256 i = 0; i < _count && aliveCount > 0; i++) {
uint256 victimId = _selectVictim();
address victimOwner = ownerOf(victimId);
// Determine the damage tier for the AfterGames token
// Mass phase (R1-R11) uses round-based tier mapping (1-5)
// Endgame (R12-R14) uses tier 5 for everyone — they made it deep
uint8 tier = _afterGamesTierForRound(currentRound);
eliminationRound[victimId] = uint8(currentRound);
// Endgame: assign placement based on aliveCount BEFORE this elimination
// aliveCount==4: this victim is 4th place
// aliveCount==3: this victim is 3rd place 🥉
// aliveCount==2: this victim is 2nd place 🥈
if (aliveCount <= ENDGAME_TRIGGER) {
placement[victimId] = uint8(aliveCount);
// 2nd and 3rd place winners get winnerFlag true so they can claim
if (aliveCount == 2 || aliveCount == 3) {
winnerFlag[victimId] = true;
crownedCount++; // H-2 fix: widens refund denominator if cancel fires mid-endgame
emit WinnerCrowned(victimId, uint8(aliveCount), victimOwner);
}
}
_removeFromAlive(victimId);
aliveCount--;
_burn(victimId);
afterGames.mintEliminated(victimOwner, victimId, tier);
emit Eliminated(victimId, currentRound, victimOwner);
}
}
/// @dev Maps round number → AfterGames damage tier (1-5).
/// R1-R3 = bandage(1), R4-R6 = sweat(2), R7-R9 = patch(3), R10-R11 = scuffs(4),
/// R12+ = knee(5, deepest tier — endgame eliminations earn this)
function _afterGamesTierForRound(uint256 _round) internal pure returns (uint8) {
if (_round <= 3) return 1;
if (_round <= 6) return 2;
if (_round <= 9) return 3;
if (_round <= 11) return 4;
return 5;
}
/// @dev Returns the tokenId at a given alive-list index (lazy-init).
function _getAliveAt(uint256 _idx) internal view returns (uint256) {
uint256 val = _aliveList[_idx];
return val == 0 ? _idx : val - 1;
}
/// @dev Swap-and-pop: remove a token from the alive list in O(1).
/// Must be called BEFORE decrementing aliveCount.
function _removeFromAlive(uint256 _tokenId) internal {
uint256 raw = _aliveIndex[_tokenId];
uint256 idx = raw == 0 ? _tokenId : raw - 1;
uint256 lastIdx = aliveCount - 1;
if (idx != lastIdx) {
uint256 lastToken = _getAliveAt(lastIdx);
_aliveList[idx] = lastToken + 1;
_aliveIndex[lastToken] = idx + 1;
}
}
/// @dev O(1) random victim selection via dense alive list.
/// C-2 fix: mixes block.prevrandao into the hash so the elimination
/// sequence isn't fully pre-computable from the locked seed alone.
/// Without prevrandao, anyone who knew (seed, currentRound, eliminations)
/// could simulate every future elimination — the game would be "solved"
/// the moment lockRandomness fires. Adding prevrandao trades one bit of
/// validator-grinding power (the round-fire block proposer) for full
/// per-round unpredictability; the proposer-bit risk is bounded because
/// (a) they don't know which call will fire the round, (b) the bounty
/// makes the round-fire block contested anyway.
/// @dev Salt input uses `selectionCounter` (monotonic per call) rather than
/// `eliminationsThisRound` (incremented by caller-chosen batch size) so the
/// caller can't shape victim selection by picking a particular `_maxCount`.
/// See pass-7 audit (codex M-1).
function _selectVictim() internal returns (uint256) {
uint256 nonce = selectionCounter++;
uint256 idx = uint256(keccak256(abi.encodePacked(
randomSeed, block.prevrandao, currentRound, nonce
))) % aliveCount;
return _getAliveAt(idx);
}
/// @notice Finalizes the game once aliveCount == 1.
/// Placements 2nd-4th were assigned during their elimination in endgame rounds.
/// The last remaining alive token is 1st place.
function _finalizeGame() internal {
if (aliveCount == 1) {
uint256 winnerId = _getAliveAt(0);
winnerFlag[winnerId] = true;
placement[winnerId] = 1;
eliminationRound[winnerId] = uint8(MAX_ROUND);
emit WinnerCrowned(winnerId, 1, ownerOf(winnerId));
}
stage = Stage.FINISHED;
finishedAt = block.timestamp;
// Snapshot the final prize pool — used for all winner payout calculations.
// This prevents claim-order from skewing payouts (C1 fix).
finalPrizeSnapshot = winnerReserve + cashOutReserve;
emit FinalPrizeSnapshot(finalPrizeSnapshot);
// Flush any leftover ops budget into creator balance.
if (opsBalance > 0) {
creatorBalance += opsBalance;
opsBalance = 0;
}
emit StageChanged(stage);
}
function _eliminationTargetForRound(uint256 /* _round */) internal view returns (uint256) {
// Endgame: eliminate exactly 1 per round once we hit ENDGAME_TRIGGER alive
// This is what produces the 4 → 3 → 2 → 1 winner sequence at the end
if (aliveCount <= ENDGAME_TRIGGER) {
// Don't eliminate the last one — they're 1st place
if (aliveCount <= 1) return 0;
return 1;
}
// Mass phase: 50% of current alive, rounded down
return aliveCount / 2;
}
/// @notice v2 share-of-pool cashout. payout = min(reserve / alive, MINT_PRICE * 200).
/// Returns 0 outside the cashout window (caller already gates on stage/round).
/// Self-balancing: payout grows as the field shrinks, capped to keep max
/// cashout strictly below 3rd-place prize (brand-safety invariant).
function _cashOutPayoutForRound(uint256 _round) internal view returns (uint256) {
if (_round < CASH_OUT_OPENS_ROUND) return 0;
if (_round >= CASH_OUT_CLOSES_ROUND) return 0;
if (aliveCount == 0) return 0;
uint256 share = cashOutReserve / aliveCount;
uint256 cap = MINT_PRICE * CASHOUT_CAP_MULT;
return share > cap ? cap : share;
}
/*//////////////////////////////////////////////////////////////
WINNER PAYOUT MATH
//////////////////////////////////////////////////////////////*/
/// @dev Uses finalPrizeSnapshot (set at game end) so claim order doesn't affect payouts.
/// Splits 60/22/10 with the remaining 8% added to 1st place.
function _winnerPayout(uint256 _tokenId) internal view returns (uint256) {
uint8 place = placement[_tokenId];
if (place == 0) return 0;
uint256 totalForWinners = finalPrizeSnapshot;
if (place == 1) {
// 60% + 8% leftover = 68%
return (totalForWinners * (PLACE_1_BPS + (10000 - PLACE_1_BPS - PLACE_2_BPS - PLACE_3_BPS))) / 10000;
} else if (place == 2) {
return (totalForWinners * PLACE_2_BPS) / 10000;
} else if (place == 3) {
return (totalForWinners * PLACE_3_BPS) / 10000;
}
return 0;
}
/*//////////////////////////////////////////////////////////////
BOT TIP MECHANIC
//////////////////////////////////////////////////////////////*/
// NOTE: a `protection` mechanic (setProtection + purchaseProtection +
// protected[]) was removed in v2 after audit pass-7 (codex). It had a
// same-batch double-pick bug where the same token could be re-selected
// within one elimination batch — protection got consumed on hit #1 and
// the token was eliminated on hit #2. The cleanest fix per product
// direction was to remove the mechanic entirely. Eliminations are now
// pure RNG with no shield. If a future season re-introduces protection,
// it MUST use round-scoped consumption tracking (one shield per token
// per round, not per attempt) and tests for same-batch re-selection.
/// @dev Pays the keeper bounty for a delayed round. Bounded by
/// KEEPER_BOUNTY_CAP across the whole game (lifetime), so worst case
/// (every round delayed = 14 × KEEPER_BOUNTY = 0.014 ETH) sits well under
/// the cap. Refunds cleanly if the caller is a reverting contract — the
/// round still progresses, just without paying out for this attempt.
function _payKeeperBounty(uint256 _round) internal {
uint256 amount = KEEPER_BOUNTY;
uint256 capRemaining = KEEPER_BOUNTY_CAP - totalBountiesPaid;
if (amount > capRemaining) amount = capRemaining;
if (amount > cashOutReserve) amount = cashOutReserve;
if (amount == 0) return;
cashOutReserve -= amount;
prizePool -= amount;
totalBountiesPaid += amount;
roundBountyPaid[_round] = true;
(bool ok, ) = payable(msg.sender).call{value: amount}("");
if (ok) {
emit KeeperBountyPaid(msg.sender, _round, amount);
} else {
// Reverting caller: roll back state so a future caller can earn it.
cashOutReserve += amount;
prizePool += amount;
totalBountiesPaid -= amount;
roundBountyPaid[_round] = false;
}
}
function _payTip() internal {
if (RUN_ROUND_TIP == 0 || prizePool < RUN_ROUND_TIP) return;
// H-1 fix: one tip per round. Without this, a caller can pass
// _maxCount = 1 and earn a tip per single elimination, draining the
// pool over thousands of batches. Same pattern as roundBountyPaid.
if (tipPaidThisRound[currentRound]) return;
tipPaidThisRound[currentRound] = true;
// Deduct from prize pool and the larger reserve
prizePool -= RUN_ROUND_TIP;
bool drainedWinner;
if (winnerReserve >= RUN_ROUND_TIP) {
winnerReserve -= RUN_ROUND_TIP;
drainedWinner = true;
} else if (cashOutReserve >= RUN_ROUND_TIP) {
cashOutReserve -= RUN_ROUND_TIP;
} else {
// Not enough in either reserve — refund prize pool, skip tip.
// Also clear the per-round flag so a later, well-funded call
// can still earn the tip for this round.
prizePool += RUN_ROUND_TIP;
tipPaidThisRound[currentRound] = false;
return;
}
(bool ok, ) = payable(msg.sender).call{value: RUN_ROUND_TIP}("");
if (ok) {
emit TipPaid(msg.sender, RUN_ROUND_TIP);
} else {
// H3 fix: refund — put it back where it came from.
// Also clear the per-round flag so a successor call can earn it.
prizePool += RUN_ROUND_TIP;
if (drainedWinner) {
winnerReserve += RUN_ROUND_TIP;
} else {
cashOutReserve += RUN_ROUND_TIP;
}
tipPaidThisRound[currentRound] = false;
}
}
/*//////////////////////////////////////////////////////////////
WITHDRAWALS
//////////////////////////////////////////////////////////////*/
function withdrawCreator() external nonReentrant {
require(msg.sender == creator, "not creator");
uint256 amount = creatorBalance;
uint256 bal = address(this).balance;
if (amount > bal) amount = bal;
creatorBalance = 0;
(bool ok, ) = payable(creator).call{value: amount}("");
require(ok, "transfer failed");
emit CreatorWithdrawn(amount);
}
function withdrawOps() external nonReentrant {
require(msg.sender == ops, "not ops");
uint256 amount = opsBalance;
opsBalance = 0;
(bool ok, ) = payable(ops).call{value: amount}("");
require(ok, "transfer failed");
emit OpsWithdrawn(amount);
}
/// @notice Time-locked emergency withdraw. Reachable from FINISHED (30d
/// after game end) or CANCELED (30d after cancellation). Sends remaining
/// balance to creator. The 30-day window gives every eligible holder
/// (winners or refund-claimers) ample time to claim normally first.
function emergencyWithdraw() external onlyOwner nonReentrant {
if (stage == Stage.FINISHED) {
require(finishedAt > 0, "no finish timestamp");
require(block.timestamp >= finishedAt + 30 days, "timelock not expired");
} else if (stage == Stage.CANCELED) {
require(canceledAt > 0, "no cancel timestamp");
require(block.timestamp >= canceledAt + CANCEL_TIMELOCK, "timelock not expired");
} else {
revert("game still active");
}
uint256 bal = address(this).balance - creatorBalance - opsBalance;
require(bal > 0, "nothing to withdraw");
// Drain remaining pools
prizePool = 0;
winnerReserve = 0;
cashOutReserve = 0;
(bool ok, ) = payable(creator).call{value: bal}("");
require(ok, "transfer failed");
emit EmergencyWithdrawn(bal);
}
/*//////////////////////////////////////////////////////////////
CANCEL + REFUND (60-day stall safety net)
//////////////////////////////////////////////////////////////*/
/// @notice Permissionless: cancel the game and open refunds if it has been
/// stalled for CANCEL_STALL_DELAY (60 days). Reachable from MAIN_SALE,
/// COMPLETE, or ARENA. Once canceled, alive holders may claimRefund() for
/// up to mint price; eliminated and cashed-out holders receive nothing
/// (they already had their outcome).
///
/// This is the safety net for catastrophic operator failure — gas spikes
/// that last weeks, a dead bot, an absent owner — so users don't have
/// their funds trapped indefinitely if the game can't progress.
function cancelGameAndRefund() external nonReentrant {
if (stage == Stage.FINISHED || stage == Stage.CANCELED) revert WrongStage();
// Compute the "no on-chain progress since" anchor per stage.
uint256 anchor;
uint256 snapshotAlive;
if (stage == Stage.MAIN_SALE) {
// If buyers are still buying, lastMintTime keeps moving and the
// clock resets. If sale opened but nobody bought, mainSaleStartedAt
// provides the fallback.
anchor = lastMintTime > mainSaleStartedAt ? lastMintTime : mainSaleStartedAt;
snapshotAlive = totalSupply();
} else if (stage == Stage.COMPLETE) {
// Arena scheduled but openArena() never called. Anchor on the
// scheduled arena start time.
anchor = arenaStartTime;
snapshotAlive = totalSupply();
} else if (stage == Stage.ARENA) {
// Rounds running but a round is wildly overdue.
// L-2 fix (audit pass-7 codex): use the pinned round interval if a
// round is in progress so cancellation timing matches the schedule
// _runRound is actually using.
uint256 currentInterval = roundInProgress
? currentRoundInterval
: (aliveCount <= ENDGAME_TRIGGER ? ENDGAME_INTERVAL : ROUND_INTERVAL);
anchor = lastRoundTimestamp + currentInterval;
snapshotAlive = aliveCount;
} else {
// PRESALE stalls are owner-controlled (no funds deposited unless
// presale claim happened; if any claims, lastMintTime is set).
revert WrongStage();
}
if (block.timestamp < anchor + CANCEL_STALL_DELAY) revert GameNotStalled();
stage = Stage.CANCELED;
canceledAt = block.timestamp;
// H-2 fix: aliveCountAtCancel now stores the refund-eligible count
// (alive holders + crowned-but-burned 2nd/3rd place). The variable
// name is kept for ABI continuity but semantically widened to cover
// both refund paths in claimRefund(). crownedCount is 0 outside the
// ARENA stage, so MAIN_SALE / COMPLETE branches are unaffected.
aliveCountAtCancel = snapshotAlive + crownedCount;
// Refund pool = balance minus what's already owed to creator/ops via
// their pull-payment balances. Bounties paid out during the game have
// already left the contract, so they're naturally not part of this.
uint256 reserved = creatorBalance + opsBalance;
refundPoolAtCancel = address(this).balance > reserved
? address(this).balance - reserved
: 0;
emit GameCanceled(block.timestamp, aliveCountAtCancel, refundPoolAtCancel);
emit StageChanged(stage);
}
/// @notice Alive holders claim their mint price back after cancellation.
/// If the refund pool fell short of (alive × MINT_PRICE) for any reason
/// (e.g., royalties already paid to creator), holders receive a pro-rata
/// share instead — capped at MINT_PRICE so nobody gets more than they put
/// in. Eliminated and cashed-out tokens are NOT refundable: their owners
/// already had their game outcome.
function claimRefund(uint256 _tokenId) external nonReentrant {
if (stage != Stage.CANCELED) revert NotCanceled();
if (refundClaimed[_tokenId]) revert AlreadyRefunded();
// Two valid eligibility paths, split for cleaner error reporting:
// (a) Alive: still owns the original PunkGames token, not eliminated,
// not cashed-out — the common case.
// (b) Crowned-but-burned (H-2 fix): 2nd/3rd place was already crowned
// via endgame elimination before the cancel fired. Their PunkGames
// token is burned; they hold the After Games token. winnerFlag=true
// distinguishes them from regular eliminated punks (placement-4 or
// mass-phase). They get the same pro-rata refund as alive holders.
// Eliminated mass-phase punks AND cashed-out punks (already paid out via
// multiplier) are NOT refundable — per the user's "losers get nothing"
// and "cashed-out already won" intent.
address pgOwner = _ownerOf(_tokenId);
if (pgOwner != address(0)) {
// Alive path. PunkGames token still exists.
if (pgOwner != msg.sender) revert NotTokenOwner();
if (eliminationRound[_tokenId] != 0) revert NotRefundEligible();
} else {
// Burned path. Only crowned 2nd/3rd qualify; eliminated-mass and
// cashed-out punks lose. afterGames.ownerOf reverts on tokens that
// were never minted there, but for a burned PG token with a valid
// tokenId in the canceled-game state, the AG mint always ran.
if (!winnerFlag[_tokenId]) revert NotRefundEligible();
if (afterGames.ownerOf(_tokenId) != msg.sender) revert NotTokenOwner();
}
// Pro-rata share if the pool was short; capped at MINT_PRICE.
uint256 fairShare = aliveCountAtCancel > 0
? refundPoolAtCancel / aliveCountAtCancel
: 0;
uint256 amount = fairShare < MINT_PRICE ? fairShare : MINT_PRICE;
require(amount > 0, "nothing to refund");
refundClaimed[_tokenId] = true;
(bool ok, ) = payable(msg.sender).call{value: amount}("");
require(ok, "transfer failed");
emit RefundClaimed(_tokenId, msg.sender, amount);
}
/*//////////////////////////////////////////////////////////////
RENDERING
//////////////////////////////////////////////////////////////*/
function tokenURI(uint256 _id) public view override returns (string memory) {
_requireOwned(_id);
// Traits are derived deterministically from tokenId via the on-chain
// PunkAnchors + PunkTraits data, so a freshly-minted punk renders
// fully on the first block. No placeholder phase — secondary trading
// and rare-hunting can start during the mint window.
return renderer.tokenURI(_id, eliminationRound[_id], winnerFlag[_id], cashedOut[_id]);
}
/*//////////////////////////////////////////////////////////////
ROYALTIES (EIP-2981)
//////////////////////////////////////////////////////////////*/
function royaltyInfo(uint256, uint256 _salePrice) external view override
returns (address receiver, uint256 royaltyAmount)
{
uint256 bps = (stage == Stage.ARENA) ? ROYALTY_BPS_GAME : ROYALTY_BPS_POST;
// Royalty receiver is the contract itself during game (so receive() routes it),
// creator post-game (direct).
receiver = (stage == Stage.ARENA) ? address(this) : creator;
royaltyAmount = (_salePrice * bps) / 10000;
}
/*//////////////////////////////////////////////////////////////
VIEW HELPERS
//////////////////////////////////////////////////////////////*/
function arenaInfo() external view returns (
uint256 round,
uint256 alive,
uint256 pool,
uint256 cashoutPool,
uint256 winnerPool,
uint256 nextRoundAt,
Stage currentStage
) {
// L-1 fix: use the correct interval for the current phase. Mainnet
// mass-phase is 8h, endgame (alive ≤ 4) is 24h; the UI was lying
// by ~16h during endgame before this.
// L-2 fix (audit pass-7 codex): if a round is in progress, use the
// pinned currentRoundInterval so this view matches the schedule
// _runRound is enforcing. Without this, the UI ETA could disagree
// with the actual round eligibility when cashouts push aliveCount
// into the endgame zone mid-round (only relevant for configs with
// different mass/endgame intervals; mainnet equal-interval is moot).
uint256 nextInterval = roundInProgress
? currentRoundInterval
: (aliveCount <= ENDGAME_TRIGGER ? ENDGAME_INTERVAL : ROUND_INTERVAL);
return (
currentRound,
aliveCount,
prizePool,
cashOutReserve,
winnerReserve,
lastRoundTimestamp + nextInterval,
stage
);
}
function getCashOutPayout() external view returns (uint256) {
return _cashOutPayoutForRound(currentRound);
}
/// @notice Frontend gate — true when the cashout window is open globally.
/// Returns false outside r3-r9, in endgame (alive ≤ 4), wrong stage, or
/// when the reserve has fully drained (payout would be 0). Does NOT
/// check per-token state — see `canCashOutToken` for that.
function canCashOut() public view returns (bool) {
if (stage != Stage.ARENA) return false;
if (currentRound < CASH_OUT_OPENS_ROUND) return false;
if (currentRound >= CASH_OUT_CLOSES_ROUND) return false;
if (aliveCount <= ENDGAME_TRIGGER) return false;
return _cashOutPayoutForRound(currentRound) > 0;
}
/// @notice Per-token frontend gate — true when `_holder` can cash out
/// `_tokenId` right now. M-2 fix (audit pass-4): the frontend was using
/// `canCashOut()` (global) and doing per-token checks itself; this view
/// folds both into a single RPC for clarity.
function canCashOutToken(uint256 _tokenId, address _holder) external view returns (bool) {
if (!canCashOut()) return false;
if (_ownerOf(_tokenId) != _holder) return false;
if (eliminationRound[_tokenId] != 0) return false;
if (cashedOut[_tokenId]) return false;
return true;
}
function myWarriors(address _owner) external view returns (uint256[] memory) {
uint256 bal = balanceOf(_owner);
uint256[] memory ids = new uint256[](bal);
for (uint256 i = 0; i < bal; i++) {
ids[i] = tokenOfOwnerByIndex(_owner, i);
}
return ids;
}
/*//////////////////////////////////////////////////////////////
OVERRIDES
//////////////////////////////////////////////////////////////*/
function _update(address to, uint256 tokenId, address auth)
internal override(ERC721, ERC721Enumerable) returns (address)
{
return super._update(to, tokenId, auth);
}
function _increaseBalance(address account, uint128 value)
internal override(ERC721, ERC721Enumerable)
{
super._increaseBalance(account, value);
}
function supportsInterface(bytes4 interfaceId)
public view override(ERC721, ERC721Enumerable, IERC165) returns (bool)
{
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
}
/*//////////////////////////////////////////////////////////////
LICENSE & ATTRIBUTION
//////////////////////////////////////////////////////////////*/
//
// PunkGames is released under the GNU General Public License v3.0
// (see the SPDX-License-Identifier at the top of this file).
//
// Originally derived from ChainFaces2 by @nftchance, also licensed
// under GPL-3.0. Game structure (round-based elimination, on-chain
// metadata, keeper-driven progression) preserved per the inherited
// license. PunkGames adds: burn-and-remint elimination → AfterGames
// secondary collection, fixed-multiplier cash-outs, top-3 placement
// payouts, future-blockhash randomness via lockRandomness(), chunked
// on-chain trait + anchor storage (SSTORE2), and ops/creator fee
// splits. All credit to @nftchance for the original ChainFaces2
// codebase that this work builds on.
//
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "./IERC721.sol";
import {IERC721Receiver} from "./IERC721Receiver.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
mapping(uint256 tokenId => address) private _owners;
mapping(address owner => uint256) private _balances;
mapping(uint256 tokenId => address) private _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual returns (uint256) {
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
* the `spender` for the specific `tokenId`.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
unchecked {
_balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
_balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
_balances[to] += 1;
}
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
_checkOnERC721Received(address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
_tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
* recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
revert ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
revert ERC721InvalidReceiver(to);
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {ERC721} from "../ERC721.sol";
import {IERC721Enumerable} from "./IERC721Enumerable.sol";
import {IERC165} from "../../../utils/introspection/ERC165.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability
* of all the token ids in the contract as well as all token ids owned by each account.
*
* CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,
* interfere with enumerability and should not be used together with `ERC721Enumerable`.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
mapping(address owner => mapping(uint256 index => uint256)) private _ownedTokens;
mapping(uint256 tokenId => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 tokenId => uint256) private _allTokensIndex;
/**
* @dev An `owner`'s token query was out of bounds for `index`.
*
* NOTE: The owner being `address(0)` indicates a global out of bounds index.
*/
error ERC721OutOfBoundsIndex(address owner, uint256 index);
/**
* @dev Batch mint is not allowed.
*/
error ERC721EnumerableForbiddenBatchMint();
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
if (index >= balanceOf(owner)) {
revert ERC721OutOfBoundsIndex(owner, index);
}
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
if (index >= totalSupply()) {
revert ERC721OutOfBoundsIndex(address(0), index);
}
return _allTokens[index];
}
/**
* @dev See {ERC721-_update}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {
address previousOwner = super._update(to, tokenId, auth);
if (previousOwner == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (previousOwner != to) {
_removeTokenFromOwnerEnumeration(previousOwner, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (previousOwner != to) {
_addTokenToOwnerEnumeration(to, tokenId);
}
return previousOwner;
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to) - 1;
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = balanceOf(from);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
*/
function _increaseBalance(address account, uint128 amount) internal virtual override {
if (amount > 0) {
revert ERC721EnumerableForbiddenBatchMint();
}
super._increaseBalance(account, amount);
}
}
lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
lib/openzeppelin-contracts/contracts/utils/Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.2) (utils/Base64.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to operate with Base64 strings.
*/
library Base64 {
/**
* @dev Base64 Encoding/Decoding Table
*/
string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/
function encode(bytes memory data) internal pure returns (string memory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/
if (data.length == 0) return "";
// Loads the table into memory
string memory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
// and split into 4 numbers of 6 bits.
// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
// - `data.length + 2` -> Round up
// - `/ 3` -> Number of 3-bytes chunks
// - `4 *` -> 4 characters for each chunk
string memory result = new string(4 * ((data.length + 2) / 3));
/// @solidity memory-safe-assembly
assembly {
// Prepare the lookup table (skip the first "length" byte)
let tablePtr := add(table, 1)
// Prepare result pointer, jump over length
let resultPtr := add(result, 0x20)
let dataPtr := data
let endPtr := add(data, mload(data))
// In some cases, the last iteration will read bytes after the end of the data. We cache the value, and
// set it to zero to make sure no dirty bytes are read in that section.
let afterPtr := add(endPtr, 0x20)
let afterCache := mload(afterPtr)
mstore(afterPtr, 0x00)
// Run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// To write each character, shift the 3 byte (24 bits) chunk
// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
// and apply logical AND with 0x3F to bitmask the least significant 6 bits.
// Use this as an index into the lookup table, mload an entire word
// so the desired character is in the least significant byte, and
// mstore8 this least significant byte into the result and continue.
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr := add(resultPtr, 1) // Advance
}
// Reset the value that was cached
mstore(afterPtr, afterCache)
// When data `bytes` is not exactly 3 bytes long
// it is padded with `=` characters at the end
switch mod(mload(data), 3)
case 1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case 2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
src/PunkGamesAfterGames.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./PunkGamesRenderer.sol";
/// @dev Minimal interface for reading placement state from the main PunkGames
/// contract without creating a circular import. Reads `placement` directly
/// (1=1st, 2=2nd, 3=3rd, 4=4th, 0=eliminated-or-cashed). winnerFlag was the
/// pass-7 codex L-1 finding — relying on it meant 4th-place tokens never
/// reached the renderer with placement=4.
interface IPunkGamesWinnerState {
function placement(uint256 tokenId) external view returns (uint8);
}
/**
* @title PunkGamesAfterGames
* @notice Secondary collection minted when a PunkGames warrior exits the game
* (either via elimination or voluntary cash-out). On-chain ERC721
* display name is "PunkGames: After Games" (symbol PGAG).
* @dev Only the PunkGames main contract can call mintEliminated() / mintCashOut().
* Token ID matches the original PunkGames token ID. Damage tier baked in at
* mint time corresponds to the round of elimination/cash-out.
*/
contract PunkGamesAfterGames is ERC721, Ownable, IERC2981 {
address public mainContract;
PunkGamesRenderer public renderer;
address public creator;
// Token state — tier matches the round they were eliminated in (1-5)
// or the cash-out round (1-3). 1st place never lives here — they keep
// their PunkGames clothed token. 2nd and 3rd place DO live here, with
// their crown drawn at render time by reading placement off the main
// contract.
mapping(uint256 => uint8) public damageTier;
mapping(uint256 => bool) public wasCashOut; // distinguishes voluntary exit
uint96 public constant ROYALTY_BPS = 500; // 5%
uint256 private _totalSupply;
/// @notice Once true, setRenderer() reverts. Owner calls lockRenderer()
/// after the art is finalized to remove the post-mint art-rug surface
/// flagged in the M-1 audit finding.
bool public rendererLocked;
error OnlyMainContract();
error MainContractAlreadySet();
error AlreadyMinted();
error RendererLocked();
event Minted(uint256 indexed tokenId, address indexed owner, uint8 tier, bool cashOut);
event RendererLockedEvent();
constructor(string memory _name, string memory _symbol, address _creator) ERC721(_name, _symbol) Ownable(msg.sender) {
creator = _creator;
}
/// @notice Wire the main game contract. Can only be done once.
function setMainContract(address _main) external onlyOwner {
if (mainContract != address(0)) revert MainContractAlreadySet();
mainContract = _main;
}
function setRenderer(address _renderer) external onlyOwner {
if (rendererLocked) revert RendererLocked();
renderer = PunkGamesRenderer(_renderer);
}
/// @notice Permanently disable setRenderer(). One-way switch — call this
/// after the art is final to remove the art-rug vector. The main game
/// contract's renderer is already immutable; this brings the After Games
/// renderer to the same trust posture.
function lockRenderer() external onlyOwner {
rendererLocked = true;
emit RendererLockedEvent();
}
/// @notice Called by PunkGames when a warrior is eliminated.
/// @param _to The wallet receiving the After Games punk
/// @param _tokenId Token ID matches the burned PunkGames token
/// @param _tier Damage tier based on round of elimination (1-5)
function mintEliminated(address _to, uint256 _tokenId, uint8 _tier) external {
if (msg.sender != mainContract) revert OnlyMainContract();
if (_ownerOf(_tokenId) != address(0)) revert AlreadyMinted();
damageTier[_tokenId] = _tier;
_totalSupply++;
// H-1 fix: use _mint instead of _safeMint. The PunkGames eliminator
// selects victims by index, so a contract holder that reverts on
// onERC721Received with _safeMint would DoS the round (same victim
// re-picked forever). _mint skips the receiver hook — safe here
// because the holder consented to receive afterlife tokens by playing.
_mint(_to, _tokenId);
emit Minted(_tokenId, _to, _tier, false);
}
/// @notice Called by PunkGames when a warrior cashes out voluntarily.
/// @dev Future expansion hook — currently cash-outs keep their clothed punk.
/// Included so the architecture supports a future season variant.
function mintCashOut(address _to, uint256 _tokenId, uint8 _tier) external {
if (msg.sender != mainContract) revert OnlyMainContract();
if (_ownerOf(_tokenId) != address(0)) revert AlreadyMinted();
damageTier[_tokenId] = _tier;
wasCashOut[_tokenId] = true;
_totalSupply++;
// H-1 fix: see mintEliminated above. Same DoS surface, same fix.
_mint(_to, _tokenId);
emit Minted(_tokenId, _to, _tier, true);
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function tokenURI(uint256 _id) public view override returns (string memory) {
_requireOwned(_id);
// L-1 fix (audit pass-7 codex): read `placement` unconditionally so
// 4th-place (placement=4) tokens reach the renderer with the right
// placement value. Previously gated on winnerFlag, which is only true
// for 1st/2nd/3rd — so 4th-place rendering branches were unreachable.
uint8 _placement = 0;
if (mainContract != address(0)) {
_placement = IPunkGamesWinnerState(mainContract).placement(_id);
}
return renderer.afterGamesTokenURI(_id, damageTier[_id], wasCashOut[_id], _placement);
}
function royaltyInfo(uint256, uint256 _salePrice) external view override
returns (address, uint256)
{
return (creator, (_salePrice * ROYALTY_BPS) / 10000);
}
function supportsInterface(bytes4 interfaceId)
public view override(ERC721, IERC165) returns (bool)
{
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
}
src/PunkGamesRenderer.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./PunkTraits.sol";
/**
* @title PunkGamesRenderer
* @notice Builds tokenURI metadata for both the clothed (in-game / 1st-place
* winner) collection and the After Games (PGAG) collection.
* @dev The `image` field of every NFT is a direct PNG URL — no SVG wrapper,
* no embedded data: URI, no in-contract overlay drawing. This guarantees
* the artwork renders correctly on OpenSea, wallets, Etherscan, and any
* other ERC-721 viewer (which sandbox SVG data: URIs and block their
* external references).
*
* Image URL is chosen by token state:
* placement 1 (1st place) → {clothedPrefix}winners/1st/{id}.webp
* placement 2 (2nd place) → {cashedPrefix}winners/2nd/{id}.webp
* placement 3 (3rd place) → {cashedPrefix}winners/3rd/{id}.webp
* cashed-out → {cashedPrefix}{id}.webp
* normal elimination → {bodyBagPrefix}{id}.webp
* alive (mid-game) / default → {clothedPrefix}{id}.webp
*
* Crowns are baked into the winner PNGs off-chain (one script run after
* the game finishes, uploads 3 composite PNGs to Arweave at the
* `winners/{place}/{id}.webp` paths). Game state — round eliminated,
* placement, cause — is exposed as JSON attributes for OpenSea filtering.
*
* OG CryptoPunks traits come from the PunkTraits contract. Slot 0 emits
* as `Type: Male/Female/Alien/Ape/Zombie` (collapsed from the 8 variants
* to match Larva Labs' convention); slots 1-7 emit as `Accessory: {name}`.
*/
contract PunkGamesRenderer is Ownable {
using Strings for uint256;
PunkTraits public immutable traits;
// Base URL prefixes (trailing slash required). Final URL is built per
// token state — see `_buildImageUrl()`.
string public clothedImagePrefix; // alive / 1st place winner art base
string public bodyBagImagePrefix; // mass-phase eliminations + 4th place
string public cashedImagePrefix; // voluntary cashouts + 2nd/3rd place
// Per-winner image URL override. Set ONCE per winning tokenId by the
// owner OR the registered delegate after the game ends, pointing at the
// off-chain composited image with the appropriate crown burned in. Once
// set, this overrides the path-based URL in `_buildImageUrl`.
// Single-write design — see `setWinnerImage` for the invariant.
mapping(uint256 => string) public winnerImage;
// Optional hot-key delegate authorized to call `setWinnerImage` without
// the owner (Ledger) needing to sign each of the 3 post-game winner
// pins. Set by owner. Bounded: delegate can ONLY call setWinnerImage,
// never any other admin function. Single-write invariant still applies —
// delegate cannot overwrite a winner image already set by the owner.
address public winnerImageDelegate;
event WinnerImageSet(uint256 indexed tokenId, string url);
event WinnerImageDelegateChanged(address indexed previous, address indexed current);
constructor(
address _traits,
string memory _clothedPrefix,
string memory _bodyBagPrefix,
string memory _cashedPrefix
) Ownable(msg.sender) {
traits = PunkTraits(_traits);
clothedImagePrefix = _clothedPrefix;
bodyBagImagePrefix = _bodyBagPrefix;
cashedImagePrefix = _cashedPrefix;
}
/*//////////////////////////////////////////////////////////////
WINNER IMAGE URL OVERRIDE
//////////////////////////////////////////////////////////////*/
/// @notice Set the canonical image URL for a single winning tokenId.
/// @dev Once set, cannot be changed. Callable by owner OR the registered
/// `winnerImageDelegate` (typically a hot bot key used by the
/// post-game crown uploader so the owner Ledger doesn't have to
/// sign each of the 3 finisher pins manually). Trust assumption:
/// the caller uploads a properly composited image (base punk + crown
/// + winner suit for 1st) to permanent storage and points this entry
/// at it. Audit note: this is a centralization point — the caller
/// picks what art shows for the 3 winners. Bounded by:
/// 1. Single-write (can't re-rug post-set, not even by owner)
/// 2. Only meaningful for tokenIds whose game-side `placement`
/// is 1, 2, or 3 (the renderer doesn't enforce this — the
/// off-chain uploader is responsible for only calling with
/// valid winner ids).
/// 3. Delegate's authority is bounded to THIS function only;
/// cannot change other admin state or rotate ownership.
function setWinnerImage(uint256 _tokenId, string calldata _url) external {
require(msg.sender == owner() || msg.sender == winnerImageDelegate, "not authorized");
require(bytes(_url).length > 0, "empty url");
require(bytes(winnerImage[_tokenId]).length == 0, "already set");
winnerImage[_tokenId] = _url;
emit WinnerImageSet(_tokenId, _url);
}
/// @notice Set or clear the hot-key delegate authorized to call
/// `setWinnerImage`. Pass address(0) to revoke.
/// @dev Owner-only. Used so the crown-uploader bot can pin per-finisher
/// image CIDs on-chain without the deployer Ledger signing each one.
/// Delegate authority is narrow: only `setWinnerImage`, nothing else.
function setWinnerImageDelegate(address _delegate) external onlyOwner {
address previous = winnerImageDelegate;
winnerImageDelegate = _delegate;
emit WinnerImageDelegateChanged(previous, _delegate);
}
/*//////////////////////////////////////////////////////////////
CLOTHED PUNK URI
//////////////////////////////////////////////////////////////*/
/// @notice Renders the clothed PunkGames collection. Used by:
/// - Alive punks during the game (placement=0, no crown)
/// - The 1st place winner who never gets burned (placement=1, gold crown
/// baked into the off-chain composite at winners/1st/{id}.webp)
function tokenURI(uint256 _id, uint8 _round, bool _winner, bool _cashedOut)
external view returns (string memory)
{
uint8 placement = _winner ? 1 : 0;
// Main-collection caller: not-an-AfterGames token. Default route is
// clothed art (alive in-game).
string memory imgUrl = _buildImageUrl(_id, placement, _cashedOut, false);
string memory attrs = _clothedAttributes(_id, _round, _winner, _cashedOut);
return _buildMetadata(
string.concat("PunkGames #", _id.toString()),
"An on-chain survival game. 10,000 enter, the strong wear the crown.",
imgUrl,
attrs
);
}
/*//////////////////////////////////////////////////////////////
AFTER GAMES TOKEN URI
//////////////////////////////////////////////////////////////*/
/// @notice Renders metadata for After Games (PGAG) tokens. Four outcomes:
/// - Cashed out (placement=0, _wasCashOut=true) → cashed art, no crown
/// - 2nd place (placement=2) → silver-crowned art
/// - 3rd place (placement=3) → bronze-crowned art
/// - Eliminated (placement=0 or 4, _wasCashOut=false) → body bag art
/// 1st place never lands here — they keep their PunkGames token.
function afterGamesTokenURI(
uint256 _id,
uint8 _tier,
bool _wasCashOut,
uint8 _placement
) external view returns (string memory) {
// L-1 fix (audit pass-7 codex): pass _isAfterGames=true so the
// (placement=0, !wasCashOut) default routes to body-bag art, not
// clothed. Previously eliminated AfterGames tokens rendered with
// the live in-game art because both callers passed identical args.
string memory imgUrl = _buildImageUrl(_id, _placement, _wasCashOut, true);
string memory attrs = _afterGamesAttributes(_id, _tier, _wasCashOut, _placement);
string memory title;
string memory desc;
if (_placement == 2) {
title = string.concat("PGAG #", _id.toString(), " (2nd Place)");
desc = "Crowned 2nd. Silver medal, locked in before the final cut.";
} else if (_placement == 3) {
title = string.concat("PGAG #", _id.toString(), " (3rd Place)");
desc = "Crowned 3rd. Bronze medal, the first off the podium.";
} else if (_wasCashOut) {
title = string.concat("PGAG #", _id.toString(), " (Cashed Out)");
desc = "Walked away with the bag. A keepsake of the warrior who knew when to leave.";
} else {
title = string.concat("PGAG #", _id.toString());
desc = "Stripped. Eliminated. A souvenir of defeat.";
}
return _buildMetadata(title, desc, imgUrl, attrs);
}
/*//////////////////////////////////////////////////////////////
IMAGE URL BUILDER
//////////////////////////////////////////////////////////////*/
/// @dev Builds the final `image` URL for a token based on its state.
/// Winners get a placement-suffixed path so the off-chain crown
/// compositing script can upload the crowned PNG to a predictable
/// location (e.g. {cashedPrefix}winners/2nd/{id}.webp).
/// @param _isAfterGames true when called from the AfterGames collection's
/// tokenURI. Disambiguates the (placement=0, !wasCashOut) default
/// between "alive in main collection" (clothed) and "eliminated in
/// AfterGames" (body-bag). L-1 fix from pass-7 audit (codex).
function _buildImageUrl(uint256 _id, uint8 _placement, bool _wasCashOut, bool _isAfterGames)
internal view returns (string memory)
{
string memory idStr = _id.toString();
// Winner override path: if the owner set a specific URL for this winner
// (Arweave permanent link, etc.), use it. Falls back to predictable
// path-based URL if not set yet (e.g. seconds after game-end before
// the off-chain uploader runs).
if (_placement >= 1 && _placement <= 3) {
string memory override_ = winnerImage[_id];
if (bytes(override_).length > 0) return override_;
}
if (_placement == 1) {
return string.concat(clothedImagePrefix, "winners/1st/", idStr, ".webp");
}
if (_placement == 2) {
return string.concat(cashedImagePrefix, "winners/2nd/", idStr, ".webp");
}
if (_placement == 3) {
return string.concat(cashedImagePrefix, "winners/3rd/", idStr, ".webp");
}
if (_wasCashOut) {
return string.concat(cashedImagePrefix, idStr, ".webp");
}
if (_placement == 4) {
// Endgame elimination short of the podium — no crown, body-bag art.
return string.concat(bodyBagImagePrefix, idStr, ".webp");
}
// AfterGames eliminated (placement=0, !wasCashOut, _isAfterGames=true):
// body-bag art. The PunkGames-side tokenURI never reaches this branch
// because eliminated PunkGames tokens are burned, so its (placement=0,
// !wasCashOut, _isAfterGames=false) call means "alive in-game" → clothed.
if (_isAfterGames) {
return string.concat(bodyBagImagePrefix, idStr, ".webp");
}
return string.concat(clothedImagePrefix, idStr, ".webp");
}
/*//////////////////////////////////////////////////////////////
ATTRIBUTES
//////////////////////////////////////////////////////////////*/
function _clothedAttributes(uint256 _id, uint8 _round, bool _winner, bool _cashedOut)
internal view returns (string memory)
{
string memory status;
string memory crown;
if (_winner) {
status = "Champion";
crown = "Gold";
} else if (_cashedOut) {
status = "Cashed Out";
crown = "None";
} else {
status = "Active";
crown = "None";
}
string memory gameStateAttrs = string.concat(
'{"trait_type":"Status","value":"', status, '"},',
'{"trait_type":"Round Reached","value":', uint256(_round).toString(), '},',
'{"trait_type":"Crown","value":"', crown, '"}'
);
return _appendOgTraits(gameStateAttrs, _id);
}
function _afterGamesAttributes(uint256 _id, uint8 _tier, bool _wasCashOut, uint8 _placement)
internal view returns (string memory)
{
string memory status;
string memory crown;
if (_placement == 2) { status = "2nd Place"; crown = "Silver"; }
else if (_placement == 3) { status = "3rd Place"; crown = "Bronze"; }
else if (_placement == 4) { status = "4th Place"; crown = "None"; }
else if (_wasCashOut) { status = "Cashed Out"; crown = "None"; }
else { status = "Eliminated"; crown = "None"; }
string memory gameStateAttrs = string.concat(
'{"trait_type":"Status","value":"', status, '"},',
'{"trait_type":"Rank Tier","value":', uint256(_tier).toString(), '},',
'{"trait_type":"Cause","value":"', _wasCashOut ? "Cash Out" : "Eliminated", '"},',
'{"trait_type":"Crown","value":"', crown, '"}'
);
return _appendOgTraits(gameStateAttrs, _id);
}
/// @dev Wraps the game-state attribute list (no brackets, no surrounding [])
/// and the OG CryptoPunks traits into a single JSON array string.
function _appendOgTraits(string memory _gameAttrs, uint256 _id)
internal view returns (string memory)
{
// Read 8-slot trait IDs for this punk (0xFF = empty).
uint8[8] memory ids = traits.traitIds(_id);
string memory ogAttrs = "";
for (uint256 i = 0; i < 8; i++) {
if (ids[i] == 0xFF) continue;
// Slot 0 is the punk type — match the OG CryptoPunks convention of
// showing just "Male" / "Female" / "Alien" / "Ape" / "Zombie" instead
// of the variant suffix ("Male 3", "Female 1", etc.). Slots 1-7 are
// accessories and use the full trait name.
string memory traitType;
string memory value;
if (i == 0) {
traitType = "Type";
value = _punkType(ids[i]);
} else {
traitType = "Accessory";
value = traits.traitName(ids[i]);
}
ogAttrs = string.concat(
ogAttrs,
',{"trait_type":"', traitType, '","value":"', value, '"}'
);
}
return string.concat('[', _gameAttrs, ogAttrs, ']');
}
/// @dev Maps a slot-0 trait id to the canonical punk type per the OG
/// CryptoPunks convention. The 4 male variants (49-52) and 4 female
/// variants (30-33) collapse to "Male" / "Female"; aliens/apes/zombies
/// are single-variant. Falls back to the raw trait name if we ever see
/// an unexpected id in slot 0 (shouldn't happen with the bundled data).
function _punkType(uint8 _id) internal view returns (string memory) {
if (_id == 1) return "Alien";
if (_id == 2) return "Ape";
if (_id == 30 || _id == 31 || _id == 32 || _id == 33) return "Female";
if (_id == 49 || _id == 50 || _id == 51 || _id == 52) return "Male";
if (_id == 97) return "Zombie";
return traits.traitName(_id);
}
/*//////////////////////////////////////////////////////////////
METADATA WRAPPER
//////////////////////////////////////////////////////////////*/
function _buildMetadata(
string memory _name,
string memory _desc,
string memory _imageUrl,
string memory _attrs
) internal pure returns (string memory) {
string memory json = string.concat(
'{"name":"', _name, '",',
'"description":"', _desc, '",',
'"image":"', _imageUrl, '",',
'"attributes":', _attrs, '}'
);
return string.concat("data:application/json;base64,", Base64.encode(bytes(json)));
}
}
src/PunkTraits.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.20;
/**
* @title PunkTraits
* @notice Stores the OG CryptoPunks trait list per token, fully on-chain.
* @dev Trait IDs (0-97) → names via traitName(). Per-token trait IDs stored
* as packed bytes via SSTORE2 (deployed as the runtime bytecode of two
* data sub-contracts, split at token 5000 to stay under the EIP-7825
* per-tx gas cap).
*
* Layout per token (8 bytes, offset = (tokenId mod 5000) * 8):
* 8 trait ID slots, each one byte. 0xFF marks an empty slot.
* Slot 0 typically contains the punk's gender/type (Male 1, Female 2, Alien,
* Ape, Zombie). Remaining slots are accessories/features in insertion order
* as published by the CryptoPunks community.
*/
contract PunkTraits {
/// @notice Sub-contract for tokens 0..2499
address public immutable dataContractA;
/// @notice Sub-contract for tokens 2500..4999
address public immutable dataContractB;
/// @notice Sub-contract for tokens 5000..7499
address public immutable dataContractC;
/// @notice Sub-contract for tokens 7500..9999
address public immutable dataContractD;
uint256 public constant SLOTS_PER_PUNK = 8;
uint256 public constant CHUNK_SIZE = 2500; // tokens per data chunk
uint256 public constant CHUNK_BYTES = CHUNK_SIZE * SLOTS_PER_PUNK; // 20,000 bytes — under EIP-170 cap
uint256 public constant TOTAL_PUNKS = 10_000;
uint8 public constant EMPTY_SLOT = 0xFF;
error InvalidTokenId();
error InvalidTraitId();
/// @dev EIP-170 limits a single contract's runtime bytecode to 24,576
/// bytes. The full trait dataset is 80,000 bytes (10k punks × 8 slots),
/// split here across FOUR pre-deployed PunkTraitsData sub-contracts of
/// 20,000 bytes each (2500 punks per chunk). Each sub-deploy is its own
/// transaction in the deploy script, well under EIP-170 AND EIP-7825.
constructor(address _a, address _b, address _c, address _d) {
require(_a != address(0) && _b != address(0), "zero A or B");
require(_c != address(0) && _d != address(0), "zero C or D");
require(_a.code.length == CHUNK_BYTES, "bad A code length");
require(_b.code.length == CHUNK_BYTES, "bad B code length");
require(_c.code.length == CHUNK_BYTES, "bad C code length");
require(_d.code.length == CHUNK_BYTES, "bad D code length");
dataContractA = _a;
dataContractB = _b;
dataContractC = _c;
dataContractD = _d;
}
/*//////////////////////////////////////////////////////////////
READERS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the 8 trait ID slots for a token. 0xFF = empty.
/// @dev Caller can iterate, ignoring slots == 0xFF.
function traitIds(uint256 _tokenId) external view returns (uint8[8] memory ids) {
if (_tokenId >= TOTAL_PUNKS) revert InvalidTokenId();
bytes memory chunk = _readTokenBytes(_tokenId);
for (uint256 i = 0; i < SLOTS_PER_PUNK; i++) {
ids[i] = uint8(chunk[i]);
}
}
/// @notice Returns the count of non-empty trait slots for a token.
function traitCount(uint256 _tokenId) external view returns (uint256 count) {
if (_tokenId >= TOTAL_PUNKS) revert InvalidTokenId();
bytes memory chunk = _readTokenBytes(_tokenId);
for (uint256 i = 0; i < SLOTS_PER_PUNK; i++) {
if (uint8(chunk[i]) != EMPTY_SLOT) count++;
}
}
/// @notice Returns the OG CryptoPunks trait name for an ID (0-97).
/// @dev Names follow the official CryptoPunks attribute set published by Larva Labs.
function traitName(uint8 _id) public pure returns (string memory) {
if (_id == 0) return "3D Glasses";
if (_id == 1) return "Alien";
if (_id == 2) return "Ape";
if (_id == 3) return "Bandana";
if (_id == 4) return "Beanie";
if (_id == 5) return "Big Beard";
if (_id == 6) return "Big Shades";
if (_id == 7) return "Black Lipstick";
if (_id == 8) return "Blonde Bob";
if (_id == 9) return "Blonde Short";
if (_id == 10) return "Blue Eye Shadow";
if (_id == 11) return "Buck Teeth";
if (_id == 12) return "Cap";
if (_id == 13) return "Cap Forward";
if (_id == 14) return "Chinstrap";
if (_id == 15) return "Choker";
if (_id == 16) return "Cigarette";
if (_id == 17) return "Classic Shades";
if (_id == 18) return "Clown Eyes Blue";
if (_id == 19) return "Clown Eyes Green";
if (_id == 20) return "Clown Hair Green";
if (_id == 21) return "Clown Nose";
if (_id == 22) return "Cowboy Hat";
if (_id == 23) return "Crazy Hair";
if (_id == 24) return "Dark Hair";
if (_id == 25) return "Do-rag";
if (_id == 26) return "Earring";
if (_id == 27) return "Eye Mask";
if (_id == 28) return "Eye Patch";
if (_id == 29) return "Fedora";
if (_id == 30) return "Female 1";
if (_id == 31) return "Female 2";
if (_id == 32) return "Female 3";
if (_id == 33) return "Female 4";
if (_id == 34) return "Front Beard";
if (_id == 35) return "Front Beard Dark";
if (_id == 36) return "Frown";
if (_id == 37) return "Frumpy Hair";
if (_id == 38) return "Goat";
if (_id == 39) return "Gold Chain";
if (_id == 40) return "Green Eye Shadow";
if (_id == 41) return "Half Shaved";
if (_id == 42) return "Handlebars";
if (_id == 43) return "Headband";
if (_id == 44) return "Hoodie";
if (_id == 45) return "Horned Rim Glasses";
if (_id == 46) return "Hot Lipstick";
if (_id == 47) return "Knitted Cap";
if (_id == 48) return "Luxurious Beard";
if (_id == 49) return "Male 1";
if (_id == 50) return "Male 2";
if (_id == 51) return "Male 3";
if (_id == 52) return "Male 4";
if (_id == 53) return "Medical Mask";
if (_id == 54) return "Messy Hair";
if (_id == 55) return "Mohawk";
if (_id == 56) return "Mohawk Dark";
if (_id == 57) return "Mohawk Thin";
if (_id == 58) return "Mole";
if (_id == 59) return "Mustache";
if (_id == 60) return "Muttonchops";
if (_id == 61) return "Nerd Glasses";
if (_id == 62) return "Normal Beard";
if (_id == 63) return "Normal Beard Black";
if (_id == 64) return "Orange Side";
if (_id == 65) return "Peak Spike";
if (_id == 66) return "Pigtails";
if (_id == 67) return "Pilot Helmet";
if (_id == 68) return "Pink With Hat";
if (_id == 69) return "Pipe";
if (_id == 70) return "Police Cap";
if (_id == 71) return "Purple Eye Shadow";
if (_id == 72) return "Purple Hair";
if (_id == 73) return "Purple Lipstick";
if (_id == 74) return "Red Mohawk";
if (_id == 75) return "Regular Shades";
if (_id == 76) return "Rosy Cheeks";
if (_id == 77) return "Shadow Beard";
if (_id == 78) return "Shaved Head";
if (_id == 79) return "Silver Chain";
if (_id == 80) return "Small Shades";
if (_id == 81) return "Smile";
if (_id == 82) return "Spots";
if (_id == 83) return "Straight Hair";
if (_id == 84) return "Straight Hair Blonde";
if (_id == 85) return "Straight Hair Dark";
if (_id == 86) return "Stringy Hair";
if (_id == 87) return "Tassle Hat";
if (_id == 88) return "Tiara";
if (_id == 89) return "Top Hat";
if (_id == 90) return "VR";
if (_id == 91) return "Vampire Hair";
if (_id == 92) return "Vape";
if (_id == 93) return "Welding Goggles";
if (_id == 94) return "Wild Blonde";
if (_id == 95) return "Wild Hair";
if (_id == 96) return "Wild White Hair";
if (_id == 97) return "Zombie";
return "";
}
/*//////////////////////////////////////////////////////////////
INTERNAL
//////////////////////////////////////////////////////////////*/
function _readTokenBytes(uint256 _tokenId) internal view returns (bytes memory chunk) {
// Route to one of four sub-contracts based on token id quarter.
address src;
uint256 localId;
if (_tokenId < CHUNK_SIZE) {
src = dataContractA;
localId = _tokenId;
} else if (_tokenId < CHUNK_SIZE * 2) {
src = dataContractB;
localId = _tokenId - CHUNK_SIZE;
} else if (_tokenId < CHUNK_SIZE * 3) {
src = dataContractC;
localId = _tokenId - CHUNK_SIZE * 2;
} else {
src = dataContractD;
localId = _tokenId - CHUNK_SIZE * 3;
}
uint256 offset = localId * SLOTS_PER_PUNK;
chunk = new bytes(SLOTS_PER_PUNK);
uint256 len = SLOTS_PER_PUNK;
assembly {
extcodecopy(src, add(chunk, 0x20), offset, len)
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.