Sub topic 2
Token standards: how ERC-20 tracks balances
This chapter assumes you know what a smart contract is, that wallets control addresses through private keys, and that you can read short Solidity or Python snippets. It explains how a token exists on a chain, what the ERC-20 standard requires, and which behaviors the standard leaves open. Later chapters rely on this: governance tokens extend ERC-20, and liquidity pools only work because every ERC-20 exposes the same functions.
A token is a ledger inside a contract
A wallet does not hold tokens. Your address appears as a key in a table stored by the token's smart contract, and the value next to it is your balance. When you "send" a token, you call a function on that contract. The function subtracts from one entry, adds to another, and announces the change.
Ethereum's native coin, ETH, is different. The protocol itself tracks ETH balances. A token is only as trustworthy as its contract code.
An ERC-20 token is a contract that follows a shared interface, defined in Ethereum Improvement Proposal 20. A standard matters because wallets, exchanges, and pools can then treat any compliant token the same way. They call balanceOf without knowing anything about the token's purpose. A utility token, a governance token, and a memecoin all look identical at this layer.
The required interface
ERC-20 defines six functions and two events.
| Member | Kind | Purpose |
|---|---|---|
| `totalSupply()` | view function | Total number of units in existence |
| `balanceOf(owner)` | view function | Units held by an address |
| `transfer(to, value)` | function | Move units from the caller to `to` |
| `approve(spender, value)` | function | Let `spender` withdraw up to `value` from the caller |
| `allowance(owner, spender)` | view function | Remaining amount `spender` may withdraw |
| `transferFrom(from, to, value)` | function | Move units from `from` to `to`, using the caller's allowance |
| `Transfer(from, to, value)` | event | Logged on every movement, including minting and burning |
| `Approval(owner, spender, value)` | event | Logged when an allowance is set |
The functions name(), symbol(), and decimals() are optional in the specification. Nearly every token implements them, and interfaces rely on them.
Two ways to move tokens
transfer is the direct path: you call it, and your balance decreases.
transferFrom is the delegated path. It exists because a contract cannot reach into your wallet. If you want to deposit tokens into a pool or a staking contract, you first call approve on the token, naming that contract as the spender. The contract then calls transferFrom to pull the tokens. This is why most DeFi interactions require two transactions: an approval, then the action.
A ledger model in Python
The following program models only the storage and rules, with no blockchain. It is a teaching sketch and not a token you could deploy.
class Token:
def __init__(self, supply, owner):
self.total_supply = supply
self.balances = {owner: supply}
self.allowances = {} # (owner, spender) -> remaining amount
def balance_of(self, account):
return self.balances.get(account, 0)
def transfer(self, sender, to, value):
if self.balance_of(sender) < value:
raise ValueError("insufficient balance")
self.balances[sender] -= value
self.balances[to] = self.balance_of(to) + value
print(f"Transfer({sender} -> {to}, {value})")
def approve(self, owner, spender, value):
self.allowances[(owner, spender)] = value
print(f"Approval({owner}, {spender}, {value})")
def transfer_from(self, spender, owner, to, value):
allowed = self.allowances.get((owner, spender), 0)
if allowed < value:
raise ValueError("insufficient allowance")
self.allowances[(owner, spender)] = allowed - value
self.transfer(owner, to, value)
token = Token(supply=1000, owner="alice")
token.transfer("alice", "bob", 100)
token.approve("alice", "pool", 300)
token.transfer_from("pool", "alice", "pool", 250)
print(token.balance_of("alice"), token.balance_of("pool"))The output ends with 650 250. Alice started with 1000, sent 100 to Bob, and the pool pulled 250 using its allowance. The remaining allowance is 50. Total supply is unchanged, because transfers only move units between entries.
The same logic in Solidity
Production tokens normally inherit from OpenZeppelin, as the memecoin example later in this tutorial does. Writing the core by hand once shows what the library does.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleToken {
string public constant name = "Simple Token";
string public constant symbol = "SIM";
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);
constructor(uint256 supply) {
totalSupply = supply;
balanceOf[msg.sender] = supply;
emit Transfer(address(0), msg.sender, supply);
}
function transfer(address to, uint256 value) external returns (bool) {
_move(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];
require(allowed >= value, "insufficient allowance");
allowance[from][msg.sender] = allowed - value;
_move(from, to, value);
return true;
}
function _move(address from, address to, uint256 value) internal {
require(balanceOf[from] >= value, "insufficient balance");
balanceOf[from] -= value;
balanceOf[to] += value;
emit Transfer(from, to, value);
}
}Three details deserve attention:
- Minting is a
Transferevent from the zero address. Burning is aTransferto the zero address. Indexers rely on this convention to track supply. - Solidity 0.8 and later reverts on arithmetic overflow, so the subtraction cannot silently wrap around.
- The constructor mints once and there is no other minting path. Supply is therefore fixed. A token with a public
mintfunction guarded by an owner role has a different supply policy, which the tokenomics chapter covers.
Decimals: integers only
The EVM has no floating-point numbers. Balances are whole integers of the smallest unit. The decimals value tells interfaces where to place the decimal point. With decimals = 18, the stored integer 1500000000000000000 is displayed as 1.5.
The default of 18 mirrors ETH, but it is a convention. USDC uses 6 and WBTC uses 8. Contracts that handle several tokens must read each token's decimals instead of assuming 18. Decimals affect display only, and the contract never knows about them when doing arithmetic.
What the standard does not guarantee
ERC-20 fixes function names and signatures. It does not fix behavior beyond that, and the gaps cause most integration bugs.
- Missing return values. Some older tokens, including USDT on Ethereum, do not return a
boolfromtransferorapprove. A caller that expects one will revert. Integrators use OpenZeppelin'sSafeERC20wrapper to handle this. - Fee-on-transfer tokens. Some tokens deduct a tax during
transfer, so the recipient receives less thanvalue. A contract that credits users withvalueinstead of measuring its actual balance change will be out of funds. - Rebasing tokens. Some tokens change balances automatically without a
Transferper holder, which breaks code that caches balances. - Hidden controls. A compliant interface can sit on a contract that lets an owner pause transfers, blacklist addresses, or mint without limit. The standard says nothing about this, so the code must be read.
- No receiver check.
transferto a contract address succeeds even if that contract cannot ever send tokens out. Those tokens are stuck permanently. - Impersonation. Anyone can deploy a token named "USDC". The name and symbol are labels, not identities. The contract address is the identity.
Approvals and permit
The two-transaction approval flow costs gas and confuses users. The ERC-2612 extension, called permit, lets a holder sign an approval off-chain. The spender submits that signature in the same transaction as the action. The governance token example in this tutorial uses ERC20Permit for this reason. Permit uses a per-owner nonce, so each signature works once.
Other token standards
ERC-20 covers fungible tokens, where every unit is interchangeable. Other standards address different needs.
| Standard | Token model | Typical use |
|---|---|---|
| ERC-20 | Fungible | Utility, governance, memecoins, stablecoins |
| ERC-721 | Non-fungible, one owner per token ID | Unique items and collectibles |
| ERC-1155 | Mixed fungible and non-fungible in one contract | Game items, batch transfers |
Other chains have their own equivalents. BNB Smart Chain uses BEP-20, which is nearly identical to ERC-20. Solana uses the SPL Token program, where balances live in separate token accounts instead of one contract's mapping. The concept of a shared ledger standard carries across, while the implementation differs.
Reading a token contract: a quick routine
When you meet an unfamiliar ERC-20, a block explorer lets you check several things quickly:
- Confirm the contract address from an official source, not from the symbol.
- Read
totalSupplyanddecimals, and compare the supply to what the project claims. - Check for functions beyond the six required ones:
mint,pause,blacklist,setFee,owner. - Look at the largest holders and whether the contract source is verified.
The later chapters on tokenomics, rug pulls, and due diligence build on this routine.
Exercise
A staking contract calls transferFrom(alice, stakingContract, 100) on a token, but the call reverts even though Alice's balance is 500. Name the most likely cause and the step Alice must take.
Show answer
Alice has not approved the staking contract as a spender, or the allowance is below 100. The transferFrom function checks allowance[alice][stakingContract], which is separate from her balance. Alice must call approve(stakingContract, 100) (or a larger amount) on the token contract first, or sign a permit if the token supports it.
Exercise
A token has decimals = 6. A wallet displays a balance of 2.5 tokens. What integer does the contract store for that balance, and what would the display show if the same integer were stored in a token with decimals = 18?
Show answer
The contract stores 2,500,000 (2.5 × 10^6). With decimals = 18 the same integer would display as 0.0000000000025, because the interface divides by 10^18.