Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 47 ยท Tokens and Standards

ERC-721 NFTs

Understand ERC-721 non-fungible tokens: ownership per token id, approvals, safeTransferFrom receivers, tokenURI and off-chain metadata, with a runnable registry.

An ERC-20 token says "this address owns 50 units", and every unit is the same. An NFT (non-fungible token) says "this address owns item number 7", and item 7 is not the same as item 8. The standard for this is ERC-721. Instead of a table from owner to amount, an ERC-721 contract keeps a table from token id to owner.

What an NFT represents (a picture, a ticket, a game item, a deed) is not stored in the standard at all. The contract only proves who owns which id, and points at a description through a URI. In this lesson you will learn the ownership model, the two kinds of approval, why safeTransferFrom exists, and where the image really lives. If you have not read Building an ERC-20 Token, do that first; the ideas of balances, approvals and events carry over.

ERC-20 vs ERC-721

ERC-20 Address maps to an amount. Units are identical.
ERC-721 Token id maps to one owner. Each id is unique.

Same ideas, different table: owner by id, not amount by owner.

1 / 2

The core data

An ERC-721 contract keeps these tables:

  • ownerOf(tokenId): the owner of each token (reverts for a token that does not exist)
  • balanceOf(owner): how many tokens an address holds (a count, not an amount)
  • a per-token approved address (getApproved(tokenId))
  • a per-owner set of operators (isApprovedForAll(owner, operator))

The events are Transfer(from, to, tokenId), Approval(owner, approved, tokenId) and ApprovalForAll(owner, operator, approved). In Transfer, all three parameters are indexed, which makes it easy for off-chain tools to ask "show me every transfer of token 7".

Two approvals exist for a reason. approve(to, tokenId) allows one address to move one token, which is what a marketplace needs when you list a single item. setApprovalForAll(operator, true) allows an address to move every token you own, which is convenient for marketplaces and dangerous if given to the wrong address. Once a token is transferred, its single-token approval is cleared.

JS A tiny ERC-721 registry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

transferFrom and safeTransferFrom

ERC-721 has two ways to move a token. They do the same ownership change, with one difference.

  • transferFrom(from, to, tokenId) just moves the token. If to is a contract that does not know what an NFT is, the token is stuck there forever.
  • safeTransferFrom(from, to, tokenId) also checks the receiver. If to is a contract (has code), the token contract calls onERC721Received(operator, from, tokenId, data) on it and requires the return value to equal that function's own selector, 0x150b7a02. Anything else reverts the whole transfer. If to is a normal wallet, no check happens.
SOLIDITY
// Read-only: a contract that is willing to receive NFTs
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

contract Vault is IERC721Receiver {
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external pure returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector; // 0x150b7a02
    }
}

Minting has the same pair: _mint and _safeMint. Prefer the safe versions when the recipient might be a contract.

There is a catch: the receiver hook is an external call in the middle of your function. A malicious receiver can call back into your contract before your state is fully updated. That is a reentrancy opening, so update your own state before the safe transfer or mint, and see Reentrancy Step by Step.

JS safeTransferFrom and receiver contracts

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Metadata and tokenURI

The optional metadata extension adds name(), symbol() and tokenURI(tokenId). The URI points to a JSON file, conventionally with fields such as name, description, image and attributes. Wallets and marketplaces download it to display the NFT.

The important thing to understand: the image and the JSON are almost never stored on chain, because storing kilobytes in contract storage is very expensive. The contract holds a short string, and the real data lives somewhere else:

Where the data lives What to know
A normal web server Easy and cheap, but the owner of the server can change or remove the file, and the NFT then shows something else
IPFS (content-addressed) The link contains a hash of the file, so the content cannot change without the link changing; someone still has to keep the file available ("pinned")
Fully on chain The contract builds the JSON and an SVG itself and returns a data: URI. Permanent and costly, so mostly for small images

A common pattern is tokenURI(id) = baseURI + id, so one base string covers the whole collection. If an owner or an API can change that base string, buyers should know it before they buy: "your NFT" is the ownership entry on chain, and the picture depends on whoever controls the URI.

JS tokenURI, base URI and a data: URI

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Using OpenZeppelin in practice

You will almost never write ERC-721 from scratch. A typical collection extends the audited base contract:

SOLIDITY
// Read-only
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract PixelPets is ERC721, Ownable {
    uint256 private _nextId = 1;

    constructor() ERC721("Pixel Pets", "PET") Ownable(msg.sender) {}

    function mint(address to) external onlyOwner returns (uint256 id) {
        id = _nextId++;
        _safeMint(to, id);
    }

    function _baseURI() internal pure override returns (string memory) {
        return "ipfs://exampleCID/";
    }
}

The base contract handles every table, event and approval rule above. You decide who may mint, how ids are assigned and where the metadata lives. See Using OpenZeppelin for how to work with these building blocks.

What is real: ownership by token id, the two kinds of approval, the receiver magic value 0x150b7a02, the on-chain vs off-chain metadata trade-offs. What is the stand-in: JavaScript maps instead of contract storage, contracts and wallets told apart by a lookup table, no ABI encoding, no gas and no real IPFS or SVG rendering.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an ERC-721 contract store about each token?

    The core table maps token id to owner. The image and description are normally off chain, referenced by the tokenURI.
  2. 2. What is the difference between approve and setApprovalForAll?

    approve is per token (and is cleared on transfer). setApprovalForAll is per owner and operator, which is convenient for marketplaces but powerful, so only grant it to addresses you trust.
  3. 3. Why does safeTransferFrom exist?

    When the receiver is a contract, the token calls onERC721Received and requires the magic return value. A contract without the hook makes the transfer revert instead of silently trapping the NFT.
  4. 4. Where are NFT images usually stored?

    On-chain storage is too expensive for most images. The tokenURI points to a JSON file that points to the image, and the permanence of the NFT depends on where those files live.

Summary

  • ERC-721 maps each token id to exactly one owner; balanceOf is a count.
  • approve covers one token, setApprovalForAll covers all of an owner's tokens; a transfer clears the single-token approval.
  • safeTransferFrom calls onERC721Received on contract receivers and requires 0x150b7a02; that call is also a reentrancy risk.
  • tokenURI points to JSON metadata, which usually lives off chain (server, IPFS) and sometimes fully on chain.
  • Whoever controls the metadata location controls what the NFT looks like, so check it before buying or building.
  • In real projects, extend an audited base contract and decide only minting rules, ids and URIs yourself.

Next: ERC-1155, ERC-4626 and Friends.