How do I write a secure ERC-20 token with OpenZeppelin? · Jumpstart Blockchain
How do I write a secure ERC-20 token with OpenZeppelin?
Inherit OpenZeppelin 5.x ERC20 instead of writing your own, mint a fixed supply to a multisig, and if you need minting add AccessControl roles and ERC20Capped. Put custom rules only in _update, then test and verify.
To write a secure ERC-20, don't implement the standard yourself: inherit OpenZeppelin Contracts 5.xERC20, set the name, symbol and supply in the constructor, and add only the extensions you need, such as ERC20Permit for gasless approvals, ERC20Capped for a hard supply limit, or AccessControl for a restricted mint. Most token failures don't come from the transfer logic, which OpenZeppelin has battle-tested, but from what developers add around it: unrestricted or single-key mint functions, custom transfer fees, modified library code and missing tests. The safest token mints a fixed supply once and has no admin powers at all.
What a minimal secure token looks like
ERC-20, the token standard used across Ethereum and EVM chains, is a small interface: totalSupply, balanceOf, transfer, approve, allowance, transferFrom, plus Transfer and Approval events. OpenZeppelin implements it with checked arithmetic, standard events and the ERC-6093 custom errors (ERC20InsufficientBalance, ERC20InvalidReceiver and so on), so you write very little code.
Set up a Foundry project and pin a released version of the library:
forge init my-token && cd my-token
forge install OpenZeppelin/[email protected]# or the latest v5 release tagecho'@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/' >> remappings.txt
With npm and Hardhat, use npm install @openzeppelin/contracts@^5, which resolves to the latest audited 5.x release. If you're still choosing tooling, see Hardhat or Foundry.
A fixed-supply token is a few lines:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
contract ExampleToken is ERC20, ERC20Permit {
constructor(address treasury)
ERC20("Example Token", "EXT")
ERC20Permit("Example Token")
{
_mint(treasury, 1_000_000 * 10 ** decimals());
}
}
delegatecall runs another contract's code on your storage by slot number, so mismatched layouts overwrite data. Delegate only to trusted code, use ERC-1967 and ERC-7201 slots, check the target has code, and diff layouts.
There is no owner, no mint function and no pause switch. Once deployed, nobody can change the supply or block transfers, which is exactly what holders and integrators want to see. ERC20Permit adds EIP-2612 permit, letting users approve by signature instead of a separate transaction; the trade-offs are covered in how approvals, permits and infinite allowances can be abused.
Mint to a treasury multisig, not the deployer's hot key. The deployer key usually lives on a laptop or in CI, and whoever controls the initial balance controls the token's distribution.
How do I add minting safely?
If the supply must grow (rewards, bridging, vesting), restrict who can mint, cap the total, and split powers between roles:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {ERC20Capped} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
import {ERC20Pausable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
contract ManagedToken is ERC20, ERC20Burnable, ERC20Capped, ERC20Pausable, ERC20Permit, AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
constructor(address admin, address minter, address pauser)
ERC20("Managed Token", "MGT")
ERC20Capped(10_000_000 * 1e18)
ERC20Permit("Managed Token")
{
_grantRole(DEFAULT_ADMIN_ROLE, admin);
_grantRole(MINTER_ROLE, minter);
_grantRole(PAUSER_ROLE, pauser);
}
function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
function pause() external onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() external onlyRole(PAUSER_ROLE) {
_unpause();
}
// ERC20Capped and ERC20Pausable both extend _update; Solidity requires an explicit override.
function _update(address from, address to, uint256 value)
internal
override(ERC20, ERC20Capped, ERC20Pausable)
{
super._update(from, to, value);
}
}
What each piece protects:
Feature
Protects against
Cost
ERC20Capped
A compromised minter inflating supply without limit
None meaningful
MINTER_ROLE
Anyone but the designated minter (for example a bridge or vesting contract) creating tokens
Role management
PAUSER_ROLE
Ongoing damage during an incident
Holders must trust the pauser not to freeze them
Separate DEFAULT_ADMIN_ROLE
One leaked key controlling everything
Admin can grant and revoke roles, so guard it most
ERC20Burnable
Nothing; lets holders destroy their own tokens
Optional
Every admin power is also a risk to holders, so add only what you'll use. A pause function on a token that claims to be decentralised is a red flag to many users, and an unused minter role is an attack surface. Give DEFAULT_ADMIN_ROLE to a Safe or similar multisig, as discussed in how teams should hold keys, and consider AccessControlDefaultAdminRules, which makes admin transfers two-step with a delay. When a role is no longer needed, revoke it (renounceRole) and say so publicly.
The v5 _update hook, and why you shouldn't override transfer
OpenZeppelin 5.x routes every balance change, whether mint, burn or transfer, through one internal function: _update(from, to, value). The 4.x hooks _beforeTokenTransfer and _afterTokenTransfer are gone. If you need custom logic, override _update and call super._update exactly once, as above.
Don't override transfer or transferFrom directly. Mints and burns don't pass through them, so any rule you put there is bypassed, and you risk breaking event emission or return values that wallets and DEXs depend on.
Keep _update overrides simple. Each extra rule runs on every transfer and is a chance to lock funds or open a hole. If you must block a destination, such as transfers to the token contract itself (a common way users lose tokens), add a single check:
function _update(address from, address to, uint256 value)
internal
override(ERC20, ERC20Capped, ERC20Pausable)
{
if (to == address(this)) revert ERC20InvalidReceiver(to);
super._update(from, to, value);
}
Features that make tokens unsafe or incompatible
These are the additions that most often cause losses, failed integrations or a token that looks like a scam:
Fee-on-transfer or rebasing balances. Many protocols assume the amount sent equals the amount received. Taxed or rebasing tokens break AMMs, lending markets and vaults, and the "tax" logic is a common hiding place for owner-only drains.
Blacklists and owner-controlled transfer limits. "Anti-bot" switches let the owner stop selling at will. Scanners flag them, and many users won't touch a token that has them.
tx.origin checks. Anti-bot code that only allows tx.origin == msg.sender doesn't do what it claims, and since EIP-7702 lets ordinary wallets run code it misclassifies real users too.
Callbacks on transfer. Hooks that call the recipient (as ERC-777 did) open reentrancy paths in every protocol that holds your token. If you integrate such tokens, apply standard reentrancy defences.
Editing library files. Copying OpenZeppelin code into your repo and changing it loses the audit, and future fixes. Inherit and override instead.
Upgradeability by default. A proxy lets the admin replace all token logic. Use it only if you need it, with @openzeppelin/contracts-upgradeable, an initializer function and a timelocked multisig, following how upgradeable proxies work.
On decimals: OpenZeppelin defaults to 18. If you want 6, like most stablecoins, override decimals() to return 6, and make sure every amount in the constructor and scripts uses the same value.
How do I test and deploy it?
Test the rules you added, not just the happy path. With Foundry:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Test} from "forge-std/Test.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ERC20Capped} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
import {ManagedToken} from "../src/ManagedToken.sol";
contract ManagedTokenTest is Test {
ManagedToken token;
address admin = makeAddr("admin");
address minter = makeAddr("minter");
address pauser = makeAddr("pauser");
address alice = makeAddr("alice");
function setUp() public {
token = new ManagedToken(admin, minter, pauser);
}
function test_OnlyMinterCanMint() public {
bytes32 role = token.MINTER_ROLE();
vm.expectRevert(
abi.encodeWithSelector(IAccessControl.AccessControlUnauthorizedAccount.selector, alice, role)
);
vm.prank(alice);
token.mint(alice, 1);
}
function test_CannotExceedCap() public {
uint256 cap = token.cap();
vm.startPrank(minter);
token.mint(alice, cap);
vm.expectRevert(abi.encodeWithSelector(ERC20Capped.ERC20ExceededCap.selector, cap + 1, cap));
token.mint(alice, 1);
vm.stopPrank();
}
function testFuzz_TransferConservesSupply(uint256 amount) public {
amount = bound(amount, 0, token.cap());
vm.prank(minter);
token.mint(alice, amount);
uint256 supply = token.totalSupply();
vm.prank(alice);
token.transfer(admin, amount);
assertEq(token.totalSupply(), supply);
assertEq(token.balanceOf(admin), amount);
}
}
Because OpenZeppelin uses custom errors, failed calls return selectors rather than strings; if a revert in your frontend shows only raw data, see how to decode "execution reverted".
Deploy to a testnet first, from a dedicated deployer key or hardware wallet, then verify the source so users can read it:
If verification fails, fixing "bytecode does not match" covers the usual causes: compiler settings, optimiser runs and constructor arguments. After deployment, read back totalSupply, cap, decimals and every role holder on-chain, and check that the deployer holds no roles or tokens it shouldn't.
Checklist
Inherit OpenZeppelin 5.x ERC20; pin a released version and never edit library files.
Prefer a fixed supply minted once to a multisig treasury, with no admin functions.
If minting is needed, use AccessControl with separate roles, ERC20Capped, and a multisig admin.
Put custom logic only in _update, call super._update once, and keep it minimal.
Avoid transfer fees, blacklists, tx.origin checks, transfer callbacks and unnecessary upgradeability.
Set decimals deliberately and use it consistently.
Test access control, caps and pausing, including fuzzed amounts.
Verify the source, read every role and parameter back after deployment, and renounce what you no longer need.
Pair an execution client such as Geth with a consensus client such as Lighthouse, linked by the Engine API on port 8551 and a shared JWT secret. Use checkpoint sync, 4 TB of NVMe and open P2P ports, then confirm both are synced.
ERC-721 maps each token id to one owner, ideal for unique items. ERC-1155 tracks quantities per id with batch transfers and mandatory receiver hooks, suiting editions and game items. Pick by data model, not hype.