Building an ERC-20 token
ERC-20 is the standard for fungible tokens, where every unit is identical and interchangeable, like stablecoins, governance tokens and in-game currencies. A standard means wallets, exchanges and other contracts can work with any token the same way.
The standard defines the functions totalSupply, balanceOf, transfer, approve, allowance and transferFrom, and two events, Transfer and Approval. A token is really just a contract with a mapping of balances and these functions.
The approve and transferFrom pair lets another contract, such as an exchange, move tokens on your behalf up to an allowance you set. You first approve the exchange, and then the exchange calls transferFrom. This lets a contract take payment without you sending tokens to an address that cannot send them back.
Tokens use whole numbers, so decimals says where the decimal point goes. With 18 decimals, one token is 10^18 units, the same scale as ether and wei. Always do the math in the smallest unit and only format numbers for display in the frontend.
The example below builds a token from scratch to show how small the core is. In production, use OpenZeppelin's ERC20, which handles many edge cases, as you will see in the OpenZeppelin lesson.
contract MyToken { string public name = "My Token"; string public symbol = "MTK"; 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 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); constructor() { totalSupply = 1_000_000 * 10 ** 18; // 1 million tokens balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function transfer(address to, uint256 amount) external returns (bool) { _move(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) { require(allowance[from][msg.sender] >= amount, "Allowance too low"); allowance[from][msg.sender] -= amount; _move(from, to, amount); return true; } function _move(address from, address to, uint256 amount) internal { require(to != address(0), "Zero address"); require(balanceOf[from] >= amount, "Low balance"); balanceOf[from] -= amount; balanceOf[to] += amount; emit Transfer(from, to, amount); } }
Try it yourself
Add a mint(address to, uint256 amount) function that only the deployer can call and that emits Transfer from address(0). Then add a burn function that reduces totalSupply.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.