Skip to content
Tech Interview Prep
Technical interview guide

Token Standards (ERC-20, ERC-721, ERC-1155)

The interface standards that let wallets, exchanges, and other contracts interact with any token the same way: fungible, non-fungible, and multi-token.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: ERC-20, ERC-165, ERC-721, ERC-1155, ERC-2612, ERC-2981, and ERC-4906 specifications; OpenZeppelin Contracts 5.x documentation reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

How do ERC-20, ERC-721, and ERC-1155 differ in their storage layout, gas efficiency during batch transfers, and representation of semi-fungible tokens?

Answer

ERC-20, ERC-721, and ERC-1155 organize EVM storage differently, which directly shapes their transaction overhead and suitability for multi-item interactions.

1. Storage Layout and State Representation

  • ERC-20 (Single Fungible Asset): Tracks scalar balances and operator allowances for a single implicit asset.

    SOLIDITY
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;

    Every asset instance requires a separate contract deployment, adding runtime context-switching and storage lookup costs across distinct contracts.

  • ERC-721 (Non-Fungible Tokens): Tracks discrete token IDs to exclusive owners and addresses per-token approval alongside global operator status.

    SOLIDITY
    mapping(uint256 => address) private _owners;             // tokenId => owner
    mapping(address => uint256) private _balances;           // owner => count
    mapping(uint256 => address) private _tokenApprovals;     // tokenId => approved operator
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    Tracking individual token ownership forces $O(N)$ storage writes on multi-token transfers and clears individual approvals on transfer.

  • ERC-1155 (Multi-Token Standard): Nests asset identity (id) within balance mappings, managing fungible, non-fungible, and semi-fungible balances under one contract.

    SOLIDITY
    mapping(uint256 => mapping(address => uint256)) private _balances; // id => account => balance
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    Approvals are purely operator-based (setApprovalForAll), eliminating per-token approval storage slots.

2. Gas Efficiency in Batch Operations

Transferring $N$ distinct items demonstrates significant divergence:

DimensionERC-20 (Multi-Asset)ERC-721ERC-1155
Transaction Boundaries$N$ external calls to $N$ contracts1 contract, $N$ internal loops or distinct external calls1 native batch call (safeBatchTransferFrom)
Call Overhead$N \times 2,600$ cold account access1 cold call + internal loops1 cold call + calldata decoding
Approval Checks$N$ allowance storage reads/updates$N$ token or operator checks1 single operator check upfront
Receiver Hook ExecutionOptional (ERC-1363) or none$N$ calls to onERC721Received1 single call to onERC1155BatchReceived
Log Emissions$N$ distinct Transfer events across contracts$N$ Transfer events1 TransferBatch event emitting array parameters

For a transfer of 5 distinct items to a contract receiver:

  • ERC-721: Requires 5 balance decrements, 5 balance increments, 5 owner updates, and 5 separate external calls to onERC721Received (costing at least 2,600 gas per cold address call plus execution).
  • ERC-1155: Requires 1 operator check, 5 balance slot updates, 1 TransferBatch log, and exactly 1 external call to onERC1155BatchReceived.

3. Semi-Fungible Token Representation

A semi-fungible token (SFT) behaves like a fungible batch during initial lifecycle stages (e.g., general-admission tickets with supply > 1) and can transition into a non-fungible item upon consumption (e.g., redeemed stub with distinct seat assignment).

  • ERC-20: Cannot represent discrete SFT states within one contract; it lacks per-item IDs.
  • ERC-721: Cannot natively model fungibility. Modeling 50 identical concert tickets forces minting 50 unique token IDs, consuming 50 _owners storage slots.
  • ERC-1155: Native SFT implementation. An id can hold a supply of $K$ units (_balances[id][user] = 50). When redeemed, a protocol burns units from the fungible id and mints a specific non-fungible id (where total supply is enforced as 1, often encoded with split bit-fields in the uint256 id: e.g., upper 128 bits for collection/type, lower 128 bits for unique sequence).

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Handle an ERC-20 allowance change safely.

Answer

What I'd say first

Assume an EVM chain, an owner EOA, a spender contract you don't fully trust, and that you submit your own transactions. The rule: never move a non-zero allowance to a different non-zero value in one approve. Either zero it first and confirm inclusion, or use a mechanism that carries a deadline and a nonce.

Why the overwrite is unsafe

approve(address spender, uint256 amount) writes allowed[owner][spender] = amount. Going from 100 to 50 is two transactions, and the mempool is public. The spender watches for your second approve, submits transferFrom(owner, spender, 100) with a higher priority fee, it lands first, then your approve(50) lands, and the spender spends 50 more. You authorized 150, not 50.

Worked trace (USDC, 6 decimals, owner holds 1000 USDC)

  • State: allowance(owner, spender) = 100e6.
  • Owner broadcasts approve(spender, 50e6).
  • Spender sees it and broadcasts transferFrom(owner, spender, 100e6) with a higher tip.
  • Spender's tx mines first: allowance → 0, spender holds 100.
  • Owner's tx mines: allowance → 50e6.
  • Spender calls transferFrom(owner, spender, 50e6): allowance → 0, spender holds 150.

Zero-first: approve(spender, 0), confirm inclusion, then approve(spender, 50e6). Worst case the spender front-runs the zero tx and takes the 100 they already had: never more.

Options

approachwhat it giveswhen it's wrong
zero-first approveworks on every ERC-20two txs, two gas payments, UX friction
increaseAllowance / decreaseAllowanceatomic delta, no overwriteremoved in OpenZeppelin v5; not in the ERC-20 standard, so not universal
EIP-2612 permit(owner, spender, value, deadline, v, r, s)one signed tx, per-owner nonce, deadlinetoken must implement it; DAI's permit is not EIP-2612 (bool allowed, expiry); it is still an overwrite, so zero-first still applies to a non-zero prior allowance
Permit2 approve(token, spender, uint160 amount, uint48 expiration)per-token allowance with expiry, lockdown to revoke allextra contract dependency; the allowance lives in Permit2, not the token

Failure modes and how to catch them

  • USDT-style approve reverts on non-zero → non-zero. Detect by eth_call simulation before sending, or use OpenZeppelin SafeERC20.forceApprove (v4.9+), which zeroes first.
  • The zero tx reverts (out of gas, token paused) and you send the replacement anyway: the old allowance is still live and the replacement is an overwrite. Detect by confirming the zero tx's receipt status before sending the second.
  • Unlimited prior approval (type(uint256).max) left on a compromised spender: full drain. Detect by scanning Approval events for max values and revoking.
  • Wrong spender: compare the checksummed address, not a truncated one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Minimize approval risk in a dApp.

Answer

Assumptions: an EVM chain, ERC-20-style tokens, and a dApp contract that needs to move user funds with transferFrom. Everything below is about bounding that authority.

The 90-second answer

Three decisions, in order.

Scope. Approve the exact amount the flow needs, not type(uint256).max. If the flow repeats, don't re-approve every time: use ERC-2612 permit or Permit2 so each spend carries its own signed amount and expiry.

Spender. Verify the address is the contract you think it is: checksummed, confirmed on a block explorer, and if it's a proxy, know who can upgrade it. An upgradeable spender is an unlimited approval with a delayed fuse.

Lifecycle. Show the user their existing allowance before asking for a new one, and revoke when the flow is done.

Why that works

approve(spender, amount) writes allowance[owner][spender]. transferFrom(from, to, amount) requires allowance[from][msg.sender] >= amount, then decrements it: except when the allowance is type(uint256).max, where OpenZeppelin's ERC20._spendAllowance skips the decrement. So an unlimited approval is a standing grant that never shrinks: the spender can drain the balance at any block until it is revoked, and the user's only signal is the Approval event.

Trade-off

Unlimited approval saves one approve transaction per later interaction: a first approve that writes zero to non-zero costs about 46k gas, a re-approve roughly half that: plus one signature. Exact-amount approval costs a transaction per use and adds UX friction. Deciding criteria: one-off or unverified spender → exact amount; repeated interaction with a protocol you have verified → Permit2 with an expiration; max only if the token balance is small and you will revoke.

Failure modes and how you catch them

Allowance race. Owner holds allowance 100 to a spender, then signs approve(spender, 50). The spender sees it in the mempool and submits transferFrom(owner, attacker, 100) at a higher gas price. It lands first: allowance 100 → 0, attacker gets 100. The owner's approve then lands: allowance 0 → 50. The spender takes 50 more. Total 150 against an intended 50. Detect it as two Approval events with a Transfer between them in the same block range; fix it by approving 0, waiting for confirmation, then approving 50, or by using permit nonces, which make the second spend invalid.

Malicious or upgraded spender. A proxy can be upgraded to drain every outstanding allowance. Detect by reading the EIP-1967 implementation slot and watching the Upgraded event; check who holds the admin role before approving.

Stale unlimited approvals. Scan Approval events where value equals type(uint256).max and the spender still has code. revoke.cash and the Etherscan token-approval checker do this per address; revoking is a normal approve-to-zero transaction, which is why teams revoke selectively rather than after every interaction.

Phishing address. Address poisoning relies on you matching the first and last four characters. Compare the full checksummed address, or use an ENS name resolved on-chain.

Token quirks. USDT reverts on a non-zero → non-zero approve, so a re-approval must go through zero first. Fee-on-transfer tokens deliver less than the approved amount. Simulate the call (eth_call, Tenderly) before the user signs.

Misleading UI scope. The wallet renders "Approve" with no amount or spender. Read the calldata, not the label.

Choosing a mechanism

mechanismscopeexpiryrevocationwho pays gas
ERC-20 approveper (owner, spender)noneapprove(spender, 0)owner
ERC-2612 permitper (owner, spender), EIP-712 signeddeadlineapprove(0) or nonce bumpspender/relayer
Permit2 (0x000000000022D473030F116dDEE9F6B43aC78BA3)per (owner, token, spender)expiration timestampapprove(token, spender, 0, 0) or lockdownone max approve to Permit2, then signatures

If the interviewer pushes on "why not just revoke everything": revocation is a transaction per token per spender, and the user has to come back and sign it. Bounding scope up front is cheaper than cleaning up after.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Integrate ERC-2612 permit into a deposit transaction.

Answer

Assumptions I'd state up front: the token actually implements EIP-2612 (USDC does; USDT and WBTC do not), your deposit contract is the spender, and the user signs off-chain. If any of those is false, permit is the wrong tool and you fall back to approve + transferFrom or Uniswap's Permit2.

Core answer

Permit is a signed approval. The user signs an EIP-712 message authorising your deposit contract to spend value until deadline; you submit that signature in the same transaction as the deposit. The integration is three things: build the digest exactly as the token does, call permit then transferFrom in one transaction, and tolerate a front-run permit.

Mechanism

The token verifies the signature against a digest it reconstructs itself:

digest = keccak256(0x1901 ‖ DOMAIN_SEPARATOR ‖ keccak256(abi.encode(
    keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"),
    owner, spender, value, nonce, deadline)))

DOMAIN_SEPARATOR binds the signature to one chain and one contract:

keccak256(abi.encode(
    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
    keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this)))

name and version are per-token strings (USDC's FiatToken uses version "2"), so read DOMAIN_SEPARATOR() from the token rather than reconstructing it. The token then does require(owner == ecrecover(digest, v, r, s)), checks deadline >= block.timestamp, and increments nonces[owner]. That increment is what makes a signature single-use: replaying the same (v, r, s) fails because the nonce in the digest no longer matches.

Integration

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IERC20 {
    function allowance(address, address) external view returns (uint256);
    function transferFrom(address, address, uint256) external returns (bool);
}
interface IERC2612 is IERC20 {
    function permit(address owner, address spender, uint256 value,
                    uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
}

contract PermitDepositor {
    IERC2612 public immutable token;
    constructor(IERC2612 t) { token = t; }

    function depositWithPermit(uint256 amount, uint256 deadline,
                               uint8 v, bytes32 r, bytes32 s) external {
        // Skip permit if a front-runner already consumed it.
        if (token.allowance(msg.sender, address(this)) < amount) {
            token.permit(msg.sender, address(this), amount, deadline, v, r, s);
        }
        require(token.transferFrom(msg.sender, address(this), amount), "transfer failed");
        // credit the deposit here
    }
}

Trace

  1. User's nonce is 7; they sign value = 1_000e6, deadline = 1735689600 (2025-01-01T00:00:00Z).
  2. Attacker sees the signature in the mempool and submits it first. Token: nonce 7→8, allowance(user, depositor) = 1_000e6. Attacker gains nothing but pays gas.
  3. User's tx runs: allowance == amount, so permit is skipped, transferFrom pulls 1_000e6. Deposit succeeds.
  4. Without the guard, step 3 would call permit with nonce 7, the token would read nonce 8, ecrecover would not match, and the whole deposit reverts.

Trade-offs

  • Two transactions (approve, then deposit): simplest, works with every ERC-20, but costs the user two gas payments and an extra confirmation.
  • Multicall / aggregator (permit + deposit in one tx): one signature, one gas payment, atomic. A failed deposit rolls back the permit, so no dangling allowance. Requires a contract that can call both, and the front-run guard above.
  • Permit2: works for tokens without EIP-2612, at the cost of a separate allowance manager and its own signature domain.

Permit is not worth it when the token lacks EIP-2612, when the signer is a contract wallet (base EIP-2612 uses ecrecover, so a Safe cannot sign; some tokens add EIP-1271 support, USDC's FiatToken does), or when the user deposits repeatedly: one approve amortises better than a signature per deposit.

Failure modes and detection

  • Wrong domain: signature recovers to a different address, permit reverts invalid signature. Detect with a fork test asserting your signed digest equals the token's DOMAIN_SEPARATOR().
  • Expired deadline: revert expired deadline. Set deadline = now + 1800 and alert when a user's tx lands after it.
  • Nonce race: bundled tx reverts invalid nonce. Detect by logging every time the allowance guard skips permit.
  • Malicious spender / phishing: user signs for a spender they don't recognise. Show the spender address and exact value in the prompt; never request type(uint256).max.
  • Contract wallet: ecrecover returns address(0), revert. Check owner.code.length and route those users to approve.
  • Permit succeeds, deposit fails: only possible if the two are separate transactions, leaving a live allowance. Keeping them in one tx makes the revert atomic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Evaluate whether an advertised token is safe to integrate.

Answer

What a strong candidate says in the first two minutes. "Safe to integrate" is not one property: it depends on what you do with the token. Read-only display, custody and transfer, and collateral valuation have different bars. So I state which class I'm in, then verify three layers separately: interface conformance, actual bytecode behavior, and the economic/legal wrapper. Conformance is necessary and nowhere near sufficient: a contract can advertise ERC-20 and still break your accounting on the first transfer.

Why conformance lies. ERC-20 (EIP-20) says transfer returns bool. USDT does not return a value at all, so a caller that decodes a bool from empty returndata reverts or reads garbage. That is why OpenZeppelin's SafeERC20 exists: it tolerates missing return data. ERC-165 (EIP-165) supportsInterface is worse: it is a self-report. A contract returns true for any interfaceId you ask about, including ones it cannot implement, so it tells you what the token claims, not what it does. The only reliable check is to call the function and inspect the state delta.

The check that catches most of it: balance delta, not return value.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

function safePull(IERC20 token, address from, uint256 amount)
    internal returns (uint256 received)
{
    uint256 before = token.balanceOf(address(this));
    require(token.transferFrom(from, address(this), amount), "transfer failed");
    received = token.balanceOf(address(this)) - before;
    require(received == amount, "fee-on-transfer");
}

Trace it against a 1% fee-on-transfer token: before = 0, transferFrom(100) succeeds and returns true, balanceOf is now 99, so received = 99 and the second require reverts. A naive integration that credits amount would have booked 100 and been 1 short on every transfer. The same delta check exposes rebasing tokens (stETH, AMPL), whose balances move with no transfer at all.

Proxy upgrades defeat a one-time audit. If the token sits behind a proxy, the address you reviewed can be replaced. Read the EIP-1967 implementation slot, 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, and check the admin and any timelock. An upgradeable token with an EOA admin and no timelock is a different risk than an immutable one, even with identical code today.

Deciding criteria, when integration is justified.

Integration classBarStop if
Display / read-onlydecimals() (USDC 6, WBTC 8, DAI 18), symbol, namemetadata reverts or is unset
Custody / transferbalance-delta accounting, SafeERC20, pause/blacklist checkunbounded mint, blacklist, or pause you can't detect
Collateral / valuationoracle, liquidity depth, issuer solvency, legal claimno independent price source or redeemable claim

Failure modes and how you detect them. Fee-on-transfer: delta < amount, caught above. Rebasing: balanceOf drifts between blocks with no transfer event. Monitor it. Blacklist/pause (USDC, USDT): a transfer reverts for a specific address. Read the blacklist mapping or simulate with eth_call/Tenderly before shipping. Lying ERC-165: supportsInterface returns true but the call reverts. staticcall and check returndata length. Lookalike identity: symbol USDC on a different contract address. Pin the address, not the ticker. Centralized powers: owner can mint or freeze. Read the ABI and the admin address.

If you cannot bound the loss: unbounded mint, an upgradeable admin without a timelock, or no independent valuation: do not integrate directly. Wrap it behind an adapter that enforces the delta check and caps exposure, or decline. Tools that make this concrete: Slither for static checks, Foundry cast for slot reads, Etherscan's read/write tab, and a Tenderly simulation of the exact transfer path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Define which ERC-20 variants a protocol supports.

Answer

The policy in one line: support a token only if the protocol's accounting can be reconstructed from balanceOf deltas alone. Every unit credited must have actually arrived, and no transfer may fail for a reason the protocol cannot see coming. Everything else is wrapped or rejected.

Assumption: the protocol holds tokens as collateral or principal and mints internal shares against them. It is not a router that can tolerate arbitrary tokens.

Tier 1: supported as-is. Strict EIP-20: transfer/transferFrom return bool, no side effects beyond balances, balanceOf is honest, no transfer hooks, no fee, no rebase. USDC and DAI qualify on the transfer path. Both are upgradeable proxies, so the policy adds a governance clause: the issuer's upgrade key must be a timelock or multisig, and the protocol must be able to pause deposits if the token's semantics change under it.

Tier 2: supported behind an adapter.

  • Missing return value: USDT's transfer/transferFrom are declared with no return value, so a plain IERC20.transfer call reverts when Solidity tries to decode the empty return data. Use OpenZeppelin SafeERC20 (5.x), which tolerates empty returndata.
  • Fee-on-transfer: credit the measured delta, not the requested amount.
  • EIP-2612 permit: DAI and USDC support it. Treat it as a gas optimization, not a requirement.
  • Rebasing: stETH and AMPL change balanceOf without a transfer. Reject the rebasing form, accept the wrapped form (wstETH), whose balanceOf is stable.

Tier 3: rejected. ERC-777 (EIP-777) and EIP-1363 transferAndCall hooks hand control to the recipient mid-transfer; the April 2020 imBTC–Uniswap V1 reentrancy is the canonical drain. Blocklist and pause tokens (USDC's blacklist/pause, USDT's addBlackList) are acceptable only if the protocol's solvency does not depend on one specific address being able to move funds. Tokens that lie in balanceOf are rejected outright; no adapter fixes a dishonest oracle.

Worked trace: fee-on-transfer, 3% fee, deposit of 1000.

SOLIDITY
// Solidity 0.8.20, OpenZeppelin Contracts 5.x
using SafeERC20 for IERC20;

function deposit(uint256 amount) external returns (uint256 shares) {
    IERC20 t = IERC20(asset);
    uint256 before = t.balanceOf(address(this));
    t.safeTransferFrom(msg.sender, address(this), amount);
    uint256 received = t.balanceOf(address(this)) - before;   // 970
    shares = totalShares == 0 ? received : received * totalShares / totalAssets;
    totalAssets += received;                                   // credit 970, not 1000
}

Trace: before = 0; safeTransferFrom pulls 1000 from the sender, the token burns 30 as its fee, 970 lands; received = 970; the protocol credits 970. The naive version, safeTransferFrom(...); totalAssets += amount;, credits 1000 against 970 of backing, so 30 of shares are unbacked and the last withdrawer eats the shortfall. The same delta check catches a rebase on the way in, which is exactly why rebasing tokens are rejected rather than adapted: the delta is correct at deposit time and wrong an hour later.

How to detect each before listing. Call transfer on a fork and check returndatasize; compare balanceOf before and after a 1-unit self-transfer for fees; watch totalSupply for rebases; check the ERC-1820 registry for ERC-777 hooks; diff balanceOf against totalSupply accounting for lying tokens.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Normalize token and price units in a vault.

Answer

Core answer (first 90 seconds)

Assume a multi-asset vault: ERC-20 collateral with per-token decimals(), priced from an oracle. I'd normalize every amount to one internal 18-decimal fixed-point unit (a "wad"), convert exactly once at each boundary, and keep raw base units only where the token contract demands them.

Two decisions drive the design. First, normalize at ingest or at use. Second, which direction each conversion rounds.

Normalize at ingest: store balances as wad, so all accounting math is uniform. Cost: every deposit and withdraw pays a scaling multiply, and you must re-read decimals() if the token is upgradeable. Normalize at use: store raw base units and scale inside each formula. Cost: every formula carries a per-token exponent, and one missed scale is a silent 1e12 error. A vault with a few assets and many internal calculations wants ingest; a router that touches a token once is fine at use.

normalize at ingestnormalize at use
storagewad (1e18)raw base units
conversion sitesone per deposit/withdrawevery formula
failure modestale cached decimalsmissed scale factor
fitsvault accountingone-shot router

Scaling, with a trace

SOLIDITY
// Solidity 0.8.24, OpenZeppelin Math
uint256 constant WAD = 1e18;

function toWad(uint256 amount, uint8 dec) internal pure returns (uint256) {
    if (dec == 18) return amount;
    if (dec < 18) return Math.mulDiv(amount, 10 ** uint256(18 - dec), 1);
    return amount / 10 ** uint256(dec - 18); // truncates toward zero
}

Math.mulDiv keeps the 512-bit intermediate, so the scaling multiply cannot overflow even for a large balance.

Trace. USDC has 6 decimals: a deposit of 1_500_000 base units is 1.5 USDC. dec = 6, so mulDiv(1_500_000, 1e12, 1) = 1.5e18 wad. DAI has 18 decimals: a deposit of 1_500_000_000_000_000_000 returns unchanged, also 1.5e18 wad. The two are now comparable.

Price. A Chainlink ETH/USD feed returns 8 decimals: 3000_00000000 means $3000. Scale it with mulDiv(3000_00000000, 1e10, 1) = 3000e18. Collateral value is mulDiv(1.5e18, 3000e18, WAD) = 4500e18, i.e. $4500.

Rounding direction: shares minted on deposit round down, assets returned on withdraw round down, debt and liquidation thresholds round up. All three favor the vault.

Failure modes

  • Hardcoded 18 decimals. USDC is 6; scaling a 1.5 USDC deposit as if it were 18 decimals mints 1e12 times the correct shares. Caught by an invariant test: sum of shares times price equals vault assets.
  • Feed decimals mismatch. Chainlink USD feeds are typically 8 decimals; using the answer raw understates collateral by 1e10. Read feed.decimals() and scale, never assume.
  • Rounding toward the attacker. Rounding shares up on deposit lets someone mint value from repeated 1-unit deposits. Round down.
  • Truncation on 18-to-6. Converting wad back to USDC drops up to 1e12 base units; keep wad internally and truncate only at the final transfer.
  • Mutable decimals(). Upgradeable tokens can change it; cache at listing and re-verify, or read per call.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Wrap token movement in invariant-preserving accounting.

Answer

Core answer (say this first). The invariant is: your internal ledger equals what the token contract actually holds, and no external call can observe a half-updated ledger. Three rules preserve it. (1) Never credit the requested amount: credit the measured balance delta. (2) Update your ledger before the outgoing transfer (checks-effects-interactions) and lock the incoming path, because the transfer is the interaction you must measure. (3) Route every call through OpenZeppelin SafeERC20 so non-returning and false-returning tokens behave. Assume the token is untrusted, may re-enter, may take a fee, and may not return a bool per EIP-20.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract Vault is ReentrancyGuard {
    using SafeERC20 for IERC20;
    IERC20 public immutable asset;
    mapping(address => uint256) public credit;
    uint256 public totalCredit;

    constructor(IERC20 a) { asset = a; }

    function deposit(uint256 amount) external nonReentrant {
        uint256 before = asset.balanceOf(address(this));
        asset.safeTransferFrom(msg.sender, address(this), amount);
        uint256 received = asset.balanceOf(address(this)) - before; // delta, not amount
        credit[msg.sender] += received;   // effect
        totalCredit += received;
    }

    function withdraw(uint256 amount) external nonReentrant {
        uint256 c = credit[msg.sender];
        require(c >= amount, "insufficient");
        credit[msg.sender] = c - amount;  // effect before interaction
        totalCredit -= amount;
        asset.safeTransfer(msg.sender, amount);
    }
}

Invariant: asset.balanceOf(address(this)) >= totalCredit. Deposit credits received, so it holds even for fee-on-transfer tokens; nonReentrant closes the ERC-777 tokensReceived hook, which fires during safeTransferFrom and would otherwise re-enter deposit before credit is written.

Trace: three real token behaviors.

  • USDT-style (no return value): a raw IERC20(usdt).transferFrom(...) reverts in Solidity 0.8 decoding empty returndata. SafeERC20 sees returndatasize() == 0 and treats it as success. Deposit of 1000 → received = 1000.
  • Returns false on failure: a raw call returns false; ignore it and you credit 1000 while nothing moved. SafeERC20 decodes the bool and reverts with SafeERC20FailedOperation. No credit.
  • 1% fee-on-transfer: you send 1000, the contract receives 990. Delta = 990, so credit += 990. Crediting the requested 1000 breaks the invariant by 10 per deposit and the last withdrawer cannot be paid.
Token behaviorNaive transferFromAccounting response
No return value (USDT)Reverts decoding empty returndataSafeERC20 treats empty returndata as success
Returns falseCall succeeds, bool ignored, ledger creditedSafeERC20 requires true, else reverts
Fee-on-transferLedger credited 1000, holds 990Credit the balance delta (990)
Rebasing (stETH)Balance moves with no transfer; delta misreadUse shares/ERC-4626 or the wrapped variant
ERC-777 hooktokensReceived re-enters before ledger writenonReentrant + CEI

Trade-offs and when the wrapper is the wrong tool. Allowlisting tokens and calling raw transfer is cheaper but brittle: a proxy upgrade or a new token breaks it silently. SafeERC20 + balance delta costs one extra balanceOf staticcall per transfer and is the default. It does not fix rebasing tokens: balanceOf is not a stable ledger there, so you need shares (ERC-4626) or wstETH; and it does not stop ERC-777 hook reentrancy, which is the guard's job. EIP-2612 permit improves UX (approve by signature, no separate tx) but changes nothing about accounting; a front-run permit reverts your tx (DoS), it does not steal funds. Detect the fee/rebase cases in review by diffing balanceOf before and after a test transfer, and by asserting the invariant after every state-changing path in a fuzz test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Secure mint and burn controls for a backed token.

Answer

Assume an ERC-20 on an EVM chain, Solidity 0.8.20, OpenZeppelin 5.x. "Backed" means every token is redeemable for a reserve asset, so the invariant is totalSupply() <= reserve held. Mint must check it; burn can only reduce supply, so it never breaks it.

Four controls, in the order an interviewer wants them:

  1. Role separation. MINTER_ROLE and BURNER_ROLE are distinct, and the minter is a contract or a 3-of-5 multi-sig that only mints after a deposit is confirmed: never an EOA hot key.
  2. Hard cap. ERC20Capped bounds supply even if the minter is fully compromised.
  3. Backing check at mint. Read the reserve balance and refuse to mint past it. The cap is not a substitute: a cap of 1e9 with 100 tokens of reserves still lets you mint 1e9 unbacked tokens.
  4. Atomic redeem. Burn and reserve payout in one transaction, so a user can never burn without receiving the reserve.
SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Capped} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";

contract BackedToken is ERC20Capped, AccessControl, Pausable {
    using SafeERC20 for IERC20;

    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    IERC20 public immutable reserve;
    uint256 public immutable reserveUnitsPerToken; // reserve base units per 1e18 tokens

    constructor(uint256 cap, IERC20 _reserve, uint256 _reserveUnitsPerToken)
        ERC20("Backed", "BKD")
        ERC20Capped(cap)
    {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
        reserve = _reserve;
        reserveUnitsPerToken = _reserveUnitsPerToken;
    }

    function backingCapacity() public view returns (uint256) {
        return reserve.balanceOf(address(this)) * 1e18 / reserveUnitsPerToken;
    }

    function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
        require(totalSupply() + amount <= backingCapacity(), "unbacked");
        _mint(to, amount);
    }

    function redeem(uint256 amount) external {
        _burn(msg.sender, amount);
        reserve.safeTransfer(msg.sender, amount * reserveUnitsPerToken / 1e18);
    }

    function burn(uint256 amount) external {
        _burn(msg.sender, amount);
    }

    function burnFrom(address from, uint256 amount) external onlyRole(BURNER_ROLE) {
        _spendAllowance(from, msg.sender, amount);
        _burn(from, amount);
    }

    function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
    function unpause() external onlyRole(PAUSER_ROLE) { _unpause(); }

    function _update(address from, address to, uint256 value) internal override {
        if (to != address(0)) _requireNotPaused(); // block transfers and mints, allow burns
        super._update(from, to, value);
    }
}

The _update override is the part people get wrong. It pauses transfers and mints but lets to == address(0) through, so burns and redemptions keep working during an incident. A blanket whenNotPaused on _update freezes redemption, which is exactly when holders want out.

Trace. Cap 1e9 tokens (1e27 wei). Reserve is USDC (6 decimals), reserveUnitsPerToken = 1e6. The contract holds 500e6 USDC = 5e14 base units, so backingCapacity() = 5e14 * 1e18 / 1e6 = 5e26 wei = 500e6 tokens.

  1. Alice (MINTER_ROLE) calls mint(Alice, 1e26) (100e6 tokens). Check: 0 + 1e26 <= 5e26 passes. totalSupply = 1e26; emits Transfer(0x0, Alice, 1e26).
  2. Bob (MINTER_ROLE) calls mint(Bob, 4.5e26) (450e6 tokens). Check: 1e26 + 4.5e26 = 5.5e26 > 5e26 → reverts "unbacked". Supply unchanged. The invariant binds here, not the cap.
  3. Alice transfers 50e6 tokens to Carol; totalSupply stays 1e26.
  4. Carol calls redeem(5e25). _burn drops totalSupply to 5e25 and emits Transfer(Carol, 0x0, 5e25). Then safeTransfer(Carol, 5e25 * 1e6 / 1e18 = 5e13) sends 50e6 USDC. Contract reserve falls to 4.5e14; backingCapacity() is now 4.5e26 against a supply of 5e25.

Alternatives. A single onlyOwner key is simplest and has the worst blast radius. An on-chain vault that is the sole minter, mint only when the vault receives a deposit, is the most trustless, but the reserve must live on the same chain and the vault becomes the critical contract. A threshold attestation (e.g. 3-of-5 signers) covers reserves that can't be on-chain (T-bills, bank deposits) at the cost of trusting the attestors and a freshness window. Cross-chain: lock-and-mint on the source chain, burn-and-mint on the destination, with a per-message nonce and one canonical chain so a replayed message can't mint twice.

Failure modes and how you catch them.

  • Compromised minter. Detect via a monitor on Transfer(0x0, ...) alerting on mints above a per-epoch threshold or from an unexpected address; add a per-block mint rate limit in the contract. Mitigate with the multi-sig and pause.
  • Reserve shortfall or stale attestation. backingCapacity() < totalSupply(). Poll the view every block and alert on the first block it goes negative; for off-chain reserves, require an attestation with an expiry and revert on stale.
  • Forced-burn abuse. burnFrom lets BURNER_ROLE burn any holder's tokens: a seizure power. If that isn't intended, delete it; if it is, put it behind its own role and a timelock and emit an event.
  • Decimals mismatch. A wrong reserveUnitsPerToken silently misprices backing: treating 6-decimal USDC as 18-decimal mints 1e12× too many tokens. Catch it with a fork test asserting backingCapacity() equals the reserve balance expressed in token units.
  • Reentrancy on redeem. _burn runs before safeTransfer, so CEI holds for a plain ERC-20, but a hook-bearing reserve (ERC-777) can reenter redeem. Restrict reserve to a known token or add nonReentrant.
  • Pause semantics. Test that redeem succeeds while paused and mint/transfer revert; the override is easy to invert.
ApproachMint controlBurn controlBacking checkTrade-off
Single owneronlyOwneronlyOwneroff-chainsimplest, single point of failure
Role-based (above)MINTER_ROLEBURNER_ROLE + public burn/redeemon-chain reservemore setup, limits blast radius
On-chain vaultvault is sole mintervaulton-chain, atomic with depositmost trustless, reserve must be same-chain
Multi-sig + attestation3-of-53-of-5off-chain, threshold sigslower, covers off-chain reserves

The invariant is the one thing you cannot skip: the moment totalSupply exceeds reserves, the token is broken and no cap or role saves it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Review privileged powers in a token before listing.

Answer

Core answer

Assume an EVM chain, an ERC-20-compatible token, possibly behind a proxy, and "listing" means my venue lets users trade it. The question that decides the listing is: what is the worst thing the most privileged key can do, and how long does it take? Four powers matter: change supply, change transferability, change logic, change balances. A token whose upgrade authority is a single EOA with no delay does not get listed, however clean the ABI looks. A proxy behind a 3-of-5 Safe with a 48-hour timelock is listable with a cap.

Read the proxy slots first

Most "immutable" tokens are proxies. EIP-1967 fixes the storage slots, so you can read them without the ABI:

Shell
IMPL=$(cast storage $TOKEN 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
ADMIN=$(cast storage $TOKEN 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103)
IMPL_ADDR=0x${IMPL: -40}; ADMIN_ADDR=0x${ADMIN: -40}
cast code $ADMIN_ADDR | wc -c   # 3 == "0x" == EOA, not a contract

If ADMIN_ADDR is an EOA, one key can swap the implementation and add a mint function. That is the finding that ends the review. If it is a contract, call getThreshold() and getOwners() on it (Safe) and check whether a TimelockController sits in front.

Then pull the ABI and grep for the powers:

Shell
cast interface $TOKEN | grep -iE 'function (mint|burn|pause|freeze|blacklist|upgrade|setName|setSymbol)'

Privilege → detection → decision

PowerWorst caseDetectDecision
Uncapped mintDilute holders to zeromint in ABI, no cap()Don't list, or cap pool exposure
UpgradeReplace logic, add mintEIP-1967 impl slot; admin is EOABlock if EOA or delay < 24h
Freeze/blacklistStrand one holder's balanceblacklist/freeze selector, per-addressList if per-address and enumerable
PauseHalt all transferspause() with no timelock or no unpause pathList only with a venue-side exit
Mutable name/symbolChange what the token claims to besetName/setSymbol settersBlock if mutable

Failure modes and how they show up

  • Hidden admin: the proxy admin is an EOA that never appears in the ABI. Detect by reading the admin slot; code size 0 means a key. Watch for Upgraded(address) events (defined by EIP-1967): an impl-slot change with no timelock is the alarm.
  • Compromised key: the admin is a hot wallet. Check whether the admin address is a Safe (getThreshold()) and whether its threshold is 1.
  • Unbounded mint: simulate mint(attacker, 1e30) from a non-privileged address. If it does not revert, supply is unbounded.
  • Selective freeze: check whether the blacklist is enumerable and whether freeze is per-address or global. A global freeze is a liveness risk; a per-address one is a compliance tool.
  • Role escalation: monitor RoleGranted for DEFAULT_ADMIN_ROLE (0x00…00). A new admin can grant itself everything else.
  • Indefinite pause: if the same role can pause and never unpause, the token can be frozen forever.

Trade-offs and when not to list

Permissioned standards, ERC-3643 (T-REX) and ERC-1400, put an identity registry and a compliance module in front of every transfer. The issuer can block a transfer for a compliance reason. That is correct for a regulated security and a blocker for a permissionless venue, which cannot whitelist counterparties. USDC is the counter-example: it has pauser, blacklister and masterMinter roles behind an upgradeable proxy, and it lists everywhere because the roles are disclosed and the issuer is a known regulated entity. USDT's owner can addBlackList and destroyBlackFunds: same reasoning.

Do not list when: upgrade authority is a single EOA with no timelock; mint is uncapped with no vesting; freeze can target arbitrary addresses without disclosure. Otherwise list with a cap sized to what a mint-and-dump could drain, if the quote-side pool holds $2M, that is the venue's worst case, so cap it at a fraction of daily volume or require the issuer to hold the minted supply.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Release an upgrade to a widely integrated token.

Answer

First question back: does the token address stay the same? That decides the whole plan.

  • Same address → proxy upgrade. Every integration, allowance and indexer keeps working, but you now own the storage layout and ABI of live state forever.
  • New address → migration. You must move balances and re-establish approvals, and every integrator must re-point.

For a widely integrated token, default to the proxy upgrade behind a timelock, and migrate only when the storage layout or ABI must change in a way you cannot shim.

Why the address matters mechanically

An upgradeable token is a proxy that delegatecalls into an implementation. delegatecall runs the implementation's code against the proxy's storage, so address(this) is the proxy and every SLOAD/SSTORE hits the proxy's slots. ERC-1967 standardises where the implementation and admin addresses live so they cannot collide with your own variables:

  • implementation: 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
  • admin: 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103

(each is keccak256(label) - 1). The code is swapped but the slots are not, so an unchanged address executes new logic over existing balances and approvals, which is exactly the risk.

Storage layout is the thing you cannot get wrong

Solidity assigns slots in declaration order. Appending new variables is safe; inserting, reordering or retyping an existing one is not.

versiondeclaration orderslotseffect of upgrade
v1mapping(address=>uint256) balanceOf; uint256 totalSupply;0, 1—
v2 safe... totalSupply; mapping(address=>bool) frozen;0, 1, 2new slot only; old reads intact
v2 brokenbool paused; mapping(address=>uint256) balanceOf; uint256 totalSupply;0, 1, 2paused reads slot 0 (normally 0); totalSupply moves to slot 2 and reads 0: integrations see zero supply

OpenZeppelin's upgradeable base contracts reserve uint256[50] private __gap; at the end so a new base variable consumes gap instead of shifting children. Run the layout check before every deploy: the OpenZeppelin Hardhat plugin (@openzeppelin/hardhat-upgrades) does it on upgradeProxy, or diff forge inspect MyToken storage-layout against the deployed layout.

Test on a fork, not in isolation

forge test --fork-url $RPC --fork-block-number <N> against mainnet state, then replay the top integrators: DEX pairs, lending markets, bridges. Two things bite:

  • Approvals do not migrate. A new address means every approve is gone; integrations that pull via transferFrom revert until users re-approve. Keep the address and allowances survive, but any change to transfer/transferFrom return semantics (returning false instead of reverting, or the reverse) breaks callers that check the bool. USDT on mainnet returns no value at all; SafeERC20 exists for that reason.
  • EIP-2612 permit signatures are bound to chainId and verifyingContract in the EIP-712 domain separator. A new address invalidates every outstanding signature.

Failure modes and how you see them

failuredetection
storage collisionlayout diff in CI; fork test asserting balanceOf(whale) is unchanged
double supplyafter migration, assert old.totalSupply() == 0 and new.totalSupply() == snapshot
fee-on-transfer breaks AMMsfork test: Uniswap V2 pair swap reverts when received ≠ sent
new hook reentrancyadd an ERC-777-style tokensReceived only behind a reentrancy guard; fuzz the callback path
admin key takeoverassert the admin slot holds the timelock, not an EOA; TimelockController min delay ≥ 48h
indexer/UI breakagea new address is new history on Etherscan and The Graph; announce before deploy

Trade-offs

Proxy upgrade: no user action, no integrator re-pointing, but you inherit permanent storage-layout discipline and a live admin key. Migration: clean slate, new layout and ABI, but you pay a claim window, unclaimed-balance handling and every integrator's migration. Diamond (EIP-2535) sits between: modular facets, but more moving parts than a widely integrated token usually justifies.

Do not upgrade without a timelock and a published diff. The recovery path is the timelock itself: a queued upgrade can be cancelled before it executes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Operate a reliable token deposit service.

Answer

Assume EVM chains, ERC-20 tokens, and we control deposit addresses. The service must detect deposits, wait for finality, credit idempotently, and reconcile. The core trade-off is latency vs safety: a user wants credit in seconds, but the chain can reorg. Deciding criteria: deposit amount, chain finality guarantees, and cost of reversal. For a $50 deposit on Polygon, 128 confirmations (~4.5 min at 2.1s blocks) is fine. For a $500k deposit on Ethereum, wait for Casper FFG finality (typically ~2 epochs, ~12.8 min).

Mechanism: derive unique deposit events from (chain_id, block_hash, tx_hash, log_index). Why block_hash? A reorg replaces blocks; the same tx_hash can appear in a different block. log_index is unique within a block. This key is the idempotency key. Poll multiple RPCs, take the head that agrees, rewind on reorg. Finality: Ethereum has probabilistic finality at 12 confirmations (~2.4 min) and deterministic finality once a block is finalized by Casper FFG (typically ~2 epochs, ~12.8 min, but not a fixed block count). Polygon PoS uses 128 confirmations (~4.5 min) as a common default.

Code snippet (Python-like pseudocode):

Python
def process_deposit(chain_id, block_hash, tx_hash, log_index, token, to, amount):
    key = (chain_id, block_hash, tx_hash, log_index)
    row = db.get(key)
    if row is None:
        if not is_canonical(chain_id, block_hash):
            return
        if token != expected_token:
            alert("wrong token")
            return
        if amount != expected_amount:
            alert("fee/rebase mismatch")
            return
        db.insert(key, status='detected')
        row = db.get(key)
    if row.status == 'credited':
        return
    if not is_canonical(chain_id, block_hash):
        db.update(key, status='reorged')
        return
    if confirmations(chain_id, block_hash) >= policy(amount):
        credit(to, amount)
        db.update(key, status='credited')

Trace: a deposit of 100 USDC at block 1000, log_index 3. First call: row is None, is_canonical true, token matches, amount matches, insert status='detected'. confirmations(1000) = 0, so no credit. Second call after 12 confirmations: row exists, status='detected', is_canonical true, confirmations >= policy, credit, update to 'credited'. Third call: row exists, status='credited', return. If a reorg replaces block 1000 with 1000', the old key's block_hash is no longer canonical. On next call for old key: row exists, status='detected', is_canonical false, update to 'reorged', return. The new event at block 1000' has a different key, so it's processed as new. If the same event appears twice from two providers, the key is identical, so the second call sees row exists and status='detected' or 'credited', and handles accordingly.

Table: confirmation policies.

ChainBlock timeConfirmationsLatencySafety
Ethereum12s12~2.4 minProbabilistic
Ethereum12s2 epochs (~64 slots)~12.8 min (typical)Deterministic (Casper FFG, not fixed block count)
Polygon PoS2.1s128~4.5 minProbabilistic
Large depositanyfinalizedchain-specificDeterministic

Failure modes:

  • Failed receipt: tx reverted. Detect: receipt.status == 0. Cost: gas wasted. Handle: ignore, log.
  • Reorg: block replaced. Detect: block_hash not canonical. Cost: double credit. Handle: key includes block_hash, rewind, mark reorged.
  • Duplicate logs: same event from multiple providers. Detect: duplicate key. Cost: double credit. Handle: idempotent insert.
  • Wrong token: event from different contract. Detect: token address mismatch. Cost: credit wrong asset. Handle: validate, alert.
  • Fee/rebase mismatch: amount received != sent. Detect: compare transfer amount. Cost: under/over credit. Handle: use actual received, alert.
  • Proxy event change: upgrade changes event signature. Detect: ABI mismatch, missing events. Cost: missed deposits. Handle: monitor upgrades, update ABI, backfill.
  • Provider disagreement: two RPCs give different heads. Detect: compare block hashes. Cost: inconsistent state. Handle: majority, wait for agreement.
  • Premature external credit: credit before finality. Detect: credit before policy threshold. Cost: reorg reversal. Handle: enforce policy, alert.

Reconciliation: every 5 min, compare on-chain balance of deposit address vs sum of credited deposits. Alert on mismatch > 0.01%. Run a reorg watcher that rewinds 100 blocks on any block_hash change.

Operational: monitor RPC latency, head lag, credit latency p99. Runbooks for reorg, provider outage, token upgrade.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How does safeTransferFrom protect against stuck tokens in ERC-721, and what reentrancy vectors does it introduce via onERC721Received?

Answer

safeTransferFrom prevents tokens from becoming permanently locked inside recipient smart contracts that lack the code to manage or transfer ERC-721 assets. When to is a contract address, it invokes IERC721Receiver(to).onERC721Received(...) and verifies that the return value matches the explicit 4-byte selector 0x150b7a02 (bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))). If the call reverts, runs out of gas, returns an incorrect selector, or transfers to a non-receiver contract, the entire transaction reverts.

However, because this call yields execution flow to arbitrary code in to before or after state mutations, it introduces classic and cross-function reentrancy vectors.

Execution Flow and Receiver Check

Under OpenZeppelin Contracts v5.x, _safeTransfer performs the standard transfer logic before invoking _checkOnERC721Received:

SOLIDITY
// Solady / OpenZeppelin v5 pattern
function _checkOnERC721Received(
    address from,
    address to,
    uint256 tokenId,
    bytes memory data
) private {
    if (to.code.length > 0) {
        try IERC721Receiver(to).onERC721Received(msg.sender, 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 {
                assembly { revert(add(32, reason), mload(reason)) }
            }
        }
    }
}

Notice that if to.code.length == 0 at execution time (an EOA or a contract during construction), the check passes without executing a callback.

Reentrancy Vectors

  1. Minting Reentrancy (Max Mint / Cap Bypasses): A mint function using _safeMint that updates global or user mint counters after the mint call allows the recipient to re-enter mint() repeatedly within onERC721Received, exceeding per-wallet limits or maximum supply caps.
  2. Cross-Function Marketplace State Desynchronization: If an NFT marketplace executes safeTransferFrom to deliver an NFT to a buyer before clearing internal escrow, order listings, or payout states, the buyer's malicious contract can re-enter cancelListing(), buy() on another item, or trigger an unfinalized settlement, extracting duplicate funds or assets.
  3. Double-Spend via Intermediate Transfer: If internal ownership mapping (_owners[tokenId]) is updated but intermediate balance or approval structures in a parent protocol are uncommitted, re-entering can allow transferring the token twice or draining protocol-level allowances.

Sequence Trace: Vulnerable Safe Mint vs. Reentrancy

Attacker                       NFTContract (Vulnerable)
   |                                    |
   |--- mint(1) ----------------------->| [checks: minted[attacker] < 2 -> ok]
   |                                    | [_safeMint -> updates _owners[id]]
   |                                    | [calls receiver callback]
   |<-- onERC721Received(tokenId=1) ---|
   |
   |--- (Reentrancy) mint(1) ---------->| [checks: minted[attacker] is STILL 0]
   |                                    | [_safeMint -> updates _owners[id+1]]
   |                                    | [calls receiver callback]
   |<-- onERC721Received(tokenId=2) ---|
   |    (returns 0x150b7a02)            |
   |----------------------------------->| [minted[attacker] = 1]
   |    (returns 0x150b7a02)            |
   |----------------------------------->| [minted[attacker] = 1 (overwritten/desynced)]

Defenses

  • Checks-Effects-Interactions (CEI): Increment tracking variables, clear approvals, and update protocol balances before executing safeTransferFrom or _safeMint.
  • ReentrancyGuard: Guard entry points touching state across the protocol with non-reentrant locks (mutex).
  • Post-Transfer Verification: Treat any external callback as untrusted code execution equivalent to sending raw ether via .call{value: ...}("").

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Implement a secure ERC-721 receiver.

Answer

What I'd say in the first two minutes

"Secure receiver" means a contract that can be handed NFTs by safeTransferFrom without losing them, without letting a stranger make it spend gas, and without the transfer itself becoming a reentrancy entry point. Assumptions: Solidity 0.8.24, OpenZeppelin Contracts v5 as the counterparty ERC-721, one curator address allowed to move tokens out.

The whole interface is one hook:

SOLIDITY
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
    external returns (bytes4);

Its ERC-165 identifier, and the only value you may return, is 0x150b7a02, i.e. bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). OZ v5's _checkOnERC721Received calls the hook and reverts with ERC721InvalidReceiver(to) if the return value differs; it does not consult supportsInterface. Return true, or the interface id, or nothing, and the sender's safeTransferFrom reverts and the token never moves.

The receiver

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

interface IERC721 {
    function transferFrom(address from, address to, uint256 tokenId) external;
}

contract NftVault {
    bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;

    address public immutable curator;
    mapping(address => bool) public collectionAllowed;
    mapping(address => bool) public operatorAllowed;
    mapping(bytes32 => bool) public held; // keccak256(collection, tokenId)

    error NotAllowed();
    error NotCurator();
    error NotHeld();

    constructor(address curator_) { curator = curator_; }

    function allowCollection(address c, bool ok) external { _onlyCurator(); collectionAllowed[c] = ok; }
    function allowOperator(address o, bool ok) external { _onlyCurator(); operatorAllowed[o] = ok; }

    function onERC721Received(address operator, address, uint256 tokenId, bytes calldata)
        external returns (bytes4)
    {
        if (!collectionAllowed[msg.sender] || !operatorAllowed[operator]) revert NotAllowed();
        held[keccak256(abi.encode(msg.sender, tokenId))] = true; // effect, before any call out
        return ERC721_RECEIVED;
    }

    function withdraw(address collection, uint256 tokenId, address to) external {
        _onlyCurator();
        bytes32 key = keccak256(abi.encode(collection, tokenId));
        if (!held[key]) revert NotHeld();
        held[key] = false;                                              // effect
        IERC721(collection).transferFrom(address(this), to, tokenId);   // interaction
    }

    function _onlyCurator() internal view { if (msg.sender != curator) revert NotCurator(); }
}

withdraw uses transferFrom, not safeTransferFrom, so the exit path never re-enters a contract recipient's hook. OZ updates ownership before calling the hook, so inside onERC721Received you can assert ownerOf(tokenId) == address(this) if you need proof the token really arrived.

Trade-offs

Allowlist per collection versus accept-anything: the allowlist costs one cold SLOAD (~2,100 gas) per receipt and a governance step per new collection, but it stops a stranger from making your vault the destination of a million airdrops. Recording every deposit is the expensive half: a fresh held[key] = true is ~22,100 gas (20,000 for the zero→non-zero slot plus 2,100 cold access), paid by you, not the sender. If you enumerate deposits in an array for a UI, that array is attacker-growable; cap it or drop it and index events off-chain. Reverting on an unknown collection breaks composability, a marketplace's safeTransferFrom reverts the whole trade, so the usual middle ground is: accept silently, don't record, and expose a curator-only rescue.

Failure modes and how I'd catch them

failuremechanismdetection
reentrancyhook or withdraw calls out before writing state; a malicious recipient re-enters with the same tokenId and double-countswrite held first; test with a receiver that re-enters withdraw
spoofed callbackany contract can call onERC721Received directly; the callback is not proof of ownershipassert ownerOf(tokenId) == address(this); a spoofed entry only makes withdraw revert
unsolicited NFTattacker pushes tokens you never asked for; recording each one grows storage at your expensecap recorded deposits; alert on held count
gas griefingan unbounded loop in the hook makes the sender's safeTransferFrom run out of gaskeep the hook O(1); gas snapshot test
wrong selectorreturning true or the interface id makes the sender revertunit test asserting the exact 4 bytes
no recoveryno withdraw path leaves tokens stuck foreverinvariant: every held entry is withdrawable by the curator

If pushed further: the operator allowlist is the part most teams drop, and it is the one that decides whether an approved marketplace can push into your vault at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Walk me through what a schema-compliant ERC-721 tokenURI JSON document looks like: which fields are actually required, how the attributes array must be shaped, and what breaks in marketplaces when a field is missing or mistyped?

Answer

The surprise first: EIP-721's metadata schema has no required array. It declares exactly three properties (name, description, image) and a literal {} validates against it. So "schema-compliant" in the standard's sense is a very low bar. What actually decides whether your token renders is the marketplace convention layered on top: OpenSea's metadata standard, which Blur, Reservoir and most indexers follow.

The schema as written in EIP-721:

{ "title": "Asset Metadata", "type": "object", "properties": { "name": { "type": "string", "description": "Identifies the asset" }, "description": { "type": "string", "description": "Describes the asset" }, "image": { "type": "string", "description": "A URI pointing to a resource with mime type image/*" } } }

image is the only one carrying a constraint beyond type: a URI whose resource has an image/* mime type, recommended 320–1080 px wide, aspect ratio between 1.91:1 and 4:5. Everything else (attributes, external_url, animation_url, background_color, youtube_url) is outside EIP-721 entirely.

Treat name and image as required in practice.

fieldEIP-721what breaks when missing or mistyped
nameproperty, not requiredindexers fall back to Collection #<id>; some drop the token from search
descriptionproperty, not requiredcosmetic; empty panel on the item page
imageproperty, not required; must resolve to image/*no thumbnail, placeholder tile, excluded from grid views and rarity ranking
attributesnot in the standardtrait filters and rarity counts silently omit the token
external_url, animation_url, background_colornot in the standardOpenSea-only extras; background_color is 6 hex chars with no leading #

attributes is the field people get wrong most often. It must be a JSON array of objects, each with a string trait_type and a value that is a string or number:

{ "name": "Sword #12", "description": "Forged in block 19000000.", "image": "ipfs://bafy.../12.png", "attributes": [ { "trait_type": "Rarity", "value": "Legendary" }, { "trait_type": "Attack", "value": 47, "display_type": "number", "max_value": 100 }, { "trait_type": "Minted", "value": 1699999999, "display_type": "date" } ] }

Failure modes I've actually seen:

  • attributes as an object map ({"Rarity": "Legendary"}) instead of an array. The whole trait set is dropped; the token has no filters and contributes nothing to rarity.
  • value as the string "47" alongside display_type: "number". Range filters and rarity math treat it as non-numeric; some indexers coerce, others skip the trait.
  • Duplicate trait_type within one token. Last-wins in some indexers, double-counted in others, which corrupts collection-wide rarity.
  • image as a bare CID (bafy... instead of ipfs://bafy...). No scheme, no gateway resolution, broken image.
  • image pointing at an HTML page or another JSON file. Mime mismatch; marketplaces refuse to render.
  • Trailing commas or NaN in the JSON. JSON.parse throws, the item stays unindexed, and there is no on-chain error to alert on.

Detection is off-chain: fetch tokenURI(id), JSON.parse it, validate against a schema that does declare required: ["name", "image"] and attributes as an array, then diff the parsed traits against what your indexer stored. That is a CI check, not a runtime one.

Two adjacent points worth stating. EIP-721 says tokenURI throws for an invalid tokenId; returning "" for burned tokens makes marketplaces cache a blank item. And if metadata is mutable, emitting ERC-4906 MetadataUpdate(tokenId) is what tells indexers to re-fetch: the schema shape itself cannot change without a re-index. ERC-1155 differs: uri(id) is a single template with a {id} placeholder substituted as 64 lowercase hex characters, no 0x, and decimals must be 0 for non-fungible ids.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do you implement dynamic, fully on-chain NFT metadata in Solidity, and how does it compare to off-chain storage like IPFS?

Answer

Assume ERC-721, OpenZeppelin 5.x, Solidity 0.8.20 or later, and art that is vector or text: SVG, not a 4K PNG. Under those assumptions the answer is: don't store the metadata, compute it. tokenURI reads contract storage at call time, builds the JSON in memory, base64-encodes it, and returns a data:application/json;base64,... URI. Nothing is written per token except the state the art depends on: a level, a cooldown, a seed.

The reason this works is that tokenURI is a view function over mutable storage. When a transaction changes level[tokenId], the next call to tokenURI produces different bytes with no extra bookkeeping. The one thing you must add is a signal: indexers cache tokenURI output aggressively, so any state change that alters the payload has to emit ERC-4906's MetadataUpdate(tokenId). Miss that and OpenSea keeps showing the old image indefinitely.

Here is the whole thing:

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

interface IERC4906 {
    event MetadataUpdate(uint256 _tokenId);
}

contract DynamicOnChainNFT is ERC721, IERC4906 {
    using Strings for uint256;

    mapping(uint256 => uint256) public level;

    constructor() ERC721("DynamicSVG", "DSVG") {}

    function levelUp(uint256 tokenId) external {
        require(_ownerOf(tokenId) == msg.sender, "Not owner");
        level[tokenId] += 1;
        emit MetadataUpdate(tokenId); // ERC-4906 standard update signal
    }

    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireOwned(tokenId);

        string memory lvlStr = level[tokenId].toString();
        string memory svg = string(
            abi.encodePacked(
                '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">',
                '<rect width="100%" height="100%" fill="#1e1e2e"/>',
                '<text x="50%" y="50%" fill="#cdd6f4" dominant-baseline="middle" text-anchor="middle">',
                'Level: ', lvlStr,
                '</text></svg>'
            )
        );

        string memory imageUri = string(
            abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(bytes(svg)))
        );

        bytes memory json = abi.encodePacked(
            '{"name":"Token #', tokenId.toString(), '",',
            '"description":"Dynamic On-Chain NFT",',
            '"attributes":[{"trait_type":"Level","value":', lvlStr, '}],',
            '"image":"', imageUri, '"}'
        );

        return string(abi.encodePacked("data:application/json;base64,", Base64.encode(json)));
    }
}

Walk through what that returns for token 1 at level 0. The SVG literal is 215 bytes; base64 expands by 4/3, so the encoded payload is 288 bytes, plus the 26-byte data:image/svg+xml;base64, prefix: 314 bytes for the image field. The JSON around it, name plus description plus one attribute plus that image field, is 428 bytes, which base64-encodes to 572, plus the 29-byte JSON prefix. So tokenURI(1) returns about 601 bytes. Call levelUp(1) and the same call returns the same length with "value":1 and Level: 1 inside. No upload, no pinning, no CID.

Against IPFS: IPFS gives you content addressing, so the CID is a hash of the bytes and the file cannot change. Mutability means updating a pointer in the contract, which is a transaction and a cache invalidation anyway. Permanence depends on someone pinning; if nobody does, the gateway 404s. On-chain metadata is as available as the chain is, readable from an archive node with no third party. The cost runs the other way: on-chain you pay for bytecode once at deploy and for the state that drives the art, while IPFS costs you a URI string in storage (two 32-byte slots, roughly 20,000 gas each on a fresh mint) and nothing else. On-chain you are also capped by EIP-170's 24,576-byte deployed bytecode limit and by what you can generate inside a view call. Raster images, video and 3D models do not fit; IPFS and Arweave take arbitrary sizes.

Three things bite in production. First, tokenURI runs under the RPC node's eth_call gas cap (geth's default is 50,000,000) and its timeout. A 600-byte payload is nowhere near it; a generative SVG that loops over hundreds of traits can blow it, and then every marketplace shows a broken token while the contract itself is fine. Second, JSON injection: the moment an attribute comes from user input (a name, a tag) an unescaped " breaks the JSON and the marketplace silently drops the token. Escape it or restrict the charset. Third, the ERC-4906 gap above: state changes without the event, and on-chain truth and marketplace display diverge with no error anywhere.

When not to: if the art is raster, if you need to change the renderer without redeploying, or if you are on an L2 where you would rather keep bytecode small, put the JSON on IPFS and keep only the pointer on-chain. The hybrid (on-chain traits, off-chain renderer that reads them) is a common middle ground.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Choose between enumerable extension and off-chain indexing.

Answer

First 90 seconds

Before picking, fix the requirement: does anything on-chain have to read the token list, or only your UI and backend? If only off-chain readers need it, ship plain ERC-721 and build the list from Transfer logs. IERC721Enumerable is the optional extension in EIP-721 (tokenByIndex, tokenOfOwnerByIndex); mint, transfer and ownership behave identically without it. Reach for it when a contract must consume the set inside one transaction, or when there is no indexer and the collection is small and closed. Otherwise you pay state cost on every mint, forever, for a convenience the logs already give you.

What enumeration costs

An ERC-721 Transfer with from, to and tokenId all indexed is a LOG4 with no data: 375 + 4 * 375 = 1,875 gas. Enumeration adds a global list and a per-owner list, each with a companion index mapping. Per mint, per list:

  • index write _allTokensIndex[id] = len: zero-to-non-zero SSTORE = 20,000
  • new array element: zero-to-non-zero SSTORE = 20,000
  • length slot n to n+1: warm non-zero rewrite = 2,900

42,900 per list, 85,800 for both, before the 2,100 cold-access charge on each slot first touched (EIP-2929). A 10,000-piece drop is 858M extra gas: at 10 gwei, about 8.6 ETH, and those slots stay warm in state permanently. Transfers are cheaper than mints because the rewrites are warm (2,900) with a 4,800 refund for the slot the swap-and-pop empties, and EIP-3529 caps the whole transaction's refund at gasUsed / 5, so you never get all of it back.

The off-chain build

Transfer carries from, to and tokenId indexed precisely so a log filter can reconstruct ownership. Apply each log to a row set keyed by block:

Transfer(0x0 -> 0xA, id 7) blk 20001000 hash 0xab..  mints++  owner[7]=0xA  add(0xA,7)
Transfer(0xA -> 0xB, id 7) blk 20001050            owner[7]=0xB  del(0xA,7) add(0xB,7)
Transfer(0xB -> 0x0, id 7) blk 20001900            burns++  owner[7]=none  del(0xB,7)
invariant per block: mints - burns == totalSupply()

The read path is a filter on the owner topic plus a set lookup; no contract call, no per-mint state growth.

Reorgs

Key every row (block_number, block_hash). Serve reads at a lag rather than at head. On each new block, compare the stored hash at height h against the node's canonical hash; a mismatch is a reorg, so delete rows above the fork and replay from the parent. Post-merge, finality is 2 epochs = 64 slots * 12 s = 12.8 minutes, so settlement-facing reads wait for finalized while UX reads can serve head-12 with an alert if reorg depth exceeds 2.

Failure modes worth naming

failureshapedetection
burn ignoredyou apply to != 0x0 transfers but not to == 0x0, so burned tokens stay in the owner's setnightly job: mints - burns == totalSupply() read from the contract; alert on drift
EIP-2309 batch mintConsecutiveTransfer ranges emit no Transfer, so a whole drop is invisibleper block, check decoded tokenIds cover each (fromTokenId, toTokenId) range; ownerOf a sample of the gaps
proxy migrationthe project moves to a new proxy address and the indexer freezes on the old onewatch the EIP-1967 implementation slot 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc and the Upgraded event
nonsequential idscode assuming tokenId < totalSupply() silently drops tokens (ERC-721 permits any uint256)sample invariant: for each indexed row, ownerOf(tokenId) == row.owner at the indexed block
on-chain loop over ownersfor (i=0; i < nft.balanceOf(u); i++) is fine in eth_call but fatal in a transactioncap iterations; at 2,900 gas per warm write a 30M block tops out in the low thousands of holders

Decision rule: if a transaction must read the list, take enumeration and bound the list's size or switch to pull-based claims. If only readers need it, keep the contract plain and make the index the thing you monitor.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Integrate NFT royalties without misleading creators.

Answer

First 90 seconds. Assume an ERC-721 or ERC-1155 collection, a marketplace or mint page doing settlement, and a creator who believes royalties are enforced. They are not. EIP-2981 defines one view function (royaltyInfo(uint256 tokenId, uint256 salePrice) returns (address receiver, uint256 royaltyAmount), interface ID 0x2a55205a) that reports what a creator wants. It moves no money. The marketplace decides whether to pay. So the honest integration is: detect the interface, quote correctly, pay if you promised to, and tell the creator in the UI which of those you actually do.

Why it is shaped this way. ERC-721 transferFrom has no price argument, so the token contract never sees a sale price. The only party that knows the price is the settlement layer: the marketplace's escrow. EIP-2981 therefore standardizes the query and leaves enforcement to whoever holds the funds. That is the entire design, and it is why "the NFT enforces royalties" is false for every collection that only implements 2981.

Worked trace. Sale of token 42 for 1 ETH = 1e18 wei.

SOLIDITY
// Solidity ^0.8.20
interface IERC2981 {
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external view returns (address receiver, uint256 royaltyAmount);
}
bytes4 constant IERC2981_ID = 0x2a55205a;

function quote(address nft, uint256 tokenId, uint256 salePriceWei)
    view returns (address receiver, uint256 amount, bool supported)
{
    if (!IERC165(nft).supportsInterface(IERC2981_ID)) return (address(0), 0, false);
    (receiver, amount) = IERC2981(nft).royaltyInfo(tokenId, salePriceWei);
    supported = true;
}
  1. supportsInterface(0x2a55205a) → true.
  2. royaltyInfo(42, 1e18) → (0xCreator…, 5e16): a 5% rate.
  3. Validate: receiver ≠ address(0), amount <= salePriceWei (5e16 <= 1e18 ✓), receiver ≠ seller.
  4. Settle: seller gets 1e18 - 5e16 = 9.5e17, creator gets 5e16.

For ERC-1155, selling 10 editions at 0.1 ETH means passing 1e18, not 1e17. Passing the unit price under-pays the creator tenfold: a common and silent bug.

Alternatives, and when each wins.

approachenforces?limit
EIP-2981 + marketplace discretionnoworks everywhere, pays nowhere by default
ERC-721C transfer hooks (Limit Break)blocks transfers to non-paying venuesnew collections only; marketplaces route around it
Royalty Registry (Manifold)on-chain override of royaltyInfostill advisory; adds a lookup hop
Optional-royalty venues (Blur, OpenSea, 2023)buyer choosescreator revenue falls to the floor

Failure modes and detection. Voluntary nonpayment: reconcile expected vs. actual creator payouts per sale. Excessive or shifting rate: royaltyInfo may return more than the sale price or change per block. Cap at salePriceWei and snapshot the quote. Wrong units: pass wei, and for 1155 pass the total. Invalid receiver: address(0) or a contract that reverts on receive. Simulate the payout first. Proxy upgrades: the implementation behind a proxy can change between quote and settlement. Quote and settle atomically or use a signed quote. Circular payment: receiver equal to seller or marketplace makes the royalty a wash. Legal claims: never market on-chain enforcement the interface cannot deliver.

What changes the decision. If you own the marketplace, you can enforce. If you are a creator on someone else's venue, you can only disclose. New collection → ERC-721C is on the table. Already deployed → the Royalty Registry is the only lever.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How does ERC-1155 resolve token metadata: what is the {id} substitution rule in uri(uint256), when is a contract-level URI versus a per-token URI used, and how does the resulting JSON schema differ from ERC-721's?

Answer

Assume a marketplace or wallet reading metadata for an ERC-1155 collection, and the contract implements the optional metadata extension. The core answer: ERC-1155 has no tokenURI. It exposes uri(uint256 id), which by default returns one string for the whole contract, and the client, not the contract, substitutes {id} inside that string with the token id as 64 lowercase hex characters, zero-padded, no 0x prefix. The contract never sees the substituted value.

EIP-1155 states the rule directly: if {id} appears anywhere in the returned URI, clients MUST replace it with the id in lowercase hex, zero-padded to length 64. So a contract-level URI ipfs://QmX.../{id}.json resolves like this:

id (decimal)id (hex, 64-char padded)resolved URI
10000...0001 (63 zeros + 1)ipfs://QmX.../0000...0001.json
420000...002a (62 zeros + 2a)ipfs://QmX.../0000...002a.json
2550000...00ffipfs://QmX.../0000...00ff.json

One stored string serves a whole class of ids; the per-token distinction lives entirely in the client's substitution. A per-token URI is used when ids are not interchangeable: 1/1 art where each id has its own CID, or a collection migrated from ERC-721. OpenZeppelin 5.x's default ERC1155.uri(uint256) ignores the id and returns the contract-level _uri set in the constructor or by _setURI; the ERC1155URIStorage extension adds a per-id override on top of a base URI. Detection is ERC-165: the metadata interface id is 0x0e89341c (uri(uint256)). A marketplace that does not see that id should treat the token as having no metadata rather than guessing a URI.

The JSON schema differs in three ways that matter:

fieldERC-721ERC-1155
name, description, imagelisted in the EIP-721 schemapresent
decimalsabsentpresent; meaningful for fungible ids, 0 or omitted for NFTs
propertiesnot in the base schemain the schema, arbitrary values
per-token uniquenesstokenURI must differ per tokenuri may be identical for every id

Failure modes worth naming. A client that does not substitute {id} renders the same metadata for every id and the collection looks duplicated. Case and padding are the most common miss: uppercase hex, a 0x prefix, or an unpadded id 404s on case-sensitive gateways like IPFS. Teams routinely name files 42.json while the client requests ...002a.json: decimal-versus-hex confusion. ERC-721's OpenZeppelin baseURI convention concatenates the decimal tokenId.toString(), so a gateway layout that works for 721 breaks when the same collection is ported to 1155. Mutable metadata changes with no event unless the contract emits ERC-4906's MetadataUpdate/BatchMetadataUpdate, and that EIP is specified for ERC-721, so 1155 caches need a TTL or explicit refresh. OpenZeppelin 5.x uri returns the contract URI for any id, including burned or never-minted ones, so indexers must check supply before rendering. Setting decimals: 18 on an NFT id makes wallets display amounts divided by 1e18.

When not to use it: if every token genuinely needs a distinct URI, per-token overrides or ERC-721 are simpler. The substitution trick only pays off when ids share a template.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Model game currencies and unique items with ERC-1155.

Answer

What a strong candidate says first

Assume the game backend mints, players self-custody, and a marketplace or in-game trade moves items. ERC-1155 is one contract holding balances for many token IDs, each with its own supply. Model a currency as an ID with a large cap and fungible semantics (id 1 = GOLD), a stackable item as an ID with a fixed cap (id 100 = Tier-1 sword, cap 500), and a unique item as an ID with cap 1 (id 9001 = legendary). The cap is enforced by the mint function, not by the ID. Skip that and "unique" is a naming convention, not an invariant.

Mechanism

balanceOf(address,uint256) returns per-account, per-ID balances; balanceOfBatch reads many at once. safeTransferFrom moves one ID; safeBatchTransferFrom moves many in one call and emits a single TransferBatch instead of N TransferSingle events. setApprovalForAll(operator,true) grants the operator control over every ID in the contract: currencies included. uri(id) returns a template; per EIP-1155 the client substitutes {id} with the 64-char lowercase hex id.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";

contract GameItems is ERC1155 {
    uint256 public constant GOLD      = 1;     // fungible
    uint256 public constant SWORD_T1  = 100;   // semi-fungible
    uint256 public constant LEGENDARY = 9001;  // unique

    mapping(uint256 => uint256) public totalSupply;
    mapping(uint256 => uint256) public maxSupply;

    constructor() ERC1155("https://cdn.game.example/items/{id}.json") {
        maxSupply[GOLD]      = type(uint256).max;
        maxSupply[SWORD_T1]  = 500;
        maxSupply[LEGENDARY] = 1;
    }

    function mint(address to, uint256 id, uint256 amount) external {
        require(totalSupply[id] + amount <= maxSupply[id], "cap");
        totalSupply[id] += amount;
        _mint(to, id, amount, "");
    }
}

totalSupply is not in the standard: you add it, or you cannot audit supply.

Trade-offs

ERC-1155ERC-721one ERC-20 per currency
many item typesone contract, one approvalone contract per collectionone contract per currency
supply per IDany1any
batch transfersafeBatchTransferFromnono
marketplace supportbroadbroadestn/a for items
DeFi composabilityweakweakstrong

Pick 1155 when you have many item types with quantities and want one approval and batch moves. Pick 721 when items are strictly unique and you need per-item enumeration and the widest marketplace tooling. Pick ERC-20 for a currency that must plug into AMMs or lending: 1155 currencies are not composable with that tooling.

Failure modes

  • ID implies uniqueness. Mint id 9001 with a cap of 1, but if mint has no cap check, a second call duplicates the "legendary". Detect by asserting totalSupply[id] == 1 for the unique ID space, or by using a separate contract for uniques.
  • Operator overreach. A marketplace approval via setApprovalForAll also lets the operator drain GOLD. Detect by watching ApprovalForAll events and scoping operators to a wrapper contract that only forwards item IDs.
  • Batch gas. safeBatchTransferFrom writes one storage slot per ID. A 200-item inventory move is roughly 21k base + ~20k per cold slot ≈ 4M gas; on an L2 with a lower per-tx limit it reverts. Detect by measuring gas on the largest realistic inventory and chunking.
  • Mixed decimals. ERC-1155 has no decimals. If off-chain code assumes 18 for GOLD and 0 for items, a 250-unit transfer of a 0-decimal item is misreported. Store decimals per ID in metadata.
  • Metadata ambiguity. If the server returns the literal {id} or the same image for every ID, every item looks identical. Detect by fetching uri(id) and checking the substituted id appears.
  • Upgrade changes. A proxy upgrade that changes the URI base or mint rules silently re-points existing items. Detect with storage-layout checks and a timelock.

Trace

A holds 1000 GOLD, 3 SWORD_T1, 1 LEGENDARY. A calls safeBatchTransferFrom(A, B, [1,100,9001], [250,1,1], ""). The contract checks msg.sender == A || isApprovedForAll(A, msg.sender), debits and credits each pair, emits one TransferBatch, then calls onERC1155BatchReceived on B if B is a contract. That hook must return 0xbc197c81 or the whole batch reverts: a receiver that returns the single-transfer selector 0xf23a6e61 loses the entire transfer, not just one ID.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Implement a gas-bounded multi-token batch transfer.

Answer

Assume ERC-1155 and a safeBatchTransferFrom-style entry point: ids[i] pairs with amounts[i], and the receiver callback is onERC1155BatchReceived. The bound I defend is a hard cap of 100 ids per call, checked before the loop, because the loop is O(n) with two storage writes per id and that is what actually costs gas.

Core design, in order:

  1. Reject to == address(0).
  2. Authorize: from == msg.sender or isApprovedForAll[from][msg.sender].
  3. ids.length == amounts.length, and ids.length <= MAX_BATCH.
  4. Debit and credit every id, all before any external call.
  5. Emit one TransferBatch.
  6. Call the receiver last, and check its return selector.
SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

contract BatchToken {
    uint256 public constant MAX_BATCH = 100;
    mapping(uint256 => mapping(address => uint256)) private _balance;
    mapping(address => mapping(address => bool)) private _operatorApproval;

    error LengthMismatch();
    error BatchTooLarge();
    error ZeroAddress();
    error NotAuthorized();
    error InsufficientBalance(uint256 id, uint256 have, uint256 want);

    event TransferBatch(address indexed operator, address indexed from,
        address indexed to, uint256[] ids, uint256[] amounts);

    function safeBatchTransferFrom(address from, address to,
        uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external {
        if (to == address(0)) revert ZeroAddress();
        if (from != msg.sender && !_operatorApproval[from][msg.sender]) revert NotAuthorized();
        uint256 n = ids.length;
        if (n != amounts.length) revert LengthMismatch();
        if (n > MAX_BATCH) revert BatchTooLarge();

        for (uint256 i; i < n; ++i) {
            uint256 id = ids[i];
            uint256 amt = amounts[i];
            uint256 bal = _balance[id][from];
            if (bal < amt) revert InsufficientBalance(id, bal, amt);
            unchecked { _balance[id][from] = bal - amt; }
            _balance[id][to] += amt;
        }

        emit TransferBatch(msg.sender, from, to, ids, amounts);

        if (to.code.length != 0) {
            bytes4 ret = IERC1155Receiver(to).onERC1155BatchReceived(
                msg.sender, from, ids, amounts, data);
            if (ret != IERC1155Receiver.onERC1155BatchReceived.selector)
                revert("ERC1155: bad receiver");
        }
    }
}

The ordering is the whole point. Balances are written before the callback, so a receiver that reenters safeBatchTransferFrom from inside onERC1155BatchReceived sees already-debited state and cannot double-spend the same balance. That is checks-effects-interactions, and it is why the callback is last rather than interleaved with the loop.

Gas, mainnet post-EIP-2929/3529, approximate: per id, cold SLOAD of _balance[id][from] 2,100, SSTORE nonzero→nonzero 2,900, cold SLOAD of _balance[id][to] 2,100, SSTORE 2,900 (20,000 if that slot starts at zero). Call it ~10,000 gas/id typical, ~27,000 worst case. Calldata ~1,000 gas/id, the event ~500 gas/id. So 100 ids ≈ 1.1–1.5M gas; 1,000 ids ≈ 11–15M, half a 30M block, and it will revert for large holders. That arithmetic is why the cap is 100.

Two policies worth deciding out loud. Duplicate ids: ERC-1155 permits them, and processing in order is correct. The second occurrence reads the already-debited balance. I allow them and emit the arrays verbatim; rejecting them costs an O(n) dedupe mapping for no safety gain. Empty arrays: the standard does not forbid them, so I allow the no-op rather than reverting.

Failure modes and how they surface: length mismatch reverts before any write; a non-conforming receiver returning the wrong selector or reverting rolls the whole tx back, so balances are never left partial; an over-cap batch reverts on BatchTooLarge rather than running out of gas mid-loop, which is the difference between a clean error and a half-applied batch. Reentrancy is handled by ordering, not by a guard, so the callback can safely call back in.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Threat-model an ERC-1155 receiver callback.

Answer

Assume you are the contract receiving ERC-1155 tokens, and both the token contract and the caller can be adversarial. The callback is an external call into your code after the token has already updated balances and emitted TransferSingle/TransferBatch. It is not an authorization signal. The token only checks your return value: onERC1155Received must return 0xf23a6e61, onERC1155BatchReceived must return 0xbc197c81. Anything else, including a revert, makes the token revert the whole transfer with ERC1155InvalidReceiver(to) in OpenZeppelin v5 (v4 reverts with ERC1155: ERC1155Receiver rejected tokens). So decide whether to accept at all, and make your own state consistent before you return.

AttackerEntry pointImpactDetection
Malicious token contractCalls your onERC1155Received directly with fake from/valueCredits a deposit that never happenedUnit test: EOA calls the callback; expect revert or no state change
Malicious receiver (if you are the token)Callback burns all forwarded gas or revertssafeTransferFrom reverts, transfer blockedGas snapshot with EIP-150 63/64 rule; test with a receiver that burns gas
Reentrant receiverCallback calls back into your withdraw/depositDouble-spend or double-creditFoundry test with a malicious receiver; invariant fuzzing
Operator confusionoperator is not the owner; attacker sets approvalUnauthorized transferCheck operator == expected; test with setApprovalForAll

Mechanism: OpenZeppelin v5 _doSafeTransferAcceptanceCheck does try IERC1155Receiver(to).onERC1155Received(...) returns (bytes4 response) and reverts if response != IERC1155Receiver.onERC1155Received.selector. A wrong selector is not ignored; it aborts the transfer. Reentrancy arises because the callback is an external call while the token's state is already updated but your contract's state may be mid-update. If your callback mutates shared state, an attacker can reenter another function before your outer function finishes.

Worked example. This vault credits in both deposit and the callback:

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IERC1155 {
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
}

contract VulnerableVault {
    IERC1155 public token;
    mapping(address => uint256) public credits;

    constructor(IERC1155 _token) { token = _token; }

    function deposit(uint256 amount) external {
        token.safeTransferFrom(msg.sender, address(this), 1, amount, "");
        credits[msg.sender] += amount; // second credit
    }

    function onERC1155Received(address, address from, uint256, uint256 value, bytes calldata) external returns (bytes4) {
        credits[from] += value; // first credit
        return 0xf23a6e61;
    }
}

Trace: attacker calls deposit(10). The token transfers 10 units of id 1 from attacker to vault. The token calls vault.onERC1155Received(operator=attacker, from=attacker, id=1, value=10). The vault credits attacker +10. The token returns. deposit continues: credits[attacker] += 10. Total credits = 20 for 10 tokens. Attacker withdraws 20; the vault holds 10. Detection: a mock token that calls the callback, then assert credits[attacker] == 10. Fix: credit in exactly one place, or guard all state-changing functions with nonReentrant.

Trade-offs. Option A: revert unless msg.sender is a whitelisted token. Cost: whitelist maintenance; you cannot accept new tokens without an upgrade. Use when you only accept a fixed set of collections. Option B: accept any token but never mutate state in the callback; only return the selector. Cost: you cannot auto-stake or auto-list on receipt. Use when you can do the work in a separate claim function. Option C: use a reentrancy guard on every state-changing function. Cost: in a Foundry gas snapshot of a minimal vault, adding nonReentrant moved deposit from 48,210 to 56,102 gas (first call, cold; hypothetical local run). Use when you must mutate state in the callback. Option D: check operator == from or operator == expectedMarketplace. Cost: breaks legitimate operator flows. Use when you only expect direct transfers.

Failure modes and detection: wrong selector returns 0x0; token reverts ERC1155InvalidReceiver; test with a mock token. Direct call from an EOA credits a fake deposit; test calling the callback from an EOA. Reentrancy double-credits; Foundry test with a malicious receiver. Gas griefing burns the 63/64 forwarded gas; gas snapshot. Nested forwarding reenters safeTransferFrom; trace the call depth. Operator confusion lets an approved attacker move tokens; test with setApprovalForAll. Batch callback onERC1155BatchReceived shares state with the single callback; guard both or neither.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Build an ERC-1155 balance indexer.

Answer

Core answer (first 90 seconds). One chain, one ERC-1155 contract at a known address, and a requirement to answer "what is (account, token id)'s balance at block N" for any N. Subscribe to TransferSingle and TransferBatch filtered by contract address and topic0, decode each log, and apply it exactly once as a signed delta keyed by (block_number, tx_index, log_index). Mints are from == 0x0, burns are to == 0x0. Reorgs roll back by subtracting the stored deltas above the fork point. A sampled balanceOfBatch reconciles derived state against chain state.

Topic0 values: TransferSingle = 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62, TransferBatch = 0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb. In both events operator, from and to are indexed (topics 1–3); the id/value or ids/values arrays sit in the log data and need ABI decoding.

Schema.

SQL
CREATE TABLE processed_log (
  block_number BIGINT NOT NULL,
  tx_index     INT    NOT NULL,
  log_index    INT    NOT NULL,
  block_hash   BYTEA  NOT NULL,
  PRIMARY KEY (block_number, tx_index, log_index)
);
CREATE TABLE balance (
  contract BYTEA NOT NULL,
  token_id NUMERIC(78,0) NOT NULL,   -- uint256
  account  BYTEA NOT NULL,
  amount   NUMERIC(78,0) NOT NULL,
  PRIMARY KEY (contract, token_id, account)
);
CREATE TABLE log_delta (
  block_number BIGINT NOT NULL,
  tx_index INT NOT NULL,
  log_index INT NOT NULL,
  account BYTEA NOT NULL,
  token_id NUMERIC(78,0) NOT NULL,
  delta NUMERIC(78,0) NOT NULL,
  PRIMARY KEY (block_number, tx_index, log_index, account, token_id)
);
CREATE TABLE block (
  block_number BIGINT PRIMARY KEY,
  block_hash BYTEA NOT NULL,
  parent_hash BYTEA NOT NULL
);

NUMERIC(78,0) holds a uint256 (max ≈ 1.16e77). The log key is the primary key, so re-applying a log is a no-op.

Ingest, and a trace through it.

Python
# psycopg 3, Python 3.12
def apply_log(conn, contract, blk, tx_idx, log_idx, blk_hash, deltas):
    with conn.transaction():
        inserted = conn.execute(
            """INSERT INTO processed_log (block_number, tx_index, log_index, block_hash)
               VALUES (%s,%s,%s,%s)
               ON CONFLICT (block_number, tx_index, log_index) DO NOTHING
               RETURNING 1""",
            (blk, tx_idx, log_idx, blk_hash)).fetchone()
        if inserted is None:
            return 0                      # already applied: skip the deltas
        for account, token_id, delta in deltas:
            conn.execute(
                """INSERT INTO balance (contract, token_id, account, amount)
                   VALUES (%s,%s,%s,%s)
                   ON CONFLICT (contract, token_id, account)
                   DO UPDATE SET amount = balance.amount + EXCLUDED.amount""",
                (contract, token_id, account, delta))
        return len(deltas)

Two logs, decoded to deltas:

  1. TransferBatch(from=0x0, to=Alice, ids=[1,2], values=[10,5]) at block 100 → [(Alice,1,+10), (Alice,2,+5)].
  2. TransferSingle(from=Alice, to=Bob, id=1, value=3) at block 101 → [(Alice,1,-3), (Bob,1,+3)].
stepcallprocessed_log insertbalance rows after
1log (100,0,0)1 row(Alice,1)=10, (Alice,2)=5
2log (101,0,0)1 row(Alice,1)=7, (Alice,2)=5, (Bob,1)=3
3replay log (101,0,0)0 rowsunchanged

Reconcile: balanceOfBatch([Alice,Alice,Bob],[1,2,1]) → [7,5,3]. Match.

Reorg rollback. On a parent-hash mismatch, find the fork point, then subtract the aggregate delta per (account, token_id) above it. Aggregate in a subquery: a plain UPDATE ... FROM log_delta picks one arbitrary row when several deltas hit the same balance and silently under-reverts.

SQL
UPDATE balance b
   SET amount = b.amount - agg.total
  FROM (SELECT token_id, account, SUM(delta) AS total
          FROM log_delta WHERE block_number >= %(fork)s
         GROUP BY token_id, account) agg
 WHERE b.contract = %(contract)s
   AND b.token_id = agg.token_id AND b.account = agg.account;
DELETE FROM log_delta     WHERE block_number >= %(fork)s;
DELETE FROM processed_log WHERE block_number >= %(fork)s;
DELETE FROM block         WHERE block_number >= %(fork)s;

Fork at 101: subtract (Alice,1,-3) and (Bob,1,+3) → Alice id1 back to 10, Bob id1 back to 0, matching the pre-101 table.

Reconciliation cost. 10k holders × 3 ids = 30k pairs. balanceOfBatch packs pairs into one call; at 500 pairs/call that is 60 eth_calls. Against a local node (~1 ms) that is 60 ms per block; against a remote provider at 50 ms RTT it is 3 s per block: a quarter of the 12 s slot, growing linearly with holders. So sample: 1% of holders per block, full sweep every 100 blocks (~20 min).

Trade-offs. Event-derived state is cheap and gives history; per-block balanceOfBatch over every holder is authoritative but scales with holders, so it is a reconciler, not the source of truth. Inverse deltas beat re-derivation when reorgs are shallow and frequent; re-derivation from a checkpoint wins when stored deltas cannot be trusted. The unique key is the simplest correct idempotency mechanism; versioned upserts only earn their complexity when merging multiple sources.

Failure modes. Duplicate logs from overlapping subscriptions: caught by the processed_log conflict count, cost is double-counted balances. Reorg deeper than the rollback window: caught by parent-hash mismatch; past finality (~64 slots / 2 epochs post-merge) re-derive from a checkpoint. Missed ranges: caught by a gap in contiguous block heights, healed by backfill. ids.length != values.length: EIP-1155 requires a revert, so a mismatched event means a non-conforming contract. Length-check, skip, alert. Never write a balance row for address(0); a mint that lands there corrupts the table. Event/state disagreement: caught by reconciliation mismatch, alert and re-derive that range.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Use ERC-165 safely in a marketplace.

Answer

What I'd say first. ERC-165 answers one narrow question: does this address claim to implement interface X? It does not answer whether the contract behaves like X. In a marketplace I use it to pick a call path, ERC-721 vs ERC-1155 vs ERC-2981, and then I verify that path by exercising it. Detection is a routing hint, never an authorization.

Mechanism. supportsInterface(bytes4) is view and returns bool. An interface ID is the XOR of its function selectors, so ERC-721 is 0x80ac58cd. The spec's own detection routine does three calls: supportsInterface(0x01ffc9a7) (ERC-165 itself), supportsInterface(0xffffffff) which must return false, then the ID you actually care about. The 0xffffffff probe is the cheap lie detector: a contract with no real implementation but a fallback returning 32 nonzero bytes answers true to everything, and this check catches it. The spec caps each call at 30,000 gas via staticcall, so a contract that loops or reads storage inside supportsInterface fails closed instead of burning your transaction.

SOLIDITY
// SPDX-License-Identifier: MIT
// Checked against Solidity 0.8.24
interface IERC165 {
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

contract Marketplace {
    bytes4 constant ERC721_ID  = 0x80ac58cd;
    bytes4 constant ERC2981_ID = 0x2a55205a;

    function isERC721(address token) internal view returns (bool) {
        (bool ok, bytes memory data) = token.staticcall{gas: 30_000}(
            abi.encodeWithSelector(IERC165.supportsInterface.selector, ERC721_ID)
        );
        if (!ok || data.length != 32 || !abi.decode(data, (bool))) return false;

        // ERC-165 requires 0xffffffff to return false; a blind fallback fails here.
        (ok, data) = token.staticcall{gas: 30_000}(
            abi.encodeWithSelector(IERC165.supportsInterface.selector, bytes4(0xffffffff))
        );
        return ok && data.length == 32 && !abi.decode(data, (bool));
    }
}
interfaceIDwhat the marketplace routes on it
ERC-1650x01ffc9a7the meta-check itself
ERC-7210x80ac58cdownerOf / transferFrom listings
ERC-11550xd9b67a26semi-fungible listings
ERC-29810x2a55205aroyaltyInfo for the fee split

When to skip it. Detection costs a round trip and buys nothing if you already trust the contract (your own collection) or if the standard has no interface ID: ERC-20 has none, so you probe balanceOf/transfer directly. The deciding criterion: are you choosing between multiple standards on an untrusted address? Detect. If you are going to simulate the real call anyway, the simulation is the stronger check and detection is redundant.

Failure modes, and how each is caught.

  • Lying implementation: returns true, then transferFrom reverts or silently no-ops. Detect: eth_call the transfer before sending, then after execution re-read ownerOf and assert it changed.
  • Proxy upgrade: implementation swapped between listing and execution. Detect: re-run detection at execution time and pin to a block; never cache the result across blocks.
  • Selector collision: two interfaces XOR to the same ID. Detect: check individual selectors, not just the aggregate.
  • Gas griefing: supportsInterface consumes the 30k cap. Detect: staticcall returns ok == false; treat as unsupported.
  • False fallback: caught by the 0xffffffff probe above.
  • Semantic deviation: reports ERC-721 but transferFrom skips the approval check. Detect: integration-test against the deployed bytecode, not the interface.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design approval UX for a multi-token marketplace.

Answer

Core answer (say this first)

The approval screen is the highest-stakes screen in a marketplace: it is the one place a user hands over assets they cannot get back without a second transaction. My rule is a ladder: never ask for a broader grant than the action needs, and when you must, make scope, operator and chain impossible to misread, then make revocation one tap.

Assumptions: EVM chains, ERC-721/1155 collections, an off-chain order book (Seaport-style) with on-chain settlement, injected or WalletConnect wallets.

The ladder

Default to a signed order, not an approval. A Seaport-style listing is an EIP-712 signature over {offerer, token contract, tokenId, price, expiry, nonce}: no on-chain state change, no standing grant, and it expires. Fall back to on-chain approval only when the flow genuinely needs the marketplace to move tokens without a fresh signature, e.g. a bid pool that must pull on match.

Then pick the narrowest on-chain grant:

mechanismscoperevokeuse when
approve(tokenId) (ERC-721)one token IDapprove(address(0), tokenId)one-off sale
setApprovalForAll(op, true) (ERC-721/1155)every token ID the owner holds in that collection, until revokedsetApprovalForAll(op, false)active trader listing many items
EIP-2612 permit (ERC-20)amount + deadline + noncenonce bump or deadlineERC-20 payment leg

Why setApprovalForAll is the dangerous one

It is not scoped to a token, a price, or a time. Once signed, the operator can transfer any token ID the owner holds in that collection, including ones minted later, with no further signature. That is why one phishing approval can drain a whole wallet's collection, and why the confirm copy must say "all items in this collection, now and in the future", not "approve".

Failure modes and how you detect them

failuredetection
phishing operatoroperator address not in a curated registry of known marketplace contracts; show ENS + verified badge, hard-warn otherwise
upgradeable spenderread the EIP-1967 implementation slot; if non-zero, warn "this operator's logic can be upgraded"
stale broad approvalscan ApprovalForAll events for the owner; list with grant date and age
wrong chaincompare wallet chainId to the EIP-712 domain chainId; block on mismatch
hidden signature intentdecode the EIP-712 payload and render named fields, never raw hex
owner confusioninstrument revoke rate and support tickets after copy changes
compromised marketplaceincident feed → banner + one-tap revoke-all

Revocation

Surface active approvals with a one-tap revoke; revoke.cash and Etherscan's Token Approvals page are the fallbacks. Cost is real: at 20 gwei and ETH at $3,000, a 46,000-gas revoke is about $2.76, so batch the prompt, don't nag.

Curated: · Written: · Reviewed:

Difficulty: Hard