Gas-optimize batch NFT minting
Minting N tokens in one transaction is dominated by ERC-721 ownership writes; a batch layout that writes ownership once cuts per-token cost, provided reads are updated to match.
Procedure
Measure the naive loop first:
forge test --match-test testMint10Naive --gas-report | grep -i mintTen separate
_safeMintcalls typically cost ~50k gas each.Adopt a batch layout that writes ownership once per batch (ERC-721A style) and stores packed owner data:
grep -nE 'balanceOf|ownerOf|_ownerships|_packedAddressData|_currentIndex' src/ERC721A.solConfirm
ownerOfandbalanceOfare overridden to read the packed bitmap; otherwise the saving is lost at read time and reads return wrong owners.Check the batch emits the ERC-2309
ConsecutiveTransferevent (and/or per-tokenTransfer) so indexers still see the mint:grep -nE 'ConsecutiveTransfer|emit Transfer' src/*.solBenchmark before and after with the same batch size:
forge snapshot --match-contract MintGasTest && diff .gas-snapshot .gas-snapshot.bakEnsure the batch is atomic — a revert mid-loop must roll back the whole batch:
require(quantity <= maxPerTx, "too many");Check the memory cost of large batches: a
uint256[]in calldata is cheap; building it in memory for 1000 tokens is not.Confirm receiver callbacks.
_safeMintin a batch callsonERC721ReceivedN times, opening N reentrancy windows; call it once or document unsafe minting.
Pitfalls
- ERC-721A
ownerOfon an uninitialized id returns the batch-start owner instead of reverting, so a burn can resurrect a token. - Marketplace tools that count
Transferevents undercount a batch mint that only emitsConsecutiveTransfer. _safeMintinside a batch loop calls the receiver hook N times, multiplying reentrancy surface.- Skipping the ownership write for the first token makes
totalSupplyand ids disagree. - Copying an ERC-721A implementation without its
_beforeTokenTransfersoverride breaks approval clearing on transfer.
Verification
forge snapshot --match-contract MintGasTest && diff .gas-snapshot .gas-snapshot.bak
Pass: per-token gas is materially lower than the naive loop and ownerOf/balanceOf return correct values for every id in the batch. Report the gas per token before and after, the batch size, and the event emitted.