How to Create an ERC20 Token in Solidity: Simple Guide
To create an
ERC20 token in Solidity, you define a contract that implements the standard ERC20 interface with functions like transfer and balanceOf. Using OpenZeppelin's ERC20 contract as a base simplifies this process by providing tested code you can extend.Syntax
An ERC20 token contract in Solidity typically includes:
- Contract declaration: Defines the token contract.
- State variables: Store token name, symbol, decimals, and total supply.
- Constructor: Sets initial supply and assigns tokens to the creator.
- Standard functions:
transfer,approve,transferFrom,balanceOf, andallowance.
solidity
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MyToken is ERC20 { constructor(uint256 initialSupply) ERC20("MyToken", "MTK") { _mint(msg.sender, initialSupply); } }
Example
This example shows a simple ERC20 token named "MyToken" with symbol "MTK" and an initial supply minted to the deployer.
solidity
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MyToken is ERC20 { constructor() ERC20("MyToken", "MTK") { _mint(msg.sender, 1000000 * 10 ** decimals()); } }
Output
No direct output; deploy contract and check balances with blockchain tools.
Common Pitfalls
Common mistakes when creating ERC20 tokens include:
- Not setting the
decimalsproperly, causing confusion in token amounts. - Forgetting to mint initial supply, resulting in zero tokens.
- Not using a well-tested library like OpenZeppelin, which can lead to security issues.
- Incorrectly implementing
transferorapprovefunctions, breaking token transfers.
solidity
/* Wrong way: Missing _mint call, no tokens created */ contract BadToken is ERC20 { constructor() ERC20("BadToken", "BDT") {} } /* Right way: Mint tokens in constructor */ contract GoodToken is ERC20 { constructor() ERC20("GoodToken", "GDT") { _mint(msg.sender, 1000 * 10 ** decimals()); } }
Quick Reference
| Concept | Description |
|---|---|
| contract MyToken is ERC20 | Defines a new token contract inheriting ERC20 standard |
| constructor() | Sets token name, symbol, and mints initial supply |
| _mint(address, amount) | Creates tokens and assigns them to an address |
| decimals() | Returns token decimal places, usually 18 |
| transfer(to, amount) | Sends tokens from caller to another address |
| balanceOf(address) | Returns token balance of an address |
Key Takeaways
Use OpenZeppelin's ERC20 contract to create secure and standard tokens easily.
Always mint an initial supply in the constructor to assign tokens.
Set decimals properly to handle token units correctly.
Test token functions like transfer and balanceOf after deployment.
Avoid rewriting ERC20 functions from scratch to prevent bugs and security risks.