Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 41 ยท Smart Contracts

Tokens, ERC-20 and NFTs

Learn fungible and non-fungible tokens: the ERC-20 interface, balances, allowances, mint and burn, and NFT metadata, with live Python models of each.

A token is a record kept inside a smart contract that says who owns how much of something. There is no coin file and no wallet that "contains" tokens. The contract holds a table, such as balances[address] = amount, and the only way to change that table is to call the contract's functions. Everything you hear about stablecoins, game items, loyalty points and digital collectibles comes down to a small contract with a table in it.

Because thousands of wallets, exchanges and apps need to work with thousands of tokens, the community agrees on standards: fixed function names and behaviors every token contract should offer. The two best known are ERC-20 (interchangeable tokens) and ERC-721 (unique tokens, or NFTs). In this lesson you will build a Python model of each, using the same ideas as the toy engine from Building a Toy Smart Contract Engine and the contract you read in Reading Solidity: A First Contract.

Fungible and non-fungible

Something is fungible when one unit is as good as any other unit. One dollar bill can replace any other dollar bill, and one unit of a token can replace any other unit of the same token. Fungible tokens only need a number per owner.

Something is non-fungible when each item is distinct. A concert seat, a house deed or a specific piece of digital art cannot be swapped for "any other one". Non-fungible tokens need an identity per item (a token ID) and a record of who owns each ID.

flowchart LR
    A["Fungible (ERC-20)<br/>balances: address to amount"] --> A1["alice: 70<br/>bob: 30"]
    B["Non-fungible (ERC-721)<br/>owners: token id to address"] --> B1["#1 to alice<br/>#2 to bob<br/>#3 to alice"]

A fungible token stores amounts per address; a non-fungible token stores one owner per token ID.

The ERC-20 interface

ERC-20 defines the functions and events a fungible token offers. Any wallet or exchange that understands the standard can handle your token without special code.

Function Purpose
name(), symbol(), decimals() Display information (all optional in the original text, but nearly universal)
totalSupply() How many units exist
balanceOf(owner) Units held by an address
transfer(to, amount) Move units from the caller to to
approve(spender, amount) Let spender take up to amount from the caller later
allowance(owner, spender) How much spender may still take from owner
transferFrom(from, to, amount) Spender moves units from from to to, within the allowance

It also defines two events: Transfer(from, to, value) and Approval(owner, spender, value). Events are written to the transaction's log, which is how block explorers and apps follow token movements without scanning storage.

Amounts are integers

Contracts have no floating-point numbers. A token with decimals = 18 stores amounts in its smallest unit: one "whole" token is 10**18 units, just like a dollar is 100 cents. Wallets divide by 10**decimals only when they display a balance. Always do contract math on the integer amounts.

An ERC-20 model in Python

The model below mirrors a real implementation. A failed require becomes an exception, and a call that reverts changes nothing. Notice that minting emits a Transfer from the zero address, and burning emits a Transfer to the zero address; that is how the standard marks new and destroyed supply.

Python A tiny ERC-20 model

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the raw balances: {'alice': 7450, 'bob': 2050}. The "decimal" amounts exist only in the display. The total supply, 9500, equals the sum of balances. That equation, supply = sum of all balances, is the invariant every token contract must protect.

Allowances: letting a contract spend for you

A contract cannot reach into your wallet. Suppose you want to swap tokens on an exchange contract. The exchange needs to pull your tokens, but only the owner can call transfer. The standard solves this in two steps:

  1. You call approve(exchange, amount) on the token. The token records allowances[(you, exchange)] = amount.
  2. The exchange later calls transferFrom(you, pool, amount). The token checks the exchange's allowance, reduces it, and moves the tokens.
sequenceDiagram
    participant U as User
    participant T as Token contract
    participant X as Exchange contract
    U->>T: approve(Exchange, 40)
    U->>X: swap(40)
    X->>T: transferFrom(User, Exchange, 40)
    T-->>X: allowance 40 becomes 0, balances updated

Two transactions: the user grants permission, then the exchange spends it.

Python approve and transferFrom

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An allowance is a standing permission. Many wallet drains happen because users approved a malicious or buggy contract for an unlimited amount (2**256 - 1) and forgot about it. Approve only what you need, and revoke allowances you no longer use. Also note that changing an allowance from one non-zero value to another has a known race: a spender can use the old value and the new one. Safer token versions offer increaseAllowance and decreaseAllowance, or require you to reset to zero first.

Mint, burn and who is in control

The ERC-20 standard does not say how supply is created. Common designs are:

  • Fixed supply: all units are minted in the constructor. Nobody can ever create more.
  • Owner-controlled minting: an admin address can mint (as in the model above). Convenient, but holders must trust that admin.
  • Rule-based minting: the contract mints when something happens, for example when you deposit collateral, and burns when you repay.

Burning permanently removes units from supply. Pausing, blacklisting and upgrade features exist in some tokens too. Each one is a power someone holds, so reading who can do what is part of understanding any token. See Smart Contract Security Pitfalls for how missing access checks go wrong.

NFTs: the ERC-721 idea

An ERC-721 contract tracks owners per token ID instead of balances per address. Its core functions are ownerOf(tokenId), balanceOf(owner) (how many NFTs an address holds), transferFrom, approve for a single token and setApprovalForAll for an operator such as a marketplace. It also has a tokenURI(tokenId) function that returns where the token's description lives.

Metadata usually lives off-chain

Storing an image on a blockchain is extremely expensive, so most NFTs store a short URI pointing to a JSON file, and that JSON points to the image. What the chain guarantees is the ownership record, not that the image will stay available. If the URI points to a normal web server, the owner of that server can change or delete the file. Content-addressed storage such as IPFS puts the file's hash in the URI, so the content cannot change without the address changing. A fully on-chain NFT is the exception.

Python An ERC-721 style model with metadata

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Token IDs are unique, an approval is cleared on transfer, and only the owner or an approved address may move a token. Real contracts add events, safe-transfer checks for receiving contracts, and optional extensions such as enumeration and royalties information.

Other standards you will meet

  • ERC-1155 holds many token types in one contract, both fungible and non-fungible, and supports batch transfers. Games like it.
  • ERC-4626 standardizes tokenized vaults (deposit assets, receive shares).
  • ERC-2612 permit lets a user approve with a signature instead of a transaction, saving a step.

A standard is only an agreement about the interface. A contract can claim to be ERC-20 and still contain surprises, such as fees on transfer or a hidden minting function, so always read the code or trust an audit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What distinguishes a non-fungible token from a fungible one?

    Fungible tokens track amounts per address. Non-fungible tokens track an owner per token ID, because each item is distinct.
  2. 2. Why does a token with 18 decimals store 1.5 tokens as 1500000000000000000?

    Decimals only tell wallets how to display the integer. All contract arithmetic uses whole units, like cents instead of dollars.
  3. 3. An exchange contract wants to pull 40 tokens from you. What must happen first?

    Only the holder can move tokens with transfer. The holder grants an allowance with approve, and then the spender calls transferFrom.
  4. 4. Which invariant must an ERC-20 contract protect?

    Mint and burn adjust the supply together with a balance, and transfers only move units. If the sum and the supply disagree, the accounting is broken.
  5. 5. Where does an NFT's image normally live?

    Storing images on-chain is costly, so tokenURI usually points to a JSON file and an image elsewhere. The chain proves ownership, not that the file stays available.

Summary

  • A token is a table inside a contract; wallets show it, but the contract owns the data.
  • ERC-20 standardizes fungible tokens: balanceOf, transfer, approve, allowance, transferFrom and the Transfer and Approval events.
  • Amounts are integers of the smallest unit; decimals is only for display.
  • Allowances let contracts spend on your behalf; unlimited approvals are a common risk.
  • Minting and burning change supply, and whoever may mint holds real power.
  • ERC-721 tracks one owner per token ID, and the metadata and image usually live off-chain.

Next: Smart Contract Security Pitfalls, where small mistakes in code like this cost real money.