ERC-721 NFTs
ERC-721 is the standard for non-fungible tokens (NFTs): tokens where each unit is unique and identified by a tokenId. Typical uses are certificates, tickets, game items, memberships and digital art. Where ERC-20 tracks how many tokens an address has, ERC-721 tracks which tokens it owns.
This lesson builds a minimal ERC-721 to understand how it works internally. The tokens exist only in the playground.
The core interface
interface IERC721 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address);
function setApprovalForAll(address operator, bool approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}The optional metadata extension adds name(), symbol() and tokenURI(tokenId), a link to a JSON file describing the token (title, image, attributes). The image itself is usually stored off-chain.
A minimal NFT: course certificates
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Certificates {
string public constant name = "TAD Certificates";
string public constant symbol = "TADC";
address public immutable issuer;
uint256 public nextId = 1;
mapping(uint256 => address) private owners;
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
mapping(uint256 => string) private courses;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
constructor() { issuer = msg.sender; }
function ownerOf(uint256 id) public view returns (address owner) {
owner = owners[id];
require(owner != address(0), "token does not exist");
}
function mint(address to, string calldata course) external returns (uint256 id) {
require(msg.sender == issuer, "only issuer");
require(to != address(0), "invalid receiver");
id = nextId++;
owners[id] = to;
balanceOf[to] += 1;
courses[id] = course;
emit Transfer(address(0), to, id);
}
function tokenURI(uint256 id) external view returns (string memory) {
ownerOf(id); // reverts for missing tokens
return string.concat("https://example.org/cert/", courses[id], ".json");
}
function approve(address to, uint256 id) external {
address owner = ownerOf(id);
require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "not authorized");
getApproved[id] = to;
emit Approval(owner, to, id);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(address from, address to, uint256 id) public {
address owner = ownerOf(id);
require(owner == from, "from is not the owner");
require(to != address(0), "invalid receiver");
require(msg.sender == owner || msg.sender == getApproved[id] || isApprovedForAll[owner][msg.sender],
"not authorized");
delete getApproved[id]; // approvals are cleared on transfer
balanceOf[from] -= 1;
balanceOf[to] += 1;
owners[id] = to;
emit Transfer(from, to, id);
}
}
contract Main {
function main() external {
Certificates certs = new Certificates();
address ada = address(0xADA);
address bob = address(0xB0B);
uint256 first = certs.mint(ada, "solidity");
certs.mint(ada, "rust");
certs.mint(bob, "python");
console.log("token", first, "owner is ada?", certs.ownerOf(first) == ada);
console.log("ada owns", certs.balanceOf(ada), "certificates");
console.log(certs.tokenURI(3));
certs.ownerOf(99);
}
}token 1 owner is ada? true
ada owns 2 certificates
https://example.org/cert/python.json
main() failed: reverted with reason: token does not exist
Unlike ERC-20, tokenId is indexed in Transfer, so indexers can follow the history of each individual token.
Transfers and approvals
Owners can transfer their tokens, approve one address for a single token, or approve an operator (typically a marketplace contract) for all their tokens:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Tickets {
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
uint256 public minted;
function mint(address to) external returns (uint256 id) {
id = ++minted;
ownerOf[id] = to;
}
function approve(address to, uint256 id) external {
require(msg.sender == ownerOf[id], "not owner");
getApproved[id] = to;
}
function transferFrom(address from, address to, uint256 id) external {
require(ownerOf[id] == from, "wrong from");
require(msg.sender == from || msg.sender == getApproved[id], "not authorized");
delete getApproved[id];
ownerOf[id] = to;
}
}
contract Fan {
function approve(Tickets t, address to, uint256 id) external { t.approve(to, id); }
function move(Tickets t, address from, address to, uint256 id) external { t.transferFrom(from, to, id); }
}
contract Main {
function main() external {
Tickets tickets = new Tickets();
Fan alice = new Fan();
Fan resaleDesk = new Fan();
Fan bob = new Fan();
uint256 id = tickets.mint(address(alice));
alice.approve(tickets, address(resaleDesk), id); // let the desk sell ticket 1
resaleDesk.move(tickets, address(alice), address(bob), id);
console.log("ticket 1 now owned by bob?", tickets.ownerOf(id) == address(bob));
console.log("approval cleared?", tickets.getApproved(id) == address(0));
resaleDesk.move(tickets, address(bob), address(resaleDesk), id); // no longer approved
}
}ticket 1 now owned by bob? true
approval cleared? true
main() failed: reverted with reason: not authorized
safeTransferFrom and receivers
Plain transferFrom to a contract that doesn't know about NFTs locks the token forever. safeTransferFrom checks: if the recipient is a contract, it must implement onERC721Received and return its selector, otherwise the transfer reverts.
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4); // must return IERC721Receiver.onERC721Received.selector
}That callback hands control to the recipient, so it's also a reentrancy entry point: update ownership before calling it.
In production
Use OpenZeppelin's audited ERC721 and add only your logic:
import { ERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
contract Certificates is ERC721 {
uint256 private nextId = 1;
constructor() ERC721("TAD Certificates", "TADC") {}
function mint(address to) external { _safeMint(to, nextId++); }
}Test yourself
What distinguishes ERC-721 from ERC-20?
- ERC-721 tokens can't be transferred
- Each ERC-721 token is unique and identified by a tokenId
- ERC-721 has no events
- ERC-721 tokens have 18 decimals
Why does safeTransferFrom call onERC721Received on contract recipients?
- To charge a fee
- To make sure the recipient can handle NFTs, so tokens don't get stuck
- To mint a new token
- To update tokenURI
What happens to a single-token approval when the token is transferred?
- It stays
- It's cleared
- It moves to the new owner
- It becomes an operator approval