ERC-20 Token — Web3

ERC-20 is the interface standard for fungible tokens: totalSupply, balanceOf, transfer, approve, allowance, transferFrom, plus the Transfer (topic0…

The RakaPoints we've written so far has earn and redeem, but Dinda can't yet give her PTS to Yoga, and wallets and exchanges can't move it either, because there's no standard function for them to call. The way out is a standard plug. Any appliance with a standard plug works in any socket, with no special adapter. For tokens, that plug is called ERC-20, the interface standard for fungible tokens on Ethereum: tokens whose every unit is exactly the same and interchangeable, like money or PTS. The standard is just a list of functions and events that must exist, with agreed names and behaviour. Wallets, exchanges and block explorers are the sockets: once RakaPoints follows ERC-20, all of them can show and move PTS straight away, with no extra code.

What the ERC-20 standard holds

Function / event What it's for
totalSupply() the number of tokens in circulation
balanceOf(account) an address's balance
transfer(to, value) moving your own tokens
approve(spender, value) letting another address use your tokens up to value
allowance(owner, spender) what is left of that permission
transferFrom(from, to, value) spender moves from's tokens, cutting the allowance
event Transfer(from indexed, to indexed, value) emitted on every token move, mint and burn included
event Approval(owner indexed, spender indexed, value) emitted on every approve

name(), symbol() and decimals() are optional, but nearly every token has them. The old RakaPoints already had balanceOf, totalSupply and the three optional ones, but no transfer, approve, allowance or transferFrom, so it wasn't ERC-20 yet.

RakaPoints as an ERC-20 with OpenZeppelin

Writing an ERC-20 yourself is easy to get wrong. OpenZeppelin Contracts is an audited, widely used contract library; its latest version on npm as of October 2026 is 5.6.1.

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

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract RakaPoints is ERC20, Ownable {
    event Earned(address indexed customer, uint256 amount);
    event Redeemed(address indexed customer, uint256 amount);

    constructor() ERC20("Raka Points", "PTS") Ownable(msg.sender) {}

    function earn(address customer, uint256 cents) external onlyOwner {
        uint256 amount = pointsFor(cents);
        _mint(customer, amount);
        emit Earned(customer, amount);
    }

    function redeem(uint256 amount) external {
        _burn(msg.sender, amount);
        emit Redeemed(msg.sender, amount);
    }

    function pointsFor(uint256 cents) public pure returns (uint256) {
        return (cents / 100) * 10 ** 18;
    }
}
npm install @openzeppelin/[email protected] [email protected]
npx solcjs --abi --bin --include-path node_modules/ --base-path . RakaPoints.sol -o build

On a fresh local chain, the deploy is again account #0's first transaction, so the address is still 0x5FbDB2315678afecb367f032d93F642f64180aa3 (1,229,240 gas, nearly twice the old version because it does more). Raka then records the same four purchases: Dinda 160 PTS, Yoga 115 PTS, totalSupply 275.

transfer: moving your own tokens

Dinda gives Yoga 20 PTS:

await dinda.writeContract({ address: PTS, abi, functionName: 'transfer', args: [YOGA, parseUnits('20', 18)] })
Dinda Yoga totalSupply
before 160 115 275
after (block 6) 140 135 275

Its receipt holds one Transfer(Dinda, Yoga, 20 PTS) log with topic0 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, the keccak256 of Transfer(address,address,uint256). That topic is the same for every ERC-20 token in the world, which is how an explorer can show the history of any token.

approve, allowance, transferFrom: permission for someone else

Dinda's tokens aren't stored in her wallet but in the contract's mapping. Another contract (or address) can't take them without permission. Take PointsSwap, an outside app that swaps PTS for vouchers. On the local chain it's played by test account #4 (0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65). It takes two steps:

  1. Dinda: approve(PointsSwap, 100 PTS) → event Approval(Dinda, PointsSwap, 100), allowance(Dinda, PointsSwap) = 100.
  2. PointsSwap: transferFrom(Dinda, PointsSwap, 30 PTS) → event Transfer(Dinda, PointsSwap, 30), 70 of the allowance left, Dinda's balance 110.

So approve is needed because the token owner must give permission first before anyone else may move their tokens. If PointsSwap asks for more, the contract refuses. viem's real message:

Error: ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)
                                 (0x15d34AAf54267DB7D7c367839AAf71A00a2C6A65, 70000000000000000000, 80000000000000000000)

Inside it's only a nested mapping. This is the core logic written by hand (compiled with solc 0.8.37); OpenZeppelin does the same with neater checks and errors:

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

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];
    require(allowed >= value, "allowance too low");
    allowance[from][msg.sender] = allowed - value;
    balanceOf[from] -= value;
    balanceOf[to] += value;
    emit Transfer(from, to, value);
    return true;
}

decimals are only for display

There are no fractions inside the contract: Dinda's balance is stored as 140000000000000000000. decimals() = 18 only tells the wallet where to put the decimal point: formatUnits(140000000000000000000n, 18) = '140'. The same raw number with decimals 6 would show as 140,000,000,000,000. That's why USDC (6 decimals) and PTS (18 decimals) must each be handled with parseUnits/formatUnits using their own decimals().

The approve race: the danger of changing an allowance

Before you read on, guess: PointsSwap's remaining allowance is 70. Dinda changes her mind and sends approve(PointsSwap, 20) to lower it. At most how many PTS can PointsSwap take from that moment: 20, 70 or 90?

approve doesn't add or subtract; it overwrites the allowance. If Dinda changes 70 into 20, a dishonest PointsSwap can spot that transaction in the mempool and get ahead of it with a higher tip. This really happened on the Hardhat node (blocks mined by hand):

Order in block 9 From Tip Effect
1 PointsSwap: transferFrom(Dinda, PointsSwap, 70) 2 gwei the old 70 allowance is used up
2 Dinda: approve(PointsSwap, 20) 1 gwei a new allowance of 20

Then in block 10 PointsSwap takes another 20. From the moment Dinda decided to lower the allowance, PointsSwap took 90 PTS, not 20. Dinda is left with 20.

The safe way: approve only what is about to be used, right before it's used; to change an allowance, set it to 0 first, wait, check allowance, then set the new value; and revoke allowances you no longer use. OpenZeppelin 5 removed increaseAllowance and decreaseAllowance, so this is the pattern to use.

⚠️ Costly missteps with ERC-20 tokens

TL;DR: ERC-20 is the interface standard for fungible tokens: totalSupply, balanceOf, transfer, approve, allowance, transferFrom, plus the Transfer (topic0 0xddf252ad...) and Approval events. Use OpenZeppelin 5.6.1: contract RakaPoints is ERC20, Ownable, _mint only through onlyOwner, _burn for redeeming, standard errors such as ERC20InsufficientBalance. transfer moves your own tokens; approve then transferFrom lets someone else move your tokens within the allowance. decimals is only for display; balances are always whole numbers. approve overwrites the old value, so changing 70 to 20 can be front-run (PointsSwap got 90); approve only what's needed and revoke what you don't use.

⚡ ERC-20: a standard plug for tokens

Meaning: ERC-20 is the list of functions and events a fungible token must have: totalSupply, balanceOf, transfer, approve, allowance, transferFrom, plus the Transfer and Approval events. Once RakaPoints follows it, wallets and exchanges can move PTS straight away.

⚡ transfer: moving your own tokens

Write:

await dinda.writeContract({ address: PTS, abi, functionName: 'transfer', args: [YOGA, parseUnits('20', 18)] })

Meaning: Dinda's balance goes from 160 to 140, Yoga's from 115 to 135, and totalSupply stays at 275.

⚡ approve first, then transferFrom

Meaning: Dinda's tokens sit in the contract's mapping, not in her wallet. The token owner must give permission first with approve; only then may PointsSwap move them with transferFrom, and only up to what's left of the allowance.

⚡ approve overwrites, it doesn't subtract

Guess first: PointsSwap's remaining allowance is 70, then Dinda sends approve(PointsSwap, 20). At most how many PTS can PointsSwap take?

90 PTS. PointsSwap gets ahead with a higher tip and uses up the 70 first, then uses the new allowance of 20.

Meaning: To change an allowance, set it to 0 first, wait, check allowance, then set the new value.

What you will learn