How NFT Smart Contracts Actually Work
A technical explanation of ERC-721 and ERC-1155 contracts — metadata, minting mechanics, royalties, and what makes them different from other smart contracts.
NFTs (Non-Fungible Tokens) are smart contracts with some unique properties — each token has a unique ID and associated metadata. The underlying mechanics are more nuanced than most tutorials suggest.
ERC-721 Basics
The core ERC-721 interface defines: balanceOf (how many tokens does an address hold), ownerOf (who owns a specific token ID), transferFrom (move a token), approve (allow another address to transfer a specific token), and setApprovalForAll (allow an operator to transfer all your tokens). These six functions are the interface that wallets, marketplaces, and other contracts use.
Where the Metadata Lives
The contract itself stores only the token ID and owner. The tokenURI function returns a URL or IPFS hash pointing to a JSON file with the actual metadata (name, description, image URL, attributes). The image itself is stored off-chain (IPFS, Arweave, or centralized server). This means the 'NFT' you see in your wallet is a pointer to data that could theoretically disappear.
The Mint Function
NFT contracts need a mint function — the mechanism for creating new tokens. Common patterns: allowlist mint (merkle tree proof required), public mint (anyone can pay and receive a token), sequential vs. random IDs (random ID minting requires a randomness source like Chainlink VRF to prevent sequential front-running).
Gas Optimization in NFT Mints
Mint events have historically suffered from gas wars — users bidding up gas to get in first. ERC-721A (by Azuki) batches the storage write for consecutive mints in the same transaction, reducing mint gas costs by 70%+ for batch mints. It's now standard for large collections.
On-Chain Royalties
EIP-2981 defines a standard for on-chain royalty information — the contract specifies recipient and percentage. Enforcing royalties on-chain has been controversial (Blur famously made them optional). Most projects now use operator filter registries or accept that royalties are a social contract rather than a technical one.
Common Vulnerabilities in NFT Contracts
Reentrancy in the mint function (especially with ETH refunds). Insecure randomness (block.timestamp and block.difficulty are manipulable by validators). Integer overflow in supply counters. Unrestricted minting (forgotten owner-only modifier). Metadata centralization (if the server goes down, NFT images disappear).
Frequently Asked Questions
Related Guides
Ready to build your Web3 project?
Tell us about your project and get a precise quote.
Get a Project Quote