NFTs with ERC-721
ERC-721 is the standard for non-fungible tokens, where each token has a unique ID and its own owner. They are used for art, tickets, game items, domain names and membership passes.
Instead of one balance per address, the contract keeps a mapping from token ID to owner. balanceOf still counts the tokens each address holds, and ownerOf tells you who holds a given ID. Transfers move one specific ID at a time.
The image and traits usually live off-chain, because storing them on-chain is expensive. The tokenURI function returns a link to a JSON metadata file, often stored on IPFS so that it does not depend on one server.
Approvals work per token with approve, or for all of an owner's tokens with setApprovalForAll, which marketplaces use. Be careful granting the second one: it lets the operator move everything you own in that collection.
In real code use _safeMint and safeTransferFrom. They check that a receiving contract knows how to handle NFTs, so tokens do not get locked in contracts that cannot move them. The simplified example below leaves that out, and it lets anyone mint, to stay short.
contract SimpleNFT { string public name = "Pass"; string public symbol = "PASS"; string public baseURI = "ipfs://YOUR_CID/"; uint256 public nextId; mapping(uint256 => address) public ownerOf; mapping(address => uint256) public balanceOf; mapping(uint256 => address) public getApproved; event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); function mint() external returns (uint256 id) { id = nextId++; ownerOf[id] = msg.sender; balanceOf[msg.sender] += 1; emit Transfer(address(0), msg.sender, id); } function approve(address spender, uint256 id) external { require(ownerOf[id] == msg.sender, "Not owner"); getApproved[id] = spender; emit Approval(msg.sender, spender, id); } function transferFrom(address from, address to, uint256 id) external { require(ownerOf[id] == from, "Wrong owner"); require(msg.sender == from || msg.sender == getApproved[id], "Not allowed"); require(to != address(0), "Zero address"); delete getApproved[id]; balanceOf[from] -= 1; balanceOf[to] += 1; ownerOf[id] = to; emit Transfer(from, to, id); } function tokenURI(uint256 id) external view returns (string memory) { require(ownerOf[id] != address(0), "No such token"); return string.concat(baseURI, _toString(id), ".json"); } function _toString(uint256 v) internal pure returns (string memory) { if (v == 0) return "0"; uint256 len; for (uint256 n = v; n != 0; n /= 10) len++; bytes memory b = new bytes(len); while (v != 0) { len--; b[len] = bytes1(uint8(48 + v % 10)); v /= 10; } return string(b); } }
Try it yourself
Restrict mint so only the deployer can call it, and add a maximum supply of 100 tokens. Then compile.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.