Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 47 ยท Tokens and Standards

Building an ERC-20 Token

Build an ERC-20 token step by step: balances, transfer, approve, transferFrom, events, decimals and the allowance race, with a runnable stand-in.

A token on Ethereum is not a coin in the protocol. It is a contract that keeps a table of who owns how much, plus a few functions that change that table. If every token contract uses the same function names and behaves the same way, then wallets, exchanges and other contracts can handle any of them without special code. The most important such agreement is ERC-20, the standard for fungible tokens (every unit is interchangeable with every other, like dollars).

In this lesson you will read a complete, small ERC-20 in Solidity, and then rebuild the same logic in JavaScript so you can run it and test the rules. You will need mappings, events and custom errors from earlier lessons.

What ERC-20 requires

balanceOf How much does this address hold?
transfer Move your own tokens.
approve Let a spender use up to N of yours.
transferFrom The spender moves them, within the allowance.
1 / 2

The data and the interface

The whole token is two tables and one number:

  • balanceOf[owner]: how many base units each address holds
  • allowance[owner][spender]: how many units spender may still move on behalf of owner
  • totalSupply: the sum of all balances

The standard functions are totalSupply(), balanceOf(address), transfer(address,uint256), approve(address,uint256), allowance(address,address) and transferFrom(address,address,uint256), plus two events:

SOLIDITY
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);

transfer and transferFrom must return a bool, and must emit Transfer (minting emits it from the zero address, burning emits it to the zero address).

A complete token

Here is a compact implementation. This is read-only code; it runs on a real chain or in Remix, not on this site.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract SimpleToken {
    string public name = "Simple Token";
    string public symbol = "SMP";
    uint8 public constant decimals = 18;
    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    error InsufficientBalance(uint256 have, uint256 need);
    error InsufficientAllowance(uint256 have, uint256 need);
    error ZeroAddress();

    constructor(uint256 initialSupply) {
        _mint(msg.sender, initialSupply);
    }

    function transfer(address to, uint256 amount) external returns (bool) {
        _transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        uint256 allowed = allowance[from][msg.sender];
        if (allowed != type(uint256).max) {
            if (allowed < amount) revert InsufficientAllowance(allowed, amount);
            allowance[from][msg.sender] = allowed - amount;
        }
        _transfer(from, to, amount);
        return true;
    }

    function _transfer(address from, address to, uint256 amount) internal {
        if (to == address(0)) revert ZeroAddress();
        uint256 balance = balanceOf[from];
        if (balance < amount) revert InsufficientBalance(balance, amount);
        unchecked {
            balanceOf[from] = balance - amount; // safe: checked just above
        }
        balanceOf[to] += amount;
        emit Transfer(from, to, amount);
    }

    function _mint(address to, uint256 amount) internal {
        totalSupply += amount;
        balanceOf[to] += amount;
        emit Transfer(address(0), to, amount);
    }
}

A few choices worth noticing:

  • unchecked is justified only because the line above it proved balance >= amount. Compare Integers, Overflow and Checked Math.
  • Unlimited allowance. Many tokens treat type(uint256).max as "infinite" and skip the decrement, which saves a storage write on every transferFrom. Wallets often offer "unlimited approval" because of this.
  • Zero address. Sending to address(0) usually means a mistake, and the tokens would be lost, so it reverts.
  • Mint and burn are not part of the standard. The token above only mints once, in the constructor. Anything beyond that (a mint function, a cap) is your design, and needs access control.

Decimals

The EVM has no fractions, so a token stores whole base units. The decimals value tells interfaces how to display them: with 18 decimals, a balance of 1500000000000000000 shows as 1.5 tokens. It is only a display hint: nothing in the contract uses it. Most tokens pick 18 (like ETH and wei), but some, such as USDC, use 6. Never assume 18 when you integrate with another token; read decimals().

JS Base units and display units

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

No output.

A stand-in you can run

The class below mirrors the Solidity contract: same tables, same checks, same events, with BigInt amounts. It uses a msg.sender-style first argument to say who is calling, and throws Error("revert: ...") where the contract would revert. A real revert also undoes earlier changes, but here every check happens before any change, so there is nothing to undo.

JS An ERC-20 stand-in and its checks

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

No output.

The allowance race

approve has a well-known weakness. Suppose Alice has approved Bob for 100 and now wants to change it to 50. She sends approve(bob, 50). Transactions wait in a public pool before they are mined, so Bob can see it coming. If he sends transferFrom for 100 with a higher fee so it runs first, he spends the old 100. Then Alice's approve(bob, 50) lands and gives him a fresh 50, which he also spends. Bob has received 150 although Alice never wanted him to have more than 100.

JS Replaying the allowance race

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

No output.

Practical defenses:

  • Approve the exact amount you need, and approve again only after the previous allowance is used up.
  • Reset to zero first (approve(spender, 0)), confirm that Bob did not spend in the meantime, and only then set the new value. Some tokens even require this.
  • Use increase/decrease helpers. They add or subtract relative to the current allowance, so the old and new values cannot be double-spent. Recent OpenZeppelin versions no longer ship them, so check what your library version offers.
  • Prefer permit-style approvals (EIP-2612), where the owner signs an off-chain message and the spender submits it; see ERC-1155, ERC-4626 and Friends.

What is real: the two tables, the transfer and transferFrom rules, the events, base units and the front-running race. What is the stand-in: a JavaScript class instead of bytecode, addresses as plain strings, no gas, no real transaction ordering (the race is replayed by hand), and no ABI. The Solidity above is read-only: copy it into Remix to run it for real.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does approve(spender, amount) do?

    approve only records an allowance. Tokens move when the spender later calls transferFrom, and each use lowers the remaining allowance.
  2. 2. A token has 6 decimals and a balance of 2500000. What amount does a wallet display?

    Display value = base units divided by 10^decimals, so 2,500,000 / 1,000,000 = 2.5. The contract itself only ever sees the integer.
  3. 3. Why is it risky to change an allowance from 100 straight to 50?

    Because pending transactions are public, the spender can get a transferFrom mined before your approval. Reset to zero first, approve exact amounts, or use permit-style approvals.
  4. 4. Which event must a successful transfer emit?

    ERC-20 requires a Transfer(from, to, value) event for every movement, including minting (from the zero address) and burning (to the zero address).

Summary

  • ERC-20 is a standard interface for fungible tokens: balanceOf, transfer, approve, allowance, transferFrom and the Transfer and Approval events.
  • A token is just two tables and a total supply; decimals is only a display hint, so never assume 18.
  • approve plus transferFrom lets other contracts pull tokens within an allowance.
  • Revert on insufficient balance, insufficient allowance and the zero address, and use unchecked only after proving safety.
  • The allowance race lets a spender use both the old and new value; approve exact amounts, reset to zero, or use permit.
  • Mint, burn and caps are not in the standard: design them carefully and protect them with access control.

Next: ERC-721 NFTs.