
Summary: ERC20 is the foundational fungible token standard of the EVM, specifying 6 functions and 2 events. Wrapping native Ether into WETH9 allows protocols to treat ETH identically to any ERC20 asset. Building a minimal 70-line raw implementation clarifies state mechanics, while inheriting OpenZeppelin v5 ensures audited security and compliance. In production, naive integrations frequently lose funds to 6 specific failure modes: missing return values on USDT transfers, frontrunning race conditions on
approve, fee-on-transfer discrepancies, decimal misalignments, unprotected mint entry points, and zero-address transfers. This guide compares raw and OpenZeppelin implementations, details these 6 hazards, and benchmarks token tests using Foundry.
1. ERC20 Architecture: Two Paths to Move Tokens
Token movement paths: direct transfers from the caller vs two-step allowances executed on behalf of owners.
The ERC20 interface specifies how balances and allowances are tracked and transferred:
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}1. Direct Transfer:
Caller (msg.sender) transfers their own tokens:
token.transfer(recipient, amount);
2. Two-Step Delegated Transfer (Allowance):
Step A (Owner): token.approve(spender, amount);
Step B (Spender): token.transferFrom(owner, recipient, amount);
In transferFrom, the caller (msg.sender) is the authorized spender, while tokens are deducted from the owner (from).
2. Raw Implementation vs. OpenZeppelin v5
From the open-source repository imminer668/Solidity-Guide, the curriculum provides two parallel implementations under foundry_projects/06_standards/24_ERC20/:
2.1 The 70-Line Raw Version (src/raw/ERC20.sol)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import "./IERC20.sol";
contract ERC20 is IERC20 {
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
string public name = "RawToken";
string public symbol = "RAW";
uint8 public decimals = 18;
function transfer(address recipient, uint256 amount) public override returns (bool) {
balanceOf[msg.sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount)
public
override
returns (bool)
{
allowance[sender][msg.sender] -= amount;
balanceOf[sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
return true;
}
// Internal mint helper
function _mint(address to, uint256 amount) internal {
totalSupply += amount;
balanceOf[to] += amount;
emit Transfer(address(0), to, amount);
}
}
2.2 The OpenZeppelin v5 Version (src/oz/ERC20Token.sol)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract ERC20Token is ERC20 {
uint8 private _decimals;
constructor(string memory name_, string memory symbol_, uint8 decimals_)
ERC20(name_, symbol_)
{
_decimals = decimals_;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function mint(address to, uint256 amount) external {
_mint(to, amount);
}
}
2.3 Implementation Trade-offs
| Property | Raw (src/raw/ERC20.sol) |
OpenZeppelin v5 (src/oz/ERC20Token.sol) |
|---|---|---|
| Line Count | ~70 lines | ~25 lines |
| State Storage | Explicit balanceOf / allowance mappings |
Private _balances managed through _update() hooks |
| Edge Cases | Relies on default 0.8+ arithmetic checks | Explicit zero-address assertions and balance checks |
| Primary Use | Understanding mechanics and state flow | Production deployments and formal audits |
3. Wrapped Ether: Why DeFi Protocols Need WETH9
Native Ether is not an ERC20 token; it precedes the standard. Protocols like Uniswap or Aave design their router interfaces around ERC20 transfer and allowance functions. Because raw ETH has no transferFrom or approve, it must be wrapped 1:1 into WETH9.
From foundry_projects/06_standards/27_WETH/src/raw/WETH.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
contract WETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
// Direct transfers to contract address automatically trigger deposit
fallback() external payable { deposit(); }
receive() external payable { deposit(); }
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public {
require(balanceOf[msg.sender] >= amount, "WETH: insufficient balance");
balanceOf[msg.sender] -= amount; // CEI state update
(bool success, ) = payable(msg.sender).call{value: amount}("");
require(success, "WETH: transfer failed");
emit Withdrawal(msg.sender, amount);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
}
The invariant: address(this).balance == totalSupply(). Depositing ETH mints WETH, and burning WETH returns native ETH.
4. 6 Production Pitfalls When Integrating ERC20
When smart contracts or payment gateways interact with third-party ERC20 tokens on mainnet, these 6 issues account for common integration bugs:
1. USDT Non-Bool Return (Missing Return Value)
- Problem: The Tether (USDT) contract on Ethereum does not return a boolean on
transferortransferFrom. Calling standardIERC20(usdt).transfer(...)expects a 32-byte boolean return and reverts when no data is returned. - Fix: Use OpenZeppelin’s
SafeERC20library (using SafeERC20 for IERC20; token.safeTransfer(to, amount)), which uses assembly to check return data size and accepts zero-length returns as success.
2. approve Frontrunning (Race Conditions)
- Problem: If Alice calls
approve(spender, 50)to lower an existing 100-token allowance, the spender can frontrun Alice’s transaction in the mempool to spend the original 100, then spend the new 50 after her transaction confirms (spending 150 total). - Fix: Use
increaseAllowanceanddecreaseAllowance, or mandate setting allowance to 0 before setting a new value.
3. Fee-on-Transfer (Deflationary Tokens)
-
Problem: Certain tokens deduct a tax (e.g. 1%) during transfers. If a contract credits a deposit based on the requested
amount, its internal accounting will exceed actual tokens received. -
Fix: Calculate the actual delta received:
uint256 balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(user, address(this), amount); uint256 actualReceived = token.balanceOf(address(this)) - balanceBefore;
4. Decimal Discrepancies
- Problem: Developers frequently assume all tokens use 18 decimals. USDC and USDT use 6 decimals; WBTC uses 8 decimals.
- Fix: Dynamically read
IERC20Metadata(token).decimals()and normalize amounts before executing calculations.
5. Unprotected Mint/Burn
- Problem: Didactic tutorials leave
mint()external for testing. Deploying this code on mainnet allows arbitrary addresses to inflate token supply. - Fix: Enforce
onlyOwneraccess or implement a fixed supply in the constructor.
6. Zero-Address Transfers
- Problem: Sending tokens to
address(0)burns tokens irrecoverably. - Fix: Assert
require(to != address(0))on all transfer endpoints (default in OpenZeppelin v5).
5. Testing with Foundry
From foundry_projects/06_standards/24_ERC20/test/raw/ERC20.t.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.35;
import {Test} from "forge-std/Test.sol";
import {ERC20} from "../../src/raw/ERC20.sol";
contract ERC20Test is Test {
ERC20 public token;
address alice = address(0x1);
address bob = address(0x2);
function setUp() public {
token = new ERC20();
}
function testApproveAndTransferFrom() public {
// Deal initial balance to alice
deal(address(token), alice, 1000);
// Alice approves this test contract to spend 500
vm.prank(alice);
token.approve(address(this), 500);
// Spender executes transferFrom on Alice's behalf
token.transferFrom(alice, bob, 300);
assertEq(token.balanceOf(bob), 300);
assertEq(token.balanceOf(alice), 700);
assertEq(token.allowance(alice, address(this)), 200);
}
}
Run tests with forge test -vv.
6. Production Systems Context
In production Web3 products: – StableIn Payments (中文版): Employs SafeERC20 and raw integer arithmetic across multi-chain USDC checkouts to prevent non-standard token failures and decimal precision drift (see Validate Stablecoin Checkout Amounts on the Server). – White-Label DEX (中文版): Uses balance delta tracking to support deflationary and fee-on-transfer tokens safely inside AMM swap pools. – Agent Wallet Guard (中文版): Intercepts token transfer requests to prevent autonomous AI agents from granting unbounded token allowances.
Review full systems on the Fone Products Center (中文版) or read technical notes on Fone Insights.
Verify It Locally with Foundry
Every contract and test pattern covered in this guide is runnable directly from the open-source imminer668/Solidity-Guide repository (foundry_projects/06_standards/24_ERC20):
# 1. Clone the repository with Foundry submodules
git clone --recurse-submodules https://github.com/imminer668/Solidity-Guide.git
cd Solidity-Guide
# 2. Run the verified Foundry test suite for this module
cd foundry_projects/06_standards/24_ERC20 && forge test -vvv
Expected local verification output:
[PASS] test_Transfer() (gas: 39120)
[PASS] test_ApproveAndTransferFrom() (gas: 46890)
Suite result: ok. 2 passed; 0 failed; 0 skipped
Frequently Asked Questions (Technical FAQ)
Why do DeFi protocols wrap ETH into WETH instead of handling native ETH directly?
Supporting both native ETH (msg.value) and ERC20 tokens (transferFrom) forces every swap, lending, and vault function to maintain duplicate code paths and branching logic. Wrapping ETH into WETH9 (foundry_projects/06_standards/27_WETH/) unifies all assets under a single IERC20 interface.
What is the type(uint256).max infinite approval optimization in ERC20?
In OpenZeppelin’s ERC20._spendAllowance, if allowance(owner, spender) == type(uint256).max, the contract skips the SSTORE operation that decrements the allowance on transferFrom, saving ~2,900–5,000 gas per transfer at the cost of granting permanent spending authority until revoked.
Why must vault contracts use SafeERC20 when interacting with mainnet USDT?
Mainnet USDT (0xdAC17F958D2ee523a2206206994597C13D831ec7) omits the returns (bool) specifier on transfer and transferFrom. Solidity 0.8+ asserts returndatasize() >= 32 for standard IERC20 calls, causing every USDT transfer to revert unless wrapped in SafeERC20.safeTransfer.
Series & Related Engineering Guides
- Previous Lesson (S07): Building Secure Contracts from Scratch: Reentrancy Defense in SimpleBank and Voting Systems
- Next Lesson (S09): NFT Asset Modeling in Solidity: ERC721 vs. ERC1155 Raw & OpenZeppelin Implementations
- Companion Security & Architecture Deep-Dive (T03): Why Naive ERC20 Integrations Lose Funds: Non-Bool Returns, Fee-on-Transfer, and Approval Race Conditions
- Production Engineering Case Study: Validate Stablecoin Checkout Amounts on the Server
- Open-Source Codebase: imminer668/Solidity-Guide (
foundry_projects/06_standards/24_ERC20) - Commercial Platforms & Advisory: Fone Products Center (中文版) | Fone Services | Contact Engineering