TExcelTAD
Home › Solidity › ERC-20 Tokens

ERC-20 Tokens

ERC-20 is the standard interface for fungible tokens: tokens where every unit is interchangeable, like points in a loyalty program, governance votes, or in-game currency. Because every ERC-20 token exposes the same functions and events, wallets, exchanges and other contracts can handle any of them without custom code.

In this lesson you'll write a complete ERC-20 token from scratch. It is a learning exercise: the token lives only in the playground and has no value.

The interface

solidity
interface IERC20 {
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 value) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 value) external returns (bool);
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

Plus optional metadata: name(), symbol() and decimals(). decimals is only for display: with 18 decimals, a balance of 1500000000000000000 is shown as 1.5.

Two ways to move tokens

  1. transfer(to, value): the holder sends their own tokens.
  2. approve(spender, value) + transferFrom(from, to, value): the holder allows another account (often a contract, such as a shop or an exchange) to move up to value tokens on their behalf. This is how contracts "pull" tokens as payment.

A complete token

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract StudyToken {
    string public constant name = "Study Token";
    string public constant symbol = "STUDY";
    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(address from, uint256 balance, uint256 needed);
    error InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
    error InvalidReceiver(address to);

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

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

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

    function transferFrom(address from, address to, uint256 value) external returns (bool) {
        uint256 allowed = allowance[from][msg.sender];
        if (allowed < value) revert InsufficientAllowance(msg.sender, allowed, value);
        if (allowed != type(uint256).max) {          // "infinite" approvals are not decreased
            allowance[from][msg.sender] = allowed - value;
        }
        _transfer(from, to, value);
        return true;
    }

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

    function _mint(address to, uint256 value) internal {
        totalSupply += value;
        balanceOf[to] += value;
        emit Transfer(address(0), to, value);        // minting = transfer from address(0)
    }
}

contract Main {
    function main() external {
        StudyToken token = new StudyToken(1000 ether);   // 1000 tokens with 18 decimals
        address alice = address(0xA11CE);

        token.transfer(alice, 250 ether);
        console.log(token.name(), token.symbol(), token.decimals());
        console.log("supply:", token.totalSupply() / 1e18);
        console.log("Main  :", token.balanceOf(address(this)) / 1e18);
        console.log("alice :", token.balanceOf(alice) / 1e18);
    }
}
Study Token STUDY 18
supply: 1000
Main  : 750
alice : 250
event Transfer(from: 0x0000000000000000000000000000000000000000, to: 0x5FbDB2315678afecb367f032d93F642f64180aa3, value: 1000000000000000000000)
event Transfer(from: 0x5FbDB2315678afecb367f032d93F642f64180aa3, to: 0x00000000000000000000000000000000000A11cE, value: 250000000000000000000)

1000 ether is just a convenient way to write 1000 * 10**18; it has nothing to do with ether here. The first Transfer event comes from the constructor (the mint), the second from transfer.

approve and transferFrom in action

A shop contract takes payment in tokens. The buyer first approves the shop, then the shop pulls exactly the price:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract MiniToken {
    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);

    constructor(address holder, uint256 amount) {
        balanceOf[holder] = amount;
    }

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

    function transferFrom(address from, address to, uint256 value) external returns (bool) {
        require(allowance[from][msg.sender] >= value, "allowance too low");
        require(balanceOf[from] >= value, "balance too low");
        allowance[from][msg.sender] -= value;
        balanceOf[from] -= value;
        balanceOf[to] += value;
        emit Transfer(from, to, value);
        return true;
    }
}

contract Shop {
    MiniToken public immutable token;
    uint256 public constant PRICE = 30;
    mapping(address => uint256) public itemsBought;

    constructor(MiniToken t) { token = t; }

    function buy() external {
        require(token.transferFrom(msg.sender, address(this), PRICE), "payment failed");
        itemsBought[msg.sender] += 1;
    }
}

contract Customer {
    function approve(MiniToken t, address spender, uint256 v) external { t.approve(spender, v); }
    function buy(Shop s) external { s.buy(); }
}

contract Main {
    function main() external {
        Customer carol = new Customer();
        MiniToken token = new MiniToken(address(carol), 100);
        Shop shop = new Shop(token);

        carol.approve(token, address(shop), 60);     // allow two purchases
        carol.buy(shop);
        carol.buy(shop);
        console.log("carol items :", shop.itemsBought(address(carol)));
        console.log("carol tokens:", token.balanceOf(address(carol)));
        console.log("shop tokens :", token.balanceOf(address(shop)));
        console.log("allowance left:", token.allowance(address(carol), address(shop)));
        carol.buy(shop);                              // third purchase: not approved
    }
}
carol items : 2
carol tokens: 40
shop tokens : 60
allowance left: 0
main() failed: reverted with reason: allowance too low

Things to watch out for

  • Approval race: changing a non-zero allowance directly to another non-zero value lets a watching spender use both. Set it to 0 first, or use increaseAllowance-style helpers.
  • Infinite approvals (type(uint256).max) are convenient but risky if the spender contract is compromised. Approve only what you need.
  • Non-standard tokens: some well-known tokens don't return a bool from transfer, or charge a fee on transfer. Libraries like OpenZeppelin's SafeERC20 handle these differences.
  • Tokens sent to contracts that don't expect them are lost forever; ERC-20 has no receive hook.
  • In production, start from the audited OpenZeppelin implementation:
solidity
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract StudyToken is ERC20 {
    constructor() ERC20("Study Token", "STUDY") {
        _mint(msg.sender, 1000 * 10 ** decimals());
    }
}

Test yourself

How does a shop contract take token payments under ERC-20?

  1. It calls transfer on the buyer's behalf
  2. The buyer calls approve(shop, amount), then the shop calls transferFrom(buyer, shop, amount)
  3. The buyer sends ether
  4. The shop edits balanceOf directly

What does decimals() == 18 mean?

  1. The token has 18 holders
  2. Balances are integers; UIs divide by 10^18 for display
  3. Only 18 tokens exist
  4. Transfers take 18 blocks

Which event does a correct ERC-20 emit when tokens are minted?

  1. Mint(to, value) only
  2. Transfer(address(0), to, value)
  3. Approval(address(0), to, value)
  4. No event