Building an ERC20 Token From Scratch

Introduction
The ERC20 standard is the most widely adopted token interface on Ethereum. Every token you've ever traded on a decentralized exchange — USDC, DAI, UNI, LINK — follows this standard. But most developers use it by importing OpenZeppelin's library and moving on. That approach gets the job done, but it hides the mechanics that make or break a token contract.
This article takes the opposite approach. We will build an ERC20 token entirely from scratch — no imports, no libraries, no inherited contracts. Every line of code will be written by hand. The goal is not to reinvent the wheel, but to understand the wheel: how Solidity's data types map onto EVM storage, why the approval mechanism exists, how transferFrom updates allowances, why zero-address checks prevent permanent token loss, and what the infamous ERC20 race condition actually is.
If you are new to Solidity, this article is designed for you. Every concept is explained before its code appears, every code block includes inline comments, and every architectural decision is justified. By the end, you will not just know how ERC20 works — you will understand why it works the way it does.
Prerequisites: The EVM and Data Location
Before we write a single line of Solidity, we need to understand where our data lives. The Ethereum Virtual Machine (EVM) is the runtime environment that executes smart contracts. It is a stack-based, 256-bit virtual machine — meaning every native word it operates on is 32 bytes wide. This single fact shapes nearly every design decision in Solidity.
Storage
Storage is the permanent state of a smart contract. It persists between function calls and between transactions. Think of it as the contract's hard drive. Every contract gets its own isolated storage space, organized as a key-value store where both keys and values are 256 bits (32 bytes) wide.
When you declare a state variable in Solidity — for example, uint256 totalSupply; — the compiler assigns it a storage slot. The first state variable gets slot 0, the second gets slot 1, and so on. Mappings and dynamic arrays use a hashing scheme (keccak256) to compute their slot locations, which is how Solidity can support arbitrarily large mappings without pre-allocating space.
Storage is expensive. Writing a fresh 32-byte value to a new storage slot costs 20,000 gas. Modifying an existing slot costs 5,000 gas. Reading costs 2,100 gas for the first access in a transaction (cold) and 100 gas for subsequent accesses (warm). These costs are the reason Solidity developers obsess over minimizing storage writes.
Memory
Memory is temporary data that exists only during a single function call. It is a byte-addressable linear array that starts empty for every external call. Memory is much cheaper than storage — it costs 3 gas to read or write a 32-byte word — but the cost grows quadratically as the memory area expands. After the function returns, everything in memory is wiped.
You use memory for intermediate computations, function arguments for reference types like arrays and structs, and string manipulation. In our ERC20 contract, the name and symbol getters return string memory, meaning the string is copied from storage into memory for the caller.
Calldata
Calldata is a read-only, non-modifiable area that contains the input data of a transaction or message call. When someone calls transfer(address to, uint256 amount), the encoded function selector and arguments arrive in calldata. For external functions that receive reference types (arrays, bytes, strings), marking them as calldata instead of memory saves gas because it avoids copying the data.
The Stack
The EVM stack is where most computation happens. It holds up to 1,024 items, each 256 bits wide. Local value-type variables (like uint256, address, bool) live on the stack. Solidity's "Stack too deep" error occurs when a function uses more than about 16 local variables, because the EVM can only access the top 16 stack items directly.
Why This Matters for ERC20
Our ERC20 token will use all of these locations. The _balances mapping lives in storage because balances must persist across transactions. The name() function returns a string memory because the caller needs a temporary copy. Function parameters arrive through calldata (though Solidity abstracts this for value types). And every local uint256 variable inside our functions sits on the stack.
Understanding data location is not academic — it directly affects gas costs, security, and correctness. A developer who accidentally stores temporary data in storage instead of memory will cost their users thousands of gas per transaction. A developer who misunderstands how mapping slots are computed might assume two mappings can collide (they effectively cannot, thanks to keccak256).
Solidity Data Types — The Building Blocks
Solidity provides a rich type system designed around the constraints of the EVM. Let's walk through every type we'll use in our ERC20 contract, explaining not just what each type is, but why it is the right choice for its role.
Value Types
Value types are types where the variable directly holds the data. When you assign one value-type variable to another, Solidity copies the data. Modifying the copy does not affect the original.
uint256 — An unsigned (non-negative) 256-bit integer. It can represent values from 0 to 2²⁵⁶ − 1 (approximately 1.16 × 10⁷⁷). This is the native word size of the EVM, which means operations on uint256 are the cheapest and most natural. We use it for token balances, total supply, and allowances because token amounts must never be negative, and 256 bits provides enough range for any practical token supply — even with 18 decimals.
// A uint256 holding a token balance
// The EVM stores this as a single 32-byte word in one storage slot
uint256 private _totalSupply;
uint8 — An unsigned 8-bit integer (0 to 255). We use this specifically for decimals because the ERC20 standard defines it as returning a uint8. The value 18 (the most common choice) represents that the token's smallest unit is 10⁻¹⁸ of the display unit. Since uint8 only occupies 1 byte, the compiler may pack it with other small variables into a single 32-byte storage slot to save gas.
// uint8 is sufficient because decimals will never exceed 255
// In practice, values above 18 are rare
uint8 private _decimals;
address — A 20-byte value representing an Ethereum account (either an externally owned account or a contract). Under the hood, the EVM pads it to 32 bytes in storage slots, but Solidity treats it as a distinct type to prevent accidental misuse. We use address for the sender and recipient of tokens, for the owner who can mint, and in mapping keys to track per-account balances.
// An address takes 20 bytes but occupies a full 32-byte slot in storage
// unless packed with other small types
address private _owner;
bool — A boolean value, either true or false. Internally stored as a single byte (0 or 1) in the EVM but padded to 32 bytes in storage unless packed. Our ERC20 functions return bool to indicate success, as the standard requires. Many functions return true on success and revert on failure rather than returning false, which we'll discuss in depth later.
// The ERC20 standard requires transfer to return a bool
// In modern practice, this always returns true (and reverts on failure)
function transfer(address to, uint256 amount) public returns (bool) {
// ...
return true;
}
string — A dynamically-sized UTF-8 encoded text type. Strings in Solidity are reference types that are stored differently depending on their length. Short strings (31 bytes or fewer) are stored compactly in a single storage slot. Longer strings use a separate storage area addressed by the keccak256 hash of their slot number. We use string for the token's name and symbol.
// Strings are stored in storage but returned as memory copies
// Short strings like "MyToken" fit in one slot, saving gas
string private _name;
string private _symbol;
Reference Types
Reference types are types where the variable holds a pointer (a reference) to data stored elsewhere — in storage, memory, or calldata. Assigning a storage reference to another storage reference does not copy data; both point to the same location.
mapping(KeyType => ValueType) — The most important reference type in our ERC20 contract. A mapping is a hash table that maps keys to values. It can only exist in storage (you cannot have a memory mapping). Mappings do not have a length, cannot be iterated, and do not store their keys — they only store values at locations computed by keccak256(key, slot).
This is critical to understand: when you write _balances[someAddress], Solidity computes keccak256(abi.encode(someAddress, slotNumber)) to find the 32-byte storage slot that holds that address's balance. The address itself is never stored in the mapping — only the value is. This means you cannot enumerate all holders of a token just by reading storage. It also means every key effectively exists with a default value of zero; reading a key that was never written simply returns 0.
// Maps each address to its token balance
// Storage location of _balances[addr] = keccak256(addr . slot_of_balances)
// where "." means concatenation
mapping(address => uint256) private _balances;
Nested mappings — A mapping whose values are themselves mappings. We use mapping(address => mapping(address => uint256)) for allowances, where the outer key is the token owner, the inner key is the spender, and the value is the approved amount. The storage slot for _allowances[owner][spender] is computed as keccak256(spender . keccak256(owner . slot_of_allowances)) — a double hash.
// Nested mapping: owner => spender => allowance amount
// This two-level structure lets each owner authorize multiple spenders independently
mapping(address => mapping(address => uint256)) private _allowances;
Special Types and Expressions
msg.sender — A global variable of type address representing the account that directly called the current function. In the context of an ERC20 transfer, msg.sender is the person sending their tokens. This is the primary authentication mechanism in Solidity — there is no username/password system, only the cryptographic guarantee that the transaction was signed by the owner of that address.
type(uint256).max — A compile-time constant representing the maximum value of uint256: 2²⁵⁶ − 1, which is 115792089237316195423570985008687907853269984665640564039457584007913129639935. We use this for infinite approvals, as we'll discuss later.
address(0) (the zero address) — The Ethereum address 0x0000000000000000000000000000000000000000. This address is special: no one holds its private key, so tokens sent to it are permanently irrecoverable. This is why every well-written ERC20 contract checks that to != address(0) before transferring — it prevents accidental permanent token loss.
The Full ERC20 Implementation
Below is the complete, manually implemented ERC20 contract. Read through it once to get the big picture, then move on to the section-by-section breakdown where every piece is explained in detail.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title ManualERC20
* @author Built from scratch — no imports, no libraries, no inherited contracts.
* @notice A production-ready ERC20 token with mint, burn, and ownership management.
* @dev Implements the ERC20 standard (https://eips.ethereum.org/EIPS/eip-20) plus:
* - Custom errors (gas-efficient, Solidity 0.8.4+)
* - Mint with access control
* - Burn (holder burns their own tokens)
* - Ownership transfer and renouncement
* - increaseAllowance / decreaseAllowance (race condition mitigation)
*
* Storage layout:
* Slot 0: mapping _balances
* Slot 1: mapping _allowances
* Slot 2: uint256 _totalSupply
* Slot 3: string _name
* Slot 4: string _symbol
* Slot 5: uint8 _decimals + address _owner (packed — 1 + 20 = 21 bytes)
*/
contract ManualERC20 {
// ════════════════════════════════════════════════════════════════════════
// CUSTOM ERRORS (cheaper than require + string — saves ~50 gas per revert)
// ════════════════════════════════════════════════════════════════════════
/// @dev Thrown when a transfer is attempted from the zero address.
error ERC20InvalidSender(address sender);
/// @dev Thrown when a transfer or mint targets the zero address.
error ERC20InvalidReceiver(address receiver);
/// @dev Thrown when the sender's balance is less than the transfer amount.
/// @param sender The address whose balance is insufficient.
/// @param balance The current balance of the sender.
/// @param needed The amount that was requested.
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/// @dev Thrown when an approval is attempted from the zero address.
error ERC20InvalidApprover(address approver);
/// @dev Thrown when an approval targets the zero address as spender.
error ERC20InvalidSpender(address spender);
/// @dev Thrown when a transferFrom caller's allowance is insufficient.
/// @param spender The address attempting to spend.
/// @param allowance The current allowance.
/// @param needed The amount that was requested.
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/// @dev Thrown when a restricted function is called by a non-owner.
/// @param caller The unauthorized caller.
error OwnableUnauthorizedAccount(address caller);
/// @dev Thrown when ownership is being transferred to the zero address
/// via transferOwnership (use renounceOwnership instead for intentional renouncement).
error OwnableInvalidOwner(address owner);
// ════════════════════════════════════════════════════════════════════════
// EVENTS
// ════════════════════════════════════════════════════════════════════════
/**
* @dev Emitted when `value` tokens move from `from` to `to`.
*
* For minting: `from` is address(0) → signals new token creation.
* For burning: `to` is address(0) → signals token destruction.
* For transfer: neither is address(0) → standard movement.
*
* Events are stored in transaction logs (NOT in contract storage),
* making them cheaper to emit than storage writes. Off-chain systems
* (wallets, block explorers, The Graph) rely on these to track activity.
*
* `indexed` parameters become "topics" — Ethereum nodes can filter on them
* efficiently, e.g., "show me all transfers TO my address."
*/
event Transfer(
address indexed from, // indexed: filterable topic
address indexed to, // indexed: filterable topic
uint256 value // not indexed: stored in log data (cheaper)
);
/**
* @dev Emitted when `owner` sets or changes the allowance for `spender`.
*
* Emitted on every approve(), increaseAllowance(), decreaseAllowance(),
* and on every transferFrom() that deducts a non-infinite allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/**
* @dev Emitted when ownership is transferred from `previousOwner` to `newOwner`.
*
* Also emitted on renouncement, where `newOwner` is address(0).
*/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
// ════════════════════════════════════════════════════════════════════════
// STATE VARIABLES
// ════════════════════════════════════════════════════════════════════════
/// @dev Maps each address to its token balance.
/// Storage slot for _balances[addr] = keccak256(abi.encode(addr, 0))
mapping(address => uint256) private _balances;
/// @dev Maps owner → spender → approved amount.
/// Storage slot for _allowances[o][s] = keccak256(abi.encode(s, keccak256(abi.encode(o, 1))))
mapping(address => mapping(address => uint256)) private _allowances;
/// @dev Total number of tokens in existence.
/// Invariant: _totalSupply == sum of all _balances[addr] for every addr.
uint256 private _totalSupply;
/// @dev Human-readable name of the token (e.g., "USD Coin").
string private _name;
/// @dev Ticker symbol (e.g., "USDC").
string private _symbol;
/// @dev Number of decimal places for display ONLY.
/// Does NOT affect any math. A value of 18 means:
/// 1 full token = 1_000_000_000_000_000_000 smallest units (like wei to ether).
/// Frontends divide raw balances by 10^decimals for display.
uint8 private _decimals;
/// @dev The address with minting privileges.
/// Packed with _decimals in Slot 5 (1 byte + 20 bytes = 21 < 32).
address private _owner;
// ════════════════════════════════════════════════════════════════════════
// MODIFIERS
// ════════════════════════════════════════════════════════════════════════
/**
* @dev Restricts a function to the current owner.
* Reverts with OwnableUnauthorizedAccount if called by anyone else.
*/
modifier onlyOwner() {
if (msg.sender != _owner) {
revert OwnableUnauthorizedAccount(msg.sender);
}
_; // ← Execute the function body
}
// ════════════════════════════════════════════════════════════════════════
// CONSTRUCTOR
// ════════════════════════════════════════════════════════════════════════
/**
* @dev Sets the token metadata and mints the initial supply to the deployer.
*
* The constructor runs exactly once — during deployment. Its code is NOT
* included in the deployed bytecode and cannot be called again.
*
* @param tokenName Human-readable name (stored in storage).
* @param tokenSymbol Ticker symbol (stored in storage).
* @param tokenDecimals Display decimals (typically 18).
* @param initialSupply Tokens to mint to the deployer (in smallest units).
* For 1,000 tokens with 18 decimals: 1000 * 10**18.
*/
constructor(
string memory tokenName, // memory: constructor params are transient
string memory tokenSymbol,
uint8 tokenDecimals,
uint256 initialSupply
) {
// Store metadata: memory → storage (permanent)
_name = tokenName;
_symbol = tokenSymbol;
_decimals = tokenDecimals;
// Record deployer as owner — msg.sender in constructor is the deploying address
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
// Mint initial supply to deployer (if any)
if (initialSupply > 0) {
_mint(msg.sender, initialSupply);
}
}
// ════════════════════════════════════════════════════════════════════════
// ERC20 — PUBLIC VIEW FUNCTIONS (read-only, free to call off-chain)
// ════════════════════════════════════════════════════════════════════════
/**
* @notice Returns the human-readable name of the token.
* @dev The string is copied from storage into memory for the return value.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @notice Returns the ticker symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @notice Returns the number of decimal places for display formatting.
* @dev This value is purely cosmetic. The contract NEVER uses it in math.
* Frontends divide raw balances by 10^decimals for human display.
* Example: if decimals() == 18, a raw balance of 1_500_000_000_000_000_000
* should be displayed as "1.5" tokens.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @notice Returns the total number of tokens currently in existence.
* @dev Increases on mint, decreases on burn, unchanged on transfer.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @notice Returns the token balance of `account`.
* @dev Returns 0 for any address that has never received tokens —
* this is the default value of uint256 in a mapping.
* No account needs to be "registered" or "created."
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @notice Returns how many tokens `spender` is still allowed to withdraw from `owner`.
* @dev Returns 0 if no approval was ever set.
* Returns type(uint256).max if an infinite approval was granted.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
// ════════════════════════════════════════════════════════════════════════
// ERC20 — STATE-CHANGING FUNCTIONS
// ════════════════════════════════════════════════════════════════════════
/**
* @notice Transfers `amount` tokens from the caller to `to`.
* @dev Reverts if the caller's balance is insufficient or `to` is address(0).
* Emits a {Transfer} event.
* @param to The recipient address.
* @param amount The number of tokens to transfer (in smallest units).
* @return True if the transfer succeeded (always true; reverts on failure).
*/
function transfer(address to, uint256 amount) public returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
/**
* @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* @dev IMPORTANT: Changing an allowance from non-zero to non-zero is vulnerable
* to the ERC20 race condition. To safely change an allowance:
* 1. Call approve(spender, 0) first
* 2. Wait for confirmation
* 3. Call approve(spender, newAmount)
* Or use increaseAllowance() / decreaseAllowance() instead.
*
* Emits an {Approval} event.
*
* @param spender The address authorized to spend tokens.
* @param amount The maximum amount they can spend.
* @return True on success (always true; reverts on failure).
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @notice Transfers `amount` tokens from `from` to `to` using the allowance mechanism.
*
* @dev The caller (msg.sender) must have been pre-approved by `from` via approve().
* The allowance is deducted by `amount` unless it is type(uint256).max (infinite).
* Emits a {Transfer} event. May also emit an {Approval} event (allowance update).
*
* @param from The address to transfer tokens from.
* @param to The address to transfer tokens to.
* @param amount The number of tokens to transfer.
* @return True on success (always true; reverts on failure).
*/
function transferFrom(address from, address to, uint256 amount) public returns (bool) {
// Step 1: Check and deduct the caller's allowance
_spendAllowance(from, msg.sender, amount);
// Step 2: Perform the actual balance transfer
_transfer(from, to, amount);
return true;
}
// ════════════════════════════════════════════════════════════════════════
// RACE CONDITION MITIGATION — increaseAllowance / decreaseAllowance
// ════════════════════════════════════════════════════════════════════════
/**
* @notice Atomically increases the allowance granted to `spender` by `addedValue`.
*
* @dev This is the safe alternative to approve() for increasing an existing allowance.
* It reads the current allowance and adds to it in a single transaction,
* eliminating the window for the front-running race condition.
*
* Emits an {Approval} event with the updated allowance.
*
* @param spender The address whose allowance is being increased.
* @param addedValue The additional amount to add to the current allowance.
* @return True on success.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
address owner = msg.sender;
_approve(owner, spender, _allowances[owner][spender] + addedValue);
// Note: the addition above uses checked arithmetic (Solidity >=0.8).
// If currentAllowance + addedValue overflows, the transaction reverts.
return true;
}
/**
* @notice Atomically decreases the allowance granted to `spender` by `subtractedValue`.
*
* @dev This is the safe alternative to approve() for decreasing an existing allowance.
* Reverts if the current allowance is less than `subtractedValue`
* (cannot decrease below zero).
*
* Emits an {Approval} event with the updated allowance.
*
* @param spender The address whose allowance is being decreased.
* @param subtractedValue The amount to subtract from the current allowance.
* @return True on success.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
address owner = msg.sender;
uint256 currentAllowance = _allowances[owner][spender];
if (currentAllowance < subtractedValue) {
revert ERC20InsufficientAllowance(spender, currentAllowance, subtractedValue);
}
unchecked {
// Safe: we just verified currentAllowance >= subtractedValue
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
// ════════════════════════════════════════════════════════════════════════
// MINT & BURN
// ════════════════════════════════════════════════════════════════════════
/**
* @notice Creates `amount` new tokens and assigns them to `to`.
* @dev Only callable by the contract owner.
* Increases totalSupply and the recipient's balance.
* Emits a {Transfer} event with `from` set to address(0).
* @param to The address to receive the minted tokens.
* @param amount The number of tokens to mint (in smallest units).
*/
function mint(address to, uint256 amount) public onlyOwner {
_mint(to, amount);
}
/**
* @notice Destroys `amount` tokens from the caller's account.
* @dev Decreases the caller's balance and totalSupply by `amount`.
* Reverts if the caller's balance is insufficient.
* Emits a {Transfer} event with `to` set to address(0).
* @param amount The number of tokens to burn (in smallest units).
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @notice Destroys `amount` tokens from `account`, deducting from the caller's allowance.
* @dev The caller must have allowance for `account`'s tokens of at least `amount`.
* Useful for contracts that need to burn tokens on behalf of a user.
* Emits a {Transfer} event with `to` set to address(0).
* @param account The address whose tokens will be burned.
* @param amount The number of tokens to burn.
*/
function burnFrom(address account, uint256 amount) public {
_spendAllowance(account, msg.sender, amount);
_burn(account, amount);
}
// ════════════════════════════════════════════════════════════════════════
// OWNERSHIP
// ════════════════════════════════════════════════════════════════════════
/**
* @notice Returns the current owner of the contract.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @notice Transfers ownership of the contract to `newOwner`.
* @dev Only callable by the current owner.
* `newOwner` cannot be address(0) — use renounceOwnership() for that.
* Emits an {OwnershipTransferred} event.
* @param newOwner The address to receive ownership.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @notice Permanently renounces ownership, leaving the contract with no owner.
* @dev Only callable by the current owner.
* After this call, no address can mint new tokens. This is IRREVERSIBLE.
* Emits an {OwnershipTransferred} event with newOwner as address(0).
*/
function renounceOwnership() public onlyOwner {
_transferOwnership(address(0));
}
// ════════════════════════════════════════════════════════════════════════
// INTERNAL FUNCTIONS (not callable from outside the contract)
// ════════════════════════════════════════════════════════════════════════
/**
* @dev Core transfer logic shared by transfer() and transferFrom().
*
* Follows the Checks-Effects-Interactions pattern:
* 1. CHECKS — validate from, to, and balance
* 2. EFFECTS — update _balances (state change)
* 3. INTERACTIONS — emit Transfer event
*
* @param from Sender (validated: not address(0), sufficient balance).
* @param to Recipient (validated: not address(0)).
* @param amount Tokens to move.
*/
function _transfer(address from, address to, uint256 amount) internal {
// ── CHECKS ──────────────────────────────────────────────────────
// Cannot transfer from the zero address.
// For msg.sender calls this is technically impossible (no private key),
// but _transfer is also called by transferFrom where `from` is user-supplied.
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
// Cannot transfer to the zero address — tokens would be irrecoverable.
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
// Read balance into a local (stack) variable — avoids a second storage read.
uint256 fromBalance = _balances[from];
// Verify sufficient balance. The custom error includes context for debugging.
if (fromBalance < amount) {
revert ERC20InsufficientBalance(from, fromBalance, amount);
}
// ── EFFECTS ─────────────────────────────────────────────────────
// unchecked is safe because:
// - Subtraction: fromBalance >= amount (verified above)
// - Addition: _balances[to] + amount <= _totalSupply (which fits in uint256)
// because the sum of all balances always equals _totalSupply, and we are
// subtracting `amount` from one balance and adding it to another.
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
// ── INTERACTIONS ────────────────────────────────────────────────
emit Transfer(from, to, amount);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`.
* Increases _totalSupply. Emits Transfer from address(0).
*
* @param account Recipient (must not be address(0)).
* @param amount Tokens to create.
*/
function _mint(address account, uint256 amount) internal {
// Minting to address(0) = supply increase with no retrievable balance
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
// _totalSupply += amount is CHECKED (not inside unchecked).
// If this overflows uint256, the transaction reverts automatically.
// This maintains the invariant: totalSupply == sum of all balances.
_totalSupply += amount;
// unchecked is safe: we just proved _totalSupply + amount didn't overflow,
// and _balances[account] <= _totalSupply, so this addition also cannot overflow.
unchecked {
_balances[account] += amount;
}
// Transfer from address(0) = "new tokens created" convention.
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.
* Decreases _totalSupply. Emits Transfer to address(0).
*
* @param account The address to burn from (must not be address(0)).
* @param amount Tokens to destroy.
*/
function _burn(address account, uint256 amount) internal {
// Cannot burn from the zero address — it holds no real tokens
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
// Verify the account has enough tokens to burn
uint256 accountBalance = _balances[account];
if (accountBalance < amount) {
revert ERC20InsufficientBalance(account, accountBalance, amount);
}
// unchecked is safe:
// - Subtraction: accountBalance >= amount (verified above)
// - _totalSupply -= amount cannot underflow because
// _totalSupply >= _balances[account] >= amount (invariant)
unchecked {
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
}
// Transfer to address(0) = "tokens destroyed" convention.
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens.
* This OVERWRITES any previous allowance (does not add to it).
*
* @param owner Token owner (must not be address(0)).
* @param spender Authorized spender (must not be address(0)).
* @param amount Maximum tokens the spender can transfer.
*/
function _approve(address owner, address spender, uint256 amount) internal {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
// Write to storage. This is an OVERWRITE, not an increment.
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Deducts `amount` from the `owner`→`spender` allowance.
* Skips deduction if the allowance is type(uint256).max (infinite).
*
* Infinite approval convention:
* - User approves type(uint256).max → "I trust this spender indefinitely"
* - The allowance is never decremented → saves ~5,000 gas per transferFrom
* - Trade-off: if the approved contract is compromised, all tokens are at risk
*
* @param owner Token owner.
* @param spender The caller of transferFrom.
* @param amount Tokens being spent.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal {
uint256 currentAllowance = _allowances[owner][spender];
// Infinite approval: skip the deduction entirely (gas optimization)
if (currentAllowance != type(uint256).max) {
// Non-infinite: verify sufficient allowance
if (currentAllowance < amount) {
revert ERC20InsufficientAllowance(spender, currentAllowance, amount);
}
// Deduct the spent amount
// unchecked is safe: currentAllowance >= amount (verified above)
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Internal ownership transfer. Emits {OwnershipTransferred}.
* @param newOwner The new owner (address(0) means no owner — renouncement).
*/
function _transferOwnership(address newOwner) internal {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Section-by-Section Breakdown
State Variables: The Contract's Permanent Memory
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address private _owner;
These seven state variables define the entire state of our token. Let's understand each one's role.
_balances is the heart of the contract. It is a mapping that answers one question: "How many tokens does this address hold?" When Alice sends 50 tokens to Bob, the contract reads _balances[alice], subtracts 50, reads _balances[bob], and adds 50. That's it. There is no physical "token" being moved — just two numbers being updated in a hash table.
The private visibility means no other contract can read this mapping directly. Instead, we expose the balanceOf() function, which the ERC20 standard requires. Making state variables private is a best practice because it gives you control over how external code accesses your data — and you can add validation or formatting in the getter function if needed.
_allowances is a nested mapping that tracks delegated spending permissions. The key insight is that the ERC20 standard needs a way for third-party contracts (like Uniswap or Aave) to move your tokens on your behalf. You can't just let anyone call transfer with your address — that would let anyone steal your tokens. Instead, you first approve a specific spender for a specific amount, and then that spender can call transferFrom to pull tokens from your account up to the approved limit.
The nesting works like this: _allowances[owner][spender] = amount means "the owner has authorized the spender to move up to amount tokens from the owner's account." This creates a per-owner, per-spender permission system.
_totalSupply tracks the sum of all balances across all addresses. It is a critical invariant: at any point, the sum of _balances[addr] for every address addr that has ever received tokens must exactly equal _totalSupply. This invariant is maintained by the mint function (which increases both a balance and _totalSupply) and the transfer function (which moves amounts between balances without changing _totalSupply).
_name, _symbol, _decimals are metadata. They don't affect any contract logic — they exist solely so wallets and interfaces can display the token correctly. MetaMask reads name() to show "USD Coin", symbol() to show "USDC", and decimals() to know that a raw balance of 1000000 should display as "1.00" (because USDC uses 6 decimals).
_owner is our simple access control mechanism. Only the deployer can mint new tokens. In production, you'd likely use a more sophisticated access control pattern (like role-based access), but for understanding ERC20, a single owner address is sufficient.
Events: The Blockchain's Notification System
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
Events are Solidity's mechanism for emitting structured log data that external systems can subscribe to and query. When a Transfer event is emitted, the data is stored in the transaction receipt's logs — not in contract storage. This makes events significantly cheaper than storage writes (about 375 gas per byte of log data versus 20,000 gas for a new storage slot).
The indexed keyword on a parameter creates a topic in the log entry. Ethereum nodes can filter logs by topics, which means a wallet can efficiently query "show me all transfers to my address" without scanning every transaction. Up to three parameters can be indexed per event. Non-indexed parameters are stored in the log's data section and are cheaper, but cannot be filtered on.
The ERC20 standard mandates that Transfer is emitted on every transfer (including mints, where from is address(0), and burns, where to is address(0)). The Approval event must be emitted whenever approve is called. Block explorers like Etherscan rely on these events to build the token transfer history you see in the UI.
The Constructor: One-Time Initialization
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals,
uint256 initialSupply
) {
_name = tokenName;
_symbol = tokenSymbol;
_decimals = tokenDecimals;
_owner = msg.sender;
_mint(msg.sender, initialSupply);
}
The constructor runs exactly once — during contract deployment — and its code is not included in the contract's deployed bytecode. This means the constructor cannot be called again after deployment, making it the ideal place for one-time setup.
Notice that tokenName and tokenSymbol are string memory parameters. Since the constructor is called during deployment (essentially an external context), these strings arrive in the transaction's calldata and are copied into memory. The assignments _name = tokenName copy them from memory into storage, where they persist permanently.
The constructor calls _mint(msg.sender, initialSupply) to create the initial token supply. This is cleaner than duplicating the mint logic inline because _mint includes the zero-address check and event emission. The msg.sender in the constructor is the account that deployed the contract.
View Functions: Reading State Without Modifying It
function name() public view returns (string memory) { return _name; }
function symbol() public view returns (string memory) { return _symbol; }
function decimals() public view returns (uint8) { return _decimals; }
function totalSupply() public view returns (uint256) { return _totalSupply; }
function balanceOf(address account) public view returns (uint256) { return _balances[account]; }
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
All view functions are marked view, meaning they read storage but do not modify it. Calling a view function from off-chain (e.g., from a frontend using ethers.js) is free — it does not create a transaction and costs no gas. However, if a state-changing function calls a view function internally during a transaction, normal gas costs still apply.
The balanceOf function is how the world reads balances. When MetaMask shows you hold 100 USDC, it called balanceOf(yourAddress) on the USDC contract. The mapping returns 0 for any address that has never interacted with the contract — this is the default value of uint256 in Solidity, and it means the contract does not need any special initialization per user.
The allowance function lets anyone check the current spending permission between an owner and a spender. This transparency is a feature, not a bug — dApps need to read allowances to determine whether an approval transaction is needed before a transferFrom.
transfer: Moving Your Own Tokens
function transfer(address to, uint256 amount) public returns (bool) {
_transfer(msg.sender, to, amount);
return true;
}
The public transfer function is a thin wrapper around the internal _transfer. It hardcodes msg.sender as the from address, which is the fundamental security model: you can only transfer tokens you own, because msg.sender is cryptographically guaranteed by the Ethereum protocol.
It returns true because the ERC20 standard requires a bool return. In our implementation, if the transfer fails (insufficient balance, zero address), the transaction reverts entirely. It never returns false. This might seem redundant — why return true if the only alternative is a revert? The answer is historical: the original ERC20 specification predates Solidity's require and revert, and some early tokens used return false for failures. Modern tokens always revert, but the return type is kept for interface compatibility.
approve: Granting Spending Permission
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
The approve function is where the delegation model of ERC20 lives. When you want to trade tokens on Uniswap, you first call approve(uniswapRouterAddress, amount). This tells the token contract: "I, msg.sender, authorize this Uniswap router contract to spend up to amount of my tokens."
The approval is not a transfer. No tokens move. It simply writes a number into the _allowances mapping. The actual transfer happens later, when the Uniswap router calls transferFrom.
A crucial point: approve sets the allowance — it does not add to it. If you approve a spender for 100, then approve them for 50, the allowance becomes 50 (not 150). This overwrite behavior is intentional but is also the source of the ERC20 race condition, which we cover in a dedicated section below.
transferFrom: Third-Party Token Transfers
function transferFrom(address from, address to, uint256 amount) public returns (bool) {
_spendAllowance(from, msg.sender, amount);
_transfer(from, to, amount);
return true;
}
This is the function that makes DeFi possible. It allows msg.sender (typically a smart contract like Uniswap's router) to transfer tokens from someone else's account, provided they have been approved.
The execution flow is:
_spendAllowance(from, msg.sender, amount)— Checks thatmsg.senderhas sufficient allowance to spendfrom's tokens. If the allowance is not infinite (type(uint256).max), it deductsamountfrom the allowance. This prevents the spender from reusing the same approval to drain the owner's account._transfer(from, to, amount)— Performs the actual balance update, identical to a regular transfer. It deductsamountfromfrom's balance and adds it toto's balance.
The order matters: we check and reduce the allowance before transferring. This is a checks-effects-interactions pattern variant. If we transferred first and then tried to reduce the allowance, a reentrant call could exploit the window where the allowance hasn't been reduced yet.
_spendAllowance: The Infinite Approval Optimization
function _spendAllowance(address owner, address spender, uint256 amount) internal {
uint256 currentAllowance = _allowances[owner][spender];
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ManualERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
This function introduces an important gas optimization: infinite approvals. When a user approves type(uint256).max (the maximum possible uint256 value), the contract interprets this as "unlimited — do not decrement."
Why does this exist? Every time _approve is called, it writes to storage (5,000 gas for a warm slot). If a user frequently trades on Uniswap, every transferFrom would cost an extra 5,000+ gas to update the allowance. With an infinite approval, the allowance check still passes (any amount is less than type(uint256).max), but the storage write is skipped entirely.
The trade-off is trust: an infinite approval means the spender can take all of your tokens at any time. If the approved contract gets hacked, your entire balance is at risk. Many security-conscious users prefer to approve only the exact amount needed for each transaction.
_mint: Creating New Tokens
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ManualERC20: mint to the zero address");
_totalSupply += amount;
unchecked {
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
}
Minting is how tokens come into existence. The function increases _totalSupply and the recipient's balance by the same amount, maintaining the invariant that total supply equals the sum of all balances.
The _totalSupply += amount line does not use unchecked, meaning if the total supply would exceed type(uint256).max, the transaction reverts automatically. This is intentional — total supply overflow would break the contract's fundamental invariant.
However, _balances[account] += amount is inside unchecked. This is safe because we just proved that _totalSupply + amount does not overflow (the previous line succeeded). Since _balances[account] <= _totalSupply must always hold (no individual balance can exceed total supply), the balance addition also cannot overflow.
The emit Transfer(address(0), account, amount) follows the ERC20 convention: a transfer from address(0) signals token creation. This is not just convention — block explorers parse these events to compute token supply and display mint transactions differently from regular transfers.
The ERC20 Approve/TransferFrom Race Condition
This is one of the most discussed vulnerabilities in the ERC20 standard, and understanding it is a rite of passage for Solidity developers.
The Scenario
Imagine Alice has approved Bob to spend 100 tokens. Alice now wants to change Bob's allowance to 50 tokens. She sends a transaction: approve(bob, 50).
But Bob is watching the mempool (the queue of pending transactions). He sees Alice's pending transaction before it's confirmed. He quickly submits his own transaction — transferFrom(alice, bob, 100) — with a higher gas price so miners include it first.
Here's the sequence that executes:
Bob's
transferFromis mined first: Bob spends all 100 of his allowance, receiving 100 tokens.Alice's
approve(bob, 50)is mined second: The allowance is now set to 50.Bob calls
transferFromagain: He spends 50 more tokens from Alice.
Bob has extracted 150 tokens from Alice, even though she only ever intended to approve 100 maximum.
Why This Happens
The problem is that approve uses an overwrite model, not an increment/decrement model. When Alice calls approve(bob, 50), it unconditionally sets the allowance to 50, regardless of the previous value. The transaction does not know or care that the old allowance was 100.
Mitigation Strategies
The standard mitigation is to use a two-step approval:
approve(spender, 0)— Reset the allowance to zero first.Wait for that transaction to confirm.
approve(spender, newAmount)— Set the new allowance.
If Bob front-runs step 1, he can spend the old allowance, but the allowance goes to zero. When Alice sets the new amount in step 3, Bob can only spend the new amount — not the old amount plus the new amount.
More modern solutions include increaseAllowance and decreaseAllowance functions (which add/subtract rather than overwrite), and the EIP-2612 permit pattern (which uses off-chain signatures instead of on-chain approve transactions, eliminating the mempool exposure entirely). Our contract keeps the standard approve to match the ERC20 specification, but production tokens should consider these enhancements.
Infinite Approvals
if (currentAllowance != type(uint256).max) {
// ... deduct allowance
}
The value type(uint256).max equals 2²⁵⁶ − 1 — a number so large that no realistic amount of tokens could ever reach it. When a user approves this amount, the contract treats it as a signal: "This approval should never expire or decrease."
This convention emerged for practical reasons. Early DeFi users found themselves approving tokens before every single swap, paying 40,000+ gas each time for the approval transaction. By approving type(uint256).max once, they pay the gas cost only once. All subsequent transferFrom calls skip the allowance update, saving approximately 5,000 gas per call.
In our _spendAllowance function, the if check is the entire implementation: if the current allowance equals type(uint256).max, we skip the require and the _approve call entirely. The allowance remains at type(uint256).max forever (unless explicitly changed by a new approve call).
The security trade-off is real. If you infinite-approve a DEX contract and that contract gets exploited, the attacker can drain your entire token balance. This is why wallet interfaces like MetaMask now default to suggesting the exact amount needed rather than the maximum.
Revert vs Return False
The ERC20 standard specifies that transfer, approve, and transferFrom return bool. This creates an ambiguity: should a failed transfer return false or revert the transaction?
The Historical Problem
Early ERC20 tokens (notably USDT on some chains) returned false on failure without reverting. This created a dangerous pattern:
// DANGEROUS: if token.transfer returns false, this code silently continues
// The caller thinks the transfer succeeded, but no tokens moved
token.transfer(recipient, amount);
If the calling contract does not check the return value, it assumes the transfer succeeded. Products have lost real funds due to this exact issue.
The Modern Approach (What Our Contract Does)
Our contract always reverts on failure (via require) and always returns true on success. There is no code path that returns false. This is the approach used by OpenZeppelin and virtually all modern tokens.
// Our transfer: reverts on failure, returns true on success
function transfer(address to, uint256 amount) public returns (bool) {
_transfer(msg.sender, to, amount); // reverts if anything goes wrong
return true; // only reached if transfer succeeded
}
This approach is safer because it's impossible for a caller to accidentally ignore a failure — the failure unwinds the entire transaction.
Handling Non-Standard Tokens
Because some legacy tokens do return false, libraries like OpenZeppelin's SafeERC20 use a wrapper (safeTransfer) that checks the return value and reverts if it's false — or if the call returned no data at all (which some non-compliant tokens do). If your contract interacts with arbitrary ERC20 tokens, always use SafeERC20 or equivalent wrappers.
Underflow and Overflow Protection in Solidity ≥ 0.8
What Changed
Before Solidity 0.8.0, arithmetic operations silently wrapped around on overflow and underflow. This means:
// Solidity < 0.8 behavior (DANGEROUS)
uint8 x = 255;
x + 1; // Result: 0 (wrapped around, no error)
uint8 y = 0;
y - 1; // Result: 255 (wrapped around, no error)
This silent wrapping was the root cause of many devastating hacks. A token contract where balances[from] -= amount could underflow would effectively give the attacker an infinite balance.
Starting with Solidity 0.8.0, all arithmetic operations check for overflow and underflow by default. If an operation would wrap, the transaction reverts with a Panic(0x11) error.
// Solidity >= 0.8 behavior (SAFE)
uint8 x = 255;
x + 1; // REVERTS with Panic(0x11)
uint8 y = 0;
y - 1; // REVERTS with Panic(0x11)
How Our Contract Uses This
In our _transfer function:
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ManualERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
The require(fromBalance >= amount) ensures the subtraction is safe. We then wrap the arithmetic in unchecked{} to skip the redundant automatic overflow check and save gas. This is a common pattern: validate first with require, then use unchecked for the actual math.
Without unchecked, Solidity would add runtime checks that cost extra gas. Since we already manually verified the safety condition, those checks are redundant. The unchecked block saves roughly 100-200 gas per arithmetic operation — small individually, but significant in frequently-called functions like transfer.
We deliberately leave _totalSupply += amount in the _mint function outside of unchecked, because we want the automatic overflow check there. A totalSupply overflow would corrupt the contract's invariant, and there's no prior manual check to make it redundant.
Why decimals Is Only for Display
This is one of the most misunderstood aspects of ERC20 tokens for beginners.
Solidity has no floating-point numbers. The EVM operates exclusively on integers. When a token has decimals = 18, it means the contract internally represents one full token as 1_000_000_000_000_000_000 (1 × 10¹⁸) — the same way Ethereum represents 1 ETH as 1 × 10¹⁸ wei.
The decimals() function tells frontends how to translate between the contract's integer representation and the human-readable display:
| Contract Balance (uint256) | Decimals | User Sees |
1000000000000000000 | 18 | 1.0 |
500000000000000000 | 18 | 0.5 |
1000000 | 6 | 1.0 (USDC) |
100000000 | 8 | 1.0 (WBTC) |
The contract itself never divides, never rounds, and never uses decimals in any calculation. All arithmetic is performed on the raw integer values. The decimals value is read by JavaScript (ethers.js, web3.js), MetaMask, Etherscan, and other off-chain tools to format numbers for human consumption.
This design avoids the precision loss and rounding errors that plague floating-point arithmetic. When Alice sends Bob exactly 0.1 tokens (with 18 decimals), the contract transfers exactly 100000000000000000 units — no rounding, no approximation.
If you're coming from traditional programming, think of it like currency: a bank doesn't store $1.50 as a float — it stores 150 cents as an integer.
Best Practices and Common Pitfalls
1. Always Check for the Zero Address
Every function that accepts an address should validate it is not address(0). Tokens transferred to the zero address are permanently lost. The zero address holds billions of dollars worth of tokens that were accidentally sent to it across various networks. Our contract checks for this in _transfer, _mint, and _approve.
2. Follow Checks-Effects-Interactions
In our transferFrom, we check the allowance, update state (reduce allowance, update balances), and then return. We never make external calls between state changes. This ordering prevents reentrancy attacks, where a malicious contract re-enters your function mid-execution to exploit stale state.
3. Use unchecked Only After Manual Validation
The unchecked block is a gas optimization tool, not a shortcut. Use it only when you have mathematically proven that the operation cannot overflow or underflow. In our contract, every unchecked block is preceded by a require or a logical argument (e.g., "a balance cannot exceed totalSupply") that guarantees safety.
4. Emit Events for Every State Change
Events are cheap and critical. Off-chain infrastructure — block explorers, indexers, analytics, wallets — all depend on events. A token that doesn't emit Transfer events won't show up in MetaMask's transaction history or Etherscan's token tracker. Our contract emits Transfer on every balance change (including mints) and Approval on every allowance change.
5. Use private State Variables with public Getters
Our state variables are private and our getters are public functions. Solidity can auto-generate getters (using the public visibility on the state variable itself), but explicit functions give you control over the return type and naming convention, and they match the ERC20 interface exactly.
6. Consider the Race Condition in Approvals
If your token is standard ERC20, document the race condition clearly. Consider adding increaseAllowance and decreaseAllowance as convenience functions. Better yet, implement EIP-2612 (permit) to allow gasless, signature-based approvals that sidestep the issue entirely.
7. Keep Access Control Simple but Explicit
Our mint function uses a simple require(msg.sender == _owner) check. For production contracts with multiple roles (minter, pauser, admin), use a role-based pattern. But always make access control visible and explicit — a mint function without access control is a critical vulnerability that lets anyone create tokens out of thin air.
Conclusion
We have built a complete ERC20 token from the ground up, touching every layer of the stack: from how the EVM stores 256-bit words in storage slots, to how mappings compute storage locations with keccak256, to why decimals is a display hint rather than a math parameter, to the subtle race condition hiding in approve.
The key takeaways are as follows. The _balances mapping is the single source of truth for who owns what. The _allowances nested mapping enables the delegation model that powers DeFi. The transferFrom function must check and reduce the allowance before transferring tokens. Zero-address checks prevent irreversible token loss. Events are the bridge between on-chain state changes and off-chain user interfaces. Solidity 0.8's built-in overflow protection eliminates an entire class of vulnerabilities, and unchecked lets you reclaim gas when you've already proven safety. Infinite approvals trade security for convenience, and the race condition in approve is a design-level issue that requires protocol-level mitigations.
Understanding these mechanics is not just academic — it's the difference between a secure token and an exploitable one. Every line of code in a smart contract is immutable once deployed. There are no patches, no hotfixes, no rollbacks. The code you deploy is the code that handles real money, permanently. Building from scratch — even if you use OpenZeppelin in production — ensures you understand what that code is doing and why.
About the author
In my free time iwrite and raise my voice in toast.
Comments
Join the discussionNo comments yet. Be the first to comment.




