Track 5 · Tokens · lesson 2
ERC-20 from scratch
20 min
Track 5 · Tokens · lesson 2
20 min
You will never write an ERC-20 by hand in production. You will import OpenZeppelin's, like everyone else.
Write one anyway, once. Every token you ever read, audit or exploit is this file with additions.
ERC-20 is not code. It is an agreed list of function signatures — a promise that if your contract exposes these, every wallet, exchange and protocol on earth can use it without knowing anything else about you.
That is the whole innovation. Not the transfers, the interoperability.
Six functions and two events. That is the entire standard:
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);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
name, symbol and decimals are optional extras that everything relies on
anyway.
Nothing is written for you. Work top down: state, constructor, then the three functions that change things.
Minting emits a Transfer from the zero address. Nothing enforces it, but
every explorer and wallet builds its picture of a token from Transfer events.
Skip it at mint time and your initial supply appears to come from nowhere —
which usually reads as a scam.
decimals is display-only. The contract stores plain integers. decimals = 18 is a note to interfaces saying "put the point 18 digits from the right".
The contract never divides by anything.
Predict
Check